@hasna/brains 0.0.9 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/cli/index.js +1055 -632
  2. package/dist/db/index.d.ts.map +1 -1
  3. package/dist/index.js +4325 -127
  4. package/dist/lib/config.d.ts +11 -0
  5. package/dist/lib/config.d.ts.map +1 -0
  6. package/dist/lib/gatherers/assistants.d.ts +3 -0
  7. package/dist/lib/gatherers/assistants.d.ts.map +1 -0
  8. package/dist/lib/gatherers/economy.d.ts +3 -0
  9. package/dist/lib/gatherers/economy.d.ts.map +1 -0
  10. package/dist/lib/gatherers/index.d.ts +3 -0
  11. package/dist/lib/gatherers/index.d.ts.map +1 -1
  12. package/dist/lib/gatherers/protocol.d.ts +29 -0
  13. package/dist/lib/gatherers/protocol.d.ts.map +1 -0
  14. package/dist/lib/gatherers/recordings.d.ts +3 -0
  15. package/dist/lib/gatherers/recordings.d.ts.map +1 -0
  16. package/dist/lib/gatherers/registry.d.ts +7 -0
  17. package/dist/lib/gatherers/registry.d.ts.map +1 -0
  18. package/dist/lib/gatherers/researcher.d.ts +3 -0
  19. package/dist/lib/gatherers/researcher.d.ts.map +1 -0
  20. package/dist/lib/gatherers/styles.d.ts +3 -0
  21. package/dist/lib/gatherers/styles.d.ts.map +1 -0
  22. package/dist/lib/gatherers/tickets.d.ts +3 -0
  23. package/dist/lib/gatherers/tickets.d.ts.map +1 -0
  24. package/dist/lib/index.d.ts +3 -0
  25. package/dist/lib/index.d.ts.map +1 -1
  26. package/dist/lib/providers/openai.d.ts +2 -0
  27. package/dist/lib/providers/openai.d.ts.map +1 -1
  28. package/dist/lib/providers/thinker-labs.d.ts +1 -0
  29. package/dist/lib/providers/thinker-labs.d.ts.map +1 -1
  30. package/dist/lib/retry.d.ts +7 -0
  31. package/dist/lib/retry.d.ts.map +1 -0
  32. package/dist/lib/schemas.d.ts +87 -0
  33. package/dist/lib/schemas.d.ts.map +1 -0
  34. package/dist/mcp/index.d.ts.map +1 -1
  35. package/dist/mcp/index.js +4619 -199
  36. package/dist/server/index.d.ts +1 -1
  37. package/dist/server/index.d.ts.map +1 -1
  38. package/dist/server/index.js +4648 -9
  39. package/package.json +1 -1
package/dist/mcp/index.js CHANGED
@@ -23,9 +23,9 @@ import {
23
23
  CallToolRequestSchema,
24
24
  ListToolsRequestSchema
25
25
  } from "@modelcontextprotocol/sdk/types.js";
26
- import { readFileSync as readFileSync3, existsSync as existsSync2 } from "fs";
27
- import { resolve as resolve2 } from "path";
28
- import { homedir as homedir3 } from "os";
26
+ import { readFileSync as readFileSync4, existsSync as existsSync5 } from "fs";
27
+ import { resolve as resolve3 } from "path";
28
+ import { homedir as homedir7 } from "os";
29
29
 
30
30
  // node_modules/drizzle-orm/entity.js
31
31
  var entityKind = Symbol.for("drizzle:entityKind");
@@ -3664,10 +3664,48 @@ function drizzle(...params) {
3664
3664
  drizzle2.mock = mock;
3665
3665
  })(drizzle || (drizzle = {}));
3666
3666
 
3667
+ // node_modules/drizzle-orm/migrator.js
3668
+ import crypto from "crypto";
3669
+ import fs from "fs";
3670
+ function readMigrationFiles(config) {
3671
+ const migrationFolderTo = config.migrationsFolder;
3672
+ const migrationQueries = [];
3673
+ const journalPath = `${migrationFolderTo}/meta/_journal.json`;
3674
+ if (!fs.existsSync(journalPath)) {
3675
+ throw new Error(`Can't find meta/_journal.json file`);
3676
+ }
3677
+ const journalAsString = fs.readFileSync(`${migrationFolderTo}/meta/_journal.json`).toString();
3678
+ const journal = JSON.parse(journalAsString);
3679
+ for (const journalEntry of journal.entries) {
3680
+ const migrationPath = `${migrationFolderTo}/${journalEntry.tag}.sql`;
3681
+ try {
3682
+ const query = fs.readFileSync(`${migrationFolderTo}/${journalEntry.tag}.sql`).toString();
3683
+ const result = query.split("--> statement-breakpoint").map((it) => {
3684
+ return it;
3685
+ });
3686
+ migrationQueries.push({
3687
+ sql: result,
3688
+ bps: journalEntry.breakpoints,
3689
+ folderMillis: journalEntry.when,
3690
+ hash: crypto.createHash("sha256").update(query).digest("hex")
3691
+ });
3692
+ } catch {
3693
+ throw new Error(`No file ${migrationPath} found in ${migrationFolderTo} folder`);
3694
+ }
3695
+ }
3696
+ return migrationQueries;
3697
+ }
3698
+
3699
+ // node_modules/drizzle-orm/bun-sqlite/migrator.js
3700
+ function migrate(db, config) {
3701
+ const migrations = readMigrationFiles(config);
3702
+ db.dialect.migrate(migrations, db.session, config);
3703
+ }
3704
+
3667
3705
  // src/db/index.ts
3668
3706
  import { Database as Database2 } from "bun:sqlite";
3669
- import { mkdirSync } from "fs";
3670
- import { dirname, join } from "path";
3707
+ import { mkdirSync, existsSync, readdirSync, copyFileSync, statSync } from "fs";
3708
+ import { dirname, join, resolve } from "path";
3671
3709
  import { homedir } from "os";
3672
3710
 
3673
3711
  // src/db/schema.ts
@@ -3715,56 +3753,80 @@ var trainingDatasets = sqliteTable("training_datasets", {
3715
3753
  });
3716
3754
 
3717
3755
  // src/db/index.ts
3718
- var DEFAULT_DB_PATH = join(homedir(), ".brains", "brains.db");
3756
+ function resolveDefaultDbPath() {
3757
+ const home = process.env["HOME"] || process.env["USERPROFILE"] || homedir();
3758
+ const newDir = join(home, ".hasna", "brains");
3759
+ const oldDir = join(home, ".brains");
3760
+ if (existsSync(oldDir) && !existsSync(newDir)) {
3761
+ mkdirSync(newDir, { recursive: true });
3762
+ try {
3763
+ for (const file of readdirSync(oldDir)) {
3764
+ const oldPath = join(oldDir, file);
3765
+ const newPath = join(newDir, file);
3766
+ try {
3767
+ if (statSync(oldPath).isFile()) {
3768
+ copyFileSync(oldPath, newPath);
3769
+ }
3770
+ } catch {}
3771
+ }
3772
+ } catch {}
3773
+ }
3774
+ mkdirSync(newDir, { recursive: true });
3775
+ return join(newDir, "brains.db");
3776
+ }
3777
+ var DEFAULT_DB_PATH = resolveDefaultDbPath();
3719
3778
  function ensureDir(filePath) {
3720
3779
  mkdirSync(dirname(filePath), { recursive: true });
3721
3780
  }
3722
- function createTables(sqlite) {
3723
- sqlite.exec(`
3724
- CREATE TABLE IF NOT EXISTS fine_tuned_models (
3725
- id TEXT PRIMARY KEY,
3726
- base_model TEXT NOT NULL,
3727
- name TEXT NOT NULL,
3728
- provider TEXT NOT NULL,
3729
- status TEXT NOT NULL DEFAULT 'pending',
3730
- fine_tune_job_id TEXT,
3731
- display_name TEXT,
3732
- description TEXT,
3733
- collection TEXT,
3734
- tags TEXT,
3735
- created_at INTEGER NOT NULL,
3736
- updated_at INTEGER NOT NULL
3737
- );
3738
-
3739
- CREATE TABLE IF NOT EXISTS training_jobs (
3740
- id TEXT PRIMARY KEY,
3741
- model_id TEXT NOT NULL REFERENCES fine_tuned_models(id),
3742
- provider TEXT NOT NULL,
3743
- status TEXT NOT NULL,
3744
- started_at INTEGER NOT NULL,
3745
- finished_at INTEGER,
3746
- metrics TEXT,
3747
- error TEXT
3748
- );
3749
-
3750
- CREATE TABLE IF NOT EXISTS training_datasets (
3751
- id TEXT PRIMARY KEY,
3752
- source TEXT NOT NULL,
3753
- file_path TEXT NOT NULL,
3754
- example_count INTEGER NOT NULL,
3755
- created_at INTEGER NOT NULL,
3756
- used_in_job_id TEXT REFERENCES training_jobs(id)
3757
- );
3758
- `);
3759
- }
3760
3781
  function getDb(dbPath) {
3761
3782
  const resolvedPath = dbPath ?? DEFAULT_DB_PATH;
3762
3783
  ensureDir(resolvedPath);
3763
3784
  const sqlite = new Database2(resolvedPath);
3764
3785
  sqlite.run("PRAGMA journal_mode = WAL");
3765
3786
  sqlite.run("PRAGMA foreign_keys = ON");
3766
- createTables(sqlite);
3767
- return drizzle(sqlite, { schema: exports_schema });
3787
+ const db = drizzle(sqlite, { schema: exports_schema });
3788
+ try {
3789
+ const migrationsFolder = resolve(import.meta.dir, "../../drizzle");
3790
+ migrate(db, { migrationsFolder });
3791
+ } catch {
3792
+ sqlite.exec(`
3793
+ CREATE TABLE IF NOT EXISTS fine_tuned_models (
3794
+ id TEXT PRIMARY KEY,
3795
+ base_model TEXT NOT NULL,
3796
+ name TEXT NOT NULL,
3797
+ provider TEXT NOT NULL,
3798
+ status TEXT NOT NULL DEFAULT 'pending',
3799
+ fine_tune_job_id TEXT,
3800
+ display_name TEXT,
3801
+ description TEXT,
3802
+ collection TEXT,
3803
+ tags TEXT,
3804
+ created_at INTEGER NOT NULL,
3805
+ updated_at INTEGER NOT NULL
3806
+ );
3807
+
3808
+ CREATE TABLE IF NOT EXISTS training_jobs (
3809
+ id TEXT PRIMARY KEY,
3810
+ model_id TEXT NOT NULL REFERENCES fine_tuned_models(id),
3811
+ provider TEXT NOT NULL,
3812
+ status TEXT NOT NULL,
3813
+ started_at INTEGER NOT NULL,
3814
+ finished_at INTEGER,
3815
+ metrics TEXT,
3816
+ error TEXT
3817
+ );
3818
+
3819
+ CREATE TABLE IF NOT EXISTS training_datasets (
3820
+ id TEXT PRIMARY KEY,
3821
+ source TEXT NOT NULL,
3822
+ file_path TEXT NOT NULL,
3823
+ example_count INTEGER NOT NULL,
3824
+ created_at INTEGER NOT NULL,
3825
+ used_in_job_id TEXT REFERENCES training_jobs(id)
3826
+ );
3827
+ `);
3828
+ }
3829
+ return db;
3768
3830
  }
3769
3831
 
3770
3832
  // node_modules/openai/internal/qs/formats.mjs
@@ -4855,8 +4917,8 @@ function _addRequestID(value, response) {
4855
4917
 
4856
4918
  class APIPromise extends Promise {
4857
4919
  constructor(responsePromise, parseResponse = defaultParseResponse) {
4858
- super((resolve) => {
4859
- resolve(null);
4920
+ super((resolve2) => {
4921
+ resolve2(null);
4860
4922
  });
4861
4923
  this.responsePromise = responsePromise;
4862
4924
  this.parseResponse = parseResponse;
@@ -5367,7 +5429,7 @@ var startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
5367
5429
  var isAbsoluteURL = (url) => {
5368
5430
  return startsWithSchemeRegexp.test(url);
5369
5431
  };
5370
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
5432
+ var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
5371
5433
  var validatePositiveInteger = (name, n) => {
5372
5434
  if (typeof n !== "number" || !Number.isInteger(n)) {
5373
5435
  throw new OpenAIError(`${name} must be an integer`);
@@ -5732,12 +5794,12 @@ class EventStream {
5732
5794
  _EventStream_errored.set(this, false);
5733
5795
  _EventStream_aborted.set(this, false);
5734
5796
  _EventStream_catchingPromiseCreated.set(this, false);
5735
- __classPrivateFieldSet3(this, _EventStream_connectedPromise, new Promise((resolve, reject) => {
5736
- __classPrivateFieldSet3(this, _EventStream_resolveConnectedPromise, resolve, "f");
5797
+ __classPrivateFieldSet3(this, _EventStream_connectedPromise, new Promise((resolve2, reject) => {
5798
+ __classPrivateFieldSet3(this, _EventStream_resolveConnectedPromise, resolve2, "f");
5737
5799
  __classPrivateFieldSet3(this, _EventStream_rejectConnectedPromise, reject, "f");
5738
5800
  }), "f");
5739
- __classPrivateFieldSet3(this, _EventStream_endPromise, new Promise((resolve, reject) => {
5740
- __classPrivateFieldSet3(this, _EventStream_resolveEndPromise, resolve, "f");
5801
+ __classPrivateFieldSet3(this, _EventStream_endPromise, new Promise((resolve2, reject) => {
5802
+ __classPrivateFieldSet3(this, _EventStream_resolveEndPromise, resolve2, "f");
5741
5803
  __classPrivateFieldSet3(this, _EventStream_rejectEndPromise, reject, "f");
5742
5804
  }), "f");
5743
5805
  __classPrivateFieldGet3(this, _EventStream_connectedPromise, "f").catch(() => {});
@@ -5789,11 +5851,11 @@ class EventStream {
5789
5851
  return this;
5790
5852
  }
5791
5853
  emitted(event) {
5792
- return new Promise((resolve, reject) => {
5854
+ return new Promise((resolve2, reject) => {
5793
5855
  __classPrivateFieldSet3(this, _EventStream_catchingPromiseCreated, true, "f");
5794
5856
  if (event !== "error")
5795
5857
  this.once("error", reject);
5796
- this.once(event, resolve);
5858
+ this.once(event, resolve2);
5797
5859
  });
5798
5860
  }
5799
5861
  async done() {
@@ -5951,7 +6013,7 @@ class AssistantStream extends EventStream {
5951
6013
  if (done) {
5952
6014
  return { value: undefined, done: true };
5953
6015
  }
5954
- return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: undefined, done: true });
6016
+ return new Promise((resolve2, reject) => readQueue.push({ resolve: resolve2, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: undefined, done: true });
5955
6017
  }
5956
6018
  const chunk = pushQueue.shift();
5957
6019
  return { value: chunk, done: false };
@@ -7516,7 +7578,7 @@ class ChatCompletionStream extends AbstractChatCompletionRunner {
7516
7578
  if (done) {
7517
7579
  return { value: undefined, done: true };
7518
7580
  }
7519
- return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: undefined, done: true });
7581
+ return new Promise((resolve2, reject) => readQueue.push({ resolve: resolve2, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: undefined, done: true });
7520
7582
  }
7521
7583
  const chunk = pushQueue.shift();
7522
7584
  return { value: chunk, done: false };
@@ -8765,7 +8827,7 @@ class ResponseStream extends EventStream {
8765
8827
  if (done) {
8766
8828
  return { value: undefined, done: true };
8767
8829
  }
8768
- return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((event2) => event2 ? { value: event2, done: false } : { value: undefined, done: true });
8830
+ return new Promise((resolve2, reject) => readQueue.push({ resolve: resolve2, reject })).then((event2) => event2 ? { value: event2, done: false } : { value: undefined, done: true });
8769
8831
  }
8770
8832
  const event = pushQueue.shift();
8771
8833
  return { value: event, done: false };
@@ -9252,60 +9314,146 @@ var _deployments_endpoints = new Set([
9252
9314
  var openai_default = OpenAI;
9253
9315
 
9254
9316
  // src/lib/providers/openai.ts
9255
- import { readFileSync } from "fs";
9317
+ import { readFileSync as readFileSync2 } from "fs";
9318
+
9319
+ // src/lib/config.ts
9320
+ import { readFileSync, writeFileSync, mkdirSync as mkdirSync2, existsSync as existsSync2, readdirSync as readdirSync2, copyFileSync as copyFileSync2, statSync as statSync2 } from "fs";
9321
+ import { join as join2, dirname as dirname2 } from "path";
9322
+ import { homedir as homedir2 } from "os";
9323
+ function resolveConfigPath() {
9324
+ const home = process.env["HOME"] || process.env["USERPROFILE"] || homedir2();
9325
+ const newDir = join2(home, ".hasna", "brains");
9326
+ const oldDir = join2(home, ".brains");
9327
+ if (existsSync2(oldDir) && !existsSync2(newDir)) {
9328
+ mkdirSync2(newDir, { recursive: true });
9329
+ try {
9330
+ for (const file of readdirSync2(oldDir)) {
9331
+ const oldPath = join2(oldDir, file);
9332
+ const newPath = join2(newDir, file);
9333
+ try {
9334
+ if (statSync2(oldPath).isFile()) {
9335
+ copyFileSync2(oldPath, newPath);
9336
+ }
9337
+ } catch {}
9338
+ }
9339
+ } catch {}
9340
+ }
9341
+ mkdirSync2(newDir, { recursive: true });
9342
+ return join2(newDir, "config.json");
9343
+ }
9344
+ var CONFIG_PATH = resolveConfigPath();
9345
+ function readConfigFile() {
9346
+ if (!existsSync2(CONFIG_PATH))
9347
+ return {};
9348
+ try {
9349
+ return JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));
9350
+ } catch {
9351
+ return {};
9352
+ }
9353
+ }
9354
+ function getConfigValue(key) {
9355
+ if (process.env[key])
9356
+ return process.env[key];
9357
+ return readConfigFile()[key];
9358
+ }
9359
+
9360
+ // src/lib/retry.ts
9361
+ var RETRYABLE_STATUS_CODES = new Set([429, 500, 502, 503, 504]);
9362
+ function isRetryableError(err) {
9363
+ if (err instanceof Error) {
9364
+ if (err.message.includes("fetch failed") || err.message.includes("ECONNRESET") || err.message.includes("ETIMEDOUT")) {
9365
+ return true;
9366
+ }
9367
+ const match = err.message.match(/^(\d{3})\s/);
9368
+ if (match) {
9369
+ const status = parseInt(match[1], 10);
9370
+ return RETRYABLE_STATUS_CODES.has(status);
9371
+ }
9372
+ const tlMatch = err.message.match(/API error (\d{3})/);
9373
+ if (tlMatch) {
9374
+ const status = parseInt(tlMatch[1], 10);
9375
+ return RETRYABLE_STATUS_CODES.has(status);
9376
+ }
9377
+ }
9378
+ return false;
9379
+ }
9380
+ async function withRetry(fn, options = {}) {
9381
+ const { maxAttempts = 3, baseDelayMs = 1000, onRetry } = options;
9382
+ let lastError = new Error("Unknown error");
9383
+ for (let attempt = 1;attempt <= maxAttempts; attempt++) {
9384
+ try {
9385
+ return await fn();
9386
+ } catch (err) {
9387
+ lastError = err instanceof Error ? err : new Error(String(err));
9388
+ if (attempt === maxAttempts || !isRetryableError(lastError)) {
9389
+ throw lastError;
9390
+ }
9391
+ const delayMs = baseDelayMs * Math.pow(2, attempt - 1);
9392
+ onRetry?.(attempt, delayMs, lastError);
9393
+ await new Promise((resolve2) => setTimeout(resolve2, delayMs));
9394
+ }
9395
+ }
9396
+ throw lastError;
9397
+ }
9398
+
9399
+ // src/lib/providers/openai.ts
9256
9400
  function getClient() {
9257
- const apiKey = process.env.OPENAI_API_KEY;
9401
+ const apiKey = getConfigValue("OPENAI_API_KEY");
9258
9402
  if (!apiKey) {
9259
- throw new Error("OPENAI_API_KEY environment variable is required");
9403
+ throw new Error("OPENAI_API_KEY is not set. Run: brains config set OPENAI_API_KEY <key>");
9260
9404
  }
9261
9405
  return new openai_default({ apiKey });
9262
9406
  }
9263
9407
  async function uploadTrainingFile(filePath) {
9264
- const client = getClient();
9265
- const fileContent = readFileSync(filePath);
9266
- const blob2 = new Blob([fileContent], { type: "application/jsonl" });
9267
- const file = new File([blob2], filePath.split("/").pop() ?? "training.jsonl", { type: "application/jsonl" });
9268
- const response = await client.files.create({
9269
- file,
9270
- purpose: "fine-tune"
9408
+ return withRetry(async () => {
9409
+ const client = getClient();
9410
+ const fileContent = readFileSync2(filePath);
9411
+ const blob2 = new Blob([fileContent], { type: "application/jsonl" });
9412
+ const file = new File([blob2], filePath.split("/").pop() ?? "training.jsonl", { type: "application/jsonl" });
9413
+ const response = await client.files.create({ file, purpose: "fine-tune" });
9414
+ return { fileId: response.id };
9271
9415
  });
9272
- return { fileId: response.id };
9273
9416
  }
9274
9417
  async function createFineTuneJob(fileId, baseModel, suffix) {
9275
- const client = getClient();
9276
- const params = {
9277
- training_file: fileId,
9278
- model: baseModel
9279
- };
9280
- if (suffix) {
9281
- params.suffix = suffix;
9282
- }
9283
- const response = await client.fineTuning.jobs.create(params);
9284
- return { jobId: response.id, status: response.status };
9418
+ return withRetry(async () => {
9419
+ const client = getClient();
9420
+ const params = { training_file: fileId, model: baseModel };
9421
+ if (suffix)
9422
+ params.suffix = suffix;
9423
+ const response = await client.fineTuning.jobs.create(params);
9424
+ return { jobId: response.id, status: response.status };
9425
+ });
9285
9426
  }
9286
9427
  async function getFineTuneStatus(jobId) {
9287
- const client = getClient();
9288
- const response = await client.fineTuning.jobs.retrieve(jobId);
9289
- return {
9290
- jobId: response.id,
9291
- status: response.status,
9292
- fineTunedModel: response.fine_tuned_model ?? undefined,
9293
- error: response.error?.message ?? undefined
9294
- };
9428
+ return withRetry(async () => {
9429
+ const client = getClient();
9430
+ const response = await client.fineTuning.jobs.retrieve(jobId);
9431
+ return {
9432
+ jobId: response.id,
9433
+ status: response.status,
9434
+ fineTunedModel: response.fine_tuned_model ?? undefined,
9435
+ baseModel: response.model ?? undefined,
9436
+ error: response.error?.message ?? undefined
9437
+ };
9438
+ });
9295
9439
  }
9296
9440
  async function listFineTunedModels() {
9297
- const client = getClient();
9298
- const jobs = await client.fineTuning.jobs.list();
9299
- return jobs.data.map((job) => ({
9300
- id: job.id,
9301
- model: job.fine_tuned_model ?? job.model,
9302
- status: job.status,
9303
- created: job.created_at
9304
- }));
9441
+ return withRetry(async () => {
9442
+ const client = getClient();
9443
+ const jobs = await client.fineTuning.jobs.list();
9444
+ return jobs.data.map((job) => ({
9445
+ id: job.id,
9446
+ model: job.fine_tuned_model ?? job.model,
9447
+ status: job.status,
9448
+ created: job.created_at
9449
+ }));
9450
+ });
9305
9451
  }
9306
9452
  async function cancelFineTuneJob(jobId) {
9307
- const client = getClient();
9308
- await client.fineTuning.jobs.cancel(jobId);
9453
+ return withRetry(async () => {
9454
+ const client = getClient();
9455
+ await client.fineTuning.jobs.cancel(jobId);
9456
+ });
9309
9457
  }
9310
9458
 
9311
9459
  class OpenAIProvider {
@@ -9329,37 +9477,39 @@ class OpenAIProvider {
9329
9477
  // src/lib/providers/thinker-labs.ts
9330
9478
  var DEFAULT_BASE_URL = "https://api.thinkerlabs.ai/v1";
9331
9479
  function getConfig() {
9332
- const apiKey = process.env.THINKER_LABS_API_KEY;
9333
- const baseUrl = process.env.THINKER_LABS_BASE_URL ?? DEFAULT_BASE_URL;
9480
+ const apiKey = getConfigValue("THINKER_LABS_API_KEY");
9481
+ const baseUrl = getConfigValue("THINKER_LABS_BASE_URL") ?? DEFAULT_BASE_URL;
9334
9482
  if (!apiKey)
9335
- throw new Error("THINKER_LABS_API_KEY environment variable is required");
9483
+ throw new Error("THINKER_LABS_API_KEY is not set. Run: brains config set THINKER_LABS_API_KEY <key>");
9336
9484
  return { apiKey, baseUrl };
9337
9485
  }
9338
9486
  async function request(method, path, body, file) {
9339
- const { apiKey, baseUrl } = getConfig();
9340
- const headers = { Authorization: `Bearer ${apiKey}` };
9341
- let fetchBody;
9342
- if (file) {
9343
- const form = new FormData;
9344
- form.append("file", new Blob([file.data], { type: "text/plain" }), file.name);
9345
- if (body) {
9346
- for (const [k, v] of Object.entries(body)) {
9347
- form.append(k, v);
9348
- }
9349
- }
9350
- fetchBody = form;
9351
- } else if (body) {
9352
- headers["Content-Type"] = "application/json";
9353
- fetchBody = JSON.stringify(body);
9354
- }
9355
- const res = await fetch(`${baseUrl}${path}`, { method, headers, body: fetchBody });
9356
- if (!res.ok) {
9357
- const text2 = await res.text();
9358
- throw new Error(`Thinker Labs API error ${res.status}: ${text2}`);
9359
- }
9360
- if (res.status === 204)
9361
- return;
9362
- return res.json();
9487
+ return withRetry(async () => {
9488
+ const { apiKey, baseUrl } = getConfig();
9489
+ const headers = { Authorization: `Bearer ${apiKey}` };
9490
+ let fetchBody;
9491
+ if (file) {
9492
+ const form = new FormData;
9493
+ form.append("file", new Blob([file.data], { type: "text/plain" }), file.name);
9494
+ if (body) {
9495
+ for (const [k, v] of Object.entries(body)) {
9496
+ form.append(k, v);
9497
+ }
9498
+ }
9499
+ fetchBody = form;
9500
+ } else if (body) {
9501
+ headers["Content-Type"] = "application/json";
9502
+ fetchBody = JSON.stringify(body);
9503
+ }
9504
+ const res = await fetch(`${baseUrl}${path}`, { method, headers, body: fetchBody });
9505
+ if (!res.ok) {
9506
+ const text2 = await res.text();
9507
+ throw new Error(`Thinker Labs API error ${res.status}: ${text2}`);
9508
+ }
9509
+ if (res.status === 204)
9510
+ return;
9511
+ return res.json();
9512
+ });
9363
9513
  }
9364
9514
  async function uploadTrainingData(filePath) {
9365
9515
  const fileContent = await Bun.file(filePath).text();
@@ -9426,8 +9576,8 @@ class ThinkerLabsProvider {
9426
9576
 
9427
9577
  // src/lib/gatherers/todos.ts
9428
9578
  import { Database as Database3 } from "bun:sqlite";
9429
- import { homedir as homedir2 } from "os";
9430
- import { join as join2 } from "path";
9579
+ import { homedir as homedir3 } from "os";
9580
+ import { join as join3 } from "path";
9431
9581
  var SYSTEM_PROMPT = "You are a task management assistant that helps users create, update, search, and manage tasks and projects.";
9432
9582
  function taskToCreateExample(task) {
9433
9583
  const userMsg = `Create a task: ${task.title}${task.description ? `
@@ -9478,7 +9628,7 @@ ${matched.map((t) => `- [${t.short_id ?? t.id}] ${t.title} (${t.status})`).join(
9478
9628
  };
9479
9629
  }
9480
9630
  async function gatherFromTodos(options = {}) {
9481
- const dbPath = join2(homedir2(), ".todos", "todos.db");
9631
+ const dbPath = join3(homedir3(), ".todos", "todos.db");
9482
9632
  const db = new Database3(dbPath, { readonly: true, create: false });
9483
9633
  try {
9484
9634
  let query = "SELECT * FROM tasks WHERE 1=1";
@@ -9515,26 +9665,261 @@ async function gatherFromTodos(options = {}) {
9515
9665
  }
9516
9666
  }
9517
9667
 
9668
+ // src/lib/gatherers/mementos.ts
9669
+ import { Database as Database4 } from "bun:sqlite";
9670
+ import { homedir as homedir4 } from "os";
9671
+ import { join as join4 } from "path";
9672
+ var SYSTEM_PROMPT2 = "You are an AI assistant with persistent memory. You can remember and recall information across sessions to provide better, more personalized assistance.";
9673
+ function memoryToRecallExample(memory) {
9674
+ return {
9675
+ messages: [
9676
+ { role: "system", content: SYSTEM_PROMPT2 },
9677
+ { role: "user", content: `What do you remember about "${memory.key}"?` },
9678
+ {
9679
+ role: "assistant",
9680
+ content: memory.summary ? `${memory.value}
9681
+
9682
+ Summary: ${memory.summary}` : memory.value
9683
+ }
9684
+ ]
9685
+ };
9686
+ }
9687
+ function memoryToSaveExample(memory) {
9688
+ const tags = JSON.parse(memory.tags ?? "[]");
9689
+ return {
9690
+ messages: [
9691
+ { role: "system", content: SYSTEM_PROMPT2 },
9692
+ {
9693
+ role: "user",
9694
+ content: `Remember this for me: ${memory.key} = ${memory.value}${tags.length ? ` (tags: ${tags.join(", ")})` : ""}`
9695
+ },
9696
+ {
9697
+ role: "assistant",
9698
+ content: `Saved to memory: "${memory.key}" with ${memory.category} category, importance ${memory.importance}/10, scope: ${memory.scope}.`
9699
+ }
9700
+ ]
9701
+ };
9702
+ }
9703
+ function memoryToSearchExample(memories, category) {
9704
+ const matched = memories.filter((m) => m.category === category && m.status === "active").slice(0, 5);
9705
+ return {
9706
+ messages: [
9707
+ { role: "system", content: SYSTEM_PROMPT2 },
9708
+ { role: "user", content: `What ${category} memories do you have?` },
9709
+ {
9710
+ role: "assistant",
9711
+ content: matched.length > 0 ? `Here are my ${category} memories:
9712
+ ${matched.map((m) => `- ${m.key}: ${m.value.slice(0, 120)}${m.value.length > 120 ? "..." : ""}`).join(`
9713
+ `)}` : `I don't have any ${category} memories stored yet.`
9714
+ }
9715
+ ]
9716
+ };
9717
+ }
9718
+ async function gatherFromMementos(options = {}) {
9719
+ const dbPath = join4(homedir4(), ".mementos", "mementos.db");
9720
+ const db = new Database4(dbPath, { readonly: true, create: false });
9721
+ try {
9722
+ let query = "SELECT * FROM memories WHERE status = 'active'";
9723
+ const params = [];
9724
+ if (options.since) {
9725
+ query += " AND created_at >= ?";
9726
+ params.push(options.since.toISOString());
9727
+ }
9728
+ query += " ORDER BY importance DESC, created_at DESC";
9729
+ if (options.limit) {
9730
+ query += " LIMIT ?";
9731
+ params.push(options.limit * 3);
9732
+ }
9733
+ const memories = db.query(query).all(...params);
9734
+ const examples = [];
9735
+ for (const memory of memories) {
9736
+ examples.push(memoryToRecallExample(memory));
9737
+ examples.push(memoryToSaveExample(memory));
9738
+ }
9739
+ const categories = [...new Set(memories.map((m) => m.category))];
9740
+ for (const category of categories) {
9741
+ examples.push(memoryToSearchExample(memories, category));
9742
+ }
9743
+ const finalExamples = options.limit ? examples.slice(0, options.limit) : examples;
9744
+ return {
9745
+ source: "mementos",
9746
+ examples: finalExamples,
9747
+ count: finalExamples.length
9748
+ };
9749
+ } finally {
9750
+ db.close();
9751
+ }
9752
+ }
9753
+
9754
+ // src/lib/gatherers/conversations.ts
9755
+ import { Database as Database5 } from "bun:sqlite";
9756
+ import { homedir as homedir5 } from "os";
9757
+ import { join as join5 } from "path";
9758
+ var SYSTEM_PROMPT3 = "You are a helpful AI assistant participating in multi-agent conversations. You communicate clearly and collaboratively with other agents and users.";
9759
+ function windowToExample(window2) {
9760
+ if (window2.length < 2)
9761
+ return null;
9762
+ const messages = [
9763
+ { role: "system", content: SYSTEM_PROMPT3 }
9764
+ ];
9765
+ for (let i = 0;i < window2.length - 1; i++) {
9766
+ const msg = window2[i];
9767
+ if (!msg)
9768
+ continue;
9769
+ const role = i % 2 === 0 ? "user" : "assistant";
9770
+ messages.push({
9771
+ role,
9772
+ content: `[${msg.from_agent} \u2192 ${msg.to_agent ?? msg.space ?? "all"}]: ${msg.content}`
9773
+ });
9774
+ }
9775
+ const last = window2[window2.length - 1];
9776
+ if (!last)
9777
+ return null;
9778
+ messages.push({
9779
+ role: "assistant",
9780
+ content: `[${last.from_agent} \u2192 ${last.to_agent ?? last.space ?? "all"}]: ${last.content}`
9781
+ });
9782
+ return { messages };
9783
+ }
9784
+ async function gatherFromConversations(options = {}) {
9785
+ const dbPath = join5(homedir5(), ".conversations", "messages.db");
9786
+ const db = new Database5(dbPath, { readonly: true, create: false });
9787
+ try {
9788
+ let query = "SELECT * FROM messages WHERE 1=1";
9789
+ const params = [];
9790
+ if (options.since) {
9791
+ query += " AND created_at >= ?";
9792
+ params.push(options.since.toISOString());
9793
+ }
9794
+ query += " ORDER BY session_id, created_at ASC";
9795
+ const allMessages = db.query(query).all(...params);
9796
+ const sessions = new Map;
9797
+ for (const msg of allMessages) {
9798
+ const msgs = sessions.get(msg.session_id) ?? [];
9799
+ msgs.push(msg);
9800
+ sessions.set(msg.session_id, msgs);
9801
+ }
9802
+ const examples = [];
9803
+ const windowSize = 4;
9804
+ for (const [, sessionMsgs] of sessions) {
9805
+ if (sessionMsgs.length < 2)
9806
+ continue;
9807
+ for (let start = 0;start <= sessionMsgs.length - 2; start++) {
9808
+ const end = Math.min(start + windowSize, sessionMsgs.length);
9809
+ const window2 = sessionMsgs.slice(start, end);
9810
+ const example = windowToExample(window2);
9811
+ if (example)
9812
+ examples.push(example);
9813
+ }
9814
+ }
9815
+ const finalExamples = options.limit ? examples.slice(0, options.limit) : examples;
9816
+ return {
9817
+ source: "conversations",
9818
+ examples: finalExamples,
9819
+ count: finalExamples.length
9820
+ };
9821
+ } finally {
9822
+ db.close();
9823
+ }
9824
+ }
9825
+
9826
+ // src/lib/gatherers/sessions.ts
9827
+ import { readdir, readFile, stat } from "fs/promises";
9828
+ import { existsSync as existsSync3 } from "fs";
9829
+ import { join as join6 } from "path";
9830
+ import { homedir as homedir6 } from "os";
9831
+ var SYSTEM_PROMPT4 = "You are Claude Code, an AI assistant built by Anthropic that helps developers with coding, architecture, debugging, and software engineering tasks.";
9832
+ function extractText(content) {
9833
+ if (typeof content === "string")
9834
+ return content;
9835
+ return content.filter((c) => c.type === "text" && c.text).map((c) => c.text).join(`
9836
+ `).trim();
9837
+ }
9838
+ async function gatherFromSessions(options = {}) {
9839
+ const { limit: limit2 = 1000 } = options;
9840
+ const examples = [];
9841
+ const claudeDir = join6(homedir6(), ".claude", "projects");
9842
+ if (!existsSync3(claudeDir)) {
9843
+ return { source: "sessions", examples: [], count: 0 };
9844
+ }
9845
+ const projectDirs = await readdir(claudeDir).catch(() => []);
9846
+ for (const projectDir of projectDirs) {
9847
+ if (examples.length >= limit2)
9848
+ break;
9849
+ const projectPath = join6(claudeDir, projectDir);
9850
+ const files = await readdir(projectPath).catch(() => []);
9851
+ for (const file of files) {
9852
+ if (examples.length >= limit2)
9853
+ break;
9854
+ if (!file.endsWith(".jsonl"))
9855
+ continue;
9856
+ const filePath = join6(projectPath, file);
9857
+ if (options.since) {
9858
+ const fileStat = await stat(filePath).catch(() => null);
9859
+ if (fileStat && fileStat.mtime < options.since)
9860
+ continue;
9861
+ }
9862
+ const content = await readFile(filePath, "utf-8").catch(() => "");
9863
+ if (!content.trim())
9864
+ continue;
9865
+ const lines = content.trim().split(`
9866
+ `);
9867
+ const turns = [];
9868
+ for (const line of lines) {
9869
+ try {
9870
+ const entry = JSON.parse(line);
9871
+ if ((entry.type === "user" || entry.type === "human") && entry.message?.content) {
9872
+ const text2 = extractText(entry.message.content);
9873
+ if (text2.trim())
9874
+ turns.push({ role: "user", content: text2.trim() });
9875
+ } else if (entry.type === "assistant" && entry.message?.content) {
9876
+ const text2 = extractText(entry.message.content);
9877
+ if (text2.trim())
9878
+ turns.push({ role: "assistant", content: text2.trim() });
9879
+ }
9880
+ } catch {}
9881
+ }
9882
+ const windowSize = 6;
9883
+ for (let start = 0;start < turns.length - 1 && examples.length < limit2; start++) {
9884
+ const window2 = turns.slice(start, start + windowSize);
9885
+ if (!window2[0] || window2[0].role !== "user")
9886
+ continue;
9887
+ const lastAssistantIdx = window2.map((t) => t.role).lastIndexOf("assistant");
9888
+ if (lastAssistantIdx < 1)
9889
+ continue;
9890
+ const usedTurns = window2.slice(0, lastAssistantIdx + 1);
9891
+ examples.push({
9892
+ messages: [
9893
+ { role: "system", content: SYSTEM_PROMPT4 },
9894
+ ...usedTurns
9895
+ ]
9896
+ });
9897
+ }
9898
+ }
9899
+ }
9900
+ return { source: "sessions", examples, count: examples.length };
9901
+ }
9902
+
9518
9903
  // src/lib/package-metadata.ts
9519
- import { existsSync, readFileSync as readFileSync2 } from "fs";
9520
- import { dirname as dirname2, resolve } from "path";
9904
+ import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
9905
+ import { dirname as dirname3, resolve as resolve2 } from "path";
9521
9906
  import { fileURLToPath } from "url";
9522
9907
  var DEFAULT_VERSION = "0.0.0";
9523
9908
  var cachedVersion;
9524
9909
  function getPackageJsonPath() {
9525
- return resolve(dirname2(fileURLToPath(import.meta.url)), "../../package.json");
9910
+ return resolve2(dirname3(fileURLToPath(import.meta.url)), "../../package.json");
9526
9911
  }
9527
9912
  function getPackageVersion() {
9528
9913
  if (cachedVersion) {
9529
9914
  return cachedVersion;
9530
9915
  }
9531
9916
  const packageJsonPath = getPackageJsonPath();
9532
- if (!existsSync(packageJsonPath)) {
9917
+ if (!existsSync4(packageJsonPath)) {
9533
9918
  cachedVersion = DEFAULT_VERSION;
9534
9919
  return cachedVersion;
9535
9920
  }
9536
9921
  try {
9537
- const packageJson = JSON.parse(readFileSync2(packageJsonPath, "utf-8"));
9922
+ const packageJson = JSON.parse(readFileSync3(packageJsonPath, "utf-8"));
9538
9923
  cachedVersion = typeof packageJson.version === "string" ? packageJson.version : DEFAULT_VERSION;
9539
9924
  } catch {
9540
9925
  cachedVersion = DEFAULT_VERSION;
@@ -9542,51 +9927,4061 @@ function getPackageVersion() {
9542
9927
  return cachedVersion;
9543
9928
  }
9544
9929
 
9545
- // src/mcp/index.ts
9546
- function getProvider(provider) {
9547
- if (provider === "openai")
9548
- return new OpenAIProvider;
9549
- if (provider === "thinker-labs")
9550
- return new ThinkerLabsProvider;
9551
- throw new Error(`Unknown provider: ${provider}`);
9552
- }
9553
- function defaultOutputDir() {
9554
- return resolve2(homedir3(), ".brains", "datasets");
9555
- }
9556
- var MCP_SERVER_INFO = {
9557
- name: "brains",
9558
- version: getPackageVersion()
9930
+ // node_modules/zod/v3/external.js
9931
+ var exports_external = {};
9932
+ __export(exports_external, {
9933
+ void: () => voidType,
9934
+ util: () => util,
9935
+ unknown: () => unknownType,
9936
+ union: () => unionType,
9937
+ undefined: () => undefinedType,
9938
+ tuple: () => tupleType,
9939
+ transformer: () => effectsType,
9940
+ symbol: () => symbolType,
9941
+ string: () => stringType,
9942
+ strictObject: () => strictObjectType,
9943
+ setErrorMap: () => setErrorMap,
9944
+ set: () => setType,
9945
+ record: () => recordType,
9946
+ quotelessJson: () => quotelessJson,
9947
+ promise: () => promiseType,
9948
+ preprocess: () => preprocessType,
9949
+ pipeline: () => pipelineType,
9950
+ ostring: () => ostring,
9951
+ optional: () => optionalType,
9952
+ onumber: () => onumber,
9953
+ oboolean: () => oboolean,
9954
+ objectUtil: () => objectUtil,
9955
+ object: () => objectType,
9956
+ number: () => numberType,
9957
+ nullable: () => nullableType,
9958
+ null: () => nullType,
9959
+ never: () => neverType,
9960
+ nativeEnum: () => nativeEnumType,
9961
+ nan: () => nanType,
9962
+ map: () => mapType,
9963
+ makeIssue: () => makeIssue,
9964
+ literal: () => literalType,
9965
+ lazy: () => lazyType,
9966
+ late: () => late,
9967
+ isValid: () => isValid,
9968
+ isDirty: () => isDirty,
9969
+ isAsync: () => isAsync,
9970
+ isAborted: () => isAborted,
9971
+ intersection: () => intersectionType,
9972
+ instanceof: () => instanceOfType,
9973
+ getParsedType: () => getParsedType,
9974
+ getErrorMap: () => getErrorMap,
9975
+ function: () => functionType,
9976
+ enum: () => enumType,
9977
+ effect: () => effectsType,
9978
+ discriminatedUnion: () => discriminatedUnionType,
9979
+ defaultErrorMap: () => en_default,
9980
+ datetimeRegex: () => datetimeRegex,
9981
+ date: () => dateType,
9982
+ custom: () => custom,
9983
+ coerce: () => coerce,
9984
+ boolean: () => booleanType,
9985
+ bigint: () => bigIntType,
9986
+ array: () => arrayType,
9987
+ any: () => anyType,
9988
+ addIssueToContext: () => addIssueToContext,
9989
+ ZodVoid: () => ZodVoid,
9990
+ ZodUnknown: () => ZodUnknown,
9991
+ ZodUnion: () => ZodUnion,
9992
+ ZodUndefined: () => ZodUndefined,
9993
+ ZodType: () => ZodType,
9994
+ ZodTuple: () => ZodTuple,
9995
+ ZodTransformer: () => ZodEffects,
9996
+ ZodSymbol: () => ZodSymbol,
9997
+ ZodString: () => ZodString,
9998
+ ZodSet: () => ZodSet,
9999
+ ZodSchema: () => ZodType,
10000
+ ZodRecord: () => ZodRecord,
10001
+ ZodReadonly: () => ZodReadonly,
10002
+ ZodPromise: () => ZodPromise,
10003
+ ZodPipeline: () => ZodPipeline,
10004
+ ZodParsedType: () => ZodParsedType,
10005
+ ZodOptional: () => ZodOptional,
10006
+ ZodObject: () => ZodObject,
10007
+ ZodNumber: () => ZodNumber,
10008
+ ZodNullable: () => ZodNullable,
10009
+ ZodNull: () => ZodNull,
10010
+ ZodNever: () => ZodNever,
10011
+ ZodNativeEnum: () => ZodNativeEnum,
10012
+ ZodNaN: () => ZodNaN,
10013
+ ZodMap: () => ZodMap,
10014
+ ZodLiteral: () => ZodLiteral,
10015
+ ZodLazy: () => ZodLazy,
10016
+ ZodIssueCode: () => ZodIssueCode,
10017
+ ZodIntersection: () => ZodIntersection,
10018
+ ZodFunction: () => ZodFunction,
10019
+ ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
10020
+ ZodError: () => ZodError,
10021
+ ZodEnum: () => ZodEnum,
10022
+ ZodEffects: () => ZodEffects,
10023
+ ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
10024
+ ZodDefault: () => ZodDefault,
10025
+ ZodDate: () => ZodDate,
10026
+ ZodCatch: () => ZodCatch,
10027
+ ZodBranded: () => ZodBranded,
10028
+ ZodBoolean: () => ZodBoolean,
10029
+ ZodBigInt: () => ZodBigInt,
10030
+ ZodArray: () => ZodArray,
10031
+ ZodAny: () => ZodAny,
10032
+ Schema: () => ZodType,
10033
+ ParseStatus: () => ParseStatus,
10034
+ OK: () => OK,
10035
+ NEVER: () => NEVER,
10036
+ INVALID: () => INVALID,
10037
+ EMPTY_PATH: () => EMPTY_PATH,
10038
+ DIRTY: () => DIRTY,
10039
+ BRAND: () => BRAND
10040
+ });
10041
+
10042
+ // node_modules/zod/v3/helpers/util.js
10043
+ var util;
10044
+ (function(util2) {
10045
+ util2.assertEqual = (_) => {};
10046
+ function assertIs(_arg) {}
10047
+ util2.assertIs = assertIs;
10048
+ function assertNever3(_x) {
10049
+ throw new Error;
10050
+ }
10051
+ util2.assertNever = assertNever3;
10052
+ util2.arrayToEnum = (items) => {
10053
+ const obj = {};
10054
+ for (const item of items) {
10055
+ obj[item] = item;
10056
+ }
10057
+ return obj;
10058
+ };
10059
+ util2.getValidEnumValues = (obj) => {
10060
+ const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
10061
+ const filtered = {};
10062
+ for (const k of validKeys) {
10063
+ filtered[k] = obj[k];
10064
+ }
10065
+ return util2.objectValues(filtered);
10066
+ };
10067
+ util2.objectValues = (obj) => {
10068
+ return util2.objectKeys(obj).map(function(e) {
10069
+ return obj[e];
10070
+ });
10071
+ };
10072
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
10073
+ const keys = [];
10074
+ for (const key in object) {
10075
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
10076
+ keys.push(key);
10077
+ }
10078
+ }
10079
+ return keys;
10080
+ };
10081
+ util2.find = (arr, checker) => {
10082
+ for (const item of arr) {
10083
+ if (checker(item))
10084
+ return item;
10085
+ }
10086
+ return;
10087
+ };
10088
+ util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
10089
+ function joinValues(array, separator = " | ") {
10090
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
10091
+ }
10092
+ util2.joinValues = joinValues;
10093
+ util2.jsonStringifyReplacer = (_, value) => {
10094
+ if (typeof value === "bigint") {
10095
+ return value.toString();
10096
+ }
10097
+ return value;
10098
+ };
10099
+ })(util || (util = {}));
10100
+ var objectUtil;
10101
+ (function(objectUtil2) {
10102
+ objectUtil2.mergeShapes = (first, second) => {
10103
+ return {
10104
+ ...first,
10105
+ ...second
10106
+ };
10107
+ };
10108
+ })(objectUtil || (objectUtil = {}));
10109
+ var ZodParsedType = util.arrayToEnum([
10110
+ "string",
10111
+ "nan",
10112
+ "number",
10113
+ "integer",
10114
+ "float",
10115
+ "boolean",
10116
+ "date",
10117
+ "bigint",
10118
+ "symbol",
10119
+ "function",
10120
+ "undefined",
10121
+ "null",
10122
+ "array",
10123
+ "object",
10124
+ "unknown",
10125
+ "promise",
10126
+ "void",
10127
+ "never",
10128
+ "map",
10129
+ "set"
10130
+ ]);
10131
+ var getParsedType = (data) => {
10132
+ const t = typeof data;
10133
+ switch (t) {
10134
+ case "undefined":
10135
+ return ZodParsedType.undefined;
10136
+ case "string":
10137
+ return ZodParsedType.string;
10138
+ case "number":
10139
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
10140
+ case "boolean":
10141
+ return ZodParsedType.boolean;
10142
+ case "function":
10143
+ return ZodParsedType.function;
10144
+ case "bigint":
10145
+ return ZodParsedType.bigint;
10146
+ case "symbol":
10147
+ return ZodParsedType.symbol;
10148
+ case "object":
10149
+ if (Array.isArray(data)) {
10150
+ return ZodParsedType.array;
10151
+ }
10152
+ if (data === null) {
10153
+ return ZodParsedType.null;
10154
+ }
10155
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
10156
+ return ZodParsedType.promise;
10157
+ }
10158
+ if (typeof Map !== "undefined" && data instanceof Map) {
10159
+ return ZodParsedType.map;
10160
+ }
10161
+ if (typeof Set !== "undefined" && data instanceof Set) {
10162
+ return ZodParsedType.set;
10163
+ }
10164
+ if (typeof Date !== "undefined" && data instanceof Date) {
10165
+ return ZodParsedType.date;
10166
+ }
10167
+ return ZodParsedType.object;
10168
+ default:
10169
+ return ZodParsedType.unknown;
10170
+ }
9559
10171
  };
9560
- function createMcpServer() {
9561
- const server = new Server(MCP_SERVER_INFO, { capabilities: { tools: {} } });
9562
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
9563
- tools: [
9564
- {
9565
- name: "list_models",
9566
- description: "List all fine-tuned models tracked in the local DB",
9567
- inputSchema: {
9568
- type: "object",
9569
- properties: {},
9570
- required: []
9571
- }
9572
- },
9573
- {
9574
- name: "get_model",
9575
- description: "Get details for a specific fine-tuned model",
9576
- inputSchema: {
9577
- type: "object",
9578
- properties: {
9579
- model_id: { type: "string", description: "Model ID" }
9580
- },
9581
- required: ["model_id"]
10172
+
10173
+ // node_modules/zod/v3/ZodError.js
10174
+ var ZodIssueCode = util.arrayToEnum([
10175
+ "invalid_type",
10176
+ "invalid_literal",
10177
+ "custom",
10178
+ "invalid_union",
10179
+ "invalid_union_discriminator",
10180
+ "invalid_enum_value",
10181
+ "unrecognized_keys",
10182
+ "invalid_arguments",
10183
+ "invalid_return_type",
10184
+ "invalid_date",
10185
+ "invalid_string",
10186
+ "too_small",
10187
+ "too_big",
10188
+ "invalid_intersection_types",
10189
+ "not_multiple_of",
10190
+ "not_finite"
10191
+ ]);
10192
+ var quotelessJson = (obj) => {
10193
+ const json = JSON.stringify(obj, null, 2);
10194
+ return json.replace(/"([^"]+)":/g, "$1:");
10195
+ };
10196
+
10197
+ class ZodError extends Error {
10198
+ get errors() {
10199
+ return this.issues;
10200
+ }
10201
+ constructor(issues) {
10202
+ super();
10203
+ this.issues = [];
10204
+ this.addIssue = (sub) => {
10205
+ this.issues = [...this.issues, sub];
10206
+ };
10207
+ this.addIssues = (subs = []) => {
10208
+ this.issues = [...this.issues, ...subs];
10209
+ };
10210
+ const actualProto = new.target.prototype;
10211
+ if (Object.setPrototypeOf) {
10212
+ Object.setPrototypeOf(this, actualProto);
10213
+ } else {
10214
+ this.__proto__ = actualProto;
10215
+ }
10216
+ this.name = "ZodError";
10217
+ this.issues = issues;
10218
+ }
10219
+ format(_mapper) {
10220
+ const mapper = _mapper || function(issue) {
10221
+ return issue.message;
10222
+ };
10223
+ const fieldErrors = { _errors: [] };
10224
+ const processError = (error) => {
10225
+ for (const issue of error.issues) {
10226
+ if (issue.code === "invalid_union") {
10227
+ issue.unionErrors.map(processError);
10228
+ } else if (issue.code === "invalid_return_type") {
10229
+ processError(issue.returnTypeError);
10230
+ } else if (issue.code === "invalid_arguments") {
10231
+ processError(issue.argumentsError);
10232
+ } else if (issue.path.length === 0) {
10233
+ fieldErrors._errors.push(mapper(issue));
10234
+ } else {
10235
+ let curr = fieldErrors;
10236
+ let i = 0;
10237
+ while (i < issue.path.length) {
10238
+ const el = issue.path[i];
10239
+ const terminal = i === issue.path.length - 1;
10240
+ if (!terminal) {
10241
+ curr[el] = curr[el] || { _errors: [] };
10242
+ } else {
10243
+ curr[el] = curr[el] || { _errors: [] };
10244
+ curr[el]._errors.push(mapper(issue));
10245
+ }
10246
+ curr = curr[el];
10247
+ i++;
10248
+ }
9582
10249
  }
9583
- },
9584
- {
9585
- name: "start_finetune",
9586
- description: "Upload a training file and start a fine-tuning job",
9587
- inputSchema: {
9588
- type: "object",
9589
- properties: {
10250
+ }
10251
+ };
10252
+ processError(this);
10253
+ return fieldErrors;
10254
+ }
10255
+ static assert(value) {
10256
+ if (!(value instanceof ZodError)) {
10257
+ throw new Error(`Not a ZodError: ${value}`);
10258
+ }
10259
+ }
10260
+ toString() {
10261
+ return this.message;
10262
+ }
10263
+ get message() {
10264
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
10265
+ }
10266
+ get isEmpty() {
10267
+ return this.issues.length === 0;
10268
+ }
10269
+ flatten(mapper = (issue) => issue.message) {
10270
+ const fieldErrors = {};
10271
+ const formErrors = [];
10272
+ for (const sub of this.issues) {
10273
+ if (sub.path.length > 0) {
10274
+ const firstEl = sub.path[0];
10275
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
10276
+ fieldErrors[firstEl].push(mapper(sub));
10277
+ } else {
10278
+ formErrors.push(mapper(sub));
10279
+ }
10280
+ }
10281
+ return { formErrors, fieldErrors };
10282
+ }
10283
+ get formErrors() {
10284
+ return this.flatten();
10285
+ }
10286
+ }
10287
+ ZodError.create = (issues) => {
10288
+ const error = new ZodError(issues);
10289
+ return error;
10290
+ };
10291
+
10292
+ // node_modules/zod/v3/locales/en.js
10293
+ var errorMap = (issue, _ctx) => {
10294
+ let message;
10295
+ switch (issue.code) {
10296
+ case ZodIssueCode.invalid_type:
10297
+ if (issue.received === ZodParsedType.undefined) {
10298
+ message = "Required";
10299
+ } else {
10300
+ message = `Expected ${issue.expected}, received ${issue.received}`;
10301
+ }
10302
+ break;
10303
+ case ZodIssueCode.invalid_literal:
10304
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
10305
+ break;
10306
+ case ZodIssueCode.unrecognized_keys:
10307
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
10308
+ break;
10309
+ case ZodIssueCode.invalid_union:
10310
+ message = `Invalid input`;
10311
+ break;
10312
+ case ZodIssueCode.invalid_union_discriminator:
10313
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
10314
+ break;
10315
+ case ZodIssueCode.invalid_enum_value:
10316
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
10317
+ break;
10318
+ case ZodIssueCode.invalid_arguments:
10319
+ message = `Invalid function arguments`;
10320
+ break;
10321
+ case ZodIssueCode.invalid_return_type:
10322
+ message = `Invalid function return type`;
10323
+ break;
10324
+ case ZodIssueCode.invalid_date:
10325
+ message = `Invalid date`;
10326
+ break;
10327
+ case ZodIssueCode.invalid_string:
10328
+ if (typeof issue.validation === "object") {
10329
+ if ("includes" in issue.validation) {
10330
+ message = `Invalid input: must include "${issue.validation.includes}"`;
10331
+ if (typeof issue.validation.position === "number") {
10332
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
10333
+ }
10334
+ } else if ("startsWith" in issue.validation) {
10335
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
10336
+ } else if ("endsWith" in issue.validation) {
10337
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
10338
+ } else {
10339
+ util.assertNever(issue.validation);
10340
+ }
10341
+ } else if (issue.validation !== "regex") {
10342
+ message = `Invalid ${issue.validation}`;
10343
+ } else {
10344
+ message = "Invalid";
10345
+ }
10346
+ break;
10347
+ case ZodIssueCode.too_small:
10348
+ if (issue.type === "array")
10349
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
10350
+ else if (issue.type === "string")
10351
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
10352
+ else if (issue.type === "number")
10353
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
10354
+ else if (issue.type === "bigint")
10355
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
10356
+ else if (issue.type === "date")
10357
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
10358
+ else
10359
+ message = "Invalid input";
10360
+ break;
10361
+ case ZodIssueCode.too_big:
10362
+ if (issue.type === "array")
10363
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
10364
+ else if (issue.type === "string")
10365
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
10366
+ else if (issue.type === "number")
10367
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
10368
+ else if (issue.type === "bigint")
10369
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
10370
+ else if (issue.type === "date")
10371
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
10372
+ else
10373
+ message = "Invalid input";
10374
+ break;
10375
+ case ZodIssueCode.custom:
10376
+ message = `Invalid input`;
10377
+ break;
10378
+ case ZodIssueCode.invalid_intersection_types:
10379
+ message = `Intersection results could not be merged`;
10380
+ break;
10381
+ case ZodIssueCode.not_multiple_of:
10382
+ message = `Number must be a multiple of ${issue.multipleOf}`;
10383
+ break;
10384
+ case ZodIssueCode.not_finite:
10385
+ message = "Number must be finite";
10386
+ break;
10387
+ default:
10388
+ message = _ctx.defaultError;
10389
+ util.assertNever(issue);
10390
+ }
10391
+ return { message };
10392
+ };
10393
+ var en_default = errorMap;
10394
+
10395
+ // node_modules/zod/v3/errors.js
10396
+ var overrideErrorMap = en_default;
10397
+ function setErrorMap(map) {
10398
+ overrideErrorMap = map;
10399
+ }
10400
+ function getErrorMap() {
10401
+ return overrideErrorMap;
10402
+ }
10403
+ // node_modules/zod/v3/helpers/parseUtil.js
10404
+ var makeIssue = (params) => {
10405
+ const { data, path, errorMaps, issueData } = params;
10406
+ const fullPath = [...path, ...issueData.path || []];
10407
+ const fullIssue = {
10408
+ ...issueData,
10409
+ path: fullPath
10410
+ };
10411
+ if (issueData.message !== undefined) {
10412
+ return {
10413
+ ...issueData,
10414
+ path: fullPath,
10415
+ message: issueData.message
10416
+ };
10417
+ }
10418
+ let errorMessage = "";
10419
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
10420
+ for (const map of maps) {
10421
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
10422
+ }
10423
+ return {
10424
+ ...issueData,
10425
+ path: fullPath,
10426
+ message: errorMessage
10427
+ };
10428
+ };
10429
+ var EMPTY_PATH = [];
10430
+ function addIssueToContext(ctx, issueData) {
10431
+ const overrideMap = getErrorMap();
10432
+ const issue = makeIssue({
10433
+ issueData,
10434
+ data: ctx.data,
10435
+ path: ctx.path,
10436
+ errorMaps: [
10437
+ ctx.common.contextualErrorMap,
10438
+ ctx.schemaErrorMap,
10439
+ overrideMap,
10440
+ overrideMap === en_default ? undefined : en_default
10441
+ ].filter((x) => !!x)
10442
+ });
10443
+ ctx.common.issues.push(issue);
10444
+ }
10445
+
10446
+ class ParseStatus {
10447
+ constructor() {
10448
+ this.value = "valid";
10449
+ }
10450
+ dirty() {
10451
+ if (this.value === "valid")
10452
+ this.value = "dirty";
10453
+ }
10454
+ abort() {
10455
+ if (this.value !== "aborted")
10456
+ this.value = "aborted";
10457
+ }
10458
+ static mergeArray(status, results) {
10459
+ const arrayValue = [];
10460
+ for (const s of results) {
10461
+ if (s.status === "aborted")
10462
+ return INVALID;
10463
+ if (s.status === "dirty")
10464
+ status.dirty();
10465
+ arrayValue.push(s.value);
10466
+ }
10467
+ return { status: status.value, value: arrayValue };
10468
+ }
10469
+ static async mergeObjectAsync(status, pairs) {
10470
+ const syncPairs = [];
10471
+ for (const pair of pairs) {
10472
+ const key = await pair.key;
10473
+ const value = await pair.value;
10474
+ syncPairs.push({
10475
+ key,
10476
+ value
10477
+ });
10478
+ }
10479
+ return ParseStatus.mergeObjectSync(status, syncPairs);
10480
+ }
10481
+ static mergeObjectSync(status, pairs) {
10482
+ const finalObject = {};
10483
+ for (const pair of pairs) {
10484
+ const { key, value } = pair;
10485
+ if (key.status === "aborted")
10486
+ return INVALID;
10487
+ if (value.status === "aborted")
10488
+ return INVALID;
10489
+ if (key.status === "dirty")
10490
+ status.dirty();
10491
+ if (value.status === "dirty")
10492
+ status.dirty();
10493
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
10494
+ finalObject[key.value] = value.value;
10495
+ }
10496
+ }
10497
+ return { status: status.value, value: finalObject };
10498
+ }
10499
+ }
10500
+ var INVALID = Object.freeze({
10501
+ status: "aborted"
10502
+ });
10503
+ var DIRTY = (value) => ({ status: "dirty", value });
10504
+ var OK = (value) => ({ status: "valid", value });
10505
+ var isAborted = (x) => x.status === "aborted";
10506
+ var isDirty = (x) => x.status === "dirty";
10507
+ var isValid = (x) => x.status === "valid";
10508
+ var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
10509
+ // node_modules/zod/v3/helpers/errorUtil.js
10510
+ var errorUtil;
10511
+ (function(errorUtil2) {
10512
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
10513
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
10514
+ })(errorUtil || (errorUtil = {}));
10515
+
10516
+ // node_modules/zod/v3/types.js
10517
+ class ParseInputLazyPath {
10518
+ constructor(parent, value, path, key) {
10519
+ this._cachedPath = [];
10520
+ this.parent = parent;
10521
+ this.data = value;
10522
+ this._path = path;
10523
+ this._key = key;
10524
+ }
10525
+ get path() {
10526
+ if (!this._cachedPath.length) {
10527
+ if (Array.isArray(this._key)) {
10528
+ this._cachedPath.push(...this._path, ...this._key);
10529
+ } else {
10530
+ this._cachedPath.push(...this._path, this._key);
10531
+ }
10532
+ }
10533
+ return this._cachedPath;
10534
+ }
10535
+ }
10536
+ var handleResult = (ctx, result) => {
10537
+ if (isValid(result)) {
10538
+ return { success: true, data: result.value };
10539
+ } else {
10540
+ if (!ctx.common.issues.length) {
10541
+ throw new Error("Validation failed but no issues detected.");
10542
+ }
10543
+ return {
10544
+ success: false,
10545
+ get error() {
10546
+ if (this._error)
10547
+ return this._error;
10548
+ const error = new ZodError(ctx.common.issues);
10549
+ this._error = error;
10550
+ return this._error;
10551
+ }
10552
+ };
10553
+ }
10554
+ };
10555
+ function processCreateParams(params) {
10556
+ if (!params)
10557
+ return {};
10558
+ const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
10559
+ if (errorMap2 && (invalid_type_error || required_error)) {
10560
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
10561
+ }
10562
+ if (errorMap2)
10563
+ return { errorMap: errorMap2, description };
10564
+ const customMap = (iss, ctx) => {
10565
+ const { message } = params;
10566
+ if (iss.code === "invalid_enum_value") {
10567
+ return { message: message ?? ctx.defaultError };
10568
+ }
10569
+ if (typeof ctx.data === "undefined") {
10570
+ return { message: message ?? required_error ?? ctx.defaultError };
10571
+ }
10572
+ if (iss.code !== "invalid_type")
10573
+ return { message: ctx.defaultError };
10574
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
10575
+ };
10576
+ return { errorMap: customMap, description };
10577
+ }
10578
+
10579
+ class ZodType {
10580
+ get description() {
10581
+ return this._def.description;
10582
+ }
10583
+ _getType(input) {
10584
+ return getParsedType(input.data);
10585
+ }
10586
+ _getOrReturnCtx(input, ctx) {
10587
+ return ctx || {
10588
+ common: input.parent.common,
10589
+ data: input.data,
10590
+ parsedType: getParsedType(input.data),
10591
+ schemaErrorMap: this._def.errorMap,
10592
+ path: input.path,
10593
+ parent: input.parent
10594
+ };
10595
+ }
10596
+ _processInputParams(input) {
10597
+ return {
10598
+ status: new ParseStatus,
10599
+ ctx: {
10600
+ common: input.parent.common,
10601
+ data: input.data,
10602
+ parsedType: getParsedType(input.data),
10603
+ schemaErrorMap: this._def.errorMap,
10604
+ path: input.path,
10605
+ parent: input.parent
10606
+ }
10607
+ };
10608
+ }
10609
+ _parseSync(input) {
10610
+ const result = this._parse(input);
10611
+ if (isAsync(result)) {
10612
+ throw new Error("Synchronous parse encountered promise.");
10613
+ }
10614
+ return result;
10615
+ }
10616
+ _parseAsync(input) {
10617
+ const result = this._parse(input);
10618
+ return Promise.resolve(result);
10619
+ }
10620
+ parse(data, params) {
10621
+ const result = this.safeParse(data, params);
10622
+ if (result.success)
10623
+ return result.data;
10624
+ throw result.error;
10625
+ }
10626
+ safeParse(data, params) {
10627
+ const ctx = {
10628
+ common: {
10629
+ issues: [],
10630
+ async: params?.async ?? false,
10631
+ contextualErrorMap: params?.errorMap
10632
+ },
10633
+ path: params?.path || [],
10634
+ schemaErrorMap: this._def.errorMap,
10635
+ parent: null,
10636
+ data,
10637
+ parsedType: getParsedType(data)
10638
+ };
10639
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
10640
+ return handleResult(ctx, result);
10641
+ }
10642
+ "~validate"(data) {
10643
+ const ctx = {
10644
+ common: {
10645
+ issues: [],
10646
+ async: !!this["~standard"].async
10647
+ },
10648
+ path: [],
10649
+ schemaErrorMap: this._def.errorMap,
10650
+ parent: null,
10651
+ data,
10652
+ parsedType: getParsedType(data)
10653
+ };
10654
+ if (!this["~standard"].async) {
10655
+ try {
10656
+ const result = this._parseSync({ data, path: [], parent: ctx });
10657
+ return isValid(result) ? {
10658
+ value: result.value
10659
+ } : {
10660
+ issues: ctx.common.issues
10661
+ };
10662
+ } catch (err) {
10663
+ if (err?.message?.toLowerCase()?.includes("encountered")) {
10664
+ this["~standard"].async = true;
10665
+ }
10666
+ ctx.common = {
10667
+ issues: [],
10668
+ async: true
10669
+ };
10670
+ }
10671
+ }
10672
+ return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
10673
+ value: result.value
10674
+ } : {
10675
+ issues: ctx.common.issues
10676
+ });
10677
+ }
10678
+ async parseAsync(data, params) {
10679
+ const result = await this.safeParseAsync(data, params);
10680
+ if (result.success)
10681
+ return result.data;
10682
+ throw result.error;
10683
+ }
10684
+ async safeParseAsync(data, params) {
10685
+ const ctx = {
10686
+ common: {
10687
+ issues: [],
10688
+ contextualErrorMap: params?.errorMap,
10689
+ async: true
10690
+ },
10691
+ path: params?.path || [],
10692
+ schemaErrorMap: this._def.errorMap,
10693
+ parent: null,
10694
+ data,
10695
+ parsedType: getParsedType(data)
10696
+ };
10697
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
10698
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
10699
+ return handleResult(ctx, result);
10700
+ }
10701
+ refine(check, message) {
10702
+ const getIssueProperties = (val) => {
10703
+ if (typeof message === "string" || typeof message === "undefined") {
10704
+ return { message };
10705
+ } else if (typeof message === "function") {
10706
+ return message(val);
10707
+ } else {
10708
+ return message;
10709
+ }
10710
+ };
10711
+ return this._refinement((val, ctx) => {
10712
+ const result = check(val);
10713
+ const setError = () => ctx.addIssue({
10714
+ code: ZodIssueCode.custom,
10715
+ ...getIssueProperties(val)
10716
+ });
10717
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
10718
+ return result.then((data) => {
10719
+ if (!data) {
10720
+ setError();
10721
+ return false;
10722
+ } else {
10723
+ return true;
10724
+ }
10725
+ });
10726
+ }
10727
+ if (!result) {
10728
+ setError();
10729
+ return false;
10730
+ } else {
10731
+ return true;
10732
+ }
10733
+ });
10734
+ }
10735
+ refinement(check, refinementData) {
10736
+ return this._refinement((val, ctx) => {
10737
+ if (!check(val)) {
10738
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
10739
+ return false;
10740
+ } else {
10741
+ return true;
10742
+ }
10743
+ });
10744
+ }
10745
+ _refinement(refinement) {
10746
+ return new ZodEffects({
10747
+ schema: this,
10748
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
10749
+ effect: { type: "refinement", refinement }
10750
+ });
10751
+ }
10752
+ superRefine(refinement) {
10753
+ return this._refinement(refinement);
10754
+ }
10755
+ constructor(def) {
10756
+ this.spa = this.safeParseAsync;
10757
+ this._def = def;
10758
+ this.parse = this.parse.bind(this);
10759
+ this.safeParse = this.safeParse.bind(this);
10760
+ this.parseAsync = this.parseAsync.bind(this);
10761
+ this.safeParseAsync = this.safeParseAsync.bind(this);
10762
+ this.spa = this.spa.bind(this);
10763
+ this.refine = this.refine.bind(this);
10764
+ this.refinement = this.refinement.bind(this);
10765
+ this.superRefine = this.superRefine.bind(this);
10766
+ this.optional = this.optional.bind(this);
10767
+ this.nullable = this.nullable.bind(this);
10768
+ this.nullish = this.nullish.bind(this);
10769
+ this.array = this.array.bind(this);
10770
+ this.promise = this.promise.bind(this);
10771
+ this.or = this.or.bind(this);
10772
+ this.and = this.and.bind(this);
10773
+ this.transform = this.transform.bind(this);
10774
+ this.brand = this.brand.bind(this);
10775
+ this.default = this.default.bind(this);
10776
+ this.catch = this.catch.bind(this);
10777
+ this.describe = this.describe.bind(this);
10778
+ this.pipe = this.pipe.bind(this);
10779
+ this.readonly = this.readonly.bind(this);
10780
+ this.isNullable = this.isNullable.bind(this);
10781
+ this.isOptional = this.isOptional.bind(this);
10782
+ this["~standard"] = {
10783
+ version: 1,
10784
+ vendor: "zod",
10785
+ validate: (data) => this["~validate"](data)
10786
+ };
10787
+ }
10788
+ optional() {
10789
+ return ZodOptional.create(this, this._def);
10790
+ }
10791
+ nullable() {
10792
+ return ZodNullable.create(this, this._def);
10793
+ }
10794
+ nullish() {
10795
+ return this.nullable().optional();
10796
+ }
10797
+ array() {
10798
+ return ZodArray.create(this);
10799
+ }
10800
+ promise() {
10801
+ return ZodPromise.create(this, this._def);
10802
+ }
10803
+ or(option) {
10804
+ return ZodUnion.create([this, option], this._def);
10805
+ }
10806
+ and(incoming) {
10807
+ return ZodIntersection.create(this, incoming, this._def);
10808
+ }
10809
+ transform(transform) {
10810
+ return new ZodEffects({
10811
+ ...processCreateParams(this._def),
10812
+ schema: this,
10813
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
10814
+ effect: { type: "transform", transform }
10815
+ });
10816
+ }
10817
+ default(def) {
10818
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
10819
+ return new ZodDefault({
10820
+ ...processCreateParams(this._def),
10821
+ innerType: this,
10822
+ defaultValue: defaultValueFunc,
10823
+ typeName: ZodFirstPartyTypeKind.ZodDefault
10824
+ });
10825
+ }
10826
+ brand() {
10827
+ return new ZodBranded({
10828
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
10829
+ type: this,
10830
+ ...processCreateParams(this._def)
10831
+ });
10832
+ }
10833
+ catch(def) {
10834
+ const catchValueFunc = typeof def === "function" ? def : () => def;
10835
+ return new ZodCatch({
10836
+ ...processCreateParams(this._def),
10837
+ innerType: this,
10838
+ catchValue: catchValueFunc,
10839
+ typeName: ZodFirstPartyTypeKind.ZodCatch
10840
+ });
10841
+ }
10842
+ describe(description) {
10843
+ const This = this.constructor;
10844
+ return new This({
10845
+ ...this._def,
10846
+ description
10847
+ });
10848
+ }
10849
+ pipe(target) {
10850
+ return ZodPipeline.create(this, target);
10851
+ }
10852
+ readonly() {
10853
+ return ZodReadonly.create(this);
10854
+ }
10855
+ isOptional() {
10856
+ return this.safeParse(undefined).success;
10857
+ }
10858
+ isNullable() {
10859
+ return this.safeParse(null).success;
10860
+ }
10861
+ }
10862
+ var cuidRegex = /^c[^\s-]{8,}$/i;
10863
+ var cuid2Regex = /^[0-9a-z]+$/;
10864
+ var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
10865
+ var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
10866
+ var nanoidRegex = /^[a-z0-9_-]{21}$/i;
10867
+ var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
10868
+ var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
10869
+ var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
10870
+ var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
10871
+ var emojiRegex;
10872
+ var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
10873
+ var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
10874
+ var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
10875
+ var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
10876
+ var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
10877
+ var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
10878
+ var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
10879
+ var dateRegex = new RegExp(`^${dateRegexSource}$`);
10880
+ function timeRegexSource(args) {
10881
+ let secondsRegexSource = `[0-5]\\d`;
10882
+ if (args.precision) {
10883
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
10884
+ } else if (args.precision == null) {
10885
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
10886
+ }
10887
+ const secondsQuantifier = args.precision ? "+" : "?";
10888
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
10889
+ }
10890
+ function timeRegex(args) {
10891
+ return new RegExp(`^${timeRegexSource(args)}$`);
10892
+ }
10893
+ function datetimeRegex(args) {
10894
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
10895
+ const opts = [];
10896
+ opts.push(args.local ? `Z?` : `Z`);
10897
+ if (args.offset)
10898
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
10899
+ regex = `${regex}(${opts.join("|")})`;
10900
+ return new RegExp(`^${regex}$`);
10901
+ }
10902
+ function isValidIP(ip, version2) {
10903
+ if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) {
10904
+ return true;
10905
+ }
10906
+ if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) {
10907
+ return true;
10908
+ }
10909
+ return false;
10910
+ }
10911
+ function isValidJWT(jwt, alg) {
10912
+ if (!jwtRegex.test(jwt))
10913
+ return false;
10914
+ try {
10915
+ const [header] = jwt.split(".");
10916
+ if (!header)
10917
+ return false;
10918
+ const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
10919
+ const decoded = JSON.parse(atob(base64));
10920
+ if (typeof decoded !== "object" || decoded === null)
10921
+ return false;
10922
+ if ("typ" in decoded && decoded?.typ !== "JWT")
10923
+ return false;
10924
+ if (!decoded.alg)
10925
+ return false;
10926
+ if (alg && decoded.alg !== alg)
10927
+ return false;
10928
+ return true;
10929
+ } catch {
10930
+ return false;
10931
+ }
10932
+ }
10933
+ function isValidCidr(ip, version2) {
10934
+ if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) {
10935
+ return true;
10936
+ }
10937
+ if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) {
10938
+ return true;
10939
+ }
10940
+ return false;
10941
+ }
10942
+
10943
+ class ZodString extends ZodType {
10944
+ _parse(input) {
10945
+ if (this._def.coerce) {
10946
+ input.data = String(input.data);
10947
+ }
10948
+ const parsedType = this._getType(input);
10949
+ if (parsedType !== ZodParsedType.string) {
10950
+ const ctx2 = this._getOrReturnCtx(input);
10951
+ addIssueToContext(ctx2, {
10952
+ code: ZodIssueCode.invalid_type,
10953
+ expected: ZodParsedType.string,
10954
+ received: ctx2.parsedType
10955
+ });
10956
+ return INVALID;
10957
+ }
10958
+ const status = new ParseStatus;
10959
+ let ctx = undefined;
10960
+ for (const check of this._def.checks) {
10961
+ if (check.kind === "min") {
10962
+ if (input.data.length < check.value) {
10963
+ ctx = this._getOrReturnCtx(input, ctx);
10964
+ addIssueToContext(ctx, {
10965
+ code: ZodIssueCode.too_small,
10966
+ minimum: check.value,
10967
+ type: "string",
10968
+ inclusive: true,
10969
+ exact: false,
10970
+ message: check.message
10971
+ });
10972
+ status.dirty();
10973
+ }
10974
+ } else if (check.kind === "max") {
10975
+ if (input.data.length > check.value) {
10976
+ ctx = this._getOrReturnCtx(input, ctx);
10977
+ addIssueToContext(ctx, {
10978
+ code: ZodIssueCode.too_big,
10979
+ maximum: check.value,
10980
+ type: "string",
10981
+ inclusive: true,
10982
+ exact: false,
10983
+ message: check.message
10984
+ });
10985
+ status.dirty();
10986
+ }
10987
+ } else if (check.kind === "length") {
10988
+ const tooBig = input.data.length > check.value;
10989
+ const tooSmall = input.data.length < check.value;
10990
+ if (tooBig || tooSmall) {
10991
+ ctx = this._getOrReturnCtx(input, ctx);
10992
+ if (tooBig) {
10993
+ addIssueToContext(ctx, {
10994
+ code: ZodIssueCode.too_big,
10995
+ maximum: check.value,
10996
+ type: "string",
10997
+ inclusive: true,
10998
+ exact: true,
10999
+ message: check.message
11000
+ });
11001
+ } else if (tooSmall) {
11002
+ addIssueToContext(ctx, {
11003
+ code: ZodIssueCode.too_small,
11004
+ minimum: check.value,
11005
+ type: "string",
11006
+ inclusive: true,
11007
+ exact: true,
11008
+ message: check.message
11009
+ });
11010
+ }
11011
+ status.dirty();
11012
+ }
11013
+ } else if (check.kind === "email") {
11014
+ if (!emailRegex.test(input.data)) {
11015
+ ctx = this._getOrReturnCtx(input, ctx);
11016
+ addIssueToContext(ctx, {
11017
+ validation: "email",
11018
+ code: ZodIssueCode.invalid_string,
11019
+ message: check.message
11020
+ });
11021
+ status.dirty();
11022
+ }
11023
+ } else if (check.kind === "emoji") {
11024
+ if (!emojiRegex) {
11025
+ emojiRegex = new RegExp(_emojiRegex, "u");
11026
+ }
11027
+ if (!emojiRegex.test(input.data)) {
11028
+ ctx = this._getOrReturnCtx(input, ctx);
11029
+ addIssueToContext(ctx, {
11030
+ validation: "emoji",
11031
+ code: ZodIssueCode.invalid_string,
11032
+ message: check.message
11033
+ });
11034
+ status.dirty();
11035
+ }
11036
+ } else if (check.kind === "uuid") {
11037
+ if (!uuidRegex.test(input.data)) {
11038
+ ctx = this._getOrReturnCtx(input, ctx);
11039
+ addIssueToContext(ctx, {
11040
+ validation: "uuid",
11041
+ code: ZodIssueCode.invalid_string,
11042
+ message: check.message
11043
+ });
11044
+ status.dirty();
11045
+ }
11046
+ } else if (check.kind === "nanoid") {
11047
+ if (!nanoidRegex.test(input.data)) {
11048
+ ctx = this._getOrReturnCtx(input, ctx);
11049
+ addIssueToContext(ctx, {
11050
+ validation: "nanoid",
11051
+ code: ZodIssueCode.invalid_string,
11052
+ message: check.message
11053
+ });
11054
+ status.dirty();
11055
+ }
11056
+ } else if (check.kind === "cuid") {
11057
+ if (!cuidRegex.test(input.data)) {
11058
+ ctx = this._getOrReturnCtx(input, ctx);
11059
+ addIssueToContext(ctx, {
11060
+ validation: "cuid",
11061
+ code: ZodIssueCode.invalid_string,
11062
+ message: check.message
11063
+ });
11064
+ status.dirty();
11065
+ }
11066
+ } else if (check.kind === "cuid2") {
11067
+ if (!cuid2Regex.test(input.data)) {
11068
+ ctx = this._getOrReturnCtx(input, ctx);
11069
+ addIssueToContext(ctx, {
11070
+ validation: "cuid2",
11071
+ code: ZodIssueCode.invalid_string,
11072
+ message: check.message
11073
+ });
11074
+ status.dirty();
11075
+ }
11076
+ } else if (check.kind === "ulid") {
11077
+ if (!ulidRegex.test(input.data)) {
11078
+ ctx = this._getOrReturnCtx(input, ctx);
11079
+ addIssueToContext(ctx, {
11080
+ validation: "ulid",
11081
+ code: ZodIssueCode.invalid_string,
11082
+ message: check.message
11083
+ });
11084
+ status.dirty();
11085
+ }
11086
+ } else if (check.kind === "url") {
11087
+ try {
11088
+ new URL(input.data);
11089
+ } catch {
11090
+ ctx = this._getOrReturnCtx(input, ctx);
11091
+ addIssueToContext(ctx, {
11092
+ validation: "url",
11093
+ code: ZodIssueCode.invalid_string,
11094
+ message: check.message
11095
+ });
11096
+ status.dirty();
11097
+ }
11098
+ } else if (check.kind === "regex") {
11099
+ check.regex.lastIndex = 0;
11100
+ const testResult = check.regex.test(input.data);
11101
+ if (!testResult) {
11102
+ ctx = this._getOrReturnCtx(input, ctx);
11103
+ addIssueToContext(ctx, {
11104
+ validation: "regex",
11105
+ code: ZodIssueCode.invalid_string,
11106
+ message: check.message
11107
+ });
11108
+ status.dirty();
11109
+ }
11110
+ } else if (check.kind === "trim") {
11111
+ input.data = input.data.trim();
11112
+ } else if (check.kind === "includes") {
11113
+ if (!input.data.includes(check.value, check.position)) {
11114
+ ctx = this._getOrReturnCtx(input, ctx);
11115
+ addIssueToContext(ctx, {
11116
+ code: ZodIssueCode.invalid_string,
11117
+ validation: { includes: check.value, position: check.position },
11118
+ message: check.message
11119
+ });
11120
+ status.dirty();
11121
+ }
11122
+ } else if (check.kind === "toLowerCase") {
11123
+ input.data = input.data.toLowerCase();
11124
+ } else if (check.kind === "toUpperCase") {
11125
+ input.data = input.data.toUpperCase();
11126
+ } else if (check.kind === "startsWith") {
11127
+ if (!input.data.startsWith(check.value)) {
11128
+ ctx = this._getOrReturnCtx(input, ctx);
11129
+ addIssueToContext(ctx, {
11130
+ code: ZodIssueCode.invalid_string,
11131
+ validation: { startsWith: check.value },
11132
+ message: check.message
11133
+ });
11134
+ status.dirty();
11135
+ }
11136
+ } else if (check.kind === "endsWith") {
11137
+ if (!input.data.endsWith(check.value)) {
11138
+ ctx = this._getOrReturnCtx(input, ctx);
11139
+ addIssueToContext(ctx, {
11140
+ code: ZodIssueCode.invalid_string,
11141
+ validation: { endsWith: check.value },
11142
+ message: check.message
11143
+ });
11144
+ status.dirty();
11145
+ }
11146
+ } else if (check.kind === "datetime") {
11147
+ const regex = datetimeRegex(check);
11148
+ if (!regex.test(input.data)) {
11149
+ ctx = this._getOrReturnCtx(input, ctx);
11150
+ addIssueToContext(ctx, {
11151
+ code: ZodIssueCode.invalid_string,
11152
+ validation: "datetime",
11153
+ message: check.message
11154
+ });
11155
+ status.dirty();
11156
+ }
11157
+ } else if (check.kind === "date") {
11158
+ const regex = dateRegex;
11159
+ if (!regex.test(input.data)) {
11160
+ ctx = this._getOrReturnCtx(input, ctx);
11161
+ addIssueToContext(ctx, {
11162
+ code: ZodIssueCode.invalid_string,
11163
+ validation: "date",
11164
+ message: check.message
11165
+ });
11166
+ status.dirty();
11167
+ }
11168
+ } else if (check.kind === "time") {
11169
+ const regex = timeRegex(check);
11170
+ if (!regex.test(input.data)) {
11171
+ ctx = this._getOrReturnCtx(input, ctx);
11172
+ addIssueToContext(ctx, {
11173
+ code: ZodIssueCode.invalid_string,
11174
+ validation: "time",
11175
+ message: check.message
11176
+ });
11177
+ status.dirty();
11178
+ }
11179
+ } else if (check.kind === "duration") {
11180
+ if (!durationRegex.test(input.data)) {
11181
+ ctx = this._getOrReturnCtx(input, ctx);
11182
+ addIssueToContext(ctx, {
11183
+ validation: "duration",
11184
+ code: ZodIssueCode.invalid_string,
11185
+ message: check.message
11186
+ });
11187
+ status.dirty();
11188
+ }
11189
+ } else if (check.kind === "ip") {
11190
+ if (!isValidIP(input.data, check.version)) {
11191
+ ctx = this._getOrReturnCtx(input, ctx);
11192
+ addIssueToContext(ctx, {
11193
+ validation: "ip",
11194
+ code: ZodIssueCode.invalid_string,
11195
+ message: check.message
11196
+ });
11197
+ status.dirty();
11198
+ }
11199
+ } else if (check.kind === "jwt") {
11200
+ if (!isValidJWT(input.data, check.alg)) {
11201
+ ctx = this._getOrReturnCtx(input, ctx);
11202
+ addIssueToContext(ctx, {
11203
+ validation: "jwt",
11204
+ code: ZodIssueCode.invalid_string,
11205
+ message: check.message
11206
+ });
11207
+ status.dirty();
11208
+ }
11209
+ } else if (check.kind === "cidr") {
11210
+ if (!isValidCidr(input.data, check.version)) {
11211
+ ctx = this._getOrReturnCtx(input, ctx);
11212
+ addIssueToContext(ctx, {
11213
+ validation: "cidr",
11214
+ code: ZodIssueCode.invalid_string,
11215
+ message: check.message
11216
+ });
11217
+ status.dirty();
11218
+ }
11219
+ } else if (check.kind === "base64") {
11220
+ if (!base64Regex.test(input.data)) {
11221
+ ctx = this._getOrReturnCtx(input, ctx);
11222
+ addIssueToContext(ctx, {
11223
+ validation: "base64",
11224
+ code: ZodIssueCode.invalid_string,
11225
+ message: check.message
11226
+ });
11227
+ status.dirty();
11228
+ }
11229
+ } else if (check.kind === "base64url") {
11230
+ if (!base64urlRegex.test(input.data)) {
11231
+ ctx = this._getOrReturnCtx(input, ctx);
11232
+ addIssueToContext(ctx, {
11233
+ validation: "base64url",
11234
+ code: ZodIssueCode.invalid_string,
11235
+ message: check.message
11236
+ });
11237
+ status.dirty();
11238
+ }
11239
+ } else {
11240
+ util.assertNever(check);
11241
+ }
11242
+ }
11243
+ return { status: status.value, value: input.data };
11244
+ }
11245
+ _regex(regex, validation, message) {
11246
+ return this.refinement((data) => regex.test(data), {
11247
+ validation,
11248
+ code: ZodIssueCode.invalid_string,
11249
+ ...errorUtil.errToObj(message)
11250
+ });
11251
+ }
11252
+ _addCheck(check) {
11253
+ return new ZodString({
11254
+ ...this._def,
11255
+ checks: [...this._def.checks, check]
11256
+ });
11257
+ }
11258
+ email(message) {
11259
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
11260
+ }
11261
+ url(message) {
11262
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
11263
+ }
11264
+ emoji(message) {
11265
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
11266
+ }
11267
+ uuid(message) {
11268
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
11269
+ }
11270
+ nanoid(message) {
11271
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
11272
+ }
11273
+ cuid(message) {
11274
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
11275
+ }
11276
+ cuid2(message) {
11277
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
11278
+ }
11279
+ ulid(message) {
11280
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
11281
+ }
11282
+ base64(message) {
11283
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
11284
+ }
11285
+ base64url(message) {
11286
+ return this._addCheck({
11287
+ kind: "base64url",
11288
+ ...errorUtil.errToObj(message)
11289
+ });
11290
+ }
11291
+ jwt(options) {
11292
+ return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
11293
+ }
11294
+ ip(options) {
11295
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
11296
+ }
11297
+ cidr(options) {
11298
+ return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
11299
+ }
11300
+ datetime(options) {
11301
+ if (typeof options === "string") {
11302
+ return this._addCheck({
11303
+ kind: "datetime",
11304
+ precision: null,
11305
+ offset: false,
11306
+ local: false,
11307
+ message: options
11308
+ });
11309
+ }
11310
+ return this._addCheck({
11311
+ kind: "datetime",
11312
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
11313
+ offset: options?.offset ?? false,
11314
+ local: options?.local ?? false,
11315
+ ...errorUtil.errToObj(options?.message)
11316
+ });
11317
+ }
11318
+ date(message) {
11319
+ return this._addCheck({ kind: "date", message });
11320
+ }
11321
+ time(options) {
11322
+ if (typeof options === "string") {
11323
+ return this._addCheck({
11324
+ kind: "time",
11325
+ precision: null,
11326
+ message: options
11327
+ });
11328
+ }
11329
+ return this._addCheck({
11330
+ kind: "time",
11331
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
11332
+ ...errorUtil.errToObj(options?.message)
11333
+ });
11334
+ }
11335
+ duration(message) {
11336
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
11337
+ }
11338
+ regex(regex, message) {
11339
+ return this._addCheck({
11340
+ kind: "regex",
11341
+ regex,
11342
+ ...errorUtil.errToObj(message)
11343
+ });
11344
+ }
11345
+ includes(value, options) {
11346
+ return this._addCheck({
11347
+ kind: "includes",
11348
+ value,
11349
+ position: options?.position,
11350
+ ...errorUtil.errToObj(options?.message)
11351
+ });
11352
+ }
11353
+ startsWith(value, message) {
11354
+ return this._addCheck({
11355
+ kind: "startsWith",
11356
+ value,
11357
+ ...errorUtil.errToObj(message)
11358
+ });
11359
+ }
11360
+ endsWith(value, message) {
11361
+ return this._addCheck({
11362
+ kind: "endsWith",
11363
+ value,
11364
+ ...errorUtil.errToObj(message)
11365
+ });
11366
+ }
11367
+ min(minLength, message) {
11368
+ return this._addCheck({
11369
+ kind: "min",
11370
+ value: minLength,
11371
+ ...errorUtil.errToObj(message)
11372
+ });
11373
+ }
11374
+ max(maxLength, message) {
11375
+ return this._addCheck({
11376
+ kind: "max",
11377
+ value: maxLength,
11378
+ ...errorUtil.errToObj(message)
11379
+ });
11380
+ }
11381
+ length(len, message) {
11382
+ return this._addCheck({
11383
+ kind: "length",
11384
+ value: len,
11385
+ ...errorUtil.errToObj(message)
11386
+ });
11387
+ }
11388
+ nonempty(message) {
11389
+ return this.min(1, errorUtil.errToObj(message));
11390
+ }
11391
+ trim() {
11392
+ return new ZodString({
11393
+ ...this._def,
11394
+ checks: [...this._def.checks, { kind: "trim" }]
11395
+ });
11396
+ }
11397
+ toLowerCase() {
11398
+ return new ZodString({
11399
+ ...this._def,
11400
+ checks: [...this._def.checks, { kind: "toLowerCase" }]
11401
+ });
11402
+ }
11403
+ toUpperCase() {
11404
+ return new ZodString({
11405
+ ...this._def,
11406
+ checks: [...this._def.checks, { kind: "toUpperCase" }]
11407
+ });
11408
+ }
11409
+ get isDatetime() {
11410
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
11411
+ }
11412
+ get isDate() {
11413
+ return !!this._def.checks.find((ch) => ch.kind === "date");
11414
+ }
11415
+ get isTime() {
11416
+ return !!this._def.checks.find((ch) => ch.kind === "time");
11417
+ }
11418
+ get isDuration() {
11419
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
11420
+ }
11421
+ get isEmail() {
11422
+ return !!this._def.checks.find((ch) => ch.kind === "email");
11423
+ }
11424
+ get isURL() {
11425
+ return !!this._def.checks.find((ch) => ch.kind === "url");
11426
+ }
11427
+ get isEmoji() {
11428
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
11429
+ }
11430
+ get isUUID() {
11431
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
11432
+ }
11433
+ get isNANOID() {
11434
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
11435
+ }
11436
+ get isCUID() {
11437
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
11438
+ }
11439
+ get isCUID2() {
11440
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
11441
+ }
11442
+ get isULID() {
11443
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
11444
+ }
11445
+ get isIP() {
11446
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
11447
+ }
11448
+ get isCIDR() {
11449
+ return !!this._def.checks.find((ch) => ch.kind === "cidr");
11450
+ }
11451
+ get isBase64() {
11452
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
11453
+ }
11454
+ get isBase64url() {
11455
+ return !!this._def.checks.find((ch) => ch.kind === "base64url");
11456
+ }
11457
+ get minLength() {
11458
+ let min = null;
11459
+ for (const ch of this._def.checks) {
11460
+ if (ch.kind === "min") {
11461
+ if (min === null || ch.value > min)
11462
+ min = ch.value;
11463
+ }
11464
+ }
11465
+ return min;
11466
+ }
11467
+ get maxLength() {
11468
+ let max = null;
11469
+ for (const ch of this._def.checks) {
11470
+ if (ch.kind === "max") {
11471
+ if (max === null || ch.value < max)
11472
+ max = ch.value;
11473
+ }
11474
+ }
11475
+ return max;
11476
+ }
11477
+ }
11478
+ ZodString.create = (params) => {
11479
+ return new ZodString({
11480
+ checks: [],
11481
+ typeName: ZodFirstPartyTypeKind.ZodString,
11482
+ coerce: params?.coerce ?? false,
11483
+ ...processCreateParams(params)
11484
+ });
11485
+ };
11486
+ function floatSafeRemainder(val, step) {
11487
+ const valDecCount = (val.toString().split(".")[1] || "").length;
11488
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
11489
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
11490
+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
11491
+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
11492
+ return valInt % stepInt / 10 ** decCount;
11493
+ }
11494
+
11495
+ class ZodNumber extends ZodType {
11496
+ constructor() {
11497
+ super(...arguments);
11498
+ this.min = this.gte;
11499
+ this.max = this.lte;
11500
+ this.step = this.multipleOf;
11501
+ }
11502
+ _parse(input) {
11503
+ if (this._def.coerce) {
11504
+ input.data = Number(input.data);
11505
+ }
11506
+ const parsedType = this._getType(input);
11507
+ if (parsedType !== ZodParsedType.number) {
11508
+ const ctx2 = this._getOrReturnCtx(input);
11509
+ addIssueToContext(ctx2, {
11510
+ code: ZodIssueCode.invalid_type,
11511
+ expected: ZodParsedType.number,
11512
+ received: ctx2.parsedType
11513
+ });
11514
+ return INVALID;
11515
+ }
11516
+ let ctx = undefined;
11517
+ const status = new ParseStatus;
11518
+ for (const check of this._def.checks) {
11519
+ if (check.kind === "int") {
11520
+ if (!util.isInteger(input.data)) {
11521
+ ctx = this._getOrReturnCtx(input, ctx);
11522
+ addIssueToContext(ctx, {
11523
+ code: ZodIssueCode.invalid_type,
11524
+ expected: "integer",
11525
+ received: "float",
11526
+ message: check.message
11527
+ });
11528
+ status.dirty();
11529
+ }
11530
+ } else if (check.kind === "min") {
11531
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
11532
+ if (tooSmall) {
11533
+ ctx = this._getOrReturnCtx(input, ctx);
11534
+ addIssueToContext(ctx, {
11535
+ code: ZodIssueCode.too_small,
11536
+ minimum: check.value,
11537
+ type: "number",
11538
+ inclusive: check.inclusive,
11539
+ exact: false,
11540
+ message: check.message
11541
+ });
11542
+ status.dirty();
11543
+ }
11544
+ } else if (check.kind === "max") {
11545
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
11546
+ if (tooBig) {
11547
+ ctx = this._getOrReturnCtx(input, ctx);
11548
+ addIssueToContext(ctx, {
11549
+ code: ZodIssueCode.too_big,
11550
+ maximum: check.value,
11551
+ type: "number",
11552
+ inclusive: check.inclusive,
11553
+ exact: false,
11554
+ message: check.message
11555
+ });
11556
+ status.dirty();
11557
+ }
11558
+ } else if (check.kind === "multipleOf") {
11559
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
11560
+ ctx = this._getOrReturnCtx(input, ctx);
11561
+ addIssueToContext(ctx, {
11562
+ code: ZodIssueCode.not_multiple_of,
11563
+ multipleOf: check.value,
11564
+ message: check.message
11565
+ });
11566
+ status.dirty();
11567
+ }
11568
+ } else if (check.kind === "finite") {
11569
+ if (!Number.isFinite(input.data)) {
11570
+ ctx = this._getOrReturnCtx(input, ctx);
11571
+ addIssueToContext(ctx, {
11572
+ code: ZodIssueCode.not_finite,
11573
+ message: check.message
11574
+ });
11575
+ status.dirty();
11576
+ }
11577
+ } else {
11578
+ util.assertNever(check);
11579
+ }
11580
+ }
11581
+ return { status: status.value, value: input.data };
11582
+ }
11583
+ gte(value, message) {
11584
+ return this.setLimit("min", value, true, errorUtil.toString(message));
11585
+ }
11586
+ gt(value, message) {
11587
+ return this.setLimit("min", value, false, errorUtil.toString(message));
11588
+ }
11589
+ lte(value, message) {
11590
+ return this.setLimit("max", value, true, errorUtil.toString(message));
11591
+ }
11592
+ lt(value, message) {
11593
+ return this.setLimit("max", value, false, errorUtil.toString(message));
11594
+ }
11595
+ setLimit(kind2, value, inclusive, message) {
11596
+ return new ZodNumber({
11597
+ ...this._def,
11598
+ checks: [
11599
+ ...this._def.checks,
11600
+ {
11601
+ kind: kind2,
11602
+ value,
11603
+ inclusive,
11604
+ message: errorUtil.toString(message)
11605
+ }
11606
+ ]
11607
+ });
11608
+ }
11609
+ _addCheck(check) {
11610
+ return new ZodNumber({
11611
+ ...this._def,
11612
+ checks: [...this._def.checks, check]
11613
+ });
11614
+ }
11615
+ int(message) {
11616
+ return this._addCheck({
11617
+ kind: "int",
11618
+ message: errorUtil.toString(message)
11619
+ });
11620
+ }
11621
+ positive(message) {
11622
+ return this._addCheck({
11623
+ kind: "min",
11624
+ value: 0,
11625
+ inclusive: false,
11626
+ message: errorUtil.toString(message)
11627
+ });
11628
+ }
11629
+ negative(message) {
11630
+ return this._addCheck({
11631
+ kind: "max",
11632
+ value: 0,
11633
+ inclusive: false,
11634
+ message: errorUtil.toString(message)
11635
+ });
11636
+ }
11637
+ nonpositive(message) {
11638
+ return this._addCheck({
11639
+ kind: "max",
11640
+ value: 0,
11641
+ inclusive: true,
11642
+ message: errorUtil.toString(message)
11643
+ });
11644
+ }
11645
+ nonnegative(message) {
11646
+ return this._addCheck({
11647
+ kind: "min",
11648
+ value: 0,
11649
+ inclusive: true,
11650
+ message: errorUtil.toString(message)
11651
+ });
11652
+ }
11653
+ multipleOf(value, message) {
11654
+ return this._addCheck({
11655
+ kind: "multipleOf",
11656
+ value,
11657
+ message: errorUtil.toString(message)
11658
+ });
11659
+ }
11660
+ finite(message) {
11661
+ return this._addCheck({
11662
+ kind: "finite",
11663
+ message: errorUtil.toString(message)
11664
+ });
11665
+ }
11666
+ safe(message) {
11667
+ return this._addCheck({
11668
+ kind: "min",
11669
+ inclusive: true,
11670
+ value: Number.MIN_SAFE_INTEGER,
11671
+ message: errorUtil.toString(message)
11672
+ })._addCheck({
11673
+ kind: "max",
11674
+ inclusive: true,
11675
+ value: Number.MAX_SAFE_INTEGER,
11676
+ message: errorUtil.toString(message)
11677
+ });
11678
+ }
11679
+ get minValue() {
11680
+ let min = null;
11681
+ for (const ch of this._def.checks) {
11682
+ if (ch.kind === "min") {
11683
+ if (min === null || ch.value > min)
11684
+ min = ch.value;
11685
+ }
11686
+ }
11687
+ return min;
11688
+ }
11689
+ get maxValue() {
11690
+ let max = null;
11691
+ for (const ch of this._def.checks) {
11692
+ if (ch.kind === "max") {
11693
+ if (max === null || ch.value < max)
11694
+ max = ch.value;
11695
+ }
11696
+ }
11697
+ return max;
11698
+ }
11699
+ get isInt() {
11700
+ return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
11701
+ }
11702
+ get isFinite() {
11703
+ let max = null;
11704
+ let min = null;
11705
+ for (const ch of this._def.checks) {
11706
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
11707
+ return true;
11708
+ } else if (ch.kind === "min") {
11709
+ if (min === null || ch.value > min)
11710
+ min = ch.value;
11711
+ } else if (ch.kind === "max") {
11712
+ if (max === null || ch.value < max)
11713
+ max = ch.value;
11714
+ }
11715
+ }
11716
+ return Number.isFinite(min) && Number.isFinite(max);
11717
+ }
11718
+ }
11719
+ ZodNumber.create = (params) => {
11720
+ return new ZodNumber({
11721
+ checks: [],
11722
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
11723
+ coerce: params?.coerce || false,
11724
+ ...processCreateParams(params)
11725
+ });
11726
+ };
11727
+
11728
+ class ZodBigInt extends ZodType {
11729
+ constructor() {
11730
+ super(...arguments);
11731
+ this.min = this.gte;
11732
+ this.max = this.lte;
11733
+ }
11734
+ _parse(input) {
11735
+ if (this._def.coerce) {
11736
+ try {
11737
+ input.data = BigInt(input.data);
11738
+ } catch {
11739
+ return this._getInvalidInput(input);
11740
+ }
11741
+ }
11742
+ const parsedType = this._getType(input);
11743
+ if (parsedType !== ZodParsedType.bigint) {
11744
+ return this._getInvalidInput(input);
11745
+ }
11746
+ let ctx = undefined;
11747
+ const status = new ParseStatus;
11748
+ for (const check of this._def.checks) {
11749
+ if (check.kind === "min") {
11750
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
11751
+ if (tooSmall) {
11752
+ ctx = this._getOrReturnCtx(input, ctx);
11753
+ addIssueToContext(ctx, {
11754
+ code: ZodIssueCode.too_small,
11755
+ type: "bigint",
11756
+ minimum: check.value,
11757
+ inclusive: check.inclusive,
11758
+ message: check.message
11759
+ });
11760
+ status.dirty();
11761
+ }
11762
+ } else if (check.kind === "max") {
11763
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
11764
+ if (tooBig) {
11765
+ ctx = this._getOrReturnCtx(input, ctx);
11766
+ addIssueToContext(ctx, {
11767
+ code: ZodIssueCode.too_big,
11768
+ type: "bigint",
11769
+ maximum: check.value,
11770
+ inclusive: check.inclusive,
11771
+ message: check.message
11772
+ });
11773
+ status.dirty();
11774
+ }
11775
+ } else if (check.kind === "multipleOf") {
11776
+ if (input.data % check.value !== BigInt(0)) {
11777
+ ctx = this._getOrReturnCtx(input, ctx);
11778
+ addIssueToContext(ctx, {
11779
+ code: ZodIssueCode.not_multiple_of,
11780
+ multipleOf: check.value,
11781
+ message: check.message
11782
+ });
11783
+ status.dirty();
11784
+ }
11785
+ } else {
11786
+ util.assertNever(check);
11787
+ }
11788
+ }
11789
+ return { status: status.value, value: input.data };
11790
+ }
11791
+ _getInvalidInput(input) {
11792
+ const ctx = this._getOrReturnCtx(input);
11793
+ addIssueToContext(ctx, {
11794
+ code: ZodIssueCode.invalid_type,
11795
+ expected: ZodParsedType.bigint,
11796
+ received: ctx.parsedType
11797
+ });
11798
+ return INVALID;
11799
+ }
11800
+ gte(value, message) {
11801
+ return this.setLimit("min", value, true, errorUtil.toString(message));
11802
+ }
11803
+ gt(value, message) {
11804
+ return this.setLimit("min", value, false, errorUtil.toString(message));
11805
+ }
11806
+ lte(value, message) {
11807
+ return this.setLimit("max", value, true, errorUtil.toString(message));
11808
+ }
11809
+ lt(value, message) {
11810
+ return this.setLimit("max", value, false, errorUtil.toString(message));
11811
+ }
11812
+ setLimit(kind2, value, inclusive, message) {
11813
+ return new ZodBigInt({
11814
+ ...this._def,
11815
+ checks: [
11816
+ ...this._def.checks,
11817
+ {
11818
+ kind: kind2,
11819
+ value,
11820
+ inclusive,
11821
+ message: errorUtil.toString(message)
11822
+ }
11823
+ ]
11824
+ });
11825
+ }
11826
+ _addCheck(check) {
11827
+ return new ZodBigInt({
11828
+ ...this._def,
11829
+ checks: [...this._def.checks, check]
11830
+ });
11831
+ }
11832
+ positive(message) {
11833
+ return this._addCheck({
11834
+ kind: "min",
11835
+ value: BigInt(0),
11836
+ inclusive: false,
11837
+ message: errorUtil.toString(message)
11838
+ });
11839
+ }
11840
+ negative(message) {
11841
+ return this._addCheck({
11842
+ kind: "max",
11843
+ value: BigInt(0),
11844
+ inclusive: false,
11845
+ message: errorUtil.toString(message)
11846
+ });
11847
+ }
11848
+ nonpositive(message) {
11849
+ return this._addCheck({
11850
+ kind: "max",
11851
+ value: BigInt(0),
11852
+ inclusive: true,
11853
+ message: errorUtil.toString(message)
11854
+ });
11855
+ }
11856
+ nonnegative(message) {
11857
+ return this._addCheck({
11858
+ kind: "min",
11859
+ value: BigInt(0),
11860
+ inclusive: true,
11861
+ message: errorUtil.toString(message)
11862
+ });
11863
+ }
11864
+ multipleOf(value, message) {
11865
+ return this._addCheck({
11866
+ kind: "multipleOf",
11867
+ value,
11868
+ message: errorUtil.toString(message)
11869
+ });
11870
+ }
11871
+ get minValue() {
11872
+ let min = null;
11873
+ for (const ch of this._def.checks) {
11874
+ if (ch.kind === "min") {
11875
+ if (min === null || ch.value > min)
11876
+ min = ch.value;
11877
+ }
11878
+ }
11879
+ return min;
11880
+ }
11881
+ get maxValue() {
11882
+ let max = null;
11883
+ for (const ch of this._def.checks) {
11884
+ if (ch.kind === "max") {
11885
+ if (max === null || ch.value < max)
11886
+ max = ch.value;
11887
+ }
11888
+ }
11889
+ return max;
11890
+ }
11891
+ }
11892
+ ZodBigInt.create = (params) => {
11893
+ return new ZodBigInt({
11894
+ checks: [],
11895
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
11896
+ coerce: params?.coerce ?? false,
11897
+ ...processCreateParams(params)
11898
+ });
11899
+ };
11900
+
11901
+ class ZodBoolean extends ZodType {
11902
+ _parse(input) {
11903
+ if (this._def.coerce) {
11904
+ input.data = Boolean(input.data);
11905
+ }
11906
+ const parsedType = this._getType(input);
11907
+ if (parsedType !== ZodParsedType.boolean) {
11908
+ const ctx = this._getOrReturnCtx(input);
11909
+ addIssueToContext(ctx, {
11910
+ code: ZodIssueCode.invalid_type,
11911
+ expected: ZodParsedType.boolean,
11912
+ received: ctx.parsedType
11913
+ });
11914
+ return INVALID;
11915
+ }
11916
+ return OK(input.data);
11917
+ }
11918
+ }
11919
+ ZodBoolean.create = (params) => {
11920
+ return new ZodBoolean({
11921
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
11922
+ coerce: params?.coerce || false,
11923
+ ...processCreateParams(params)
11924
+ });
11925
+ };
11926
+
11927
+ class ZodDate extends ZodType {
11928
+ _parse(input) {
11929
+ if (this._def.coerce) {
11930
+ input.data = new Date(input.data);
11931
+ }
11932
+ const parsedType = this._getType(input);
11933
+ if (parsedType !== ZodParsedType.date) {
11934
+ const ctx2 = this._getOrReturnCtx(input);
11935
+ addIssueToContext(ctx2, {
11936
+ code: ZodIssueCode.invalid_type,
11937
+ expected: ZodParsedType.date,
11938
+ received: ctx2.parsedType
11939
+ });
11940
+ return INVALID;
11941
+ }
11942
+ if (Number.isNaN(input.data.getTime())) {
11943
+ const ctx2 = this._getOrReturnCtx(input);
11944
+ addIssueToContext(ctx2, {
11945
+ code: ZodIssueCode.invalid_date
11946
+ });
11947
+ return INVALID;
11948
+ }
11949
+ const status = new ParseStatus;
11950
+ let ctx = undefined;
11951
+ for (const check of this._def.checks) {
11952
+ if (check.kind === "min") {
11953
+ if (input.data.getTime() < check.value) {
11954
+ ctx = this._getOrReturnCtx(input, ctx);
11955
+ addIssueToContext(ctx, {
11956
+ code: ZodIssueCode.too_small,
11957
+ message: check.message,
11958
+ inclusive: true,
11959
+ exact: false,
11960
+ minimum: check.value,
11961
+ type: "date"
11962
+ });
11963
+ status.dirty();
11964
+ }
11965
+ } else if (check.kind === "max") {
11966
+ if (input.data.getTime() > check.value) {
11967
+ ctx = this._getOrReturnCtx(input, ctx);
11968
+ addIssueToContext(ctx, {
11969
+ code: ZodIssueCode.too_big,
11970
+ message: check.message,
11971
+ inclusive: true,
11972
+ exact: false,
11973
+ maximum: check.value,
11974
+ type: "date"
11975
+ });
11976
+ status.dirty();
11977
+ }
11978
+ } else {
11979
+ util.assertNever(check);
11980
+ }
11981
+ }
11982
+ return {
11983
+ status: status.value,
11984
+ value: new Date(input.data.getTime())
11985
+ };
11986
+ }
11987
+ _addCheck(check) {
11988
+ return new ZodDate({
11989
+ ...this._def,
11990
+ checks: [...this._def.checks, check]
11991
+ });
11992
+ }
11993
+ min(minDate, message) {
11994
+ return this._addCheck({
11995
+ kind: "min",
11996
+ value: minDate.getTime(),
11997
+ message: errorUtil.toString(message)
11998
+ });
11999
+ }
12000
+ max(maxDate, message) {
12001
+ return this._addCheck({
12002
+ kind: "max",
12003
+ value: maxDate.getTime(),
12004
+ message: errorUtil.toString(message)
12005
+ });
12006
+ }
12007
+ get minDate() {
12008
+ let min = null;
12009
+ for (const ch of this._def.checks) {
12010
+ if (ch.kind === "min") {
12011
+ if (min === null || ch.value > min)
12012
+ min = ch.value;
12013
+ }
12014
+ }
12015
+ return min != null ? new Date(min) : null;
12016
+ }
12017
+ get maxDate() {
12018
+ let max = null;
12019
+ for (const ch of this._def.checks) {
12020
+ if (ch.kind === "max") {
12021
+ if (max === null || ch.value < max)
12022
+ max = ch.value;
12023
+ }
12024
+ }
12025
+ return max != null ? new Date(max) : null;
12026
+ }
12027
+ }
12028
+ ZodDate.create = (params) => {
12029
+ return new ZodDate({
12030
+ checks: [],
12031
+ coerce: params?.coerce || false,
12032
+ typeName: ZodFirstPartyTypeKind.ZodDate,
12033
+ ...processCreateParams(params)
12034
+ });
12035
+ };
12036
+
12037
+ class ZodSymbol extends ZodType {
12038
+ _parse(input) {
12039
+ const parsedType = this._getType(input);
12040
+ if (parsedType !== ZodParsedType.symbol) {
12041
+ const ctx = this._getOrReturnCtx(input);
12042
+ addIssueToContext(ctx, {
12043
+ code: ZodIssueCode.invalid_type,
12044
+ expected: ZodParsedType.symbol,
12045
+ received: ctx.parsedType
12046
+ });
12047
+ return INVALID;
12048
+ }
12049
+ return OK(input.data);
12050
+ }
12051
+ }
12052
+ ZodSymbol.create = (params) => {
12053
+ return new ZodSymbol({
12054
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
12055
+ ...processCreateParams(params)
12056
+ });
12057
+ };
12058
+
12059
+ class ZodUndefined extends ZodType {
12060
+ _parse(input) {
12061
+ const parsedType = this._getType(input);
12062
+ if (parsedType !== ZodParsedType.undefined) {
12063
+ const ctx = this._getOrReturnCtx(input);
12064
+ addIssueToContext(ctx, {
12065
+ code: ZodIssueCode.invalid_type,
12066
+ expected: ZodParsedType.undefined,
12067
+ received: ctx.parsedType
12068
+ });
12069
+ return INVALID;
12070
+ }
12071
+ return OK(input.data);
12072
+ }
12073
+ }
12074
+ ZodUndefined.create = (params) => {
12075
+ return new ZodUndefined({
12076
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
12077
+ ...processCreateParams(params)
12078
+ });
12079
+ };
12080
+
12081
+ class ZodNull extends ZodType {
12082
+ _parse(input) {
12083
+ const parsedType = this._getType(input);
12084
+ if (parsedType !== ZodParsedType.null) {
12085
+ const ctx = this._getOrReturnCtx(input);
12086
+ addIssueToContext(ctx, {
12087
+ code: ZodIssueCode.invalid_type,
12088
+ expected: ZodParsedType.null,
12089
+ received: ctx.parsedType
12090
+ });
12091
+ return INVALID;
12092
+ }
12093
+ return OK(input.data);
12094
+ }
12095
+ }
12096
+ ZodNull.create = (params) => {
12097
+ return new ZodNull({
12098
+ typeName: ZodFirstPartyTypeKind.ZodNull,
12099
+ ...processCreateParams(params)
12100
+ });
12101
+ };
12102
+
12103
+ class ZodAny extends ZodType {
12104
+ constructor() {
12105
+ super(...arguments);
12106
+ this._any = true;
12107
+ }
12108
+ _parse(input) {
12109
+ return OK(input.data);
12110
+ }
12111
+ }
12112
+ ZodAny.create = (params) => {
12113
+ return new ZodAny({
12114
+ typeName: ZodFirstPartyTypeKind.ZodAny,
12115
+ ...processCreateParams(params)
12116
+ });
12117
+ };
12118
+
12119
+ class ZodUnknown extends ZodType {
12120
+ constructor() {
12121
+ super(...arguments);
12122
+ this._unknown = true;
12123
+ }
12124
+ _parse(input) {
12125
+ return OK(input.data);
12126
+ }
12127
+ }
12128
+ ZodUnknown.create = (params) => {
12129
+ return new ZodUnknown({
12130
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
12131
+ ...processCreateParams(params)
12132
+ });
12133
+ };
12134
+
12135
+ class ZodNever extends ZodType {
12136
+ _parse(input) {
12137
+ const ctx = this._getOrReturnCtx(input);
12138
+ addIssueToContext(ctx, {
12139
+ code: ZodIssueCode.invalid_type,
12140
+ expected: ZodParsedType.never,
12141
+ received: ctx.parsedType
12142
+ });
12143
+ return INVALID;
12144
+ }
12145
+ }
12146
+ ZodNever.create = (params) => {
12147
+ return new ZodNever({
12148
+ typeName: ZodFirstPartyTypeKind.ZodNever,
12149
+ ...processCreateParams(params)
12150
+ });
12151
+ };
12152
+
12153
+ class ZodVoid extends ZodType {
12154
+ _parse(input) {
12155
+ const parsedType = this._getType(input);
12156
+ if (parsedType !== ZodParsedType.undefined) {
12157
+ const ctx = this._getOrReturnCtx(input);
12158
+ addIssueToContext(ctx, {
12159
+ code: ZodIssueCode.invalid_type,
12160
+ expected: ZodParsedType.void,
12161
+ received: ctx.parsedType
12162
+ });
12163
+ return INVALID;
12164
+ }
12165
+ return OK(input.data);
12166
+ }
12167
+ }
12168
+ ZodVoid.create = (params) => {
12169
+ return new ZodVoid({
12170
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
12171
+ ...processCreateParams(params)
12172
+ });
12173
+ };
12174
+
12175
+ class ZodArray extends ZodType {
12176
+ _parse(input) {
12177
+ const { ctx, status } = this._processInputParams(input);
12178
+ const def = this._def;
12179
+ if (ctx.parsedType !== ZodParsedType.array) {
12180
+ addIssueToContext(ctx, {
12181
+ code: ZodIssueCode.invalid_type,
12182
+ expected: ZodParsedType.array,
12183
+ received: ctx.parsedType
12184
+ });
12185
+ return INVALID;
12186
+ }
12187
+ if (def.exactLength !== null) {
12188
+ const tooBig = ctx.data.length > def.exactLength.value;
12189
+ const tooSmall = ctx.data.length < def.exactLength.value;
12190
+ if (tooBig || tooSmall) {
12191
+ addIssueToContext(ctx, {
12192
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
12193
+ minimum: tooSmall ? def.exactLength.value : undefined,
12194
+ maximum: tooBig ? def.exactLength.value : undefined,
12195
+ type: "array",
12196
+ inclusive: true,
12197
+ exact: true,
12198
+ message: def.exactLength.message
12199
+ });
12200
+ status.dirty();
12201
+ }
12202
+ }
12203
+ if (def.minLength !== null) {
12204
+ if (ctx.data.length < def.minLength.value) {
12205
+ addIssueToContext(ctx, {
12206
+ code: ZodIssueCode.too_small,
12207
+ minimum: def.minLength.value,
12208
+ type: "array",
12209
+ inclusive: true,
12210
+ exact: false,
12211
+ message: def.minLength.message
12212
+ });
12213
+ status.dirty();
12214
+ }
12215
+ }
12216
+ if (def.maxLength !== null) {
12217
+ if (ctx.data.length > def.maxLength.value) {
12218
+ addIssueToContext(ctx, {
12219
+ code: ZodIssueCode.too_big,
12220
+ maximum: def.maxLength.value,
12221
+ type: "array",
12222
+ inclusive: true,
12223
+ exact: false,
12224
+ message: def.maxLength.message
12225
+ });
12226
+ status.dirty();
12227
+ }
12228
+ }
12229
+ if (ctx.common.async) {
12230
+ return Promise.all([...ctx.data].map((item, i) => {
12231
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
12232
+ })).then((result2) => {
12233
+ return ParseStatus.mergeArray(status, result2);
12234
+ });
12235
+ }
12236
+ const result = [...ctx.data].map((item, i) => {
12237
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
12238
+ });
12239
+ return ParseStatus.mergeArray(status, result);
12240
+ }
12241
+ get element() {
12242
+ return this._def.type;
12243
+ }
12244
+ min(minLength, message) {
12245
+ return new ZodArray({
12246
+ ...this._def,
12247
+ minLength: { value: minLength, message: errorUtil.toString(message) }
12248
+ });
12249
+ }
12250
+ max(maxLength, message) {
12251
+ return new ZodArray({
12252
+ ...this._def,
12253
+ maxLength: { value: maxLength, message: errorUtil.toString(message) }
12254
+ });
12255
+ }
12256
+ length(len, message) {
12257
+ return new ZodArray({
12258
+ ...this._def,
12259
+ exactLength: { value: len, message: errorUtil.toString(message) }
12260
+ });
12261
+ }
12262
+ nonempty(message) {
12263
+ return this.min(1, message);
12264
+ }
12265
+ }
12266
+ ZodArray.create = (schema2, params) => {
12267
+ return new ZodArray({
12268
+ type: schema2,
12269
+ minLength: null,
12270
+ maxLength: null,
12271
+ exactLength: null,
12272
+ typeName: ZodFirstPartyTypeKind.ZodArray,
12273
+ ...processCreateParams(params)
12274
+ });
12275
+ };
12276
+ function deepPartialify(schema2) {
12277
+ if (schema2 instanceof ZodObject) {
12278
+ const newShape = {};
12279
+ for (const key in schema2.shape) {
12280
+ const fieldSchema = schema2.shape[key];
12281
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
12282
+ }
12283
+ return new ZodObject({
12284
+ ...schema2._def,
12285
+ shape: () => newShape
12286
+ });
12287
+ } else if (schema2 instanceof ZodArray) {
12288
+ return new ZodArray({
12289
+ ...schema2._def,
12290
+ type: deepPartialify(schema2.element)
12291
+ });
12292
+ } else if (schema2 instanceof ZodOptional) {
12293
+ return ZodOptional.create(deepPartialify(schema2.unwrap()));
12294
+ } else if (schema2 instanceof ZodNullable) {
12295
+ return ZodNullable.create(deepPartialify(schema2.unwrap()));
12296
+ } else if (schema2 instanceof ZodTuple) {
12297
+ return ZodTuple.create(schema2.items.map((item) => deepPartialify(item)));
12298
+ } else {
12299
+ return schema2;
12300
+ }
12301
+ }
12302
+
12303
+ class ZodObject extends ZodType {
12304
+ constructor() {
12305
+ super(...arguments);
12306
+ this._cached = null;
12307
+ this.nonstrict = this.passthrough;
12308
+ this.augment = this.extend;
12309
+ }
12310
+ _getCached() {
12311
+ if (this._cached !== null)
12312
+ return this._cached;
12313
+ const shape = this._def.shape();
12314
+ const keys = util.objectKeys(shape);
12315
+ this._cached = { shape, keys };
12316
+ return this._cached;
12317
+ }
12318
+ _parse(input) {
12319
+ const parsedType = this._getType(input);
12320
+ if (parsedType !== ZodParsedType.object) {
12321
+ const ctx2 = this._getOrReturnCtx(input);
12322
+ addIssueToContext(ctx2, {
12323
+ code: ZodIssueCode.invalid_type,
12324
+ expected: ZodParsedType.object,
12325
+ received: ctx2.parsedType
12326
+ });
12327
+ return INVALID;
12328
+ }
12329
+ const { status, ctx } = this._processInputParams(input);
12330
+ const { shape, keys: shapeKeys } = this._getCached();
12331
+ const extraKeys = [];
12332
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
12333
+ for (const key in ctx.data) {
12334
+ if (!shapeKeys.includes(key)) {
12335
+ extraKeys.push(key);
12336
+ }
12337
+ }
12338
+ }
12339
+ const pairs = [];
12340
+ for (const key of shapeKeys) {
12341
+ const keyValidator = shape[key];
12342
+ const value = ctx.data[key];
12343
+ pairs.push({
12344
+ key: { status: "valid", value: key },
12345
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
12346
+ alwaysSet: key in ctx.data
12347
+ });
12348
+ }
12349
+ if (this._def.catchall instanceof ZodNever) {
12350
+ const unknownKeys = this._def.unknownKeys;
12351
+ if (unknownKeys === "passthrough") {
12352
+ for (const key of extraKeys) {
12353
+ pairs.push({
12354
+ key: { status: "valid", value: key },
12355
+ value: { status: "valid", value: ctx.data[key] }
12356
+ });
12357
+ }
12358
+ } else if (unknownKeys === "strict") {
12359
+ if (extraKeys.length > 0) {
12360
+ addIssueToContext(ctx, {
12361
+ code: ZodIssueCode.unrecognized_keys,
12362
+ keys: extraKeys
12363
+ });
12364
+ status.dirty();
12365
+ }
12366
+ } else if (unknownKeys === "strip") {} else {
12367
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
12368
+ }
12369
+ } else {
12370
+ const catchall = this._def.catchall;
12371
+ for (const key of extraKeys) {
12372
+ const value = ctx.data[key];
12373
+ pairs.push({
12374
+ key: { status: "valid", value: key },
12375
+ value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
12376
+ alwaysSet: key in ctx.data
12377
+ });
12378
+ }
12379
+ }
12380
+ if (ctx.common.async) {
12381
+ return Promise.resolve().then(async () => {
12382
+ const syncPairs = [];
12383
+ for (const pair of pairs) {
12384
+ const key = await pair.key;
12385
+ const value = await pair.value;
12386
+ syncPairs.push({
12387
+ key,
12388
+ value,
12389
+ alwaysSet: pair.alwaysSet
12390
+ });
12391
+ }
12392
+ return syncPairs;
12393
+ }).then((syncPairs) => {
12394
+ return ParseStatus.mergeObjectSync(status, syncPairs);
12395
+ });
12396
+ } else {
12397
+ return ParseStatus.mergeObjectSync(status, pairs);
12398
+ }
12399
+ }
12400
+ get shape() {
12401
+ return this._def.shape();
12402
+ }
12403
+ strict(message) {
12404
+ errorUtil.errToObj;
12405
+ return new ZodObject({
12406
+ ...this._def,
12407
+ unknownKeys: "strict",
12408
+ ...message !== undefined ? {
12409
+ errorMap: (issue, ctx) => {
12410
+ const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
12411
+ if (issue.code === "unrecognized_keys")
12412
+ return {
12413
+ message: errorUtil.errToObj(message).message ?? defaultError
12414
+ };
12415
+ return {
12416
+ message: defaultError
12417
+ };
12418
+ }
12419
+ } : {}
12420
+ });
12421
+ }
12422
+ strip() {
12423
+ return new ZodObject({
12424
+ ...this._def,
12425
+ unknownKeys: "strip"
12426
+ });
12427
+ }
12428
+ passthrough() {
12429
+ return new ZodObject({
12430
+ ...this._def,
12431
+ unknownKeys: "passthrough"
12432
+ });
12433
+ }
12434
+ extend(augmentation) {
12435
+ return new ZodObject({
12436
+ ...this._def,
12437
+ shape: () => ({
12438
+ ...this._def.shape(),
12439
+ ...augmentation
12440
+ })
12441
+ });
12442
+ }
12443
+ merge(merging) {
12444
+ const merged = new ZodObject({
12445
+ unknownKeys: merging._def.unknownKeys,
12446
+ catchall: merging._def.catchall,
12447
+ shape: () => ({
12448
+ ...this._def.shape(),
12449
+ ...merging._def.shape()
12450
+ }),
12451
+ typeName: ZodFirstPartyTypeKind.ZodObject
12452
+ });
12453
+ return merged;
12454
+ }
12455
+ setKey(key, schema2) {
12456
+ return this.augment({ [key]: schema2 });
12457
+ }
12458
+ catchall(index) {
12459
+ return new ZodObject({
12460
+ ...this._def,
12461
+ catchall: index
12462
+ });
12463
+ }
12464
+ pick(mask) {
12465
+ const shape = {};
12466
+ for (const key of util.objectKeys(mask)) {
12467
+ if (mask[key] && this.shape[key]) {
12468
+ shape[key] = this.shape[key];
12469
+ }
12470
+ }
12471
+ return new ZodObject({
12472
+ ...this._def,
12473
+ shape: () => shape
12474
+ });
12475
+ }
12476
+ omit(mask) {
12477
+ const shape = {};
12478
+ for (const key of util.objectKeys(this.shape)) {
12479
+ if (!mask[key]) {
12480
+ shape[key] = this.shape[key];
12481
+ }
12482
+ }
12483
+ return new ZodObject({
12484
+ ...this._def,
12485
+ shape: () => shape
12486
+ });
12487
+ }
12488
+ deepPartial() {
12489
+ return deepPartialify(this);
12490
+ }
12491
+ partial(mask) {
12492
+ const newShape = {};
12493
+ for (const key of util.objectKeys(this.shape)) {
12494
+ const fieldSchema = this.shape[key];
12495
+ if (mask && !mask[key]) {
12496
+ newShape[key] = fieldSchema;
12497
+ } else {
12498
+ newShape[key] = fieldSchema.optional();
12499
+ }
12500
+ }
12501
+ return new ZodObject({
12502
+ ...this._def,
12503
+ shape: () => newShape
12504
+ });
12505
+ }
12506
+ required(mask) {
12507
+ const newShape = {};
12508
+ for (const key of util.objectKeys(this.shape)) {
12509
+ if (mask && !mask[key]) {
12510
+ newShape[key] = this.shape[key];
12511
+ } else {
12512
+ const fieldSchema = this.shape[key];
12513
+ let newField = fieldSchema;
12514
+ while (newField instanceof ZodOptional) {
12515
+ newField = newField._def.innerType;
12516
+ }
12517
+ newShape[key] = newField;
12518
+ }
12519
+ }
12520
+ return new ZodObject({
12521
+ ...this._def,
12522
+ shape: () => newShape
12523
+ });
12524
+ }
12525
+ keyof() {
12526
+ return createZodEnum(util.objectKeys(this.shape));
12527
+ }
12528
+ }
12529
+ ZodObject.create = (shape, params) => {
12530
+ return new ZodObject({
12531
+ shape: () => shape,
12532
+ unknownKeys: "strip",
12533
+ catchall: ZodNever.create(),
12534
+ typeName: ZodFirstPartyTypeKind.ZodObject,
12535
+ ...processCreateParams(params)
12536
+ });
12537
+ };
12538
+ ZodObject.strictCreate = (shape, params) => {
12539
+ return new ZodObject({
12540
+ shape: () => shape,
12541
+ unknownKeys: "strict",
12542
+ catchall: ZodNever.create(),
12543
+ typeName: ZodFirstPartyTypeKind.ZodObject,
12544
+ ...processCreateParams(params)
12545
+ });
12546
+ };
12547
+ ZodObject.lazycreate = (shape, params) => {
12548
+ return new ZodObject({
12549
+ shape,
12550
+ unknownKeys: "strip",
12551
+ catchall: ZodNever.create(),
12552
+ typeName: ZodFirstPartyTypeKind.ZodObject,
12553
+ ...processCreateParams(params)
12554
+ });
12555
+ };
12556
+
12557
+ class ZodUnion extends ZodType {
12558
+ _parse(input) {
12559
+ const { ctx } = this._processInputParams(input);
12560
+ const options = this._def.options;
12561
+ function handleResults(results) {
12562
+ for (const result of results) {
12563
+ if (result.result.status === "valid") {
12564
+ return result.result;
12565
+ }
12566
+ }
12567
+ for (const result of results) {
12568
+ if (result.result.status === "dirty") {
12569
+ ctx.common.issues.push(...result.ctx.common.issues);
12570
+ return result.result;
12571
+ }
12572
+ }
12573
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
12574
+ addIssueToContext(ctx, {
12575
+ code: ZodIssueCode.invalid_union,
12576
+ unionErrors
12577
+ });
12578
+ return INVALID;
12579
+ }
12580
+ if (ctx.common.async) {
12581
+ return Promise.all(options.map(async (option) => {
12582
+ const childCtx = {
12583
+ ...ctx,
12584
+ common: {
12585
+ ...ctx.common,
12586
+ issues: []
12587
+ },
12588
+ parent: null
12589
+ };
12590
+ return {
12591
+ result: await option._parseAsync({
12592
+ data: ctx.data,
12593
+ path: ctx.path,
12594
+ parent: childCtx
12595
+ }),
12596
+ ctx: childCtx
12597
+ };
12598
+ })).then(handleResults);
12599
+ } else {
12600
+ let dirty = undefined;
12601
+ const issues = [];
12602
+ for (const option of options) {
12603
+ const childCtx = {
12604
+ ...ctx,
12605
+ common: {
12606
+ ...ctx.common,
12607
+ issues: []
12608
+ },
12609
+ parent: null
12610
+ };
12611
+ const result = option._parseSync({
12612
+ data: ctx.data,
12613
+ path: ctx.path,
12614
+ parent: childCtx
12615
+ });
12616
+ if (result.status === "valid") {
12617
+ return result;
12618
+ } else if (result.status === "dirty" && !dirty) {
12619
+ dirty = { result, ctx: childCtx };
12620
+ }
12621
+ if (childCtx.common.issues.length) {
12622
+ issues.push(childCtx.common.issues);
12623
+ }
12624
+ }
12625
+ if (dirty) {
12626
+ ctx.common.issues.push(...dirty.ctx.common.issues);
12627
+ return dirty.result;
12628
+ }
12629
+ const unionErrors = issues.map((issues2) => new ZodError(issues2));
12630
+ addIssueToContext(ctx, {
12631
+ code: ZodIssueCode.invalid_union,
12632
+ unionErrors
12633
+ });
12634
+ return INVALID;
12635
+ }
12636
+ }
12637
+ get options() {
12638
+ return this._def.options;
12639
+ }
12640
+ }
12641
+ ZodUnion.create = (types, params) => {
12642
+ return new ZodUnion({
12643
+ options: types,
12644
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
12645
+ ...processCreateParams(params)
12646
+ });
12647
+ };
12648
+ var getDiscriminator = (type) => {
12649
+ if (type instanceof ZodLazy) {
12650
+ return getDiscriminator(type.schema);
12651
+ } else if (type instanceof ZodEffects) {
12652
+ return getDiscriminator(type.innerType());
12653
+ } else if (type instanceof ZodLiteral) {
12654
+ return [type.value];
12655
+ } else if (type instanceof ZodEnum) {
12656
+ return type.options;
12657
+ } else if (type instanceof ZodNativeEnum) {
12658
+ return util.objectValues(type.enum);
12659
+ } else if (type instanceof ZodDefault) {
12660
+ return getDiscriminator(type._def.innerType);
12661
+ } else if (type instanceof ZodUndefined) {
12662
+ return [undefined];
12663
+ } else if (type instanceof ZodNull) {
12664
+ return [null];
12665
+ } else if (type instanceof ZodOptional) {
12666
+ return [undefined, ...getDiscriminator(type.unwrap())];
12667
+ } else if (type instanceof ZodNullable) {
12668
+ return [null, ...getDiscriminator(type.unwrap())];
12669
+ } else if (type instanceof ZodBranded) {
12670
+ return getDiscriminator(type.unwrap());
12671
+ } else if (type instanceof ZodReadonly) {
12672
+ return getDiscriminator(type.unwrap());
12673
+ } else if (type instanceof ZodCatch) {
12674
+ return getDiscriminator(type._def.innerType);
12675
+ } else {
12676
+ return [];
12677
+ }
12678
+ };
12679
+
12680
+ class ZodDiscriminatedUnion extends ZodType {
12681
+ _parse(input) {
12682
+ const { ctx } = this._processInputParams(input);
12683
+ if (ctx.parsedType !== ZodParsedType.object) {
12684
+ addIssueToContext(ctx, {
12685
+ code: ZodIssueCode.invalid_type,
12686
+ expected: ZodParsedType.object,
12687
+ received: ctx.parsedType
12688
+ });
12689
+ return INVALID;
12690
+ }
12691
+ const discriminator = this.discriminator;
12692
+ const discriminatorValue = ctx.data[discriminator];
12693
+ const option = this.optionsMap.get(discriminatorValue);
12694
+ if (!option) {
12695
+ addIssueToContext(ctx, {
12696
+ code: ZodIssueCode.invalid_union_discriminator,
12697
+ options: Array.from(this.optionsMap.keys()),
12698
+ path: [discriminator]
12699
+ });
12700
+ return INVALID;
12701
+ }
12702
+ if (ctx.common.async) {
12703
+ return option._parseAsync({
12704
+ data: ctx.data,
12705
+ path: ctx.path,
12706
+ parent: ctx
12707
+ });
12708
+ } else {
12709
+ return option._parseSync({
12710
+ data: ctx.data,
12711
+ path: ctx.path,
12712
+ parent: ctx
12713
+ });
12714
+ }
12715
+ }
12716
+ get discriminator() {
12717
+ return this._def.discriminator;
12718
+ }
12719
+ get options() {
12720
+ return this._def.options;
12721
+ }
12722
+ get optionsMap() {
12723
+ return this._def.optionsMap;
12724
+ }
12725
+ static create(discriminator, options, params) {
12726
+ const optionsMap = new Map;
12727
+ for (const type of options) {
12728
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
12729
+ if (!discriminatorValues.length) {
12730
+ throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
12731
+ }
12732
+ for (const value of discriminatorValues) {
12733
+ if (optionsMap.has(value)) {
12734
+ throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
12735
+ }
12736
+ optionsMap.set(value, type);
12737
+ }
12738
+ }
12739
+ return new ZodDiscriminatedUnion({
12740
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
12741
+ discriminator,
12742
+ options,
12743
+ optionsMap,
12744
+ ...processCreateParams(params)
12745
+ });
12746
+ }
12747
+ }
12748
+ function mergeValues(a, b) {
12749
+ const aType = getParsedType(a);
12750
+ const bType = getParsedType(b);
12751
+ if (a === b) {
12752
+ return { valid: true, data: a };
12753
+ } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
12754
+ const bKeys = util.objectKeys(b);
12755
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
12756
+ const newObj = { ...a, ...b };
12757
+ for (const key of sharedKeys) {
12758
+ const sharedValue = mergeValues(a[key], b[key]);
12759
+ if (!sharedValue.valid) {
12760
+ return { valid: false };
12761
+ }
12762
+ newObj[key] = sharedValue.data;
12763
+ }
12764
+ return { valid: true, data: newObj };
12765
+ } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
12766
+ if (a.length !== b.length) {
12767
+ return { valid: false };
12768
+ }
12769
+ const newArray = [];
12770
+ for (let index = 0;index < a.length; index++) {
12771
+ const itemA = a[index];
12772
+ const itemB = b[index];
12773
+ const sharedValue = mergeValues(itemA, itemB);
12774
+ if (!sharedValue.valid) {
12775
+ return { valid: false };
12776
+ }
12777
+ newArray.push(sharedValue.data);
12778
+ }
12779
+ return { valid: true, data: newArray };
12780
+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
12781
+ return { valid: true, data: a };
12782
+ } else {
12783
+ return { valid: false };
12784
+ }
12785
+ }
12786
+
12787
+ class ZodIntersection extends ZodType {
12788
+ _parse(input) {
12789
+ const { status, ctx } = this._processInputParams(input);
12790
+ const handleParsed = (parsedLeft, parsedRight) => {
12791
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
12792
+ return INVALID;
12793
+ }
12794
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
12795
+ if (!merged.valid) {
12796
+ addIssueToContext(ctx, {
12797
+ code: ZodIssueCode.invalid_intersection_types
12798
+ });
12799
+ return INVALID;
12800
+ }
12801
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
12802
+ status.dirty();
12803
+ }
12804
+ return { status: status.value, value: merged.data };
12805
+ };
12806
+ if (ctx.common.async) {
12807
+ return Promise.all([
12808
+ this._def.left._parseAsync({
12809
+ data: ctx.data,
12810
+ path: ctx.path,
12811
+ parent: ctx
12812
+ }),
12813
+ this._def.right._parseAsync({
12814
+ data: ctx.data,
12815
+ path: ctx.path,
12816
+ parent: ctx
12817
+ })
12818
+ ]).then(([left, right]) => handleParsed(left, right));
12819
+ } else {
12820
+ return handleParsed(this._def.left._parseSync({
12821
+ data: ctx.data,
12822
+ path: ctx.path,
12823
+ parent: ctx
12824
+ }), this._def.right._parseSync({
12825
+ data: ctx.data,
12826
+ path: ctx.path,
12827
+ parent: ctx
12828
+ }));
12829
+ }
12830
+ }
12831
+ }
12832
+ ZodIntersection.create = (left, right, params) => {
12833
+ return new ZodIntersection({
12834
+ left,
12835
+ right,
12836
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
12837
+ ...processCreateParams(params)
12838
+ });
12839
+ };
12840
+
12841
+ class ZodTuple extends ZodType {
12842
+ _parse(input) {
12843
+ const { status, ctx } = this._processInputParams(input);
12844
+ if (ctx.parsedType !== ZodParsedType.array) {
12845
+ addIssueToContext(ctx, {
12846
+ code: ZodIssueCode.invalid_type,
12847
+ expected: ZodParsedType.array,
12848
+ received: ctx.parsedType
12849
+ });
12850
+ return INVALID;
12851
+ }
12852
+ if (ctx.data.length < this._def.items.length) {
12853
+ addIssueToContext(ctx, {
12854
+ code: ZodIssueCode.too_small,
12855
+ minimum: this._def.items.length,
12856
+ inclusive: true,
12857
+ exact: false,
12858
+ type: "array"
12859
+ });
12860
+ return INVALID;
12861
+ }
12862
+ const rest = this._def.rest;
12863
+ if (!rest && ctx.data.length > this._def.items.length) {
12864
+ addIssueToContext(ctx, {
12865
+ code: ZodIssueCode.too_big,
12866
+ maximum: this._def.items.length,
12867
+ inclusive: true,
12868
+ exact: false,
12869
+ type: "array"
12870
+ });
12871
+ status.dirty();
12872
+ }
12873
+ const items = [...ctx.data].map((item, itemIndex) => {
12874
+ const schema2 = this._def.items[itemIndex] || this._def.rest;
12875
+ if (!schema2)
12876
+ return null;
12877
+ return schema2._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
12878
+ }).filter((x) => !!x);
12879
+ if (ctx.common.async) {
12880
+ return Promise.all(items).then((results) => {
12881
+ return ParseStatus.mergeArray(status, results);
12882
+ });
12883
+ } else {
12884
+ return ParseStatus.mergeArray(status, items);
12885
+ }
12886
+ }
12887
+ get items() {
12888
+ return this._def.items;
12889
+ }
12890
+ rest(rest) {
12891
+ return new ZodTuple({
12892
+ ...this._def,
12893
+ rest
12894
+ });
12895
+ }
12896
+ }
12897
+ ZodTuple.create = (schemas, params) => {
12898
+ if (!Array.isArray(schemas)) {
12899
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
12900
+ }
12901
+ return new ZodTuple({
12902
+ items: schemas,
12903
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
12904
+ rest: null,
12905
+ ...processCreateParams(params)
12906
+ });
12907
+ };
12908
+
12909
+ class ZodRecord extends ZodType {
12910
+ get keySchema() {
12911
+ return this._def.keyType;
12912
+ }
12913
+ get valueSchema() {
12914
+ return this._def.valueType;
12915
+ }
12916
+ _parse(input) {
12917
+ const { status, ctx } = this._processInputParams(input);
12918
+ if (ctx.parsedType !== ZodParsedType.object) {
12919
+ addIssueToContext(ctx, {
12920
+ code: ZodIssueCode.invalid_type,
12921
+ expected: ZodParsedType.object,
12922
+ received: ctx.parsedType
12923
+ });
12924
+ return INVALID;
12925
+ }
12926
+ const pairs = [];
12927
+ const keyType = this._def.keyType;
12928
+ const valueType = this._def.valueType;
12929
+ for (const key in ctx.data) {
12930
+ pairs.push({
12931
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
12932
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
12933
+ alwaysSet: key in ctx.data
12934
+ });
12935
+ }
12936
+ if (ctx.common.async) {
12937
+ return ParseStatus.mergeObjectAsync(status, pairs);
12938
+ } else {
12939
+ return ParseStatus.mergeObjectSync(status, pairs);
12940
+ }
12941
+ }
12942
+ get element() {
12943
+ return this._def.valueType;
12944
+ }
12945
+ static create(first, second, third) {
12946
+ if (second instanceof ZodType) {
12947
+ return new ZodRecord({
12948
+ keyType: first,
12949
+ valueType: second,
12950
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
12951
+ ...processCreateParams(third)
12952
+ });
12953
+ }
12954
+ return new ZodRecord({
12955
+ keyType: ZodString.create(),
12956
+ valueType: first,
12957
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
12958
+ ...processCreateParams(second)
12959
+ });
12960
+ }
12961
+ }
12962
+
12963
+ class ZodMap extends ZodType {
12964
+ get keySchema() {
12965
+ return this._def.keyType;
12966
+ }
12967
+ get valueSchema() {
12968
+ return this._def.valueType;
12969
+ }
12970
+ _parse(input) {
12971
+ const { status, ctx } = this._processInputParams(input);
12972
+ if (ctx.parsedType !== ZodParsedType.map) {
12973
+ addIssueToContext(ctx, {
12974
+ code: ZodIssueCode.invalid_type,
12975
+ expected: ZodParsedType.map,
12976
+ received: ctx.parsedType
12977
+ });
12978
+ return INVALID;
12979
+ }
12980
+ const keyType = this._def.keyType;
12981
+ const valueType = this._def.valueType;
12982
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
12983
+ return {
12984
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
12985
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
12986
+ };
12987
+ });
12988
+ if (ctx.common.async) {
12989
+ const finalMap = new Map;
12990
+ return Promise.resolve().then(async () => {
12991
+ for (const pair of pairs) {
12992
+ const key = await pair.key;
12993
+ const value = await pair.value;
12994
+ if (key.status === "aborted" || value.status === "aborted") {
12995
+ return INVALID;
12996
+ }
12997
+ if (key.status === "dirty" || value.status === "dirty") {
12998
+ status.dirty();
12999
+ }
13000
+ finalMap.set(key.value, value.value);
13001
+ }
13002
+ return { status: status.value, value: finalMap };
13003
+ });
13004
+ } else {
13005
+ const finalMap = new Map;
13006
+ for (const pair of pairs) {
13007
+ const key = pair.key;
13008
+ const value = pair.value;
13009
+ if (key.status === "aborted" || value.status === "aborted") {
13010
+ return INVALID;
13011
+ }
13012
+ if (key.status === "dirty" || value.status === "dirty") {
13013
+ status.dirty();
13014
+ }
13015
+ finalMap.set(key.value, value.value);
13016
+ }
13017
+ return { status: status.value, value: finalMap };
13018
+ }
13019
+ }
13020
+ }
13021
+ ZodMap.create = (keyType, valueType, params) => {
13022
+ return new ZodMap({
13023
+ valueType,
13024
+ keyType,
13025
+ typeName: ZodFirstPartyTypeKind.ZodMap,
13026
+ ...processCreateParams(params)
13027
+ });
13028
+ };
13029
+
13030
+ class ZodSet extends ZodType {
13031
+ _parse(input) {
13032
+ const { status, ctx } = this._processInputParams(input);
13033
+ if (ctx.parsedType !== ZodParsedType.set) {
13034
+ addIssueToContext(ctx, {
13035
+ code: ZodIssueCode.invalid_type,
13036
+ expected: ZodParsedType.set,
13037
+ received: ctx.parsedType
13038
+ });
13039
+ return INVALID;
13040
+ }
13041
+ const def = this._def;
13042
+ if (def.minSize !== null) {
13043
+ if (ctx.data.size < def.minSize.value) {
13044
+ addIssueToContext(ctx, {
13045
+ code: ZodIssueCode.too_small,
13046
+ minimum: def.minSize.value,
13047
+ type: "set",
13048
+ inclusive: true,
13049
+ exact: false,
13050
+ message: def.minSize.message
13051
+ });
13052
+ status.dirty();
13053
+ }
13054
+ }
13055
+ if (def.maxSize !== null) {
13056
+ if (ctx.data.size > def.maxSize.value) {
13057
+ addIssueToContext(ctx, {
13058
+ code: ZodIssueCode.too_big,
13059
+ maximum: def.maxSize.value,
13060
+ type: "set",
13061
+ inclusive: true,
13062
+ exact: false,
13063
+ message: def.maxSize.message
13064
+ });
13065
+ status.dirty();
13066
+ }
13067
+ }
13068
+ const valueType = this._def.valueType;
13069
+ function finalizeSet(elements2) {
13070
+ const parsedSet = new Set;
13071
+ for (const element of elements2) {
13072
+ if (element.status === "aborted")
13073
+ return INVALID;
13074
+ if (element.status === "dirty")
13075
+ status.dirty();
13076
+ parsedSet.add(element.value);
13077
+ }
13078
+ return { status: status.value, value: parsedSet };
13079
+ }
13080
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
13081
+ if (ctx.common.async) {
13082
+ return Promise.all(elements).then((elements2) => finalizeSet(elements2));
13083
+ } else {
13084
+ return finalizeSet(elements);
13085
+ }
13086
+ }
13087
+ min(minSize, message) {
13088
+ return new ZodSet({
13089
+ ...this._def,
13090
+ minSize: { value: minSize, message: errorUtil.toString(message) }
13091
+ });
13092
+ }
13093
+ max(maxSize, message) {
13094
+ return new ZodSet({
13095
+ ...this._def,
13096
+ maxSize: { value: maxSize, message: errorUtil.toString(message) }
13097
+ });
13098
+ }
13099
+ size(size, message) {
13100
+ return this.min(size, message).max(size, message);
13101
+ }
13102
+ nonempty(message) {
13103
+ return this.min(1, message);
13104
+ }
13105
+ }
13106
+ ZodSet.create = (valueType, params) => {
13107
+ return new ZodSet({
13108
+ valueType,
13109
+ minSize: null,
13110
+ maxSize: null,
13111
+ typeName: ZodFirstPartyTypeKind.ZodSet,
13112
+ ...processCreateParams(params)
13113
+ });
13114
+ };
13115
+
13116
+ class ZodFunction extends ZodType {
13117
+ constructor() {
13118
+ super(...arguments);
13119
+ this.validate = this.implement;
13120
+ }
13121
+ _parse(input) {
13122
+ const { ctx } = this._processInputParams(input);
13123
+ if (ctx.parsedType !== ZodParsedType.function) {
13124
+ addIssueToContext(ctx, {
13125
+ code: ZodIssueCode.invalid_type,
13126
+ expected: ZodParsedType.function,
13127
+ received: ctx.parsedType
13128
+ });
13129
+ return INVALID;
13130
+ }
13131
+ function makeArgsIssue(args, error) {
13132
+ return makeIssue({
13133
+ data: args,
13134
+ path: ctx.path,
13135
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
13136
+ issueData: {
13137
+ code: ZodIssueCode.invalid_arguments,
13138
+ argumentsError: error
13139
+ }
13140
+ });
13141
+ }
13142
+ function makeReturnsIssue(returns, error) {
13143
+ return makeIssue({
13144
+ data: returns,
13145
+ path: ctx.path,
13146
+ errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
13147
+ issueData: {
13148
+ code: ZodIssueCode.invalid_return_type,
13149
+ returnTypeError: error
13150
+ }
13151
+ });
13152
+ }
13153
+ const params = { errorMap: ctx.common.contextualErrorMap };
13154
+ const fn = ctx.data;
13155
+ if (this._def.returns instanceof ZodPromise) {
13156
+ const me = this;
13157
+ return OK(async function(...args) {
13158
+ const error = new ZodError([]);
13159
+ const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
13160
+ error.addIssue(makeArgsIssue(args, e));
13161
+ throw error;
13162
+ });
13163
+ const result = await Reflect.apply(fn, this, parsedArgs);
13164
+ const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
13165
+ error.addIssue(makeReturnsIssue(result, e));
13166
+ throw error;
13167
+ });
13168
+ return parsedReturns;
13169
+ });
13170
+ } else {
13171
+ const me = this;
13172
+ return OK(function(...args) {
13173
+ const parsedArgs = me._def.args.safeParse(args, params);
13174
+ if (!parsedArgs.success) {
13175
+ throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
13176
+ }
13177
+ const result = Reflect.apply(fn, this, parsedArgs.data);
13178
+ const parsedReturns = me._def.returns.safeParse(result, params);
13179
+ if (!parsedReturns.success) {
13180
+ throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
13181
+ }
13182
+ return parsedReturns.data;
13183
+ });
13184
+ }
13185
+ }
13186
+ parameters() {
13187
+ return this._def.args;
13188
+ }
13189
+ returnType() {
13190
+ return this._def.returns;
13191
+ }
13192
+ args(...items) {
13193
+ return new ZodFunction({
13194
+ ...this._def,
13195
+ args: ZodTuple.create(items).rest(ZodUnknown.create())
13196
+ });
13197
+ }
13198
+ returns(returnType) {
13199
+ return new ZodFunction({
13200
+ ...this._def,
13201
+ returns: returnType
13202
+ });
13203
+ }
13204
+ implement(func) {
13205
+ const validatedFunc = this.parse(func);
13206
+ return validatedFunc;
13207
+ }
13208
+ strictImplement(func) {
13209
+ const validatedFunc = this.parse(func);
13210
+ return validatedFunc;
13211
+ }
13212
+ static create(args, returns, params) {
13213
+ return new ZodFunction({
13214
+ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
13215
+ returns: returns || ZodUnknown.create(),
13216
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
13217
+ ...processCreateParams(params)
13218
+ });
13219
+ }
13220
+ }
13221
+
13222
+ class ZodLazy extends ZodType {
13223
+ get schema() {
13224
+ return this._def.getter();
13225
+ }
13226
+ _parse(input) {
13227
+ const { ctx } = this._processInputParams(input);
13228
+ const lazySchema = this._def.getter();
13229
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
13230
+ }
13231
+ }
13232
+ ZodLazy.create = (getter, params) => {
13233
+ return new ZodLazy({
13234
+ getter,
13235
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
13236
+ ...processCreateParams(params)
13237
+ });
13238
+ };
13239
+
13240
+ class ZodLiteral extends ZodType {
13241
+ _parse(input) {
13242
+ if (input.data !== this._def.value) {
13243
+ const ctx = this._getOrReturnCtx(input);
13244
+ addIssueToContext(ctx, {
13245
+ received: ctx.data,
13246
+ code: ZodIssueCode.invalid_literal,
13247
+ expected: this._def.value
13248
+ });
13249
+ return INVALID;
13250
+ }
13251
+ return { status: "valid", value: input.data };
13252
+ }
13253
+ get value() {
13254
+ return this._def.value;
13255
+ }
13256
+ }
13257
+ ZodLiteral.create = (value, params) => {
13258
+ return new ZodLiteral({
13259
+ value,
13260
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
13261
+ ...processCreateParams(params)
13262
+ });
13263
+ };
13264
+ function createZodEnum(values, params) {
13265
+ return new ZodEnum({
13266
+ values,
13267
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
13268
+ ...processCreateParams(params)
13269
+ });
13270
+ }
13271
+
13272
+ class ZodEnum extends ZodType {
13273
+ _parse(input) {
13274
+ if (typeof input.data !== "string") {
13275
+ const ctx = this._getOrReturnCtx(input);
13276
+ const expectedValues = this._def.values;
13277
+ addIssueToContext(ctx, {
13278
+ expected: util.joinValues(expectedValues),
13279
+ received: ctx.parsedType,
13280
+ code: ZodIssueCode.invalid_type
13281
+ });
13282
+ return INVALID;
13283
+ }
13284
+ if (!this._cache) {
13285
+ this._cache = new Set(this._def.values);
13286
+ }
13287
+ if (!this._cache.has(input.data)) {
13288
+ const ctx = this._getOrReturnCtx(input);
13289
+ const expectedValues = this._def.values;
13290
+ addIssueToContext(ctx, {
13291
+ received: ctx.data,
13292
+ code: ZodIssueCode.invalid_enum_value,
13293
+ options: expectedValues
13294
+ });
13295
+ return INVALID;
13296
+ }
13297
+ return OK(input.data);
13298
+ }
13299
+ get options() {
13300
+ return this._def.values;
13301
+ }
13302
+ get enum() {
13303
+ const enumValues = {};
13304
+ for (const val of this._def.values) {
13305
+ enumValues[val] = val;
13306
+ }
13307
+ return enumValues;
13308
+ }
13309
+ get Values() {
13310
+ const enumValues = {};
13311
+ for (const val of this._def.values) {
13312
+ enumValues[val] = val;
13313
+ }
13314
+ return enumValues;
13315
+ }
13316
+ get Enum() {
13317
+ const enumValues = {};
13318
+ for (const val of this._def.values) {
13319
+ enumValues[val] = val;
13320
+ }
13321
+ return enumValues;
13322
+ }
13323
+ extract(values, newDef = this._def) {
13324
+ return ZodEnum.create(values, {
13325
+ ...this._def,
13326
+ ...newDef
13327
+ });
13328
+ }
13329
+ exclude(values, newDef = this._def) {
13330
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
13331
+ ...this._def,
13332
+ ...newDef
13333
+ });
13334
+ }
13335
+ }
13336
+ ZodEnum.create = createZodEnum;
13337
+
13338
+ class ZodNativeEnum extends ZodType {
13339
+ _parse(input) {
13340
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
13341
+ const ctx = this._getOrReturnCtx(input);
13342
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
13343
+ const expectedValues = util.objectValues(nativeEnumValues);
13344
+ addIssueToContext(ctx, {
13345
+ expected: util.joinValues(expectedValues),
13346
+ received: ctx.parsedType,
13347
+ code: ZodIssueCode.invalid_type
13348
+ });
13349
+ return INVALID;
13350
+ }
13351
+ if (!this._cache) {
13352
+ this._cache = new Set(util.getValidEnumValues(this._def.values));
13353
+ }
13354
+ if (!this._cache.has(input.data)) {
13355
+ const expectedValues = util.objectValues(nativeEnumValues);
13356
+ addIssueToContext(ctx, {
13357
+ received: ctx.data,
13358
+ code: ZodIssueCode.invalid_enum_value,
13359
+ options: expectedValues
13360
+ });
13361
+ return INVALID;
13362
+ }
13363
+ return OK(input.data);
13364
+ }
13365
+ get enum() {
13366
+ return this._def.values;
13367
+ }
13368
+ }
13369
+ ZodNativeEnum.create = (values, params) => {
13370
+ return new ZodNativeEnum({
13371
+ values,
13372
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
13373
+ ...processCreateParams(params)
13374
+ });
13375
+ };
13376
+
13377
+ class ZodPromise extends ZodType {
13378
+ unwrap() {
13379
+ return this._def.type;
13380
+ }
13381
+ _parse(input) {
13382
+ const { ctx } = this._processInputParams(input);
13383
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
13384
+ addIssueToContext(ctx, {
13385
+ code: ZodIssueCode.invalid_type,
13386
+ expected: ZodParsedType.promise,
13387
+ received: ctx.parsedType
13388
+ });
13389
+ return INVALID;
13390
+ }
13391
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
13392
+ return OK(promisified.then((data) => {
13393
+ return this._def.type.parseAsync(data, {
13394
+ path: ctx.path,
13395
+ errorMap: ctx.common.contextualErrorMap
13396
+ });
13397
+ }));
13398
+ }
13399
+ }
13400
+ ZodPromise.create = (schema2, params) => {
13401
+ return new ZodPromise({
13402
+ type: schema2,
13403
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
13404
+ ...processCreateParams(params)
13405
+ });
13406
+ };
13407
+
13408
+ class ZodEffects extends ZodType {
13409
+ innerType() {
13410
+ return this._def.schema;
13411
+ }
13412
+ sourceType() {
13413
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
13414
+ }
13415
+ _parse(input) {
13416
+ const { status, ctx } = this._processInputParams(input);
13417
+ const effect = this._def.effect || null;
13418
+ const checkCtx = {
13419
+ addIssue: (arg) => {
13420
+ addIssueToContext(ctx, arg);
13421
+ if (arg.fatal) {
13422
+ status.abort();
13423
+ } else {
13424
+ status.dirty();
13425
+ }
13426
+ },
13427
+ get path() {
13428
+ return ctx.path;
13429
+ }
13430
+ };
13431
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
13432
+ if (effect.type === "preprocess") {
13433
+ const processed = effect.transform(ctx.data, checkCtx);
13434
+ if (ctx.common.async) {
13435
+ return Promise.resolve(processed).then(async (processed2) => {
13436
+ if (status.value === "aborted")
13437
+ return INVALID;
13438
+ const result = await this._def.schema._parseAsync({
13439
+ data: processed2,
13440
+ path: ctx.path,
13441
+ parent: ctx
13442
+ });
13443
+ if (result.status === "aborted")
13444
+ return INVALID;
13445
+ if (result.status === "dirty")
13446
+ return DIRTY(result.value);
13447
+ if (status.value === "dirty")
13448
+ return DIRTY(result.value);
13449
+ return result;
13450
+ });
13451
+ } else {
13452
+ if (status.value === "aborted")
13453
+ return INVALID;
13454
+ const result = this._def.schema._parseSync({
13455
+ data: processed,
13456
+ path: ctx.path,
13457
+ parent: ctx
13458
+ });
13459
+ if (result.status === "aborted")
13460
+ return INVALID;
13461
+ if (result.status === "dirty")
13462
+ return DIRTY(result.value);
13463
+ if (status.value === "dirty")
13464
+ return DIRTY(result.value);
13465
+ return result;
13466
+ }
13467
+ }
13468
+ if (effect.type === "refinement") {
13469
+ const executeRefinement = (acc) => {
13470
+ const result = effect.refinement(acc, checkCtx);
13471
+ if (ctx.common.async) {
13472
+ return Promise.resolve(result);
13473
+ }
13474
+ if (result instanceof Promise) {
13475
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
13476
+ }
13477
+ return acc;
13478
+ };
13479
+ if (ctx.common.async === false) {
13480
+ const inner = this._def.schema._parseSync({
13481
+ data: ctx.data,
13482
+ path: ctx.path,
13483
+ parent: ctx
13484
+ });
13485
+ if (inner.status === "aborted")
13486
+ return INVALID;
13487
+ if (inner.status === "dirty")
13488
+ status.dirty();
13489
+ executeRefinement(inner.value);
13490
+ return { status: status.value, value: inner.value };
13491
+ } else {
13492
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
13493
+ if (inner.status === "aborted")
13494
+ return INVALID;
13495
+ if (inner.status === "dirty")
13496
+ status.dirty();
13497
+ return executeRefinement(inner.value).then(() => {
13498
+ return { status: status.value, value: inner.value };
13499
+ });
13500
+ });
13501
+ }
13502
+ }
13503
+ if (effect.type === "transform") {
13504
+ if (ctx.common.async === false) {
13505
+ const base = this._def.schema._parseSync({
13506
+ data: ctx.data,
13507
+ path: ctx.path,
13508
+ parent: ctx
13509
+ });
13510
+ if (!isValid(base))
13511
+ return INVALID;
13512
+ const result = effect.transform(base.value, checkCtx);
13513
+ if (result instanceof Promise) {
13514
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
13515
+ }
13516
+ return { status: status.value, value: result };
13517
+ } else {
13518
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
13519
+ if (!isValid(base))
13520
+ return INVALID;
13521
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
13522
+ status: status.value,
13523
+ value: result
13524
+ }));
13525
+ });
13526
+ }
13527
+ }
13528
+ util.assertNever(effect);
13529
+ }
13530
+ }
13531
+ ZodEffects.create = (schema2, effect, params) => {
13532
+ return new ZodEffects({
13533
+ schema: schema2,
13534
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
13535
+ effect,
13536
+ ...processCreateParams(params)
13537
+ });
13538
+ };
13539
+ ZodEffects.createWithPreprocess = (preprocess, schema2, params) => {
13540
+ return new ZodEffects({
13541
+ schema: schema2,
13542
+ effect: { type: "preprocess", transform: preprocess },
13543
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
13544
+ ...processCreateParams(params)
13545
+ });
13546
+ };
13547
+ class ZodOptional extends ZodType {
13548
+ _parse(input) {
13549
+ const parsedType = this._getType(input);
13550
+ if (parsedType === ZodParsedType.undefined) {
13551
+ return OK(undefined);
13552
+ }
13553
+ return this._def.innerType._parse(input);
13554
+ }
13555
+ unwrap() {
13556
+ return this._def.innerType;
13557
+ }
13558
+ }
13559
+ ZodOptional.create = (type, params) => {
13560
+ return new ZodOptional({
13561
+ innerType: type,
13562
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
13563
+ ...processCreateParams(params)
13564
+ });
13565
+ };
13566
+
13567
+ class ZodNullable extends ZodType {
13568
+ _parse(input) {
13569
+ const parsedType = this._getType(input);
13570
+ if (parsedType === ZodParsedType.null) {
13571
+ return OK(null);
13572
+ }
13573
+ return this._def.innerType._parse(input);
13574
+ }
13575
+ unwrap() {
13576
+ return this._def.innerType;
13577
+ }
13578
+ }
13579
+ ZodNullable.create = (type, params) => {
13580
+ return new ZodNullable({
13581
+ innerType: type,
13582
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
13583
+ ...processCreateParams(params)
13584
+ });
13585
+ };
13586
+
13587
+ class ZodDefault extends ZodType {
13588
+ _parse(input) {
13589
+ const { ctx } = this._processInputParams(input);
13590
+ let data = ctx.data;
13591
+ if (ctx.parsedType === ZodParsedType.undefined) {
13592
+ data = this._def.defaultValue();
13593
+ }
13594
+ return this._def.innerType._parse({
13595
+ data,
13596
+ path: ctx.path,
13597
+ parent: ctx
13598
+ });
13599
+ }
13600
+ removeDefault() {
13601
+ return this._def.innerType;
13602
+ }
13603
+ }
13604
+ ZodDefault.create = (type, params) => {
13605
+ return new ZodDefault({
13606
+ innerType: type,
13607
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
13608
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
13609
+ ...processCreateParams(params)
13610
+ });
13611
+ };
13612
+
13613
+ class ZodCatch extends ZodType {
13614
+ _parse(input) {
13615
+ const { ctx } = this._processInputParams(input);
13616
+ const newCtx = {
13617
+ ...ctx,
13618
+ common: {
13619
+ ...ctx.common,
13620
+ issues: []
13621
+ }
13622
+ };
13623
+ const result = this._def.innerType._parse({
13624
+ data: newCtx.data,
13625
+ path: newCtx.path,
13626
+ parent: {
13627
+ ...newCtx
13628
+ }
13629
+ });
13630
+ if (isAsync(result)) {
13631
+ return result.then((result2) => {
13632
+ return {
13633
+ status: "valid",
13634
+ value: result2.status === "valid" ? result2.value : this._def.catchValue({
13635
+ get error() {
13636
+ return new ZodError(newCtx.common.issues);
13637
+ },
13638
+ input: newCtx.data
13639
+ })
13640
+ };
13641
+ });
13642
+ } else {
13643
+ return {
13644
+ status: "valid",
13645
+ value: result.status === "valid" ? result.value : this._def.catchValue({
13646
+ get error() {
13647
+ return new ZodError(newCtx.common.issues);
13648
+ },
13649
+ input: newCtx.data
13650
+ })
13651
+ };
13652
+ }
13653
+ }
13654
+ removeCatch() {
13655
+ return this._def.innerType;
13656
+ }
13657
+ }
13658
+ ZodCatch.create = (type, params) => {
13659
+ return new ZodCatch({
13660
+ innerType: type,
13661
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
13662
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
13663
+ ...processCreateParams(params)
13664
+ });
13665
+ };
13666
+
13667
+ class ZodNaN extends ZodType {
13668
+ _parse(input) {
13669
+ const parsedType = this._getType(input);
13670
+ if (parsedType !== ZodParsedType.nan) {
13671
+ const ctx = this._getOrReturnCtx(input);
13672
+ addIssueToContext(ctx, {
13673
+ code: ZodIssueCode.invalid_type,
13674
+ expected: ZodParsedType.nan,
13675
+ received: ctx.parsedType
13676
+ });
13677
+ return INVALID;
13678
+ }
13679
+ return { status: "valid", value: input.data };
13680
+ }
13681
+ }
13682
+ ZodNaN.create = (params) => {
13683
+ return new ZodNaN({
13684
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
13685
+ ...processCreateParams(params)
13686
+ });
13687
+ };
13688
+ var BRAND = Symbol("zod_brand");
13689
+
13690
+ class ZodBranded extends ZodType {
13691
+ _parse(input) {
13692
+ const { ctx } = this._processInputParams(input);
13693
+ const data = ctx.data;
13694
+ return this._def.type._parse({
13695
+ data,
13696
+ path: ctx.path,
13697
+ parent: ctx
13698
+ });
13699
+ }
13700
+ unwrap() {
13701
+ return this._def.type;
13702
+ }
13703
+ }
13704
+
13705
+ class ZodPipeline extends ZodType {
13706
+ _parse(input) {
13707
+ const { status, ctx } = this._processInputParams(input);
13708
+ if (ctx.common.async) {
13709
+ const handleAsync = async () => {
13710
+ const inResult = await this._def.in._parseAsync({
13711
+ data: ctx.data,
13712
+ path: ctx.path,
13713
+ parent: ctx
13714
+ });
13715
+ if (inResult.status === "aborted")
13716
+ return INVALID;
13717
+ if (inResult.status === "dirty") {
13718
+ status.dirty();
13719
+ return DIRTY(inResult.value);
13720
+ } else {
13721
+ return this._def.out._parseAsync({
13722
+ data: inResult.value,
13723
+ path: ctx.path,
13724
+ parent: ctx
13725
+ });
13726
+ }
13727
+ };
13728
+ return handleAsync();
13729
+ } else {
13730
+ const inResult = this._def.in._parseSync({
13731
+ data: ctx.data,
13732
+ path: ctx.path,
13733
+ parent: ctx
13734
+ });
13735
+ if (inResult.status === "aborted")
13736
+ return INVALID;
13737
+ if (inResult.status === "dirty") {
13738
+ status.dirty();
13739
+ return {
13740
+ status: "dirty",
13741
+ value: inResult.value
13742
+ };
13743
+ } else {
13744
+ return this._def.out._parseSync({
13745
+ data: inResult.value,
13746
+ path: ctx.path,
13747
+ parent: ctx
13748
+ });
13749
+ }
13750
+ }
13751
+ }
13752
+ static create(a, b) {
13753
+ return new ZodPipeline({
13754
+ in: a,
13755
+ out: b,
13756
+ typeName: ZodFirstPartyTypeKind.ZodPipeline
13757
+ });
13758
+ }
13759
+ }
13760
+
13761
+ class ZodReadonly extends ZodType {
13762
+ _parse(input) {
13763
+ const result = this._def.innerType._parse(input);
13764
+ const freeze = (data) => {
13765
+ if (isValid(data)) {
13766
+ data.value = Object.freeze(data.value);
13767
+ }
13768
+ return data;
13769
+ };
13770
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
13771
+ }
13772
+ unwrap() {
13773
+ return this._def.innerType;
13774
+ }
13775
+ }
13776
+ ZodReadonly.create = (type, params) => {
13777
+ return new ZodReadonly({
13778
+ innerType: type,
13779
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
13780
+ ...processCreateParams(params)
13781
+ });
13782
+ };
13783
+ function cleanParams(params, data) {
13784
+ const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
13785
+ const p2 = typeof p === "string" ? { message: p } : p;
13786
+ return p2;
13787
+ }
13788
+ function custom(check, _params = {}, fatal) {
13789
+ if (check)
13790
+ return ZodAny.create().superRefine((data, ctx) => {
13791
+ const r = check(data);
13792
+ if (r instanceof Promise) {
13793
+ return r.then((r2) => {
13794
+ if (!r2) {
13795
+ const params = cleanParams(_params, data);
13796
+ const _fatal = params.fatal ?? fatal ?? true;
13797
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
13798
+ }
13799
+ });
13800
+ }
13801
+ if (!r) {
13802
+ const params = cleanParams(_params, data);
13803
+ const _fatal = params.fatal ?? fatal ?? true;
13804
+ ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
13805
+ }
13806
+ return;
13807
+ });
13808
+ return ZodAny.create();
13809
+ }
13810
+ var late = {
13811
+ object: ZodObject.lazycreate
13812
+ };
13813
+ var ZodFirstPartyTypeKind;
13814
+ (function(ZodFirstPartyTypeKind2) {
13815
+ ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
13816
+ ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
13817
+ ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
13818
+ ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
13819
+ ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
13820
+ ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
13821
+ ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
13822
+ ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
13823
+ ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
13824
+ ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
13825
+ ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
13826
+ ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
13827
+ ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
13828
+ ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
13829
+ ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
13830
+ ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
13831
+ ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
13832
+ ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
13833
+ ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
13834
+ ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
13835
+ ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
13836
+ ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
13837
+ ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
13838
+ ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
13839
+ ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
13840
+ ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
13841
+ ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
13842
+ ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
13843
+ ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
13844
+ ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
13845
+ ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
13846
+ ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
13847
+ ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
13848
+ ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
13849
+ ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
13850
+ ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
13851
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
13852
+ var instanceOfType = (cls, params = {
13853
+ message: `Input not instance of ${cls.name}`
13854
+ }) => custom((data) => data instanceof cls, params);
13855
+ var stringType = ZodString.create;
13856
+ var numberType = ZodNumber.create;
13857
+ var nanType = ZodNaN.create;
13858
+ var bigIntType = ZodBigInt.create;
13859
+ var booleanType = ZodBoolean.create;
13860
+ var dateType = ZodDate.create;
13861
+ var symbolType = ZodSymbol.create;
13862
+ var undefinedType = ZodUndefined.create;
13863
+ var nullType = ZodNull.create;
13864
+ var anyType = ZodAny.create;
13865
+ var unknownType = ZodUnknown.create;
13866
+ var neverType = ZodNever.create;
13867
+ var voidType = ZodVoid.create;
13868
+ var arrayType = ZodArray.create;
13869
+ var objectType = ZodObject.create;
13870
+ var strictObjectType = ZodObject.strictCreate;
13871
+ var unionType = ZodUnion.create;
13872
+ var discriminatedUnionType = ZodDiscriminatedUnion.create;
13873
+ var intersectionType = ZodIntersection.create;
13874
+ var tupleType = ZodTuple.create;
13875
+ var recordType = ZodRecord.create;
13876
+ var mapType = ZodMap.create;
13877
+ var setType = ZodSet.create;
13878
+ var functionType = ZodFunction.create;
13879
+ var lazyType = ZodLazy.create;
13880
+ var literalType = ZodLiteral.create;
13881
+ var enumType = ZodEnum.create;
13882
+ var nativeEnumType = ZodNativeEnum.create;
13883
+ var promiseType = ZodPromise.create;
13884
+ var effectsType = ZodEffects.create;
13885
+ var optionalType = ZodOptional.create;
13886
+ var nullableType = ZodNullable.create;
13887
+ var preprocessType = ZodEffects.createWithPreprocess;
13888
+ var pipelineType = ZodPipeline.create;
13889
+ var ostring = () => stringType().optional();
13890
+ var onumber = () => numberType().optional();
13891
+ var oboolean = () => booleanType().optional();
13892
+ var coerce = {
13893
+ string: (arg) => ZodString.create({ ...arg, coerce: true }),
13894
+ number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
13895
+ boolean: (arg) => ZodBoolean.create({
13896
+ ...arg,
13897
+ coerce: true
13898
+ }),
13899
+ bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
13900
+ date: (arg) => ZodDate.create({ ...arg, coerce: true })
13901
+ };
13902
+ var NEVER = INVALID;
13903
+ // src/lib/schemas.ts
13904
+ var ProviderSchema = exports_external.enum(["openai", "thinker-labs"], {
13905
+ errorMap: () => ({ message: "Invalid provider. Must be one of: openai, thinker-labs" })
13906
+ });
13907
+ var FinetuneStartSchema = exports_external.object({
13908
+ provider: ProviderSchema,
13909
+ baseModel: exports_external.string().min(1, "Base model is required"),
13910
+ dataset: exports_external.string().optional(),
13911
+ name: exports_external.string().min(1, "Name is required")
13912
+ });
13913
+ var GatherOptionsSchema = exports_external.object({
13914
+ source: exports_external.enum(["todos", "mementos", "conversations", "sessions", "all"]).default("all"),
13915
+ output: exports_external.string().optional(),
13916
+ limit: exports_external.coerce.number().int().positive("Limit must be a positive integer").default(500)
13917
+ });
13918
+ var ModelUpdateSchema = exports_external.object({
13919
+ displayName: exports_external.string().optional(),
13920
+ description: exports_external.string().optional(),
13921
+ collection: exports_external.string().optional(),
13922
+ tags: exports_external.array(exports_external.string()).optional()
13923
+ });
13924
+ var McpGatherSchema = exports_external.object({
13925
+ sources: exports_external.array(exports_external.enum(["todos", "mementos", "conversations", "sessions"])).min(1, "At least one source required"),
13926
+ limit: exports_external.number().int().positive().optional(),
13927
+ output_dir: exports_external.string().optional()
13928
+ });
13929
+ var McpFinetuneStartSchema = exports_external.object({
13930
+ provider: ProviderSchema,
13931
+ base_model: exports_external.string().min(1, "Base model is required"),
13932
+ dataset_path: exports_external.string().optional(),
13933
+ name: exports_external.string().optional()
13934
+ });
13935
+ var McpFinetuneStatusSchema = exports_external.object({
13936
+ job_id: exports_external.string().min(1, "Job ID is required"),
13937
+ provider: ProviderSchema
13938
+ });
13939
+
13940
+ // src/mcp/index.ts
13941
+ function getProvider(provider) {
13942
+ if (provider === "openai")
13943
+ return new OpenAIProvider;
13944
+ if (provider === "thinker-labs")
13945
+ return new ThinkerLabsProvider;
13946
+ throw new Error(`Unknown provider: ${provider}`);
13947
+ }
13948
+ function defaultOutputDir() {
13949
+ return resolve3(homedir7(), ".brains", "datasets");
13950
+ }
13951
+ var MCP_SERVER_INFO = {
13952
+ name: "brains",
13953
+ version: getPackageVersion()
13954
+ };
13955
+ function createMcpServer() {
13956
+ const server = new Server(MCP_SERVER_INFO, { capabilities: { tools: {} } });
13957
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
13958
+ tools: [
13959
+ {
13960
+ name: "list_models",
13961
+ description: "List all fine-tuned models tracked in the local DB",
13962
+ inputSchema: {
13963
+ type: "object",
13964
+ properties: {},
13965
+ required: []
13966
+ }
13967
+ },
13968
+ {
13969
+ name: "get_model",
13970
+ description: "Get details for a specific fine-tuned model",
13971
+ inputSchema: {
13972
+ type: "object",
13973
+ properties: {
13974
+ model_id: { type: "string", description: "Model ID" }
13975
+ },
13976
+ required: ["model_id"]
13977
+ }
13978
+ },
13979
+ {
13980
+ name: "start_finetune",
13981
+ description: "Upload a training file and start a fine-tuning job",
13982
+ inputSchema: {
13983
+ type: "object",
13984
+ properties: {
9590
13985
  provider: {
9591
13986
  type: "string",
9592
13987
  enum: ["openai", "thinker-labs"],
@@ -9598,14 +13993,14 @@ function createMcpServer() {
9598
13993
  },
9599
13994
  dataset_path: {
9600
13995
  type: "string",
9601
- description: "Absolute path to the JSONL training file"
13996
+ description: "Absolute path to the JSONL training file (auto-detects latest if omitted)"
9602
13997
  },
9603
13998
  name: {
9604
13999
  type: "string",
9605
14000
  description: "Optional friendly name for this model"
9606
14001
  }
9607
14002
  },
9608
- required: ["provider", "base_model", "dataset_path"]
14003
+ required: ["provider", "base_model"]
9609
14004
  }
9610
14005
  },
9611
14006
  {
@@ -9707,14 +14102,26 @@ function createMcpServer() {
9707
14102
  };
9708
14103
  }
9709
14104
  case "start_finetune": {
9710
- const {
9711
- provider,
9712
- base_model,
9713
- dataset_path,
9714
- name: modelName
9715
- } = args;
9716
- const resolvedPath = resolve2(dataset_path);
9717
- if (!existsSync2(resolvedPath)) {
14105
+ const parsed = McpFinetuneStartSchema.safeParse(args);
14106
+ if (!parsed.success) {
14107
+ return { content: [{ type: "text", text: parsed.error.issues.map((i) => i.message).join("; ") }], isError: true };
14108
+ }
14109
+ const { provider, base_model, dataset_path, name: modelName } = parsed.data;
14110
+ let resolvedPath;
14111
+ if (dataset_path) {
14112
+ resolvedPath = resolve3(dataset_path);
14113
+ } else {
14114
+ const db2 = getDb();
14115
+ const [latest] = await db2.select().from(trainingDatasets).orderBy(desc(trainingDatasets.createdAt)).limit(1);
14116
+ if (!latest?.filePath) {
14117
+ return {
14118
+ content: [{ type: "text", text: "No datasets found. Run gather_training_data first." }],
14119
+ isError: true
14120
+ };
14121
+ }
14122
+ resolvedPath = latest.filePath;
14123
+ }
14124
+ if (!existsSync5(resolvedPath)) {
9718
14125
  return {
9719
14126
  content: [
9720
14127
  {
@@ -9751,7 +14158,11 @@ function createMcpServer() {
9751
14158
  };
9752
14159
  }
9753
14160
  case "get_finetune_status": {
9754
- const { job_id, provider } = args;
14161
+ const parsed = McpFinetuneStatusSchema.safeParse(args);
14162
+ if (!parsed.success) {
14163
+ return { content: [{ type: "text", text: parsed.error.issues.map((i) => i.message).join("; ") }], isError: true };
14164
+ }
14165
+ const { job_id, provider } = parsed.data;
9755
14166
  const p = getProvider(provider);
9756
14167
  const result = await p.getFineTuneStatus(job_id);
9757
14168
  const db = getDb();
@@ -9789,15 +14200,15 @@ function createMcpServer() {
9789
14200
  };
9790
14201
  }
9791
14202
  case "gather_training_data": {
9792
- const {
9793
- sources,
9794
- limit: limit2,
9795
- output_dir
9796
- } = args;
9797
- const { mkdirSync: mkdirSync2, writeFileSync } = await import("fs");
9798
- const { join: join3 } = await import("path");
14203
+ const parsed = McpGatherSchema.safeParse(args);
14204
+ if (!parsed.success) {
14205
+ return { content: [{ type: "text", text: parsed.error.issues.map((i) => i.message).join("; ") }], isError: true };
14206
+ }
14207
+ const { sources, limit: limit2, output_dir } = parsed.data;
14208
+ const { mkdirSync: mkdirSync3, writeFileSync: writeFileSync2 } = await import("fs");
14209
+ const { join: join7 } = await import("path");
9799
14210
  const outDir = output_dir ?? defaultOutputDir();
9800
- mkdirSync2(outDir, { recursive: true });
14211
+ mkdirSync3(outDir, { recursive: true });
9801
14212
  const datasets = [];
9802
14213
  let totalExamples = 0;
9803
14214
  for (const source of sources) {
@@ -9805,13 +14216,22 @@ function createMcpServer() {
9805
14216
  if (source === "todos") {
9806
14217
  const result = await gatherFromTodos({ limit: limit2 });
9807
14218
  examples = result.examples;
14219
+ } else if (source === "mementos") {
14220
+ const result = await gatherFromMementos({ limit: limit2 });
14221
+ examples = result.examples;
14222
+ } else if (source === "conversations") {
14223
+ const result = await gatherFromConversations({ limit: limit2 });
14224
+ examples = result.examples;
14225
+ } else if (source === "sessions") {
14226
+ const result = await gatherFromSessions({ limit: limit2 });
14227
+ examples = result.examples;
9808
14228
  } else {
9809
14229
  examples = [];
9810
14230
  }
9811
- const filePath = join3(outDir, `${source}-${Date.now()}.jsonl`);
14231
+ const filePath = join7(outDir, `${source}-${Date.now()}.jsonl`);
9812
14232
  const jsonl = examples.map((ex) => JSON.stringify(ex)).join(`
9813
14233
  `);
9814
- writeFileSync(filePath, jsonl, "utf-8");
14234
+ writeFileSync2(filePath, jsonl, "utf-8");
9815
14235
  datasets.push({ source, count: examples.length, file_path: filePath });
9816
14236
  totalExamples += examples.length;
9817
14237
  }
@@ -9826,8 +14246,8 @@ function createMcpServer() {
9826
14246
  }
9827
14247
  case "preview_training_data": {
9828
14248
  const { file_path, limit: limit2 = 5 } = args;
9829
- const resolvedPath = resolve2(file_path);
9830
- if (!existsSync2(resolvedPath)) {
14249
+ const resolvedPath = resolve3(file_path);
14250
+ if (!existsSync5(resolvedPath)) {
9831
14251
  return {
9832
14252
  content: [
9833
14253
  { type: "text", text: `File not found: ${resolvedPath}` }
@@ -9835,7 +14255,7 @@ function createMcpServer() {
9835
14255
  isError: true
9836
14256
  };
9837
14257
  }
9838
- const content = readFileSync3(resolvedPath, "utf-8");
14258
+ const content = readFileSync4(resolvedPath, "utf-8");
9839
14259
  const lines = content.split(`
9840
14260
  `).map((l) => l.trim()).filter(Boolean);
9841
14261
  const total = lines.length;