@tankpkg/cli 0.0.0-nightly.20260707.fa8ec41 → 0.0.0-nightly.20261102.dea0b15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/tank.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as VERSION, i as USER_AGENT, l as setConfig, n as flushLogs, o as getConfig, s as getConfigDir, t as authFlowLog } from "../debug-logger-CxLLfU5D.js";
2
+ import { a as VERSION, i as USER_AGENT, l as setConfig, n as flushLogs, o as getConfig, s as getConfigDir, t as authFlowLog } from "../debug-logger-Dcz0ytwe.js";
3
3
  import { t as logger } from "../logger-BhULz3Uz.js";
4
4
  import { createRequire } from "node:module";
5
5
  import { Command } from "commander";
@@ -3178,79 +3178,33 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
3178
3178
  value: mod,
3179
3179
  enumerable: true
3180
3180
  }) : target, mod));
3181
- Object.freeze({ status: "aborted" });
3182
- function $constructor(name, initializer, params) {
3183
- function init(inst, def) {
3184
- if (!inst._zod) Object.defineProperty(inst, "_zod", {
3185
- value: {
3186
- def,
3187
- constr: _,
3188
- traits: /* @__PURE__ */ new Set()
3189
- },
3190
- enumerable: false
3191
- });
3192
- if (inst._zod.traits.has(name)) return;
3193
- inst._zod.traits.add(name);
3194
- initializer(inst, def);
3195
- const proto = _.prototype;
3196
- const keys = Object.keys(proto);
3197
- for (let i = 0; i < keys.length; i++) {
3198
- const k = keys[i];
3199
- if (!(k in inst)) inst[k] = proto[k].bind(inst);
3200
- }
3201
- }
3202
- const Parent = params?.Parent ?? Object;
3203
- class Definition extends Parent {}
3204
- Object.defineProperty(Definition, "name", { value: name });
3205
- function _(def) {
3206
- var _a;
3207
- const inst = params?.Parent ? new Definition() : this;
3208
- init(inst, def);
3209
- (_a = inst._zod).deferred ?? (_a.deferred = []);
3210
- for (const fn of inst._zod.deferred) fn();
3211
- return inst;
3212
- }
3213
- Object.defineProperty(_, "init", { value: init });
3214
- Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => {
3215
- if (params?.Parent && inst instanceof params.Parent) return true;
3216
- return inst?._zod?.traits?.has(name);
3217
- } });
3218
- Object.defineProperty(_, "name", { value: name });
3219
- return _;
3220
- }
3221
- var $ZodAsyncError = class extends Error {
3222
- constructor() {
3223
- super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
3224
- }
3225
- };
3226
- var $ZodEncodeError = class extends Error {
3227
- constructor(name) {
3228
- super(`Encountered unidirectional transform during encode: ${name}`);
3229
- this.name = "ZodEncodeError";
3230
- }
3231
- };
3232
- const globalConfig = {};
3233
- function config(newConfig) {
3234
- if (newConfig) Object.assign(globalConfig, newConfig);
3235
- return globalConfig;
3236
- }
3237
3181
  function getEnumValues(entries) {
3238
3182
  const numericValues = Object.values(entries).filter((v) => typeof v === "number");
3239
3183
  return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
3240
3184
  }
3185
+ function joinValues(array, separator = "|") {
3186
+ return array.map((val) => stringifyPrimitive(val)).join(separator);
3187
+ }
3241
3188
  function jsonStringifyReplacer(_, value) {
3242
3189
  if (typeof value === "bigint") return value.toString();
3243
3190
  return value;
3244
3191
  }
3245
- function cached(getter) {
3246
- return { get value() {
3247
- {
3248
- const value = getter();
3249
- Object.defineProperty(this, "value", { value });
3250
- return value;
3192
+ var Cached = class {
3193
+ constructor(getter) {
3194
+ this._getter = getter;
3195
+ this._value = void 0;
3196
+ }
3197
+ get value() {
3198
+ const getter = this._getter;
3199
+ if (getter !== void 0) {
3200
+ this._value = getter();
3201
+ this._getter = void 0;
3251
3202
  }
3252
- throw new Error("cached value already set");
3253
- } };
3203
+ return this._value;
3204
+ }
3205
+ };
3206
+ function cached(getter) {
3207
+ return new Cached(getter);
3254
3208
  }
3255
3209
  function nullish(input) {
3256
3210
  return input === null || input === void 0;
@@ -3261,33 +3215,11 @@ function cleanRegex(source) {
3261
3215
  return source.slice(start, end);
3262
3216
  }
3263
3217
  function floatSafeRemainder(val, step) {
3264
- const valDecCount = (val.toString().split(".")[1] || "").length;
3265
- const stepString = step.toString();
3266
- let stepDecCount = (stepString.split(".")[1] || "").length;
3267
- if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) {
3268
- const match = stepString.match(/\d?e-(\d?)/);
3269
- if (match?.[1]) stepDecCount = Number.parseInt(match[1]);
3270
- }
3271
- const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
3272
- return Number.parseInt(val.toFixed(decCount).replace(".", "")) % Number.parseInt(step.toFixed(decCount).replace(".", "")) / 10 ** decCount;
3273
- }
3274
- const EVALUATING = Symbol("evaluating");
3275
- function defineLazy(object, key, getter) {
3276
- let value = void 0;
3277
- Object.defineProperty(object, key, {
3278
- get() {
3279
- if (value === EVALUATING) return;
3280
- if (value === void 0) {
3281
- value = EVALUATING;
3282
- value = getter();
3283
- }
3284
- return value;
3285
- },
3286
- set(v) {
3287
- Object.defineProperty(object, key, { value: v });
3288
- },
3289
- configurable: true
3290
- });
3218
+ const ratio = val / step;
3219
+ const roundedRatio = Math.round(ratio);
3220
+ const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);
3221
+ if (Math.abs(ratio - roundedRatio) < tolerance) return 0;
3222
+ return ratio - roundedRatio;
3291
3223
  }
3292
3224
  function assignProp(target, prop, value) {
3293
3225
  Object.defineProperty(target, prop, {
@@ -3297,6 +3229,58 @@ function assignProp(target, prop, value) {
3297
3229
  configurable: true
3298
3230
  });
3299
3231
  }
3232
+ /**
3233
+ * Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it.
3234
+ *
3235
+ * Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none.
3236
+ */
3237
+ function rawShape(def) {
3238
+ const desc = Object.getOwnPropertyDescriptor(def, "shape");
3239
+ return desc?.get ? desc.get.raw : desc?.value;
3240
+ }
3241
+ function sourceShape(schema) {
3242
+ return rawShape(schema._zod.def) ?? schema._zod.def.shape;
3243
+ }
3244
+ function deferProp(target, key, getter) {
3245
+ Object.defineProperty(target, key, {
3246
+ get() {
3247
+ const value = getter();
3248
+ assignProp(this, key, value);
3249
+ return value;
3250
+ },
3251
+ enumerable: true,
3252
+ configurable: true
3253
+ });
3254
+ }
3255
+ function putProp(target, key, value) {
3256
+ if (key in target) assignProp(target, key, value);
3257
+ else target[key] = value;
3258
+ }
3259
+ /**
3260
+ * Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`.
3261
+ *
3262
+ * A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema.
3263
+ */
3264
+ function mirrorShape(target, source, keys, wrap) {
3265
+ const raw = sourceShape(source);
3266
+ for (const key of keys) {
3267
+ const desc = Object.getOwnPropertyDescriptor(raw, key);
3268
+ if (!desc.enumerable) continue;
3269
+ if (desc.get) deferProp(target, key, () => {
3270
+ const value = source._zod.def.shape[key];
3271
+ return wrap ? wrap(value, key) : value;
3272
+ });
3273
+ else putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);
3274
+ }
3275
+ }
3276
+ function mirrorProps(target, source) {
3277
+ for (const key of Reflect.ownKeys(source)) {
3278
+ const desc = Object.getOwnPropertyDescriptor(source, key);
3279
+ if (!desc.enumerable) continue;
3280
+ if (desc.get) deferProp(target, key, () => source[key]);
3281
+ else putProp(target, key, desc.value);
3282
+ }
3283
+ }
3300
3284
  function mergeDefs(...defs) {
3301
3285
  const mergedDescriptors = {};
3302
3286
  for (const def of defs) Object.assign(mergedDescriptors, Object.getOwnPropertyDescriptors(def));
@@ -3312,7 +3296,8 @@ const captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace
3312
3296
  function isObject(data) {
3313
3297
  return typeof data === "object" && data !== null && !Array.isArray(data);
3314
3298
  }
3315
- const allowsEval = cached(() => {
3299
+ const allowsEval = /* @__PURE__ */ cached(() => {
3300
+ if (globalConfig.jitless) return false;
3316
3301
  if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false;
3317
3302
  try {
3318
3303
  new Function("");
@@ -3334,9 +3319,11 @@ function isPlainObject(o) {
3334
3319
  function shallowClone(o) {
3335
3320
  if (isPlainObject(o)) return { ...o };
3336
3321
  if (Array.isArray(o)) return [...o];
3322
+ if (o instanceof Map) return new Map(o);
3323
+ if (o instanceof Set) return new Set(o);
3337
3324
  return o;
3338
3325
  }
3339
- const propertyKeyTypes = new Set([
3326
+ const propertyKeyTypes = /* @__PURE__ */ new Set([
3340
3327
  "string",
3341
3328
  "number",
3342
3329
  "symbol"
@@ -3364,9 +3351,14 @@ function normalizeParams(_params) {
3364
3351
  };
3365
3352
  return params;
3366
3353
  }
3354
+ function stringifyPrimitive(value) {
3355
+ if (typeof value === "bigint") return value.toString() + "n";
3356
+ if (typeof value === "string") return `"${value}"`;
3357
+ return `${value}`;
3358
+ }
3367
3359
  function optionalKeys(shape) {
3368
3360
  return Object.keys(shape).filter((k) => {
3369
- return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
3361
+ return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === "optional";
3370
3362
  });
3371
3363
  }
3372
3364
  const NUMBER_FORMAT_RANGES = {
@@ -3376,39 +3368,39 @@ const NUMBER_FORMAT_RANGES = {
3376
3368
  float32: [-34028234663852886e22, 34028234663852886e22],
3377
3369
  float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
3378
3370
  };
3371
+ const BIGINT_FORMAT_RANGES = {
3372
+ int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],
3373
+ uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]
3374
+ };
3379
3375
  function pick(schema, mask) {
3380
3376
  const currDef = schema._zod.def;
3381
3377
  const checks = currDef.checks;
3382
3378
  if (checks && checks.length > 0) throw new Error(".pick() cannot be used on object schemas containing refinements");
3383
- return clone(schema, mergeDefs(schema._zod.def, {
3384
- get shape() {
3385
- const newShape = {};
3386
- for (const key in mask) {
3387
- if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
3388
- if (!mask[key]) continue;
3389
- newShape[key] = currDef.shape[key];
3390
- }
3391
- assignProp(this, "shape", newShape);
3392
- return newShape;
3393
- },
3379
+ const newShape = {};
3380
+ mirrorShape(newShape, schema, maskedKeys(schema, mask));
3381
+ return clone(schema, mergeDefs(currDef, {
3382
+ shape: newShape,
3394
3383
  checks: []
3395
3384
  }));
3396
3385
  }
3386
+ function maskedKeys(schema, mask) {
3387
+ const raw = sourceShape(schema);
3388
+ const keys = [];
3389
+ for (const key of Reflect.ownKeys(mask)) {
3390
+ if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) throw new Error(`Unrecognized key: "${String(key)}"`);
3391
+ if (mask[key]) keys.push(key);
3392
+ }
3393
+ return keys;
3394
+ }
3397
3395
  function omit(schema, mask) {
3398
3396
  const currDef = schema._zod.def;
3399
3397
  const checks = currDef.checks;
3400
3398
  if (checks && checks.length > 0) throw new Error(".omit() cannot be used on object schemas containing refinements");
3401
- return clone(schema, mergeDefs(schema._zod.def, {
3402
- get shape() {
3403
- const newShape = { ...schema._zod.def.shape };
3404
- for (const key in mask) {
3405
- if (!(key in currDef.shape)) throw new Error(`Unrecognized key: "${key}"`);
3406
- if (!mask[key]) continue;
3407
- delete newShape[key];
3408
- }
3409
- assignProp(this, "shape", newShape);
3410
- return newShape;
3411
- },
3399
+ const omitted = new Set(maskedKeys(schema, mask));
3400
+ const newShape = {};
3401
+ mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));
3402
+ return clone(schema, mergeDefs(currDef, {
3403
+ shape: newShape,
3412
3404
  checks: []
3413
3405
  }));
3414
3406
  }
@@ -3416,95 +3408,68 @@ function extend(schema, shape) {
3416
3408
  if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object");
3417
3409
  const checks = schema._zod.def.checks;
3418
3410
  if (checks && checks.length > 0) {
3419
- const existingShape = schema._zod.def.shape;
3420
- for (const key in shape) if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
3411
+ const existingShape = sourceShape(schema);
3412
+ for (const key of Reflect.ownKeys(shape)) if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
3421
3413
  }
3422
- return clone(schema, mergeDefs(schema._zod.def, { get shape() {
3423
- const _shape = {
3424
- ...schema._zod.def.shape,
3425
- ...shape
3426
- };
3427
- assignProp(this, "shape", _shape);
3428
- return _shape;
3429
- } }));
3414
+ return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));
3415
+ }
3416
+ function extended(schema, shape) {
3417
+ const newShape = {};
3418
+ mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));
3419
+ mirrorProps(newShape, shape);
3420
+ return newShape;
3430
3421
  }
3431
3422
  function safeExtend(schema, shape) {
3432
3423
  if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
3433
- return clone(schema, mergeDefs(schema._zod.def, { get shape() {
3434
- const _shape = {
3435
- ...schema._zod.def.shape,
3436
- ...shape
3437
- };
3438
- assignProp(this, "shape", _shape);
3439
- return _shape;
3440
- } }));
3424
+ return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));
3441
3425
  }
3442
3426
  function merge(a, b) {
3427
+ if (!b?._zod?.def) throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");
3428
+ if (a._zod.def.checks?.length) throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
3429
+ const newShape = {};
3430
+ mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));
3431
+ mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));
3443
3432
  return clone(a, mergeDefs(a._zod.def, {
3444
- get shape() {
3445
- const _shape = {
3446
- ...a._zod.def.shape,
3447
- ...b._zod.def.shape
3448
- };
3449
- assignProp(this, "shape", _shape);
3450
- return _shape;
3451
- },
3433
+ shape: newShape,
3452
3434
  get catchall() {
3453
3435
  return b._zod.def.catchall;
3454
3436
  },
3455
- checks: []
3437
+ checks: b._zod.def.checks ?? []
3456
3438
  }));
3457
3439
  }
3458
- function partial(Class, schema, mask) {
3440
+ function partial(Class, schema, mask, name = "partial") {
3459
3441
  const checks = schema._zod.def.checks;
3460
- if (checks && checks.length > 0) throw new Error(".partial() cannot be used on object schemas containing refinements");
3442
+ if (checks && checks.length > 0) throw new Error(`.${name}() cannot be used on object schemas containing refinements`);
3443
+ const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0;
3444
+ const newShape = {};
3445
+ mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class && ((value, key) => selected && !selected.has(key) ? value : new Class({
3446
+ type: "optional",
3447
+ innerType: value
3448
+ })));
3461
3449
  return clone(schema, mergeDefs(schema._zod.def, {
3462
- get shape() {
3463
- const oldShape = schema._zod.def.shape;
3464
- const shape = { ...oldShape };
3465
- if (mask) for (const key in mask) {
3466
- if (!(key in oldShape)) throw new Error(`Unrecognized key: "${key}"`);
3467
- if (!mask[key]) continue;
3468
- shape[key] = Class ? new Class({
3469
- type: "optional",
3470
- innerType: oldShape[key]
3471
- }) : oldShape[key];
3472
- }
3473
- else for (const key in oldShape) shape[key] = Class ? new Class({
3474
- type: "optional",
3475
- innerType: oldShape[key]
3476
- }) : oldShape[key];
3477
- assignProp(this, "shape", shape);
3478
- return shape;
3479
- },
3450
+ shape: newShape,
3480
3451
  checks: []
3481
3452
  }));
3482
3453
  }
3483
3454
  function required(Class, schema, mask) {
3484
- return clone(schema, mergeDefs(schema._zod.def, { get shape() {
3485
- const oldShape = schema._zod.def.shape;
3486
- const shape = { ...oldShape };
3487
- if (mask) for (const key in mask) {
3488
- if (!(key in shape)) throw new Error(`Unrecognized key: "${key}"`);
3489
- if (!mask[key]) continue;
3490
- shape[key] = new Class({
3491
- type: "nonoptional",
3492
- innerType: oldShape[key]
3493
- });
3494
- }
3495
- else for (const key in oldShape) shape[key] = new Class({
3496
- type: "nonoptional",
3497
- innerType: oldShape[key]
3498
- });
3499
- assignProp(this, "shape", shape);
3500
- return shape;
3501
- } }));
3455
+ const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0;
3456
+ const newShape = {};
3457
+ mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => selected && !selected.has(key) ? value : new Class({
3458
+ type: "nonoptional",
3459
+ innerType: value
3460
+ }));
3461
+ return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));
3502
3462
  }
3503
3463
  function aborted(x, startIndex = 0) {
3504
3464
  if (x.aborted === true) return true;
3505
3465
  for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true;
3506
3466
  return false;
3507
3467
  }
3468
+ function explicitlyAborted(x, startIndex = 0) {
3469
+ if (x.aborted === true) return true;
3470
+ for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue === false) return true;
3471
+ return false;
3472
+ }
3508
3473
  function prefixIssues(path, issues) {
3509
3474
  return issues.map((iss) => {
3510
3475
  var _a;
@@ -3516,22 +3481,67 @@ function prefixIssues(path, issues) {
3516
3481
  function unwrapMessage(message) {
3517
3482
  return typeof message === "string" ? message : message?.message;
3518
3483
  }
3484
+ /** The leading size checks of `defChecks` that set an upper bound, each paired with it. */
3485
+ function sizeCaps(defChecks) {
3486
+ const caps = [];
3487
+ for (const ch of defChecks ?? []) {
3488
+ const d = ch._zod.def;
3489
+ if (!/_(length|size)$|_equals$/.test(d.check)) break;
3490
+ const max = d.maximum ?? d.length ?? d.size;
3491
+ if (max >= 0) caps.push([max, ch]);
3492
+ }
3493
+ return caps;
3494
+ }
3495
+ function attachSchema(issues, start, inst) {
3496
+ var _a;
3497
+ for (let i = start; i < issues.length; i++) (_a = issues[i]).schema ?? (_a.schema = inst);
3498
+ }
3519
3499
  function finalizeIssue(iss, ctx, config) {
3520
- const full = {
3521
- ...iss,
3522
- path: iss.path ?? []
3523
- };
3524
- if (!iss.message) full.message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
3525
- delete full.inst;
3526
- delete full.continue;
3527
- if (!ctx?.reportInput) delete full.input;
3500
+ var _a;
3501
+ const traits = iss.inst?._zod?.traits;
3502
+ if (traits?.has("$ZodType")) if (traits.has("$ZodCheck")) (_a = iss).schema ?? (_a.schema = iss.inst);
3503
+ else iss.schema = iss.inst;
3504
+ const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0;
3505
+ const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
3506
+ const full = {};
3507
+ for (const k of Object.keys(iss)) {
3508
+ if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__") continue;
3509
+ full[k] = iss[k];
3510
+ }
3511
+ full.path ?? (full.path = []);
3512
+ full.message = message;
3513
+ if (ctx?.reportInput) full.input = iss.input;
3528
3514
  return full;
3529
3515
  }
3516
+ const highSurrogate = /[\uD800-\uDBFF]/;
3517
+ function codePointLength(str) {
3518
+ const units = str.length;
3519
+ if (!highSurrogate.test(str)) return units;
3520
+ let count = units;
3521
+ for (let i = 0; i < units - 1; i++) if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) {
3522
+ count--;
3523
+ i++;
3524
+ }
3525
+ return count;
3526
+ }
3530
3527
  function getLengthableOrigin(input) {
3531
3528
  if (Array.isArray(input)) return "array";
3532
3529
  if (typeof input === "string") return "string";
3533
3530
  return "unknown";
3534
3531
  }
3532
+ function parsedType(data) {
3533
+ const t = typeof data;
3534
+ switch (t) {
3535
+ case "number": return Number.isNaN(data) ? "nan" : "number";
3536
+ case "object": {
3537
+ if (data === null) return "null";
3538
+ if (Array.isArray(data)) return "array";
3539
+ const obj = data;
3540
+ if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) return obj.constructor.name;
3541
+ }
3542
+ }
3543
+ return t;
3544
+ }
3535
3545
  function issue(...args) {
3536
3546
  const [iss, input, inst] = args;
3537
3547
  if (typeof iss === "string") return {
@@ -3542,31 +3552,333 @@ function issue(...args) {
3542
3552
  };
3543
3553
  return { ...iss };
3544
3554
  }
3545
- const initializer$1 = (inst, def) => {
3546
- inst.name = "$ZodError";
3547
- Object.defineProperty(inst, "_zod", {
3548
- value: inst._zod,
3549
- enumerable: false
3555
+ /**
3556
+ * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working.
3557
+ *
3558
+ * Call this from a `proto` initializer, which runs once per prototype — never per instance.
3559
+ */
3560
+ function members(proto, table) {
3561
+ for (const key in table) {
3562
+ const desc = Object.getOwnPropertyDescriptor(table, key);
3563
+ if (desc.get) Object.defineProperty(proto, key, {
3564
+ ...desc,
3565
+ enumerable: false
3566
+ });
3567
+ else defineBound(proto, key, desc.value);
3568
+ }
3569
+ }
3570
+ /** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */
3571
+ function own(inst, key, value, enumerable = true) {
3572
+ Object.defineProperty(inst, key, {
3573
+ configurable: true,
3574
+ writable: true,
3575
+ enumerable,
3576
+ value
3577
+ });
3578
+ return value;
3579
+ }
3580
+ /** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */
3581
+ function hide(inst, key, value) {
3582
+ return own(inst, key, value, false);
3583
+ }
3584
+ /** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */
3585
+ function derived(computes, table) {
3586
+ for (const key in computes) {
3587
+ const compute = computes[key];
3588
+ Object.defineProperty(table, key, {
3589
+ configurable: true,
3590
+ enumerable: true,
3591
+ get() {
3592
+ return own(this, key, compute(this));
3593
+ },
3594
+ set(value) {
3595
+ own(this, key, value);
3596
+ }
3597
+ });
3598
+ }
3599
+ return table;
3600
+ }
3601
+ function defineBound(proto, key, fn) {
3602
+ Object.defineProperty(proto, key, {
3603
+ configurable: true,
3604
+ get() {
3605
+ return this == null ? fn : own(this, key, fn.bind(this));
3606
+ },
3607
+ set(value) {
3608
+ own(this, key, value);
3609
+ }
3550
3610
  });
3551
- Object.defineProperty(inst, "issues", {
3552
- value: def,
3553
- enumerable: false
3611
+ }
3612
+ /** Returns the prototype to install on, or `undefined` if this group is already installed on it. */
3613
+ function claim(inst, sentinel) {
3614
+ const proto = Object.getPrototypeOf(inst);
3615
+ return sentinel in proto ? void 0 : proto;
3616
+ }
3617
+ let installing;
3618
+ let broke = false;
3619
+ const breaker = {
3620
+ configurable: true,
3621
+ get() {
3622
+ broke = true;
3623
+ }
3624
+ };
3625
+ /**
3626
+ * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s
3627
+ * constructor, computed from the internals object itself and cached there on
3628
+ * first read. One accessor per constructor rather than one per instance.
3629
+ */
3630
+ function defineLazyInternal(inst, key, compute) {
3631
+ const proto = Object.getPrototypeOf(inst._zod);
3632
+ if (key in proto && installing !== inst._zod) {
3633
+ installing = void 0;
3634
+ return;
3635
+ }
3636
+ installing = inst._zod;
3637
+ Object.defineProperty(proto, key, {
3638
+ configurable: true,
3639
+ get() {
3640
+ Object.defineProperty(this, key, breaker);
3641
+ const outer = broke;
3642
+ broke = false;
3643
+ try {
3644
+ const value = compute(this);
3645
+ if (broke) delete this[key];
3646
+ else Object.defineProperty(this, key, {
3647
+ configurable: true,
3648
+ writable: true,
3649
+ value
3650
+ });
3651
+ broke = broke || outer;
3652
+ return value;
3653
+ } catch (err) {
3654
+ delete this[key];
3655
+ broke = broke || outer;
3656
+ throw err;
3657
+ }
3658
+ },
3659
+ set(value) {
3660
+ Object.defineProperty(this, key, {
3661
+ configurable: true,
3662
+ writable: true,
3663
+ value
3664
+ });
3665
+ }
3554
3666
  });
3555
- inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
3556
- Object.defineProperty(inst, "toString", {
3557
- value: () => inst.message,
3558
- enumerable: false
3667
+ }
3668
+ /**
3669
+ * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own
3670
+ * data property. One accessor per constructor rather than one per instance, because an own accessor
3671
+ * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.
3672
+ */
3673
+ function installLazyProp(inst, key, make, enumerable) {
3674
+ const proto = claim(inst, key);
3675
+ if (!proto) return;
3676
+ Object.defineProperty(proto, key, {
3677
+ configurable: true,
3678
+ get() {
3679
+ const desc = {
3680
+ configurable: true,
3681
+ writable: true,
3682
+ enumerable,
3683
+ value: void 0
3684
+ };
3685
+ Object.defineProperty(this, key, desc);
3686
+ desc.value = make(this);
3687
+ Object.defineProperty(this, key, desc);
3688
+ return desc.value;
3689
+ },
3690
+ set(value) {
3691
+ Object.defineProperty(this, key, {
3692
+ configurable: true,
3693
+ writable: true,
3694
+ enumerable,
3695
+ value
3696
+ });
3697
+ }
3559
3698
  });
3699
+ }
3700
+ /** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */
3701
+ const CONSTANT_CATCH = "~constantCatch";
3702
+ /** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */
3703
+ function constantCatch(value) {
3704
+ const fn = () => value;
3705
+ fn[CONSTANT_CATCH] = true;
3706
+ return fn;
3707
+ }
3708
+ var _a$1;
3709
+ const _zodDesc = {
3710
+ value: void 0,
3711
+ enumerable: false
3712
+ };
3713
+ let _E = "captureStackTrace" in Error ? Error : null;
3714
+ function newError(Definition) {
3715
+ const E = _E;
3716
+ if (E) {
3717
+ const saved = E.stackTraceLimit;
3718
+ if (typeof saved === "number") {
3719
+ try {
3720
+ E.stackTraceLimit = 0;
3721
+ } catch {
3722
+ _E = null;
3723
+ return new Definition();
3724
+ }
3725
+ try {
3726
+ return new Definition();
3727
+ } finally {
3728
+ E.stackTraceLimit = saved;
3729
+ }
3730
+ }
3731
+ }
3732
+ return new Definition();
3733
+ }
3734
+ function $constructor(name, initializer, proto, params) {
3735
+ const zodProto = {};
3736
+ function Internals(def) {
3737
+ this.def = def;
3738
+ this.constr = _;
3739
+ this.traits = /* @__PURE__ */ new Set();
3740
+ }
3741
+ Internals.prototype = zodProto;
3742
+ const protoMembers = proto;
3743
+ const initialized = protoMembers && /* @__PURE__ */ new WeakSet();
3744
+ function init(inst, def) {
3745
+ if (!inst._zod) {
3746
+ _zodDesc.value = new Internals(def);
3747
+ try {
3748
+ Object.defineProperty(inst, "_zod", _zodDesc);
3749
+ } finally {
3750
+ _zodDesc.value = void 0;
3751
+ }
3752
+ } else if (inst._zod.traits.has(name)) return;
3753
+ inst._zod.traits.add(name);
3754
+ initializer(inst, def);
3755
+ if (initialized) {
3756
+ const own = Object.getPrototypeOf(inst);
3757
+ const ctorProto = inst._zod.constr.prototype;
3758
+ let up = own;
3759
+ while (up && up !== ctorProto) up = Object.getPrototypeOf(up);
3760
+ const target = up ?? own;
3761
+ if (!initialized.has(target)) {
3762
+ initialized.add(target);
3763
+ members(target, protoMembers);
3764
+ }
3765
+ }
3766
+ const proto = _.prototype;
3767
+ for (const k in proto) {
3768
+ if (!Object.prototype.hasOwnProperty.call(proto, k)) continue;
3769
+ if (!(k in inst)) inst[k] = proto[k].bind(inst);
3770
+ }
3771
+ }
3772
+ const Parent = params?.Parent ?? Object;
3773
+ class Definition extends Parent {}
3774
+ Object.defineProperty(Definition, "name", { value: name });
3775
+ function _(def) {
3776
+ const inst = params?.Parent ? newError(Definition) : this;
3777
+ init(inst, def);
3778
+ const deferred = inst._zod.deferred;
3779
+ if (deferred) {
3780
+ for (const fn of deferred) fn();
3781
+ inst._zod.deferred = void 0;
3782
+ }
3783
+ const pp = globalThis.__zod_globalConfig?.postProcessor;
3784
+ if (pp) pp(inst);
3785
+ return inst;
3786
+ }
3787
+ Object.defineProperty(_, "init", { value: init });
3788
+ Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => {
3789
+ if (params?.Parent && inst instanceof params.Parent) return true;
3790
+ return inst?._zod?.traits?.has(name);
3791
+ } });
3792
+ Object.defineProperty(_, "name", { value: name });
3793
+ return _;
3794
+ }
3795
+ var $ZodAsyncError = class extends Error {
3796
+ constructor() {
3797
+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
3798
+ }
3799
+ };
3800
+ var $ZodEncodeError = class extends Error {
3801
+ constructor(name) {
3802
+ super(`Encountered unidirectional transform during encode: ${name}`);
3803
+ this.name = "ZodEncodeError";
3804
+ }
3805
+ };
3806
+ (_a$1 = globalThis).__zod_globalConfig ?? (_a$1.__zod_globalConfig = {});
3807
+ const globalConfig = globalThis.__zod_globalConfig;
3808
+ function config(newConfig) {
3809
+ if (newConfig) Object.assign(globalConfig, newConfig);
3810
+ return globalConfig;
3811
+ }
3812
+ function _getMessage() {
3813
+ const internals = this._zod;
3814
+ internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2));
3815
+ return internals.message;
3816
+ }
3817
+ function _setMessage(value) {
3818
+ this._zod.message = value;
3819
+ }
3820
+ const _messageDesc = {
3821
+ get: _getMessage,
3822
+ set: _setMessage,
3823
+ enumerable: true,
3824
+ configurable: true
3825
+ };
3826
+ const _issuesDesc = {
3827
+ value: void 0,
3828
+ enumerable: false
3829
+ };
3830
+ const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
3831
+ const initializer$1 = (inst, def) => {
3832
+ inst.name = "$ZodError";
3833
+ _issuesDesc.value = def;
3834
+ Object.defineProperty(inst, "issues", _issuesDesc);
3835
+ _issuesDesc.value = void 0;
3836
+ Object.defineProperty(inst, "message", _messageDesc);
3837
+ const proto = Object.getPrototypeOf(inst);
3838
+ if (!_installedToString.has(proto)) {
3839
+ _installedToString.add(proto);
3840
+ Object.defineProperty(proto, "toString", {
3841
+ configurable: true,
3842
+ enumerable: false,
3843
+ get() {
3844
+ const value = () => this.message;
3845
+ Object.defineProperty(this, "toString", {
3846
+ value,
3847
+ configurable: true,
3848
+ writable: true
3849
+ });
3850
+ return value;
3851
+ },
3852
+ set(value) {
3853
+ Object.defineProperty(this, "toString", {
3854
+ value,
3855
+ configurable: true,
3856
+ writable: true
3857
+ });
3858
+ }
3859
+ });
3860
+ }
3560
3861
  };
3561
3862
  const $ZodError = $constructor("$ZodError", initializer$1);
3562
- const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
3863
+ $constructor("$ZodError", initializer$1, void 0, { Parent: Error });
3864
+ /** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member
3865
+ * ("toString", "constructor") would otherwise read through to the prototype, and assigning
3866
+ * "__proto__" would hit the setter instead of creating a key. */
3867
+ function node(obj, key, make) {
3868
+ if (!Object.prototype.hasOwnProperty.call(obj, key)) if (key === "__proto__") Object.defineProperty(obj, key, {
3869
+ value: make(),
3870
+ writable: true,
3871
+ enumerable: true,
3872
+ configurable: true
3873
+ });
3874
+ else obj[key] = make();
3875
+ return obj[key];
3876
+ }
3563
3877
  function flattenError(error, mapper = (issue) => issue.message) {
3564
3878
  const fieldErrors = {};
3565
3879
  const formErrors = [];
3566
- for (const sub of error.issues) if (sub.path.length > 0) {
3567
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
3568
- fieldErrors[sub.path[0]].push(mapper(sub));
3569
- } else formErrors.push(mapper(sub));
3880
+ for (const sub of error.issues) if (sub.path.length > 0) node(fieldErrors, sub.path[0], () => []).push(mapper(sub));
3881
+ else formErrors.push(mapper(sub));
3570
3882
  return {
3571
3883
  formErrors,
3572
3884
  fieldErrors
@@ -3574,56 +3886,86 @@ function flattenError(error, mapper = (issue) => issue.message) {
3574
3886
  }
3575
3887
  function formatError(error, mapper = (issue) => issue.message) {
3576
3888
  const fieldErrors = { _errors: [] };
3577
- const processError = (error) => {
3578
- for (const issue of error.issues) if (issue.code === "invalid_union" && issue.errors.length) issue.errors.map((issues) => processError({ issues }));
3579
- else if (issue.code === "invalid_key") processError({ issues: issue.issues });
3580
- else if (issue.code === "invalid_element") processError({ issues: issue.issues });
3581
- else if (issue.path.length === 0) fieldErrors._errors.push(mapper(issue));
3889
+ const processError = (error, path = []) => {
3890
+ for (const issue of error.issues) if (issue.code === "invalid_union" && issue.errors.length) issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));
3891
+ else if (issue.code === "invalid_key") processError({ issues: issue.issues }, [...path, ...issue.path]);
3892
+ else if (issue.code === "invalid_element") processError({ issues: issue.issues }, [...path, ...issue.path]);
3582
3893
  else {
3583
- let curr = fieldErrors;
3584
- let i = 0;
3585
- while (i < issue.path.length) {
3586
- const el = issue.path[i];
3587
- if (!(i === issue.path.length - 1)) curr[el] = curr[el] || { _errors: [] };
3588
- else {
3589
- curr[el] = curr[el] || { _errors: [] };
3590
- curr[el]._errors.push(mapper(issue));
3894
+ const fullpath = [...path, ...issue.path];
3895
+ if (fullpath.length === 0) fieldErrors._errors.push(mapper(issue));
3896
+ else {
3897
+ let curr = fieldErrors;
3898
+ let i = 0;
3899
+ while (i < fullpath.length) {
3900
+ const el = fullpath[i];
3901
+ const terminal = i === fullpath.length - 1;
3902
+ if (el === "_errors") {
3903
+ if (terminal) curr._errors.push(mapper(issue));
3904
+ i++;
3905
+ continue;
3906
+ }
3907
+ if (!Object.prototype.hasOwnProperty.call(curr, el)) Object.defineProperty(curr, el, {
3908
+ value: { _errors: [] },
3909
+ enumerable: true,
3910
+ writable: true,
3911
+ configurable: true
3912
+ });
3913
+ const node = curr[el];
3914
+ if (terminal) node._errors.push(mapper(issue));
3915
+ curr = node;
3916
+ i++;
3591
3917
  }
3592
- curr = curr[el];
3593
- i++;
3594
3918
  }
3595
3919
  }
3596
3920
  };
3597
3921
  processError(error);
3598
3922
  return fieldErrors;
3599
3923
  }
3600
- const _parse = (_Err) => (schema, value, _ctx, _params) => {
3601
- const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
3602
- const result = schema._zod.run({
3603
- value,
3604
- issues: []
3605
- }, ctx);
3606
- if (result instanceof Promise) throw new $ZodAsyncError();
3607
- if (result.issues.length) {
3608
- const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
3609
- captureStackTrace(e, _params?.callee);
3610
- throw e;
3611
- }
3612
- return result.value;
3924
+ function finalizeParams(callee, params) {
3925
+ return {
3926
+ callee: params?.callee ?? callee,
3927
+ Err: params?.Err
3928
+ };
3929
+ }
3930
+ const _parse = (_Err) => {
3931
+ const fn = (schema, value, _ctx, _params) => {
3932
+ const ctx = _ctx ? {
3933
+ ..._ctx,
3934
+ async: false
3935
+ } : { async: false };
3936
+ const result = schema._zod.run({
3937
+ value,
3938
+ issues: []
3939
+ }, ctx);
3940
+ if (result instanceof Promise) throw new $ZodAsyncError();
3941
+ if (result.issues.length) {
3942
+ const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
3943
+ captureStackTrace(e, _params?.callee ?? fn);
3944
+ throw e;
3945
+ }
3946
+ return result.value;
3947
+ };
3948
+ return fn;
3613
3949
  };
3614
- const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
3615
- const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
3616
- let result = schema._zod.run({
3617
- value,
3618
- issues: []
3619
- }, ctx);
3620
- if (result instanceof Promise) result = await result;
3621
- if (result.issues.length) {
3622
- const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
3623
- captureStackTrace(e, params?.callee);
3624
- throw e;
3625
- }
3626
- return result.value;
3950
+ const _parseAsync = (_Err) => {
3951
+ const fn = async (schema, value, _ctx, params) => {
3952
+ const ctx = _ctx ? {
3953
+ ..._ctx,
3954
+ async: true
3955
+ } : { async: true };
3956
+ let result = schema._zod.run({
3957
+ value,
3958
+ issues: []
3959
+ }, ctx);
3960
+ if (result instanceof Promise) result = await result;
3961
+ if (result.issues.length) {
3962
+ const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
3963
+ captureStackTrace(e, params?.callee ?? fn);
3964
+ throw e;
3965
+ }
3966
+ return result.value;
3967
+ };
3968
+ return fn;
3627
3969
  };
3628
3970
  const _safeParse = (_Err) => (schema, value, _ctx) => {
3629
3971
  const ctx = _ctx ? {
@@ -3635,67 +3977,165 @@ const _safeParse = (_Err) => (schema, value, _ctx) => {
3635
3977
  issues: []
3636
3978
  }, ctx);
3637
3979
  if (result instanceof Promise) throw new $ZodAsyncError();
3638
- return result.issues.length ? {
3639
- success: false,
3640
- error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
3641
- } : {
3980
+ return result.issues.length ? failure(_Err, result.issues, ctx) : {
3642
3981
  success: true,
3643
3982
  data: result.value
3644
3983
  };
3645
3984
  };
3646
- const safeParse$1 = /* @__PURE__ */ _safeParse($ZodRealError);
3985
+ function failure(Err, issues, ctx) {
3986
+ let error;
3987
+ return {
3988
+ success: false,
3989
+ get error() {
3990
+ if (!error) {
3991
+ error = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config())));
3992
+ issues = void 0;
3993
+ ctx = void 0;
3994
+ }
3995
+ return error;
3996
+ },
3997
+ set error(e) {
3998
+ error = e;
3999
+ issues = void 0;
4000
+ ctx = void 0;
4001
+ }
4002
+ };
4003
+ }
3647
4004
  const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
3648
- const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
4005
+ const ctx = _ctx ? {
4006
+ ..._ctx,
4007
+ async: true
4008
+ } : { async: true };
3649
4009
  let result = schema._zod.run({
3650
4010
  value,
3651
4011
  issues: []
3652
4012
  }, ctx);
3653
4013
  if (result instanceof Promise) result = await result;
3654
- return result.issues.length ? {
3655
- success: false,
3656
- error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
3657
- } : {
4014
+ return result.issues.length ? failure(_Err, result.issues, ctx) : {
3658
4015
  success: true,
3659
4016
  data: result.value
3660
4017
  };
3661
4018
  };
3662
- const safeParseAsync$1 = /* @__PURE__ */ _safeParseAsync($ZodRealError);
3663
- const _encode = (_Err) => (schema, value, _ctx) => {
3664
- const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
3665
- return _parse(_Err)(schema, value, ctx);
4019
+ const COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid");
4020
+ const COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback");
4021
+ const validate = ((schema, value, _ctx) => {
4022
+ const validator = schema._zod.bag.validator;
4023
+ if (validator !== void 0) {
4024
+ if (validator(value) !== COMPILE_INVALID) return true;
4025
+ if (validator.definite === true && _ctx === void 0) return false;
4026
+ }
4027
+ return validateFallback(schema, value, _ctx);
4028
+ });
4029
+ function validateFallback(schema, value, _ctx) {
4030
+ const ctx = _ctx ? {
4031
+ ..._ctx,
4032
+ async: false,
4033
+ abortEarly: true
4034
+ } : {
4035
+ async: false,
4036
+ abortEarly: true
4037
+ };
4038
+ const fallbackRun = schema._zod.bag.fallbackRun;
4039
+ let result;
4040
+ if (fallbackRun) {
4041
+ ctx[COMPILE_FALLBACK] = true;
4042
+ result = fallbackRun({
4043
+ value,
4044
+ issues: []
4045
+ }, ctx);
4046
+ } else result = schema._zod.run({
4047
+ value,
4048
+ issues: []
4049
+ }, ctx);
4050
+ if (result instanceof Promise) throw new $ZodAsyncError();
4051
+ return result.issues.length === 0;
4052
+ }
4053
+ const validateAsync$1 = async (schema, value, _ctx) => {
4054
+ const ctx = _ctx ? {
4055
+ ..._ctx,
4056
+ async: true,
4057
+ abortEarly: true
4058
+ } : {
4059
+ async: true,
4060
+ abortEarly: true
4061
+ };
4062
+ let result = schema._zod.run({
4063
+ value,
4064
+ issues: []
4065
+ }, ctx);
4066
+ if (result instanceof Promise) result = await result;
4067
+ return result.issues.length === 0;
4068
+ };
4069
+ const _encode = (_Err) => {
4070
+ const parse = _parse(_Err);
4071
+ const fn = (schema, value, _ctx, _params) => {
4072
+ return parse(schema, value, _ctx ? {
4073
+ ..._ctx,
4074
+ direction: "backward"
4075
+ } : { direction: "backward" }, finalizeParams(fn, _params));
4076
+ };
4077
+ return fn;
3666
4078
  };
3667
- const _decode = (_Err) => (schema, value, _ctx) => {
3668
- return _parse(_Err)(schema, value, _ctx);
4079
+ const _decode = (_Err) => {
4080
+ const parse = _parse(_Err);
4081
+ const fn = (schema, value, _ctx, _params) => {
4082
+ return parse(schema, value, _ctx, finalizeParams(fn, _params));
4083
+ };
4084
+ return fn;
3669
4085
  };
3670
- const _encodeAsync = (_Err) => async (schema, value, _ctx) => {
3671
- const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
3672
- return _parseAsync(_Err)(schema, value, ctx);
4086
+ const _encodeAsync = (_Err) => {
4087
+ const parseAsync = _parseAsync(_Err);
4088
+ const fn = async (schema, value, _ctx, _params) => {
4089
+ return await parseAsync(schema, value, _ctx ? {
4090
+ ..._ctx,
4091
+ direction: "backward"
4092
+ } : { direction: "backward" }, finalizeParams(fn, _params));
4093
+ };
4094
+ return fn;
3673
4095
  };
3674
- const _decodeAsync = (_Err) => async (schema, value, _ctx) => {
3675
- return _parseAsync(_Err)(schema, value, _ctx);
4096
+ const _decodeAsync = (_Err) => {
4097
+ const parseAsync = _parseAsync(_Err);
4098
+ const fn = async (schema, value, _ctx, _params) => {
4099
+ return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));
4100
+ };
4101
+ return fn;
3676
4102
  };
3677
4103
  const _safeEncode = (_Err) => (schema, value, _ctx) => {
3678
- const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
4104
+ const ctx = _ctx ? {
4105
+ ..._ctx,
4106
+ direction: "backward"
4107
+ } : { direction: "backward" };
3679
4108
  return _safeParse(_Err)(schema, value, ctx);
3680
4109
  };
3681
4110
  const _safeDecode = (_Err) => (schema, value, _ctx) => {
3682
4111
  return _safeParse(_Err)(schema, value, _ctx);
3683
4112
  };
3684
4113
  const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
3685
- const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
4114
+ const ctx = _ctx ? {
4115
+ ..._ctx,
4116
+ direction: "backward"
4117
+ } : { direction: "backward" };
3686
4118
  return _safeParseAsync(_Err)(schema, value, ctx);
3687
4119
  };
3688
4120
  const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
3689
4121
  return _safeParseAsync(_Err)(schema, value, _ctx);
3690
4122
  };
3691
- const cuid = /^[cC][^\s-]{8,}$/;
4123
+ /**
4124
+ * @deprecated CUID v1 is deprecated by its authors due to information leakage
4125
+ * (timestamps embedded in the id). Use {@link cuid2} instead.
4126
+ * See https://github.com/paralleldrive/cuid.
4127
+ */
4128
+ const cuid = /^[cC][0-9a-z]{6,}$/;
3692
4129
  const cuid2 = /^[0-9a-z]+$/;
3693
- const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
4130
+ const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;
3694
4131
  const xid = /^[0-9a-vA-V]{20}$/;
3695
4132
  const ksuid = /^[A-Za-z0-9]{27}$/;
3696
4133
  const nanoid = /^[a-zA-Z0-9_-]{21}$/;
4134
+ function nanoidOfLength(length) {
4135
+ return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);
4136
+ }
3697
4137
  /** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */
3698
- const duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
4138
+ const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
3699
4139
  /** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */
3700
4140
  const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
3701
4141
  /** Returns a regex for validating an RFC 9562/4122 UUID.
@@ -3706,39 +4146,45 @@ const uuid = (version) => {
3706
4146
  return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
3707
4147
  };
3708
4148
  /** Practical email validation */
3709
- const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
3710
- const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
4149
+ const email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
4150
+ const _emoji$1 = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;
3711
4151
  function emoji() {
3712
4152
  return new RegExp(_emoji$1, "u");
3713
4153
  }
3714
4154
  const ipv4 = /^(?:(?: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])$/;
3715
4155
  const ipv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))$/;
3716
4156
  const cidrv4 = /^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/;
3717
- const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
4157
+ const cidrv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
3718
4158
  const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
3719
- const base64url = /^[A-Za-z0-9_-]*$/;
4159
+ const base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;
4160
+ const httpProtocol = /^https?$/;
3720
4161
  const e164 = /^\+[1-9]\d{6,14}$/;
3721
4162
  const dateSource = `(?:(?:\\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])))`;
3722
- const date$1 = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
4163
+ /** Anchors a pattern source. The interpolation lives here rather than at the call site because
4164
+ * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it
4165
+ * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */
4166
+ function anchor(source) {
4167
+ return new RegExp(`^${source}$`);
4168
+ }
4169
+ const date = /* @__PURE__ */ anchor(dateSource);
3723
4170
  function timeSource(args) {
3724
4171
  const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
3725
- return typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
4172
+ return typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
3726
4173
  }
3727
- function time$1(args) {
4174
+ function time(args) {
3728
4175
  return new RegExp(`^${timeSource(args)}$`);
3729
4176
  }
3730
- function datetime$1(args) {
3731
- const time = timeSource({ precision: args.precision });
4177
+ function datetime(args) {
3732
4178
  const opts = ["Z"];
3733
- if (args.local) opts.push("");
3734
4179
  if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
3735
- const timeRegex = `${time}(?:${opts.join("|")})`;
4180
+ const qualified = `${timeSource({
4181
+ precision: args.precision,
4182
+ seconds: true
4183
+ })}(?:${opts.join("|")})`;
4184
+ const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;
3736
4185
  return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
3737
4186
  }
3738
- const string$1 = (params) => {
3739
- const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
3740
- return new RegExp(`^${regex}$`);
3741
- };
4187
+ const anyString = /^[\s\S]{0,}$/;
3742
4188
  const integer = /^-?\d+$/;
3743
4189
  const number$1 = /^-?\d+(?:\.\d+)?$/;
3744
4190
  const boolean$1 = /^(?:true|false)$/i;
@@ -3750,6 +4196,11 @@ const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
3750
4196
  inst._zod.def = def;
3751
4197
  (_a = inst._zod).onattach ?? (_a.onattach = []);
3752
4198
  });
4199
+ /** Default `when` for length-based checks: run only on non-nullish values with a `length`. */
4200
+ const _whenHasLength = (payload) => {
4201
+ const val = payload.value;
4202
+ return !nullish(val) && val.length !== void 0;
4203
+ };
3753
4204
  const numericOriginMap = {
3754
4205
  number: "number",
3755
4206
  bigint: "bigint",
@@ -3758,16 +4209,10 @@ const numericOriginMap = {
3758
4209
  const $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
3759
4210
  $ZodCheck.init(inst, def);
3760
4211
  const origin = numericOriginMap[typeof def.value];
3761
- inst._zod.onattach.push((inst) => {
3762
- const bag = inst._zod.bag;
3763
- const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;
3764
- if (def.value < curr) if (def.inclusive) bag.maximum = def.value;
3765
- else bag.exclusiveMaximum = def.value;
3766
- });
3767
4212
  inst._zod.check = (payload) => {
3768
4213
  if (def.inclusive ? payload.value <= def.value : payload.value < def.value) return;
3769
4214
  payload.issues.push({
3770
- origin,
4215
+ origin: numericOriginMap[typeof payload.value] ?? origin,
3771
4216
  code: "too_big",
3772
4217
  maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
3773
4218
  input: payload.value,
@@ -3780,16 +4225,10 @@ const $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (ins
3780
4225
  const $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
3781
4226
  $ZodCheck.init(inst, def);
3782
4227
  const origin = numericOriginMap[typeof def.value];
3783
- inst._zod.onattach.push((inst) => {
3784
- const bag = inst._zod.bag;
3785
- const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;
3786
- if (def.value > curr) if (def.inclusive) bag.minimum = def.value;
3787
- else bag.exclusiveMinimum = def.value;
3788
- });
3789
4228
  inst._zod.check = (payload) => {
3790
4229
  if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return;
3791
4230
  payload.issues.push({
3792
- origin,
4231
+ origin: numericOriginMap[typeof payload.value] ?? origin,
3793
4232
  code: "too_small",
3794
4233
  minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
3795
4234
  input: payload.value,
@@ -3801,13 +4240,9 @@ const $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan"
3801
4240
  });
3802
4241
  const $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
3803
4242
  $ZodCheck.init(inst, def);
3804
- inst._zod.onattach.push((inst) => {
3805
- var _a;
3806
- (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);
3807
- });
3808
4243
  inst._zod.check = (payload) => {
3809
4244
  if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check.");
3810
- if (typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0) return;
4245
+ if (typeof payload.value === "bigint" ? def.value !== BigInt(0) && payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0) return;
3811
4246
  payload.issues.push({
3812
4247
  origin: typeof payload.value,
3813
4248
  code: "not_multiple_of",
@@ -3824,13 +4259,6 @@ const $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberForma
3824
4259
  const isInt = def.format?.includes("int");
3825
4260
  const origin = isInt ? "int" : "number";
3826
4261
  const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
3827
- inst._zod.onattach.push((inst) => {
3828
- const bag = inst._zod.bag;
3829
- bag.format = def.format;
3830
- bag.minimum = minimum;
3831
- bag.maximum = maximum;
3832
- if (isInt) bag.pattern = integer;
3833
- });
3834
4262
  inst._zod.check = (payload) => {
3835
4263
  const input = payload.value;
3836
4264
  if (isInt) {
@@ -3892,17 +4320,11 @@ const $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberForma
3892
4320
  const $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
3893
4321
  var _a;
3894
4322
  $ZodCheck.init(inst, def);
3895
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
3896
- const val = payload.value;
3897
- return !nullish(val) && val.length !== void 0;
3898
- });
3899
- inst._zod.onattach.push((inst) => {
3900
- const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
3901
- if (def.maximum < curr) inst._zod.bag.maximum = def.maximum;
3902
- });
4323
+ (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
3903
4324
  inst._zod.check = (payload) => {
3904
4325
  const input = payload.value;
3905
- if (input.length <= def.maximum) return;
4326
+ const units = input.length;
4327
+ if ((typeof input === "string" && units > def.maximum ? codePointLength(input) : units) <= def.maximum) return;
3906
4328
  const origin = getLengthableOrigin(input);
3907
4329
  payload.issues.push({
3908
4330
  origin,
@@ -3918,17 +4340,11 @@ const $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (i
3918
4340
  const $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
3919
4341
  var _a;
3920
4342
  $ZodCheck.init(inst, def);
3921
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
3922
- const val = payload.value;
3923
- return !nullish(val) && val.length !== void 0;
3924
- });
3925
- inst._zod.onattach.push((inst) => {
3926
- const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
3927
- if (def.minimum > curr) inst._zod.bag.minimum = def.minimum;
3928
- });
4343
+ (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
3929
4344
  inst._zod.check = (payload) => {
3930
4345
  const input = payload.value;
3931
- if (input.length >= def.minimum) return;
4346
+ const units = input.length;
4347
+ if ((typeof input === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input) : units) >= def.minimum) return;
3932
4348
  const origin = getLengthableOrigin(input);
3933
4349
  payload.issues.push({
3934
4350
  origin,
@@ -3944,19 +4360,11 @@ const $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (i
3944
4360
  const $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
3945
4361
  var _a;
3946
4362
  $ZodCheck.init(inst, def);
3947
- (_a = inst._zod.def).when ?? (_a.when = (payload) => {
3948
- const val = payload.value;
3949
- return !nullish(val) && val.length !== void 0;
3950
- });
3951
- inst._zod.onattach.push((inst) => {
3952
- const bag = inst._zod.bag;
3953
- bag.minimum = def.length;
3954
- bag.maximum = def.length;
3955
- bag.length = def.length;
3956
- });
4363
+ (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
3957
4364
  inst._zod.check = (payload) => {
3958
4365
  const input = payload.value;
3959
- const length = input.length;
4366
+ const units = input.length;
4367
+ const length = typeof input === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input) : units;
3960
4368
  if (length === def.length) return;
3961
4369
  const origin = getLengthableOrigin(input);
3962
4370
  const tooBig = length > def.length;
@@ -3980,14 +4388,6 @@ const $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEqual
3980
4388
  const $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
3981
4389
  var _a, _b;
3982
4390
  $ZodCheck.init(inst, def);
3983
- inst._zod.onattach.push((inst) => {
3984
- const bag = inst._zod.bag;
3985
- bag.format = def.format;
3986
- if (def.pattern) {
3987
- bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
3988
- bag.patterns.add(def.pattern);
3989
- }
3990
- });
3991
4391
  if (def.pattern) (_a = inst._zod).check ?? (_a.check = (payload) => {
3992
4392
  def.pattern.lastIndex = 0;
3993
4393
  if (def.pattern.test(payload.value)) return;
@@ -4030,13 +4430,7 @@ const $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (i
4030
4430
  const $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
4031
4431
  $ZodCheck.init(inst, def);
4032
4432
  const escapedRegex = escapeRegex(def.includes);
4033
- const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
4034
- def.pattern = pattern;
4035
- inst._zod.onattach.push((inst) => {
4036
- const bag = inst._zod.bag;
4037
- bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
4038
- bag.patterns.add(pattern);
4039
- });
4433
+ def.pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);
4040
4434
  inst._zod.check = (payload) => {
4041
4435
  if (payload.value.includes(def.includes, def.position)) return;
4042
4436
  payload.issues.push({
@@ -4054,11 +4448,6 @@ const $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith",
4054
4448
  $ZodCheck.init(inst, def);
4055
4449
  const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
4056
4450
  def.pattern ?? (def.pattern = pattern);
4057
- inst._zod.onattach.push((inst) => {
4058
- const bag = inst._zod.bag;
4059
- bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
4060
- bag.patterns.add(pattern);
4061
- });
4062
4451
  inst._zod.check = (payload) => {
4063
4452
  if (payload.value.startsWith(def.prefix)) return;
4064
4453
  payload.issues.push({
@@ -4076,11 +4465,6 @@ const $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (ins
4076
4465
  $ZodCheck.init(inst, def);
4077
4466
  const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
4078
4467
  def.pattern ?? (def.pattern = pattern);
4079
- inst._zod.onattach.push((inst) => {
4080
- const bag = inst._zod.bag;
4081
- bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
4082
- bag.patterns.add(pattern);
4083
- });
4084
4468
  inst._zod.check = (payload) => {
4085
4469
  if (payload.value.endsWith(def.suffix)) return;
4086
4470
  payload.issues.push({
@@ -4101,15 +4485,19 @@ const $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (i
4101
4485
  };
4102
4486
  });
4103
4487
  var Doc = class {
4104
- constructor(args = []) {
4488
+ constructor(args = [], closed = {}) {
4105
4489
  this.content = [];
4106
4490
  this.indent = 0;
4107
- if (this) this.args = args;
4491
+ this.args = args;
4492
+ this.closed = closed;
4108
4493
  }
4109
4494
  indented(fn) {
4110
4495
  this.indent += 1;
4111
- fn(this);
4112
- this.indent -= 1;
4496
+ try {
4497
+ fn(this);
4498
+ } finally {
4499
+ this.indent -= 1;
4500
+ }
4113
4501
  }
4114
4502
  write(arg) {
4115
4503
  if (typeof arg === "function") {
@@ -4124,15 +4512,14 @@ var Doc = class {
4124
4512
  }
4125
4513
  compile() {
4126
4514
  const F = Function;
4127
- const args = this?.args;
4128
- const lines = [...(this?.content ?? [``]).map((x) => ` ${x}`)];
4129
- return new F(...args, lines.join("\n"));
4515
+ const content = this?.content ?? [``];
4516
+ return new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`)(...Object.values(this.closed));
4130
4517
  }
4131
4518
  };
4132
4519
  const version = {
4133
4520
  major: 4,
4134
- minor: 3,
4135
- patch: 6
4521
+ minor: 6,
4522
+ patch: 7
4136
4523
  };
4137
4524
  const $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
4138
4525
  var _a;
@@ -4140,8 +4527,8 @@ const $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
4140
4527
  inst._zod.def = def;
4141
4528
  inst._zod.bag = inst._zod.bag || {};
4142
4529
  inst._zod.version = version;
4143
- const checks = [...inst._zod.def.checks ?? []];
4144
- if (inst._zod.traits.has("$ZodCheck")) checks.unshift(inst);
4530
+ const defChecks = inst._zod.def.checks;
4531
+ const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : [];
4145
4532
  for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst);
4146
4533
  if (checks.length === 0) {
4147
4534
  (_a = inst._zod).deferred ?? (_a.deferred = []);
@@ -4150,10 +4537,12 @@ const $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
4150
4537
  });
4151
4538
  } else {
4152
4539
  const runChecks = (payload, checks, ctx) => {
4540
+ if (payload.memo) return payload;
4153
4541
  let isAborted = aborted(payload);
4154
4542
  let asyncResult;
4155
4543
  for (const ch of checks) {
4156
4544
  if (ch._zod.def.when) {
4545
+ if (explicitlyAborted(payload)) continue;
4157
4546
  if (!ch._zod.def.when(payload)) continue;
4158
4547
  } else if (isAborted) continue;
4159
4548
  const currLen = payload.issues.length;
@@ -4162,10 +4551,12 @@ const $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
4162
4551
  if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
4163
4552
  await _;
4164
4553
  if (payload.issues.length === currLen) return;
4554
+ attachSchema(payload.issues, currLen, inst);
4165
4555
  if (!isAborted) isAborted = aborted(payload, currLen);
4166
4556
  });
4167
4557
  else {
4168
4558
  if (payload.issues.length === currLen) continue;
4559
+ attachSchema(payload.issues, currLen, inst);
4169
4560
  if (!isAborted) isAborted = aborted(payload, currLen);
4170
4561
  }
4171
4562
  }
@@ -4209,22 +4600,43 @@ const $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
4209
4600
  return runChecks(result, checks, ctx);
4210
4601
  };
4211
4602
  }
4212
- defineLazy(inst, "~standard", () => ({
4603
+ }, {
4604
+ get "~standard"() {
4605
+ return hide(this, "~standard", standardProps(this));
4606
+ },
4607
+ set "~standard"(value) {
4608
+ own(this, "~standard", value);
4609
+ }
4610
+ });
4611
+ /** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */
4612
+ const toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value };
4613
+ async function validateAsync(inst, value) {
4614
+ const ctx = { async: true };
4615
+ return toStandardResult(await inst._zod.run({
4616
+ value,
4617
+ issues: []
4618
+ }, ctx), ctx);
4619
+ }
4620
+ function standardProps(inst) {
4621
+ return {
4213
4622
  validate: (value) => {
4623
+ const ctx = { async: false };
4214
4624
  try {
4215
- const r = safeParse$1(inst, value);
4216
- return r.success ? { value: r.data } : { issues: r.error?.issues };
4217
- } catch (_) {
4218
- return safeParseAsync$1(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
4219
- }
4625
+ const r = inst._zod.run({
4626
+ value,
4627
+ issues: []
4628
+ }, ctx);
4629
+ if (!(r instanceof Promise)) return toStandardResult(r, ctx);
4630
+ } catch (_) {}
4631
+ return validateAsync(inst, value);
4220
4632
  },
4221
4633
  vendor: "zod",
4222
4634
  version: 1
4223
- }));
4224
- });
4635
+ };
4636
+ }
4225
4637
  const $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
4226
4638
  $ZodType.init(inst, def);
4227
- inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string$1(inst._zod.bag);
4639
+ inst._zod.pattern = def.pattern ?? anyString;
4228
4640
  inst._zod.parse = (payload, _) => {
4229
4641
  if (def.coerce) try {
4230
4642
  payload.value = String(payload.value);
@@ -4268,38 +4680,95 @@ const $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
4268
4680
  def.pattern ?? (def.pattern = email);
4269
4681
  $ZodStringFormat.init(inst, def);
4270
4682
  });
4683
+ function canParseURL(input) {
4684
+ try {
4685
+ if (typeof URL !== "undefined" && typeof URL.canParse === "function") return URL.canParse(input);
4686
+ new URL(input);
4687
+ return true;
4688
+ } catch {
4689
+ return false;
4690
+ }
4691
+ }
4692
+ function validateURL(trimmed, def) {
4693
+ if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) return canParseURL(trimmed) || 2;
4694
+ return parseURLObject(trimmed, def);
4695
+ }
4696
+ /** Parses a URL while preserving the non-normalizing HTTP guard. */
4697
+ function parseURLObject(trimmed, def) {
4698
+ if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) return 1;
4699
+ try {
4700
+ if (typeof URL !== "undefined") {
4701
+ const URLStatic = URL;
4702
+ if (typeof URLStatic.parse === "function") return URLStatic.parse(trimmed) ?? 2;
4703
+ }
4704
+ return new URL(trimmed);
4705
+ } catch {
4706
+ return 2;
4707
+ }
4708
+ }
4709
+ const asciiTabOrNewline = /[\t\n\r]/g;
4710
+ /** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL("https://exa\nmple.com")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */
4711
+ function stripTabAndNewline(value) {
4712
+ return value.replace(asciiTabOrNewline, "");
4713
+ }
4714
+ function urlHostnameOk(url, hostname) {
4715
+ hostname.lastIndex = 0;
4716
+ return hostname.test(url.hostname);
4717
+ }
4718
+ function urlProtocolOk(url, protocol) {
4719
+ protocol.lastIndex = 0;
4720
+ return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol);
4721
+ }
4271
4722
  const $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
4272
4723
  $ZodStringFormat.init(inst, def);
4273
4724
  inst._zod.check = (payload) => {
4274
4725
  try {
4275
4726
  const trimmed = payload.value.trim();
4276
- const url = new URL(trimmed);
4277
- if (def.hostname) {
4278
- def.hostname.lastIndex = 0;
4279
- if (!def.hostname.test(url.hostname)) payload.issues.push({
4727
+ const url = validateURL(trimmed, def);
4728
+ if (url === 1) {
4729
+ payload.issues.push({
4280
4730
  code: "invalid_format",
4281
4731
  format: "url",
4282
- note: "Invalid hostname",
4283
- pattern: def.hostname.source,
4732
+ note: "Invalid URL format",
4284
4733
  input: payload.value,
4285
4734
  inst,
4286
4735
  continue: !def.abort
4287
4736
  });
4737
+ return;
4288
4738
  }
4289
- if (def.protocol) {
4290
- def.protocol.lastIndex = 0;
4291
- if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) payload.issues.push({
4739
+ if (url === 2) {
4740
+ payload.issues.push({
4292
4741
  code: "invalid_format",
4293
4742
  format: "url",
4294
- note: "Invalid protocol",
4295
- pattern: def.protocol.source,
4296
4743
  input: payload.value,
4297
4744
  inst,
4298
4745
  continue: !def.abort
4299
4746
  });
4747
+ return;
4300
4748
  }
4301
- if (def.normalize) payload.value = url.href;
4302
- else payload.value = trimmed;
4749
+ if (url === true) {
4750
+ payload.value = stripTabAndNewline(trimmed);
4751
+ return;
4752
+ }
4753
+ if (def.hostname && !urlHostnameOk(url, def.hostname)) payload.issues.push({
4754
+ code: "invalid_format",
4755
+ format: "url",
4756
+ note: "Invalid hostname",
4757
+ pattern: def.hostname.source,
4758
+ input: payload.value,
4759
+ inst,
4760
+ continue: !def.abort
4761
+ });
4762
+ if (def.protocol && !urlProtocolOk(url, def.protocol)) payload.issues.push({
4763
+ code: "invalid_format",
4764
+ format: "url",
4765
+ note: "Invalid protocol",
4766
+ pattern: def.protocol.source,
4767
+ input: payload.value,
4768
+ inst,
4769
+ continue: !def.abort
4770
+ });
4771
+ payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);
4303
4772
  return;
4304
4773
  } catch (_) {
4305
4774
  payload.issues.push({
@@ -4317,9 +4786,15 @@ const $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
4317
4786
  $ZodStringFormat.init(inst, def);
4318
4787
  });
4319
4788
  const $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
4320
- def.pattern ?? (def.pattern = nanoid);
4789
+ if (def.length !== void 0 && (!Number.isInteger(def.length) || def.length < 1)) throw new Error(`Invalid nanoid length: ${def.length}`);
4790
+ def.pattern ?? (def.pattern = def.length === void 0 ? nanoid : nanoidOfLength(def.length));
4321
4791
  $ZodStringFormat.init(inst, def);
4322
4792
  });
4793
+ /**
4794
+ * @deprecated CUID v1 is deprecated by its authors due to information leakage
4795
+ * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.
4796
+ * See https://github.com/paralleldrive/cuid.
4797
+ */
4323
4798
  const $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
4324
4799
  def.pattern ?? (def.pattern = cuid);
4325
4800
  $ZodStringFormat.init(inst, def);
@@ -4341,74 +4816,74 @@ const $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
4341
4816
  $ZodStringFormat.init(inst, def);
4342
4817
  });
4343
4818
  const $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
4344
- def.pattern ?? (def.pattern = datetime$1(def));
4819
+ def.pattern ?? (def.pattern = datetime(def));
4345
4820
  $ZodStringFormat.init(inst, def);
4346
4821
  });
4347
4822
  const $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
4348
- def.pattern ?? (def.pattern = date$1);
4823
+ def.pattern ?? (def.pattern = date);
4349
4824
  $ZodStringFormat.init(inst, def);
4350
4825
  });
4351
4826
  const $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
4352
- def.pattern ?? (def.pattern = time$1(def));
4827
+ def.pattern ?? (def.pattern = time(def));
4353
4828
  $ZodStringFormat.init(inst, def);
4354
4829
  });
4355
4830
  const $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
4356
- def.pattern ?? (def.pattern = duration$1);
4831
+ def.pattern ?? (def.pattern = duration);
4357
4832
  $ZodStringFormat.init(inst, def);
4358
4833
  });
4359
4834
  const $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
4360
4835
  def.pattern ?? (def.pattern = ipv4);
4361
4836
  $ZodStringFormat.init(inst, def);
4362
- inst._zod.bag.format = `ipv4`;
4363
4837
  });
4838
+ /** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL("http://[...]")` parses an authority, not an address, so `@` and `\` re-delimit it and `"::@1\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `"::1\n"` validated as `::1`. */
4839
+ const ipv6Alphabet = /^[0-9a-fA-F:.]+$/;
4840
+ function isValidIPv6(value) {
4841
+ if (!ipv6Alphabet.test(value)) return false;
4842
+ return canParseURL(`http://[${value}]`);
4843
+ }
4364
4844
  const $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
4365
4845
  def.pattern ?? (def.pattern = ipv6);
4366
4846
  $ZodStringFormat.init(inst, def);
4367
- inst._zod.bag.format = `ipv6`;
4368
4847
  inst._zod.check = (payload) => {
4369
- try {
4370
- new URL(`http://[${payload.value}]`);
4371
- } catch {
4372
- payload.issues.push({
4373
- code: "invalid_format",
4374
- format: "ipv6",
4375
- input: payload.value,
4376
- inst,
4377
- continue: !def.abort
4378
- });
4379
- }
4848
+ if (!isValidIPv6(payload.value)) payload.issues.push({
4849
+ code: "invalid_format",
4850
+ format: "ipv6",
4851
+ input: payload.value,
4852
+ inst,
4853
+ continue: !def.abort
4854
+ });
4380
4855
  };
4381
4856
  });
4382
4857
  const $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
4383
4858
  def.pattern ?? (def.pattern = cidrv4);
4384
4859
  $ZodStringFormat.init(inst, def);
4385
4860
  });
4861
+ function isValidCIDRv6(value) {
4862
+ const parts = value.split("/");
4863
+ if (parts.length !== 2) return false;
4864
+ const [address, prefix] = parts;
4865
+ if (!prefix) return false;
4866
+ const prefixNum = Number(prefix);
4867
+ if (`${prefixNum}` !== prefix) return false;
4868
+ if (prefixNum < 0 || prefixNum > 128) return false;
4869
+ return isValidIPv6(address);
4870
+ }
4386
4871
  const $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
4387
4872
  def.pattern ?? (def.pattern = cidrv6);
4388
4873
  $ZodStringFormat.init(inst, def);
4389
4874
  inst._zod.check = (payload) => {
4390
- const parts = payload.value.split("/");
4391
- try {
4392
- if (parts.length !== 2) throw new Error();
4393
- const [address, prefix] = parts;
4394
- if (!prefix) throw new Error();
4395
- const prefixNum = Number(prefix);
4396
- if (`${prefixNum}` !== prefix) throw new Error();
4397
- if (prefixNum < 0 || prefixNum > 128) throw new Error();
4398
- new URL(`http://[${address}]`);
4399
- } catch {
4400
- payload.issues.push({
4401
- code: "invalid_format",
4402
- format: "cidrv6",
4403
- input: payload.value,
4404
- inst,
4405
- continue: !def.abort
4406
- });
4407
- }
4875
+ if (!isValidCIDRv6(payload.value)) payload.issues.push({
4876
+ code: "invalid_format",
4877
+ format: "cidrv6",
4878
+ input: payload.value,
4879
+ inst,
4880
+ continue: !def.abort
4881
+ });
4408
4882
  };
4409
4883
  });
4410
4884
  function isValidBase64(data) {
4411
4885
  if (data === "") return true;
4886
+ if (/\s/.test(data)) return false;
4412
4887
  if (data.length % 4 !== 0) return false;
4413
4888
  try {
4414
4889
  atob(data);
@@ -4417,10 +4892,10 @@ function isValidBase64(data) {
4417
4892
  return false;
4418
4893
  }
4419
4894
  }
4895
+ const base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;
4420
4896
  const $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
4421
- def.pattern ?? (def.pattern = base64);
4897
+ def.pattern ?? (def.pattern = base64Charset);
4422
4898
  $ZodStringFormat.init(inst, def);
4423
- inst._zod.bag.contentEncoding = "base64";
4424
4899
  inst._zod.check = (payload) => {
4425
4900
  if (isValidBase64(payload.value)) return;
4426
4901
  payload.issues.push({
@@ -4432,15 +4907,15 @@ const $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
4432
4907
  });
4433
4908
  };
4434
4909
  });
4910
+ const base64urlCharset = /^[A-Za-z0-9_-]*$/;
4435
4911
  function isValidBase64URL(data) {
4436
- if (!base64url.test(data)) return false;
4912
+ if (!base64urlCharset.test(data)) return false;
4437
4913
  const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
4438
4914
  return isValidBase64(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="));
4439
4915
  }
4440
4916
  const $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
4441
- def.pattern ?? (def.pattern = base64url);
4917
+ def.pattern ?? (def.pattern = base64urlCharset);
4442
4918
  $ZodStringFormat.init(inst, def);
4443
- inst._zod.bag.contentEncoding = "base64url";
4444
4919
  inst._zod.check = (payload) => {
4445
4920
  if (isValidBase64URL(payload.value)) return;
4446
4921
  payload.issues.push({
@@ -4486,14 +4961,14 @@ const $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
4486
4961
  });
4487
4962
  const $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
4488
4963
  $ZodType.init(inst, def);
4489
- inst._zod.pattern = inst._zod.bag.pattern ?? number$1;
4964
+ inst._zod.pattern = number$1;
4490
4965
  inst._zod.parse = (payload, _ctx) => {
4491
4966
  if (def.coerce) try {
4492
4967
  payload.value = Number(payload.value);
4493
4968
  } catch (_) {}
4494
4969
  const input = payload.value;
4495
4970
  if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) return payload;
4496
- const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
4971
+ const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? String(input) : void 0 : void 0;
4497
4972
  payload.issues.push({
4498
4973
  expected: "number",
4499
4974
  code: "invalid_type",
@@ -4542,12 +5017,34 @@ const $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
4542
5017
  return payload;
4543
5018
  };
4544
5019
  });
5020
+ function capSize(inst, size) {
5021
+ const caps = sizeCaps(inst._zod.def.checks);
5022
+ if (!caps.length) return;
5023
+ const cap = Math.min(...caps.map((c) => c[0]));
5024
+ const parse = inst._zod.parse;
5025
+ inst._zod.parse = (payload, ctx) => {
5026
+ const n = size(payload.value);
5027
+ if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") {
5028
+ for (const [max, ch] of sizeCaps(inst._zod.def.checks)) if (n > max && ch._zod.def.when(payload)) {
5029
+ const start = payload.issues.length;
5030
+ ch._zod.check(payload);
5031
+ payload.issues[start].continue = false;
5032
+ attachSchema(payload.issues, start, inst);
5033
+ return payload;
5034
+ }
5035
+ }
5036
+ return parse(payload, ctx);
5037
+ };
5038
+ }
5039
+ const arraySize = (input) => Array.isArray(input) ? input.length : -1;
4545
5040
  function handleArrayResult(result, final, index) {
4546
5041
  if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues));
4547
5042
  final.value[index] = result.value;
4548
5043
  }
4549
5044
  const $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
4550
5045
  $ZodType.init(inst, def);
5046
+ const memo = globalConfig.memoizer;
5047
+ memo?.attach(inst);
4551
5048
  inst._zod.parse = (payload, ctx) => {
4552
5049
  const input = payload.value;
4553
5050
  if (!Array.isArray(input)) {
@@ -4559,8 +5056,9 @@ const $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
4559
5056
  });
4560
5057
  return payload;
4561
5058
  }
4562
- payload.value = Array(input.length);
5059
+ payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);
4563
5060
  const proms = [];
5061
+ const abortEarly = ctx?.abortEarly;
4564
5062
  for (let i = 0; i < input.length; i++) {
4565
5063
  const item = input[i];
4566
5064
  const result = def.element._zod.run({
@@ -4568,41 +5066,72 @@ const $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
4568
5066
  issues: []
4569
5067
  }, ctx);
4570
5068
  if (result instanceof Promise) proms.push(result.then((result) => handleArrayResult(result, payload, i)));
4571
- else handleArrayResult(result, payload, i);
5069
+ else {
5070
+ handleArrayResult(result, payload, i);
5071
+ if (abortEarly && result.issues.length !== 0 && aborted(result)) break;
5072
+ }
4572
5073
  }
4573
5074
  if (proms.length) return Promise.all(proms).then(() => payload);
4574
5075
  return payload;
4575
5076
  };
5077
+ capSize(inst, arraySize);
4576
5078
  });
4577
- function handlePropertyResult(result, final, key, input, isOptionalOut) {
5079
+ function handlePropertyResult(result, final, key, input, optin, optout) {
5080
+ const isPresent = key in input;
5081
+ const isOptionalOut = optout === "optional";
5082
+ if (!isPresent && isOptionalOut && optin === "optional") return;
4578
5083
  if (result.issues.length) {
4579
- if (isOptionalOut && !(key in input)) return;
5084
+ if (optin !== void 0 && isOptionalOut && !isPresent) return;
4580
5085
  final.issues.push(...prefixIssues(key, result.issues));
4581
5086
  }
5087
+ if (!isPresent && optin === void 0) {
5088
+ if (!result.issues.length) final.issues.push({
5089
+ code: "invalid_type",
5090
+ expected: "nonoptional",
5091
+ input: void 0,
5092
+ path: [key]
5093
+ });
5094
+ return;
5095
+ }
4582
5096
  if (result.value === void 0) {
4583
- if (key in input) final.value[key] = void 0;
5097
+ if (isPresent || optin === "defaulted" && !isOptionalOut) final.value[key] = void 0;
4584
5098
  } else final.value[key] = result.value;
4585
5099
  }
5100
+ const NO_SYMBOL_KEYS = [];
4586
5101
  function normalizeDef(def) {
4587
5102
  const keys = Object.keys(def.shape);
4588
- for (const k of keys) if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
5103
+ const ownSymbols = Object.getOwnPropertySymbols(def.shape);
5104
+ const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;
5105
+ const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;
5106
+ for (const k of allKeys) if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`);
4589
5107
  const okeys = optionalKeys(def.shape);
4590
5108
  return {
4591
5109
  ...def,
4592
- keys,
5110
+ allKeys,
5111
+ symbolKeys,
4593
5112
  keySet: new Set(keys),
4594
5113
  numKeys: keys.length,
4595
5114
  optionalKeys: new Set(okeys)
4596
5115
  };
4597
5116
  }
4598
- function handleCatchall(proms, input, payload, ctx, def, inst) {
5117
+ function handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {
4599
5118
  const unrecognized = [];
4600
5119
  const keySet = def.keySet;
4601
5120
  const _catchall = def.catchall._zod;
4602
5121
  const t = _catchall.def.type;
4603
- const isOptionalOut = _catchall.optout === "optional";
5122
+ const optin = _catchall.optin;
5123
+ const optout = _catchall.optout;
5124
+ let seen = 0;
4604
5125
  for (const key in input) {
5126
+ if (abortEarly && payload.issues.length !== seen) {
5127
+ if (aborted(payload, seen)) break;
5128
+ seen = payload.issues.length;
5129
+ }
4605
5130
  if (keySet.has(key)) continue;
5131
+ if (key === "__proto__") {
5132
+ if (t === "never") unrecognized.push(key);
5133
+ continue;
5134
+ }
4606
5135
  if (t === "never") {
4607
5136
  unrecognized.push(key);
4608
5137
  continue;
@@ -4611,14 +5140,15 @@ function handleCatchall(proms, input, payload, ctx, def, inst) {
4611
5140
  value: input[key],
4612
5141
  issues: []
4613
5142
  }, ctx);
4614
- if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));
4615
- else handlePropertyResult(r, payload, key, input, isOptionalOut);
5143
+ if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));
5144
+ else handlePropertyResult(r, payload, key, input, optin, optout);
4616
5145
  }
4617
5146
  if (unrecognized.length) payload.issues.push({
4618
5147
  code: "unrecognized_keys",
4619
5148
  keys: unrecognized,
4620
5149
  input,
4621
- inst
5150
+ inst,
5151
+ continue: true
4622
5152
  });
4623
5153
  if (!proms.length) return payload;
4624
5154
  return Promise.all(proms).then(() => {
@@ -4627,34 +5157,41 @@ function handleCatchall(proms, input, payload, ctx, def, inst) {
4627
5157
  }
4628
5158
  const $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
4629
5159
  $ZodType.init(inst, def);
4630
- if (!Object.getOwnPropertyDescriptor(def, "shape")?.get) {
4631
- const sh = def.shape;
4632
- Object.defineProperty(def, "shape", { get: () => {
5160
+ const desc = Object.getOwnPropertyDescriptor(def, "shape");
5161
+ const sh = desc?.get ? desc.get.raw : def.shape ?? {};
5162
+ if (sh) {
5163
+ const get = () => {
4633
5164
  const newSh = { ...sh };
4634
5165
  Object.defineProperty(def, "shape", { value: newSh });
5166
+ get.raw = newSh;
4635
5167
  return newSh;
4636
- } });
5168
+ };
5169
+ get.raw = sh;
5170
+ Object.defineProperty(def, "shape", { get });
4637
5171
  }
4638
5172
  const _normalized = cached(() => normalizeDef(def));
4639
- defineLazy(inst._zod, "propValues", () => {
4640
- const shape = def.shape;
5173
+ defineLazyInternal(inst, "propValues", (zod) => {
5174
+ const shape = zod.def.shape;
4641
5175
  const propValues = {};
4642
5176
  for (const key in shape) {
4643
5177
  const field = shape[key]._zod;
4644
5178
  if (field.values) {
4645
- propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
5179
+ if (!Object.prototype.hasOwnProperty.call(propValues, key)) assignProp(propValues, key, /* @__PURE__ */ new Set());
4646
5180
  for (const v of field.values) propValues[key].add(v);
5181
+ if (field.optin !== void 0) propValues[key].add(void 0);
4647
5182
  }
4648
5183
  }
4649
5184
  return propValues;
4650
5185
  });
4651
- const isObject$2 = isObject;
5186
+ const isObject$1 = isObject;
4652
5187
  const catchall = def.catchall;
4653
5188
  let value;
5189
+ const memo = globalConfig.memoizer;
5190
+ memo?.attach(inst);
4654
5191
  inst._zod.parse = (payload, ctx) => {
4655
5192
  value ?? (value = _normalized.value);
4656
5193
  const input = payload.value;
4657
- if (!isObject$2(input)) {
5194
+ if (!isObject$1(input)) {
4658
5195
  payload.issues.push({
4659
5196
  expected: "object",
4660
5197
  code: "invalid_type",
@@ -4663,92 +5200,128 @@ const $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
4663
5200
  });
4664
5201
  return payload;
4665
5202
  }
4666
- payload.value = {};
5203
+ payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
4667
5204
  const proms = [];
4668
5205
  const shape = value.shape;
4669
- for (const key of value.keys) {
5206
+ const abortEarly = ctx?.abortEarly;
5207
+ let seen = payload.issues.length;
5208
+ for (const key of value.allKeys) {
5209
+ if (abortEarly && payload.issues.length !== seen) {
5210
+ if (aborted(payload, seen)) break;
5211
+ seen = payload.issues.length;
5212
+ }
5213
+ if (key === "__proto__") continue;
4670
5214
  const el = shape[key];
4671
- const isOptionalOut = el._zod.optout === "optional";
5215
+ const optin = el._zod.optin;
5216
+ const optout = el._zod.optout;
4672
5217
  const r = el._zod.run({
4673
5218
  value: input[key],
4674
5219
  issues: []
4675
5220
  }, ctx);
4676
- if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalOut)));
4677
- else handlePropertyResult(r, payload, key, input, isOptionalOut);
5221
+ if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));
5222
+ else handlePropertyResult(r, payload, key, input, optin, optout);
4678
5223
  }
4679
5224
  if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload;
4680
- return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
5225
+ return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);
4681
5226
  };
4682
5227
  });
4683
5228
  const $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
4684
5229
  $ZodObject.init(inst, def);
4685
5230
  const superParse = inst._zod.parse;
4686
5231
  const _normalized = cached(() => normalizeDef(def));
5232
+ const memo = globalConfig.memoizer;
4687
5233
  const generateFastpass = (shape) => {
4688
- const doc = new Doc([
4689
- "shape",
4690
- "payload",
4691
- "ctx"
4692
- ]);
4693
5234
  const normalized = _normalized.value;
4694
- const parseStr = (key) => {
4695
- const k = esc(key);
4696
- return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
4697
- };
5235
+ const syms = normalized.symbolKeys;
5236
+ const doc = new Doc(["payload", "ctx"], {
5237
+ shape,
5238
+ inst,
5239
+ memo,
5240
+ syms
5241
+ });
5242
+ const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
5243
+ const prefixStr = (id, k) => `
5244
+ let ${id}_ab = false;
5245
+ for (let i = 0; i < ${id}.issues.length; i++) {
5246
+ const iss = ${id}.issues[i];
5247
+ iss.path = iss.path ? [${k}, ...iss.path] : [${k}];
5248
+ payload.issues.push(iss);
5249
+ if (iss.continue !== true) ${id}_ab = true;
5250
+ }
5251
+ if (${id}_ab && ctx && ctx.abortEarly) {
5252
+ payload.value = newResult;
5253
+ return payload;
5254
+ }`;
4698
5255
  doc.write(`const input = payload.value;`);
4699
5256
  const ids = Object.create(null);
4700
5257
  let counter = 0;
4701
- for (const key of normalized.keys) ids[key] = `key_${counter++}`;
4702
- doc.write(`const newResult = {};`);
4703
- for (const key of normalized.keys) {
5258
+ for (const key of normalized.allKeys) ids[key] = `key_${counter++}`;
5259
+ doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);
5260
+ for (const key of normalized.allKeys) {
5261
+ if (key === "__proto__") continue;
4704
5262
  const id = ids[key];
4705
- const k = esc(key);
4706
- const isOptionalOut = shape[key]?._zod?.optout === "optional";
4707
- doc.write(`const ${id} = ${parseStr(key)};`);
4708
- if (isOptionalOut) doc.write(`
4709
- if (${id}.issues.length) {
4710
- if (${k} in input) {
4711
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
4712
- ...iss,
4713
- path: iss.path ? [${k}, ...iss.path] : [${k}]
4714
- })));
5263
+ const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key);
5264
+ const isPresent = `${k} in input`;
5265
+ const schema = shape[key];
5266
+ const optin = schema?._zod?.optin;
5267
+ const isOptionalIn = optin !== void 0;
5268
+ const isOptionalOut = schema?._zod?.optout === "optional";
5269
+ doc.write(`const ${id} = ${parseStr(k)};`);
5270
+ if (isOptionalIn && isOptionalOut) {
5271
+ const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;
5272
+ doc.write(`
5273
+ const ${id}_present = ${isPresent};
5274
+ if (!${id}.issues.length || ${id}_present) {
5275
+ if (${id}.issues.length) {${prefixStr(id, k)}
5276
+ }
5277
+
5278
+ if (${assign}) {
5279
+ newResult[${k}] = ${id}.value;
4715
5280
  }
4716
5281
  }
4717
-
4718
- if (${id}.value === undefined) {
4719
- if (${k} in input) {
4720
- newResult[${k}] = undefined;
5282
+
5283
+ `);
5284
+ } else if (!isOptionalIn) doc.write(`
5285
+ const ${id}_present = ${isPresent};
5286
+ if (${id}.issues.length) {${prefixStr(id, k)}
5287
+ }
5288
+ if (!${id}_present && !${id}.issues.length) {
5289
+ payload.issues.push({
5290
+ code: "invalid_type",
5291
+ expected: "nonoptional",
5292
+ input: undefined,
5293
+ path: [${k}]
5294
+ });
5295
+ if (ctx && ctx.abortEarly) {
5296
+ payload.value = newResult;
5297
+ return payload;
4721
5298
  }
4722
- } else {
5299
+ }
5300
+
5301
+ if (${id}_present) {
4723
5302
  newResult[${k}] = ${id}.value;
4724
5303
  }
4725
-
5304
+
4726
5305
  `);
4727
- else doc.write(`
4728
- if (${id}.issues.length) {
4729
- payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
4730
- ...iss,
4731
- path: iss.path ? [${k}, ...iss.path] : [${k}]
4732
- })));
5306
+ else {
5307
+ doc.write(`
5308
+ if (${id}.issues.length) {${prefixStr(id, k)}
4733
5309
  }
4734
-
4735
- if (${id}.value === undefined) {
4736
- if (${k} in input) {
4737
- newResult[${k}] = undefined;
4738
- }
4739
- } else {
5310
+ `);
5311
+ if (optin === "defaulted") doc.write(`newResult[${k}] = ${id}.value;`);
5312
+ else doc.write(`
5313
+ if (${id}.value !== undefined || ${isPresent}) {
4740
5314
  newResult[${k}] = ${id}.value;
4741
5315
  }
4742
-
4743
5316
  `);
5317
+ }
4744
5318
  }
4745
5319
  doc.write(`payload.value = newResult;`);
4746
5320
  doc.write(`return payload;`);
4747
- const fn = doc.compile();
4748
- return (payload, ctx) => fn(shape, payload, ctx);
5321
+ return doc.compile();
4749
5322
  };
4750
5323
  let fastpass;
4751
- const isObject$1 = isObject;
5324
+ const isObject$2 = isObject;
4752
5325
  const jit = !globalConfig.jitless;
4753
5326
  const fastEnabled = jit && allowsEval.value;
4754
5327
  const catchall = def.catchall;
@@ -4756,7 +5329,7 @@ const $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def)
4756
5329
  inst._zod.parse = (payload, ctx) => {
4757
5330
  value ?? (value = _normalized.value);
4758
5331
  const input = payload.value;
4759
- if (!isObject$1(input)) {
5332
+ if (!isObject$2(input)) {
4760
5333
  payload.issues.push({
4761
5334
  expected: "object",
4762
5335
  code: "invalid_type",
@@ -4769,7 +5342,7 @@ const $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def)
4769
5342
  if (!fastpass) fastpass = generateFastpass(def.shape);
4770
5343
  payload = fastpass(payload, ctx);
4771
5344
  if (!catchall) return payload;
4772
- return handleCatchall([], input, payload, ctx, value, inst);
5345
+ return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true);
4773
5346
  }
4774
5347
  return superParse(payload, ctx);
4775
5348
  };
@@ -4794,21 +5367,20 @@ function handleUnionResults(results, final, inst, ctx) {
4794
5367
  }
4795
5368
  const $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
4796
5369
  $ZodType.init(inst, def);
4797
- defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);
4798
- defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
4799
- defineLazy(inst._zod, "values", () => {
4800
- if (def.options.every((o) => o._zod.values)) return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
4801
- });
4802
- defineLazy(inst._zod, "pattern", () => {
4803
- if (def.options.every((o) => o._zod.pattern)) {
4804
- const patterns = def.options.map((o) => o._zod.pattern);
5370
+ defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") ? "defaulted" : zod.def.options.some((o) => o._zod.optin !== void 0) ? "optional" : void 0);
5371
+ defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
5372
+ defineLazyInternal(inst, "values", (zod) => {
5373
+ if (zod.def.options.every((o) => o._zod.values)) return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));
5374
+ });
5375
+ defineLazyInternal(inst, "pattern", (zod) => {
5376
+ if (zod.def.options.every((o) => o._zod.pattern)) {
5377
+ const patterns = zod.def.options.map((o) => o._zod.pattern);
4805
5378
  return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
4806
5379
  }
4807
5380
  });
4808
- const single = def.options.length === 1;
4809
- const first = def.options[0]._zod.run;
5381
+ const first = def.options.length === 1 ? def.options[0]._zod.run : null;
4810
5382
  inst._zod.parse = (payload, ctx) => {
4811
- if (single) return first(payload, ctx);
5383
+ if (first) return first(payload, ctx);
4812
5384
  let async = false;
4813
5385
  const results = [];
4814
5386
  for (const option of def.options) {
@@ -4830,35 +5402,42 @@ const $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
4830
5402
  });
4831
5403
  };
4832
5404
  });
5405
+ function discriminatorMap(def) {
5406
+ const map = /* @__PURE__ */ new Map();
5407
+ for (const option of def.options) {
5408
+ const values = option._zod.propValues?.[def.discriminator];
5409
+ if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
5410
+ for (const value of values) if (map.has(value)) {
5411
+ if (value !== void 0) throw new Error(`Duplicate discriminator value "${String(value)}"`);
5412
+ map.set(value, null);
5413
+ } else map.set(value, option);
5414
+ }
5415
+ return map;
5416
+ }
4833
5417
  const $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
4834
5418
  def.inclusive = false;
4835
5419
  $ZodUnion.init(inst, def);
4836
5420
  const _super = inst._zod.parse;
4837
- defineLazy(inst._zod, "propValues", () => {
5421
+ defineLazyInternal(inst, "propValues", (zod) => {
4838
5422
  const propValues = {};
4839
- for (const option of def.options) {
5423
+ let undefinedCount = 0;
5424
+ for (const option of zod.def.options) {
4840
5425
  const pv = option._zod.propValues;
4841
- if (!pv || Object.keys(pv).length === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
5426
+ if (!pv || Object.keys(pv).length === 0) throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`);
5427
+ if (pv[zod.def.discriminator]?.has(void 0)) undefinedCount++;
4842
5428
  for (const [k, v] of Object.entries(pv)) {
4843
- if (!propValues[k]) propValues[k] = /* @__PURE__ */ new Set();
5429
+ if (!Object.prototype.hasOwnProperty.call(propValues, k)) assignProp(propValues, k, /* @__PURE__ */ new Set());
4844
5430
  for (const val of v) propValues[k].add(val);
4845
5431
  }
4846
5432
  }
5433
+ if (!zod.def.unionFallback && undefinedCount > 1) propValues[zod.def.discriminator]?.delete(void 0);
4847
5434
  return propValues;
4848
5435
  });
4849
- const disc = cached(() => {
4850
- const opts = def.options;
4851
- const map = /* @__PURE__ */ new Map();
4852
- for (const o of opts) {
4853
- const values = o._zod.propValues?.[def.discriminator];
4854
- if (!values || values.size === 0) throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
4855
- for (const v of values) {
4856
- if (map.has(v)) throw new Error(`Duplicate discriminator value "${String(v)}"`);
4857
- map.set(v, o);
4858
- }
4859
- }
4860
- return map;
5436
+ def.options.forEach((option, i) => {
5437
+ const propShape = rawShape(option._zod.def);
5438
+ if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) throw new Error(`Invalid discriminated union option at index "${i}"`);
4861
5439
  });
5440
+ const disc = cached(() => discriminatorMap(def));
4862
5441
  inst._zod.parse = (payload, ctx) => {
4863
5442
  const input = payload.value;
4864
5443
  if (!isObject(input)) {
@@ -4870,14 +5449,16 @@ const $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUn
4870
5449
  });
4871
5450
  return payload;
4872
5451
  }
4873
- const opt = disc.value.get(input?.[def.discriminator]);
4874
- if (opt) return opt._zod.run(payload, ctx);
4875
- if (def.unionFallback) return _super(payload, ctx);
5452
+ const value = input?.[def.discriminator];
5453
+ const opt = disc.value.get(value);
5454
+ if (opt && (value !== void 0 || ctx.direction !== "backward")) return opt._zod.run(payload, ctx);
5455
+ if (def.unionFallback || ctx.direction === "backward") return _super(payload, ctx);
4876
5456
  payload.issues.push({
4877
5457
  code: "invalid_union",
4878
5458
  errors: [],
4879
5459
  note: "No matching discriminator",
4880
5460
  discriminator: def.discriminator,
5461
+ options: Array.from(disc.value.keys()).filter((value) => disc.value.get(value) !== null),
4881
5462
  input,
4882
5463
  path: [def.discriminator],
4883
5464
  inst
@@ -4919,7 +5500,9 @@ function mergeValues(a, b) {
4919
5500
  ...a,
4920
5501
  ...b
4921
5502
  };
5503
+ if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) delete newObj.__proto__;
4922
5504
  for (const key of sharedKeys) {
5505
+ if (key === "__proto__") continue;
4923
5506
  const sharedValue = mergeValues(a[key], b[key]);
4924
5507
  if (!sharedValue.valid) return {
4925
5508
  valid: false,
@@ -4961,31 +5544,46 @@ function mergeValues(a, b) {
4961
5544
  function handleIntersectionResults(result, left, right) {
4962
5545
  const unrecKeys = /* @__PURE__ */ new Map();
4963
5546
  let unrecIssue;
4964
- for (const iss of left.issues) if (iss.code === "unrecognized_keys") {
4965
- unrecIssue ?? (unrecIssue = iss);
4966
- for (const k of iss.keys) {
5547
+ const keyIssues = /* @__PURE__ */ new Map();
5548
+ const collect = (iss, side) => {
5549
+ let keys;
5550
+ if (iss.code === "unrecognized_keys" && !iss.path?.length) {
5551
+ unrecIssue ?? (unrecIssue = iss);
5552
+ keys = iss.keys;
5553
+ } else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) {
5554
+ const k = String(iss.path[0]);
5555
+ if (!keyIssues.has(k)) keyIssues.set(k, iss);
5556
+ keys = [k];
5557
+ } else return false;
5558
+ for (const k of keys) {
4967
5559
  if (!unrecKeys.has(k)) unrecKeys.set(k, {});
4968
- unrecKeys.get(k).l = true;
5560
+ unrecKeys.get(k)[side] = true;
4969
5561
  }
4970
- } else result.issues.push(iss);
4971
- for (const iss of right.issues) if (iss.code === "unrecognized_keys") for (const k of iss.keys) {
4972
- if (!unrecKeys.has(k)) unrecKeys.set(k, {});
4973
- unrecKeys.get(k).r = true;
4974
- }
4975
- else result.issues.push(iss);
5562
+ return true;
5563
+ };
5564
+ for (const iss of left.issues) if (!collect(iss, "l")) result.issues.push(iss);
5565
+ for (const iss of right.issues) if (!collect(iss, "r")) result.issues.push(iss);
4976
5566
  const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
4977
- if (bothKeys.length && unrecIssue) result.issues.push({
4978
- ...unrecIssue,
4979
- keys: bothKeys
4980
- });
4981
- if (aborted(result)) return result;
5567
+ if (bothKeys.length) {
5568
+ const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];
5569
+ if (aggregated.length) result.issues.push({
5570
+ ...unrecIssue,
5571
+ keys: aggregated
5572
+ });
5573
+ for (const k of bothKeys) if (!aggregated.includes(k) && keyIssues.has(k)) result.issues.push(keyIssues.get(k));
5574
+ }
4982
5575
  const merged = mergeValues(left.value, right.value);
4983
- if (!merged.valid) throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
5576
+ if (!merged.valid) {
5577
+ if (aborted(result)) return result;
5578
+ throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
5579
+ }
4984
5580
  result.value = merged.data;
4985
5581
  return result;
4986
5582
  }
4987
5583
  const $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
4988
5584
  $ZodType.init(inst, def);
5585
+ const memo = globalConfig.memoizer;
5586
+ memo?.attach(inst);
4989
5587
  inst._zod.parse = (payload, ctx) => {
4990
5588
  const input = payload.value;
4991
5589
  if (!isPlainObject(input)) {
@@ -4999,26 +5597,48 @@ const $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
4999
5597
  }
5000
5598
  const proms = [];
5001
5599
  const values = def.keyType._zod.values;
5002
- if (values) {
5003
- payload.value = {};
5600
+ if (values && !def.partial) {
5601
+ payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
5004
5602
  const recordKeys = /* @__PURE__ */ new Set();
5005
5603
  for (const key of values) if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
5006
5604
  recordKeys.add(typeof key === "number" ? key.toString() : key);
5605
+ if (key === "__proto__") continue;
5606
+ const keyResult = def.keyType._zod.run({
5607
+ value: key,
5608
+ issues: []
5609
+ }, ctx);
5610
+ if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
5611
+ if (keyResult.issues.length) {
5612
+ payload.issues.push({
5613
+ code: "invalid_key",
5614
+ origin: "record",
5615
+ issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
5616
+ input: key,
5617
+ path: [key],
5618
+ inst
5619
+ });
5620
+ continue;
5621
+ }
5622
+ const outKey = keyResult.value;
5623
+ if (outKey === "__proto__") continue;
5007
5624
  const result = def.valueType._zod.run({
5008
5625
  value: input[key],
5009
5626
  issues: []
5010
5627
  }, ctx);
5011
5628
  if (result instanceof Promise) proms.push(result.then((result) => {
5012
5629
  if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
5013
- payload.value[key] = result.value;
5630
+ payload.value[outKey] = result.value;
5014
5631
  }));
5015
5632
  else {
5016
5633
  if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
5017
- payload.value[key] = result.value;
5634
+ payload.value[outKey] = result.value;
5018
5635
  }
5019
5636
  }
5020
5637
  let unrecognized;
5021
- for (const key in input) if (!recordKeys.has(key)) {
5638
+ for (const key in input) if (!recordKeys.has(key)) if (def.mode === "loose") {
5639
+ if (key === "__proto__") continue;
5640
+ payload.value[key] = input[key];
5641
+ } else {
5022
5642
  unrecognized = unrecognized ?? [];
5023
5643
  unrecognized.push(key);
5024
5644
  }
@@ -5026,12 +5646,15 @@ const $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
5026
5646
  code: "unrecognized_keys",
5027
5647
  input,
5028
5648
  inst,
5029
- keys: unrecognized
5649
+ keys: unrecognized,
5650
+ continue: true
5030
5651
  });
5031
5652
  } else {
5032
- payload.value = {};
5653
+ payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
5654
+ let unrecognized;
5033
5655
  for (const key of Reflect.ownKeys(input)) {
5034
5656
  if (key === "__proto__") continue;
5657
+ if (!Object.prototype.propertyIsEnumerable.call(input, key)) continue;
5035
5658
  let keyResult = def.keyType._zod.run({
5036
5659
  value: key,
5037
5660
  issues: []
@@ -5047,7 +5670,10 @@ const $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
5047
5670
  }
5048
5671
  if (keyResult.issues.length) {
5049
5672
  if (def.mode === "loose") payload.value[key] = input[key];
5050
- else payload.issues.push({
5673
+ else if (values) {
5674
+ unrecognized = unrecognized ?? [];
5675
+ unrecognized.push(key);
5676
+ } else payload.issues.push({
5051
5677
  code: "invalid_key",
5052
5678
  origin: "record",
5053
5679
  issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
@@ -5057,19 +5683,28 @@ const $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
5057
5683
  });
5058
5684
  continue;
5059
5685
  }
5686
+ const outKey = keyResult.value;
5687
+ if (outKey === "__proto__") continue;
5060
5688
  const result = def.valueType._zod.run({
5061
5689
  value: input[key],
5062
5690
  issues: []
5063
5691
  }, ctx);
5064
5692
  if (result instanceof Promise) proms.push(result.then((result) => {
5065
5693
  if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
5066
- payload.value[keyResult.value] = result.value;
5694
+ payload.value[outKey] = result.value;
5067
5695
  }));
5068
5696
  else {
5069
5697
  if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
5070
- payload.value[keyResult.value] = result.value;
5698
+ payload.value[outKey] = result.value;
5071
5699
  }
5072
5700
  }
5701
+ if (unrecognized && unrecognized.length > 0) payload.issues.push({
5702
+ code: "unrecognized_keys",
5703
+ input,
5704
+ inst,
5705
+ keys: unrecognized,
5706
+ continue: true
5707
+ });
5073
5708
  }
5074
5709
  if (proms.length) return Promise.all(proms).then(() => payload);
5075
5710
  return payload;
@@ -5080,7 +5715,10 @@ const $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
5080
5715
  const values = getEnumValues(def.entries);
5081
5716
  const valuesSet = new Set(values);
5082
5717
  inst._zod.values = valuesSet;
5083
- inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
5718
+ defineLazyInternal(inst, "pattern", (zod) => {
5719
+ const patternValues = getEnumValues(zod.def.entries).filter((k) => propertyKeyTypes.has(typeof k));
5720
+ return new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$");
5721
+ });
5084
5722
  inst._zod.parse = (payload, _ctx) => {
5085
5723
  const input = payload.value;
5086
5724
  if (valuesSet.has(input)) return payload;
@@ -5095,10 +5733,12 @@ const $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
5095
5733
  });
5096
5734
  const $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
5097
5735
  $ZodType.init(inst, def);
5098
- if (def.values.length === 0) throw new Error("Cannot create literal schema with no valid values");
5099
5736
  const values = new Set(def.values);
5100
5737
  inst._zod.values = values;
5101
- inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
5738
+ defineLazyInternal(inst, "pattern", (zod) => {
5739
+ const vals = zod.def.values;
5740
+ return new RegExp(vals.length ? `^(${vals.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$` : "^[^\\s\\S]$");
5741
+ });
5102
5742
  inst._zod.parse = (payload, _ctx) => {
5103
5743
  const input = payload.value;
5104
5744
  if (values.has(input)) return payload;
@@ -5113,6 +5753,8 @@ const $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
5113
5753
  });
5114
5754
  const $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
5115
5755
  $ZodType.init(inst, def);
5756
+ inst._zod.optin = "optional";
5757
+ globalConfig.memoizer?.guard(inst);
5116
5758
  inst._zod.parse = (payload, ctx) => {
5117
5759
  if (ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name);
5118
5760
  const _out = def.transform(payload.value, payload);
@@ -5125,52 +5767,53 @@ const $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def)
5125
5767
  return payload;
5126
5768
  };
5127
5769
  });
5128
- function handleOptionalResult(result, input) {
5129
- if (result.issues.length && input === void 0) return {
5130
- issues: [],
5131
- value: void 0
5132
- };
5133
- return result;
5770
+ function handleOptionalResult(payload, result) {
5771
+ payload.value = result.issues.length ? void 0 : result.value;
5772
+ return payload;
5134
5773
  }
5135
5774
  const $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
5136
5775
  $ZodType.init(inst, def);
5137
- inst._zod.optin = "optional";
5776
+ defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional");
5138
5777
  inst._zod.optout = "optional";
5139
- defineLazy(inst._zod, "values", () => {
5140
- return def.innerType._zod.values ? new Set([...def.innerType._zod.values, void 0]) : void 0;
5778
+ defineLazyInternal(inst, "values", (zod) => {
5779
+ const values = zod.def.innerType._zod.values;
5780
+ return values ? new Set([...values, void 0]) : void 0;
5141
5781
  });
5142
- defineLazy(inst._zod, "pattern", () => {
5143
- const pattern = def.innerType._zod.pattern;
5782
+ defineLazyInternal(inst, "pattern", (zod) => {
5783
+ const pattern = zod.def.innerType._zod.pattern;
5144
5784
  return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
5145
5785
  });
5146
5786
  inst._zod.parse = (payload, ctx) => {
5147
- if (def.innerType._zod.optin === "optional") {
5148
- const result = def.innerType._zod.run(payload, ctx);
5149
- if (result instanceof Promise) return result.then((r) => handleOptionalResult(r, payload.value));
5150
- return handleOptionalResult(result, payload.value);
5787
+ if (payload.value === void 0) {
5788
+ if (def.innerType._zod.optin !== "defaulted") return payload;
5789
+ const result = def.innerType._zod.run({
5790
+ value: payload.value,
5791
+ issues: []
5792
+ }, ctx);
5793
+ if (result instanceof Promise) return result.then((result) => handleOptionalResult(payload, result));
5794
+ return handleOptionalResult(payload, result);
5151
5795
  }
5152
- if (payload.value === void 0) return payload;
5153
5796
  return def.innerType._zod.run(payload, ctx);
5154
5797
  };
5155
5798
  });
5156
5799
  const $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => {
5157
5800
  $ZodOptional.init(inst, def);
5158
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
5159
- defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern);
5801
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
5802
+ defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern);
5160
5803
  inst._zod.parse = (payload, ctx) => {
5161
5804
  return def.innerType._zod.run(payload, ctx);
5162
5805
  };
5163
5806
  });
5164
5807
  const $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
5165
5808
  $ZodType.init(inst, def);
5166
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
5167
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
5168
- defineLazy(inst._zod, "pattern", () => {
5169
- const pattern = def.innerType._zod.pattern;
5809
+ defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin);
5810
+ defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout);
5811
+ defineLazyInternal(inst, "pattern", (zod) => {
5812
+ const pattern = zod.def.innerType._zod.pattern;
5170
5813
  return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
5171
5814
  });
5172
- defineLazy(inst._zod, "values", () => {
5173
- return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : void 0;
5815
+ defineLazyInternal(inst, "values", (zod) => {
5816
+ return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : void 0;
5174
5817
  });
5175
5818
  inst._zod.parse = (payload, ctx) => {
5176
5819
  if (payload.value === null) return payload;
@@ -5179,8 +5822,8 @@ const $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) =>
5179
5822
  });
5180
5823
  const $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
5181
5824
  $ZodType.init(inst, def);
5182
- inst._zod.optin = "optional";
5183
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
5825
+ inst._zod.optin = "defaulted";
5826
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
5184
5827
  inst._zod.parse = (payload, ctx) => {
5185
5828
  if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
5186
5829
  if (payload.value === void 0) {
@@ -5201,8 +5844,8 @@ function handleDefaultResult(payload, def) {
5201
5844
  }
5202
5845
  const $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
5203
5846
  $ZodType.init(inst, def);
5204
- inst._zod.optin = "optional";
5205
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
5847
+ inst._zod.optin = "defaulted";
5848
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
5206
5849
  inst._zod.parse = (payload, ctx) => {
5207
5850
  if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
5208
5851
  if (payload.value === void 0) payload.value = def.defaultValue;
@@ -5211,8 +5854,8 @@ const $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) =>
5211
5854
  });
5212
5855
  const $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
5213
5856
  $ZodType.init(inst, def);
5214
- defineLazy(inst._zod, "values", () => {
5215
- const v = def.innerType._zod.values;
5857
+ defineLazyInternal(inst, "values", (zod) => {
5858
+ const v = zod.def.innerType._zod.values;
5216
5859
  return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;
5217
5860
  });
5218
5861
  inst._zod.parse = (payload, ctx) => {
@@ -5230,44 +5873,41 @@ function handleNonOptionalResult(payload, inst) {
5230
5873
  });
5231
5874
  return payload;
5232
5875
  }
5876
+ function handleCatchResult(payload, result, def, ctx) {
5877
+ if (!result.issues.length) {
5878
+ payload.value = result.value;
5879
+ if (result.memo) payload.memo = true;
5880
+ return payload;
5881
+ }
5882
+ payload.value = def.catchValue({
5883
+ ...result,
5884
+ value: payload.value,
5885
+ error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) },
5886
+ input: payload.value
5887
+ });
5888
+ return payload;
5889
+ }
5233
5890
  const $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
5234
5891
  $ZodType.init(inst, def);
5235
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
5236
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
5237
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
5892
+ defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional");
5893
+ defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout);
5894
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
5238
5895
  inst._zod.parse = (payload, ctx) => {
5239
5896
  if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
5240
- const result = def.innerType._zod.run(payload, ctx);
5241
- if (result instanceof Promise) return result.then((result) => {
5242
- payload.value = result.value;
5243
- if (result.issues.length) {
5244
- payload.value = def.catchValue({
5245
- ...payload,
5246
- error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) },
5247
- input: payload.value
5248
- });
5249
- payload.issues = [];
5250
- }
5251
- return payload;
5252
- });
5253
- payload.value = result.value;
5254
- if (result.issues.length) {
5255
- payload.value = def.catchValue({
5256
- ...payload,
5257
- error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) },
5258
- input: payload.value
5259
- });
5260
- payload.issues = [];
5261
- }
5262
- return payload;
5897
+ const result = def.innerType._zod.run({
5898
+ value: payload.value,
5899
+ issues: []
5900
+ }, ctx);
5901
+ if (result instanceof Promise) return result.then((result) => handleCatchResult(payload, result, def, ctx));
5902
+ return handleCatchResult(payload, result, def, ctx);
5263
5903
  };
5264
5904
  });
5265
5905
  const $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
5266
5906
  $ZodType.init(inst, def);
5267
- defineLazy(inst._zod, "values", () => def.in._zod.values);
5268
- defineLazy(inst._zod, "optin", () => def.in._zod.optin);
5269
- defineLazy(inst._zod, "optout", () => def.out._zod.optout);
5270
- defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
5907
+ defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values);
5908
+ defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin);
5909
+ defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout);
5910
+ defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues);
5271
5911
  inst._zod.parse = (payload, ctx) => {
5272
5912
  if (ctx.direction === "backward") {
5273
5913
  const right = def.out._zod.run(payload, ctx);
@@ -5280,7 +5920,7 @@ const $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
5280
5920
  };
5281
5921
  });
5282
5922
  function handlePipeResult(left, next, ctx) {
5283
- if (left.issues.length) {
5923
+ if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) {
5284
5924
  left.aborted = true;
5285
5925
  return left;
5286
5926
  }
@@ -5291,10 +5931,10 @@ function handlePipeResult(left, next, ctx) {
5291
5931
  }
5292
5932
  const $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
5293
5933
  $ZodType.init(inst, def);
5294
- defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
5295
- defineLazy(inst._zod, "values", () => def.innerType._zod.values);
5296
- defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
5297
- defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
5934
+ defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues);
5935
+ defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
5936
+ defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin);
5937
+ defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout);
5298
5938
  inst._zod.parse = (payload, ctx) => {
5299
5939
  if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
5300
5940
  const result = def.innerType._zod.run(payload, ctx);
@@ -5303,7 +5943,7 @@ const $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) =>
5303
5943
  };
5304
5944
  });
5305
5945
  function handleReadonlyResult(payload) {
5306
- payload.value = Object.freeze(payload.value);
5946
+ if (!payload.memo) payload.value = Object.freeze(payload.value);
5307
5947
  return payload;
5308
5948
  }
5309
5949
  const $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
@@ -5332,6 +5972,363 @@ function handleRefineResult(result, payload, input, inst) {
5332
5972
  payload.issues.push(issue(_iss));
5333
5973
  }
5334
5974
  }
5975
+ var $ZodCyclicError = class extends Error {
5976
+ constructor() {
5977
+ super(`Cannot parse a reference cycle that closes through a transform`);
5978
+ this.name = "ZodCyclicError";
5979
+ }
5980
+ };
5981
+ /** Keyed off the context object every schema in one parse call already shares. */
5982
+ const STATE = "~memo";
5983
+ const NO_ISSUES = [];
5984
+ function isRef(value) {
5985
+ return value !== null && typeof value === "object";
5986
+ }
5987
+ function cloneIssues(issues) {
5988
+ return issues.map((iss) => iss.path ? {
5989
+ ...iss,
5990
+ path: iss.path.slice()
5991
+ } : { ...iss });
5992
+ }
5993
+ const recursive = /* @__PURE__ */ new WeakMap();
5994
+ /** What the walk established, in order of certainty: ordered so the strongest answer among children wins. */
5995
+ const NONE = 0;
5996
+ const ASSUMED = 1;
5997
+ const PROVEN = 2;
5998
+ /** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */
5999
+ function isRecursive(inst, stack, resolve) {
6000
+ const cached = recursive.get(inst);
6001
+ if (cached !== void 0) return cached ? PROVEN : NONE;
6002
+ if (stack.has(inst)) return PROVEN;
6003
+ stack.add(inst);
6004
+ let result = NONE;
6005
+ const check = (child) => {
6006
+ if (result !== PROVEN && child?._zod) {
6007
+ const answer = isRecursive(child, stack, resolve);
6008
+ if (answer > result) result = answer;
6009
+ }
6010
+ };
6011
+ const shape = (sh, spread) => {
6012
+ let answer = NONE;
6013
+ for (const key of Reflect.ownKeys(sh)) {
6014
+ const desc = Object.getOwnPropertyDescriptor(sh, key);
6015
+ if (spread && !desc.enumerable) continue;
6016
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;
6017
+ if (child > answer) answer = child;
6018
+ }
6019
+ return answer;
6020
+ };
6021
+ const merge = (answer) => {
6022
+ if (answer > result) result = answer;
6023
+ };
6024
+ const def = inst._zod.def;
6025
+ switch (def.type) {
6026
+ case "object": {
6027
+ const raw = rawShape(def);
6028
+ merge(raw ? shape(raw, true) : ASSUMED);
6029
+ check(def.catchall);
6030
+ break;
6031
+ }
6032
+ case "array":
6033
+ check(def.element);
6034
+ break;
6035
+ case "tuple":
6036
+ for (const el of def.items) check(el);
6037
+ check(def.rest);
6038
+ break;
6039
+ case "record":
6040
+ case "map":
6041
+ check(def.keyType);
6042
+ check(def.valueType);
6043
+ break;
6044
+ case "set":
6045
+ check(def.valueType);
6046
+ break;
6047
+ case "union":
6048
+ for (const el of def.options) check(el);
6049
+ break;
6050
+ case "intersection":
6051
+ check(def.left);
6052
+ check(def.right);
6053
+ break;
6054
+ case "optional":
6055
+ case "nullable":
6056
+ case "default":
6057
+ case "prefault":
6058
+ case "catch":
6059
+ case "readonly":
6060
+ case "nonoptional":
6061
+ case "promise":
6062
+ case "success":
6063
+ check(def.innerType);
6064
+ break;
6065
+ case "pipe":
6066
+ check(def.in);
6067
+ check(def.out);
6068
+ break;
6069
+ case "function":
6070
+ check(def.input);
6071
+ check(def.output);
6072
+ break;
6073
+ case "lazy": {
6074
+ const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : void 0);
6075
+ merge(inner ? isRecursive(inner, stack, false) : ASSUMED);
6076
+ break;
6077
+ }
6078
+ case "template_literal":
6079
+ case "string":
6080
+ case "number":
6081
+ case "int":
6082
+ case "boolean":
6083
+ case "bigint":
6084
+ case "symbol":
6085
+ case "undefined":
6086
+ case "null":
6087
+ case "void":
6088
+ case "never":
6089
+ case "any":
6090
+ case "unknown":
6091
+ case "date":
6092
+ case "nan":
6093
+ case "enum":
6094
+ case "literal":
6095
+ case "file":
6096
+ case "transform":
6097
+ case "custom": break;
6098
+ default: for (const key in def) {
6099
+ const desc = Object.getOwnPropertyDescriptor(def, key);
6100
+ if (!desc || desc.get) continue;
6101
+ const value = desc.value;
6102
+ if (!value || typeof value !== "object") continue;
6103
+ if (value._zod) check(value);
6104
+ else if (Array.isArray(value)) for (const el of value) check(el);
6105
+ }
6106
+ }
6107
+ stack.delete(inst);
6108
+ return settle(inst, result);
6109
+ }
6110
+ /** An assumed answer must not outlive the resolution that settles it, so only a certain one is cached. */
6111
+ function settle(inst, answer) {
6112
+ if (answer !== ASSUMED) recursive.set(inst, answer === PROVEN);
6113
+ return answer;
6114
+ }
6115
+ function bucketFor(state, inst) {
6116
+ let bucket = state.buckets.get(inst);
6117
+ if (!bucket) {
6118
+ bucket = /* @__PURE__ */ new WeakMap();
6119
+ state.buckets.set(inst, bucket);
6120
+ }
6121
+ return bucket;
6122
+ }
6123
+ let handoff;
6124
+ const open$1 = [];
6125
+ const memo = {
6126
+ alloc(_inst, payload, empty) {
6127
+ const bucket = handoff;
6128
+ if (!bucket) return empty;
6129
+ handoff = void 0;
6130
+ const entry = {
6131
+ value: empty,
6132
+ issues: null
6133
+ };
6134
+ bucket.set(payload.value, entry);
6135
+ open$1.push(entry);
6136
+ return empty;
6137
+ },
6138
+ guard(inst) {
6139
+ var _a;
6140
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
6141
+ inst._zod.deferred.push(() => {
6142
+ const base = inst._zod.parse;
6143
+ const wrapped = (payload, ctx) => {
6144
+ if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) throw new $ZodCyclicError();
6145
+ return base(payload, ctx);
6146
+ };
6147
+ inst._zod.parse = wrapped;
6148
+ if (inst._zod.run === base) inst._zod.run = wrapped;
6149
+ });
6150
+ },
6151
+ attach(inst) {
6152
+ var _a;
6153
+ let isRecursiveInst;
6154
+ let rechecked = false;
6155
+ let lastCtx;
6156
+ let lastBucket;
6157
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
6158
+ inst._zod.deferred.push(() => {
6159
+ const base = inst._zod.parse;
6160
+ const wrapped = (payload, ctx) => {
6161
+ if (isRecursiveInst === void 0) {
6162
+ const walked = isRecursive(inst, /* @__PURE__ */ new Set(), false);
6163
+ if (walked === NONE) {
6164
+ inst._zod.parse = base;
6165
+ if (inst._zod.run === wrapped) inst._zod.run = base;
6166
+ return base(payload, ctx);
6167
+ }
6168
+ if (walked === PROVEN || rechecked) isRecursiveInst = true;
6169
+ else rechecked = true;
6170
+ }
6171
+ const input = payload.value;
6172
+ if (!isRef(input)) return base(payload, ctx);
6173
+ let state = ctx[STATE];
6174
+ if (!state) {
6175
+ state = {
6176
+ buckets: /* @__PURE__ */ new WeakMap(),
6177
+ backEdges: void 0
6178
+ };
6179
+ ctx[STATE] = state;
6180
+ }
6181
+ let bucket;
6182
+ if (lastCtx === ctx) bucket = lastBucket;
6183
+ else {
6184
+ bucket = bucketFor(state, inst);
6185
+ lastCtx = ctx;
6186
+ lastBucket = bucket;
6187
+ }
6188
+ const hit = bucket.get(input);
6189
+ if (hit) {
6190
+ payload.value = hit.value;
6191
+ if (hit.issues) {
6192
+ if (hit.issues.length) payload.issues.push(...cloneIssues(hit.issues));
6193
+ } else {
6194
+ payload.memo = true;
6195
+ state.backEdges ?? (state.backEdges = /* @__PURE__ */ new WeakSet());
6196
+ state.backEdges.add(hit.value);
6197
+ }
6198
+ return payload;
6199
+ }
6200
+ handoff = bucket;
6201
+ const depth = open$1.length;
6202
+ const result = base(payload, ctx);
6203
+ handoff = void 0;
6204
+ const entry = open$1.length > depth ? open$1.pop() : void 0;
6205
+ if (result instanceof Promise) return result.then((r) => {
6206
+ if (entry) entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;
6207
+ return r;
6208
+ });
6209
+ if (entry) entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;
6210
+ return result;
6211
+ };
6212
+ inst._zod.parse = wrapped;
6213
+ if (inst._zod.run === base) inst._zod.run = wrapped;
6214
+ });
6215
+ }
6216
+ };
6217
+ /** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */
6218
+ function memoizer() {
6219
+ return memo;
6220
+ }
6221
+ /** Whether this value is a node a back-edge resolved to before it finished. */
6222
+ function isBackEdge(ctx, value) {
6223
+ const backEdges = ctx[STATE]?.backEdges;
6224
+ return backEdges !== void 0 && isRef(value) && backEdges.has(value);
6225
+ }
6226
+ const error = () => {
6227
+ const Sizable = {
6228
+ string: {
6229
+ unit: "characters",
6230
+ verb: "to have"
6231
+ },
6232
+ file: {
6233
+ unit: "bytes",
6234
+ verb: "to have"
6235
+ },
6236
+ array: {
6237
+ unit: "items",
6238
+ verb: "to have"
6239
+ },
6240
+ set: {
6241
+ unit: "items",
6242
+ verb: "to have"
6243
+ },
6244
+ map: {
6245
+ unit: "entries",
6246
+ verb: "to have"
6247
+ }
6248
+ };
6249
+ function getSizing(origin) {
6250
+ return Sizable[origin] ?? null;
6251
+ }
6252
+ const FormatDictionary = {
6253
+ regex: "input",
6254
+ email: "email address",
6255
+ url: "URL",
6256
+ emoji: "emoji",
6257
+ uuid: "UUID",
6258
+ uuidv4: "UUIDv4",
6259
+ uuidv6: "UUIDv6",
6260
+ nanoid: "nanoid",
6261
+ guid: "GUID",
6262
+ cuid: "cuid",
6263
+ cuid2: "cuid2",
6264
+ ulid: "ULID",
6265
+ xid: "XID",
6266
+ ksuid: "KSUID",
6267
+ datetime: "ISO datetime",
6268
+ date: "ISO date",
6269
+ time: "ISO time",
6270
+ duration: "ISO duration",
6271
+ ipv4: "IPv4 address",
6272
+ ipv6: "IPv6 address",
6273
+ mac: "MAC address",
6274
+ cidrv4: "IPv4 range",
6275
+ cidrv6: "IPv6 range",
6276
+ base64: "base64-encoded string",
6277
+ base64url: "base64url-encoded string",
6278
+ json_string: "JSON string",
6279
+ e164: "E.164 number",
6280
+ currency_code: "currency code",
6281
+ credit_card: "credit card number",
6282
+ iban: "IBAN",
6283
+ jwt: "JWT",
6284
+ template_literal: "input"
6285
+ };
6286
+ const TypeDictionary = { nan: "NaN" };
6287
+ function getTypeName(type, input) {
6288
+ if (type === "number" && typeof input === "number" && !Number.isFinite(input)) return String(input);
6289
+ return TypeDictionary[type] ?? type;
6290
+ }
6291
+ return (issue) => {
6292
+ switch (issue.code) {
6293
+ case "invalid_type": return `Invalid input: expected ${getTypeName(issue.expected)}, received ${getTypeName(parsedType(issue.input), issue.input)}`;
6294
+ case "invalid_value":
6295
+ if (issue.values.length === 1) return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`;
6296
+ return `Invalid option: expected one of ${joinValues(issue.values, "|")}`;
6297
+ case "too_big": {
6298
+ const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<";
6299
+ const sizing = getSizing(issue.origin);
6300
+ if (sizing) return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`;
6301
+ return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`;
6302
+ }
6303
+ case "too_small": {
6304
+ const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">";
6305
+ const sizing = getSizing(issue.origin);
6306
+ if (sizing) return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;
6307
+ return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;
6308
+ }
6309
+ case "invalid_format": {
6310
+ const _issue = issue;
6311
+ if (_issue.format === "starts_with") return `Invalid string: must start with "${_issue.prefix}"`;
6312
+ if (_issue.format === "ends_with") return `Invalid string: must end with "${_issue.suffix}"`;
6313
+ if (_issue.format === "includes") return `Invalid string: must include "${_issue.includes}"`;
6314
+ if (_issue.format === "regex") return `Invalid string: must match pattern ${_issue.pattern}`;
6315
+ return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;
6316
+ }
6317
+ case "not_multiple_of": return `Invalid number: must be a multiple of ${issue.divisor}`;
6318
+ case "unrecognized_keys": return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`;
6319
+ case "invalid_key": return `Invalid key in ${issue.origin}`;
6320
+ case "invalid_union":
6321
+ if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) return `Invalid discriminator value. Expected ${issue.options.map((o) => `'${o}'`).join(" | ")}`;
6322
+ if (issue.inclusive === false) return "Invalid input: more than one option matched";
6323
+ return "Invalid input";
6324
+ case "invalid_element": return `Invalid value in ${issue.origin}`;
6325
+ default: return `Invalid input`;
6326
+ }
6327
+ };
6328
+ };
6329
+ function en_default() {
6330
+ return { localeError: error() };
6331
+ }
5335
6332
  var _a;
5336
6333
  var $ZodRegistry = class {
5337
6334
  constructor() {
@@ -5377,12 +6374,16 @@ function registry() {
5377
6374
  }
5378
6375
  (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
5379
6376
  const globalRegistry = globalThis.__zod_globalRegistry;
6377
+ function snapshotChecks(def) {
6378
+ if (def.checks) def.checks = [...def.checks];
6379
+ return def;
6380
+ }
5380
6381
  /* @__NO_SIDE_EFFECTS__ */
5381
6382
  function _string(Class, params) {
5382
- return new Class({
6383
+ return new Class(snapshotChecks({
5383
6384
  type: "string",
5384
6385
  ...normalizeParams(params)
5385
- });
6386
+ }));
5386
6387
  }
5387
6388
  /* @__NO_SIDE_EFFECTS__ */
5388
6389
  function _email(Class, params) {
@@ -5477,6 +6478,11 @@ function _nanoid(Class, params) {
5477
6478
  ...normalizeParams(params)
5478
6479
  });
5479
6480
  }
6481
+ /**
6482
+ * @deprecated CUID v1 is deprecated by its authors due to information leakage
6483
+ * (timestamps embedded in the id). Use {@link _cuid2} instead.
6484
+ * See https://github.com/paralleldrive/cuid.
6485
+ */
5480
6486
  /* @__NO_SIDE_EFFECTS__ */
5481
6487
  function _cuid(Class, params) {
5482
6488
  return new Class({
@@ -5649,11 +6655,11 @@ function _isoDuration(Class, params) {
5649
6655
  }
5650
6656
  /* @__NO_SIDE_EFFECTS__ */
5651
6657
  function _number(Class, params) {
5652
- return new Class({
6658
+ return new Class(snapshotChecks({
5653
6659
  type: "number",
5654
6660
  checks: [],
5655
6661
  ...normalizeParams(params)
5656
- });
6662
+ }));
5657
6663
  }
5658
6664
  /* @__NO_SIDE_EFFECTS__ */
5659
6665
  function _int(Class, params) {
@@ -5848,7 +6854,7 @@ function _refine(Class, fn, _params) {
5848
6854
  });
5849
6855
  }
5850
6856
  /* @__NO_SIDE_EFFECTS__ */
5851
- function _superRefine(fn) {
6857
+ function _superRefine(fn, params) {
5852
6858
  const ch = /* @__PURE__ */ _check((payload) => {
5853
6859
  payload.addIssue = (issue$2) => {
5854
6860
  if (typeof issue$2 === "string") payload.issues.push(issue(issue$2, payload.value, ch._zod.def));
@@ -5856,14 +6862,14 @@ function _superRefine(fn) {
5856
6862
  const _issue = issue$2;
5857
6863
  if (_issue.fatal) _issue.continue = false;
5858
6864
  _issue.code ?? (_issue.code = "custom");
5859
- _issue.input ?? (_issue.input = payload.value);
6865
+ if (!("input" in _issue)) _issue.input = payload.value;
5860
6866
  _issue.inst ?? (_issue.inst = ch);
5861
6867
  _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
5862
6868
  payload.issues.push(issue(_issue));
5863
6869
  }
5864
6870
  };
5865
6871
  return fn(payload.value, payload);
5866
- });
6872
+ }, params);
5867
6873
  return ch;
5868
6874
  }
5869
6875
  /* @__NO_SIDE_EFFECTS__ */
@@ -5875,6 +6881,10 @@ function _check(fn, params) {
5875
6881
  ch._zod.check = fn;
5876
6882
  return ch;
5877
6883
  }
6884
+ function assignProps(target, ...sources) {
6885
+ for (const source of sources) for (const key of Reflect.ownKeys(source)) if (Object.prototype.propertyIsEnumerable.call(source, key)) assignProp(target, key, source[key]);
6886
+ return target;
6887
+ }
5878
6888
  function initializeContext(params) {
5879
6889
  let target = params?.target ?? "draft-2020-12";
5880
6890
  if (target === "draft-4") target = "draft-04";
@@ -5888,12 +6898,32 @@ function initializeContext(params) {
5888
6898
  io: params?.io ?? "output",
5889
6899
  counter: 0,
5890
6900
  seen: /* @__PURE__ */ new Map(),
6901
+ sharedDefsExtractedFor: void 0,
6902
+ sharedEmitDoneFor: void 0,
5891
6903
  cycles: params?.cycles ?? "ref",
5892
6904
  reused: params?.reused ?? "inline",
6905
+ intersections: [],
6906
+ deferred: [],
5893
6907
  external: params?.external ?? void 0
5894
6908
  };
5895
6909
  }
5896
- function process$1(schema, ctx, _params = {
6910
+ /**
6911
+ * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws
6912
+ * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a
6913
+ * custom JSON Schema was written into `json`, in which case the caller must not write its own.
6914
+ */
6915
+ function handleUnrepresentable(schema, ctx, json, params, message) {
6916
+ const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({
6917
+ zodSchema: schema,
6918
+ path: params.path,
6919
+ message
6920
+ }) : ctx.unrepresentable;
6921
+ if (result === "any") return false;
6922
+ if (result === void 0 || result === "throw") throw new Error(message);
6923
+ Object.assign(json, result);
6924
+ return true;
6925
+ }
6926
+ function processSchema(schema, ctx, _params = {
5897
6927
  path: [],
5898
6928
  schemaPath: []
5899
6929
  }) {
@@ -5912,6 +6942,8 @@ function process$1(schema, ctx, _params = {
5912
6942
  path: _params.path
5913
6943
  };
5914
6944
  ctx.seen.set(schema, result);
6945
+ ctx.sharedDefsExtractedFor = void 0;
6946
+ ctx.sharedEmitDoneFor = void 0;
5915
6947
  const overrideSchema = schema._zod.toJSONSchema?.();
5916
6948
  if (overrideSchema) result.schema = overrideSchema;
5917
6949
  else {
@@ -5930,23 +6962,27 @@ function process$1(schema, ctx, _params = {
5930
6962
  const parent = schema._zod.parent;
5931
6963
  if (parent) {
5932
6964
  if (!result.ref) result.ref = parent;
5933
- process$1(parent, ctx, params);
6965
+ processSchema(parent, ctx, params);
5934
6966
  ctx.seen.get(parent).isParent = true;
5935
6967
  }
5936
6968
  }
5937
6969
  const meta = ctx.metadataRegistry.get(schema);
5938
- if (meta) Object.assign(result.schema, meta);
6970
+ if (meta) assignProps(result.schema, meta);
5939
6971
  if (ctx.io === "input" && isTransforming(schema)) {
5940
6972
  delete result.schema.examples;
5941
6973
  delete result.schema.default;
5942
6974
  }
5943
- if (ctx.io === "input" && result.schema._prefault) (_a = result.schema).default ?? (_a.default = result.schema._prefault);
6975
+ if (ctx.io === "input" && "_prefault" in result.schema) (_a = result.schema).default ?? (_a.default = result.schema._prefault);
5944
6976
  delete result.schema._prefault;
5945
6977
  return ctx.seen.get(schema).schema;
5946
6978
  }
6979
+ function encodeJSONPointerSegment(segment) {
6980
+ return segment.replace(/~/g, "~0").replace(/\//g, "~1");
6981
+ }
5947
6982
  function extractDefs(ctx, schema) {
5948
6983
  const root = ctx.seen.get(schema);
5949
6984
  if (!root) throw new Error("Unprocessed schema. This is a bug in Zod.");
6985
+ if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) return;
5950
6986
  const idToSchema = /* @__PURE__ */ new Map();
5951
6987
  for (const entry of ctx.seen.entries()) {
5952
6988
  const id = ctx.metadataRegistry.get(entry[0])?.id;
@@ -5966,15 +7002,16 @@ function extractDefs(ctx, schema) {
5966
7002
  entry[1].defId = id;
5967
7003
  return {
5968
7004
  defId: id,
5969
- ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}`
7005
+ ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}`
5970
7006
  };
5971
7007
  }
5972
- if (entry[1] === root) return { ref: "#" };
5973
- const defUriPrefix = `#/${defsSegment}/`;
7008
+ const uriPrefix = `#`;
7009
+ const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
7010
+ if (entry[1] === root && !entry[1].schema.id) return { ref: uriPrefix };
5974
7011
  const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
5975
7012
  return {
5976
7013
  defId,
5977
- ref: defUriPrefix + defId
7014
+ ref: defUriPrefix + encodeJSONPointerSegment(defId)
5978
7015
  };
5979
7016
  };
5980
7017
  const extractToDef = (entry) => {
@@ -6015,12 +7052,114 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
6015
7052
  continue;
6016
7053
  }
6017
7054
  if (seen.count > 1) {
6018
- if (ctx.reused === "ref") {
6019
- extractToDef(entry);
6020
- continue;
7055
+ if (ctx.reused === "ref") extractToDef(entry);
7056
+ }
7057
+ }
7058
+ if (ctx.external) ctx.sharedDefsExtractedFor = ctx.external;
7059
+ }
7060
+ /** Rewrites `anyOf: [{type: "a"}, {type: "b"}]` to `type: ["a", "b"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so "exactly one" and "at least one" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */
7061
+ function compactTypeUnion(schema) {
7062
+ const options = schema.anyOf;
7063
+ if (!Array.isArray(options) || options.length === 0 || schema.type !== void 0) return;
7064
+ const types = [];
7065
+ for (const option of options) {
7066
+ if (!option || typeof option !== "object") return;
7067
+ compactTypeUnion(option);
7068
+ const keys = Object.keys(option);
7069
+ if (keys.length !== 1 || keys[0] !== "type") return;
7070
+ const type = option.type;
7071
+ for (const member of Array.isArray(type) ? type : [type]) {
7072
+ if (typeof member !== "string") return;
7073
+ if (!types.includes(member)) types.push(member);
7074
+ }
7075
+ }
7076
+ delete schema.anyOf;
7077
+ schema.type = types.length === 1 ? types[0] : types;
7078
+ }
7079
+ /** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`,
7080
+ * an annotation like `description` — makes a member unfoldable, so a constraint this does not
7081
+ * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */
7082
+ const FOLDABLE_KEYS = new Set([
7083
+ "type",
7084
+ "properties",
7085
+ "required",
7086
+ "additionalProperties"
7087
+ ]);
7088
+ const UNION_KEYS = ["oneOf", "anyOf"];
7089
+ /** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */
7090
+ function undeclaredConstraint(member) {
7091
+ const extra = member.additionalProperties;
7092
+ if (extra === void 0 || extra === false || typeof extra !== "object" || extra === null) return null;
7093
+ return Object.keys(extra).length ? extra : null;
7094
+ }
7095
+ /** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */
7096
+ function foldObjects(members) {
7097
+ const objects = [];
7098
+ for (const member of members) {
7099
+ if (typeof member !== "object" || member.type !== "object") return null;
7100
+ for (const key in member) if (!FOLDABLE_KEYS.has(key)) return null;
7101
+ objects.push(member);
7102
+ }
7103
+ const properties = {};
7104
+ const required = /* @__PURE__ */ new Set();
7105
+ for (const object of objects) {
7106
+ for (const key in object.properties) {
7107
+ if (Object.prototype.hasOwnProperty.call(properties, key)) continue;
7108
+ const parts = [];
7109
+ for (const other of objects) {
7110
+ const part = other.properties?.[key] ?? undeclaredConstraint(other);
7111
+ if (part === null || part === void 0) continue;
7112
+ if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) parts.push(part);
6021
7113
  }
7114
+ assignProp(properties, key, parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts });
7115
+ }
7116
+ for (const key of object.required ?? []) required.add(key);
7117
+ }
7118
+ const folded = {
7119
+ type: "object",
7120
+ properties
7121
+ };
7122
+ if (required.size) folded.required = [...required];
7123
+ if (objects.every((object) => object.additionalProperties === false)) folded.additionalProperties = false;
7124
+ else {
7125
+ const constraints = [];
7126
+ for (const object of objects) {
7127
+ const constraint = undeclaredConstraint(object);
7128
+ if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) constraints.push(constraint);
6022
7129
  }
7130
+ if (constraints.length === 1) folded.additionalProperties = constraints[0];
7131
+ else if (constraints.length > 1) folded.additionalProperties = { allOf: constraints };
6023
7132
  }
7133
+ return folded;
7134
+ }
7135
+ /** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two
7136
+ * closed object members reject each other's keys and the schema validates nothing. Zod's parser
7137
+ * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when
7138
+ * *every* side rejects it — so the emitted schema has to pool them too, and folding the members
7139
+ * into one object is the encoding that says so on every target.
7140
+ *
7141
+ * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref`
7142
+ * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it
7143
+ * keeps its reference and its own closedness rather than being inlined as a stale copy. */
7144
+ function foldIntersection(json) {
7145
+ const allOf = json.allOf;
7146
+ if (!Array.isArray(allOf) || allOf.length < 2) return;
7147
+ for (const key of FOLDABLE_KEYS) if (key in json) return;
7148
+ const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k])));
7149
+ let folded = null;
7150
+ if (!unions.length) folded = foldObjects(allOf);
7151
+ else {
7152
+ const union = unions[0];
7153
+ const keyword = UNION_KEYS.find((k) => Array.isArray(union[k]));
7154
+ if (Object.keys(union).length !== 1) return;
7155
+ const rest = allOf.filter((m) => m !== union);
7156
+ const branches = union[keyword].map((branch) => foldObjects([...rest, branch]));
7157
+ if (branches.some((b) => !b)) return;
7158
+ folded = { [keyword]: branches };
7159
+ }
7160
+ if (!folded) return;
7161
+ delete json.allOf;
7162
+ assignProps(json, folded);
6024
7163
  }
6025
7164
  function finalize(ctx, schema) {
6026
7165
  const root = ctx.seen.get(schema);
@@ -6039,8 +7178,8 @@ function finalize(ctx, schema) {
6039
7178
  if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
6040
7179
  schema.allOf = schema.allOf ?? [];
6041
7180
  schema.allOf.push(refSchema);
6042
- } else Object.assign(schema, refSchema);
6043
- Object.assign(schema, _cached);
7181
+ } else assignProps(schema, refSchema);
7182
+ assignProps(schema, _cached);
6044
7183
  if (zodSchema._zod.parent === ref) for (const key in schema) {
6045
7184
  if (key === "$ref" || key === "allOf") continue;
6046
7185
  if (!(key in _cached)) delete schema[key];
@@ -6068,7 +7207,22 @@ function finalize(ctx, schema) {
6068
7207
  path: seen.path ?? []
6069
7208
  });
6070
7209
  };
6071
- for (const entry of [...ctx.seen.entries()].reverse()) flattenRef(entry[0]);
7210
+ if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {
7211
+ for (const entry of [...ctx.seen.entries()].reverse()) flattenRef(entry[0]);
7212
+ if (ctx.target !== "openapi-3.0") for (const entry of ctx.seen.entries()) compactTypeUnion(entry[1].def ?? entry[1].schema);
7213
+ for (const rewrite of ctx.deferred) rewrite();
7214
+ if (ctx.intersections.length) {
7215
+ const carriers = /* @__PURE__ */ new Map();
7216
+ for (const seen of ctx.seen.values()) for (const json of [seen.schema, seen.def]) {
7217
+ const allOf = json?.allOf;
7218
+ if (!Array.isArray(allOf)) continue;
7219
+ const existing = carriers.get(allOf);
7220
+ if (existing) existing.push(json);
7221
+ else carriers.set(allOf, [json]);
7222
+ }
7223
+ for (const allOf of ctx.intersections) for (const json of carriers.get(allOf) ?? []) foldIntersection(json);
7224
+ }
7225
+ }
6072
7226
  const result = {};
6073
7227
  if (ctx.target === "draft-2020-12") result.$schema = "https://json-schema.org/draft/2020-12/schema";
6074
7228
  else if (ctx.target === "draft-07") result.$schema = "http://json-schema.org/draft-07/schema#";
@@ -6079,12 +7233,18 @@ function finalize(ctx, schema) {
6079
7233
  if (!id) throw new Error("Schema is missing an `id` property");
6080
7234
  result.$id = ctx.external.uri(id);
6081
7235
  }
6082
- Object.assign(result, root.def ?? root.schema);
7236
+ assignProps(result, root.defId ? root.schema : root.def ?? root.schema);
7237
+ const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
7238
+ if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id;
6083
7239
  const defs = ctx.external?.defs ?? {};
6084
- for (const entry of ctx.seen.entries()) {
7240
+ if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) for (const entry of ctx.seen.entries()) {
6085
7241
  const seen = entry[1];
6086
- if (seen.def && seen.defId) defs[seen.defId] = seen.def;
7242
+ if (seen.def && seen.defId) {
7243
+ if (seen.def.id === seen.defId) delete seen.def.id;
7244
+ assignProp(defs, seen.defId, seen.def);
7245
+ }
6087
7246
  }
7247
+ if (ctx.external) ctx.sharedEmitDoneFor = ctx.external;
6088
7248
  if (ctx.external) {} else if (Object.keys(defs).length > 0) if (ctx.target === "draft-2020-12") result.$defs = defs;
6089
7249
  else result.definitions = defs;
6090
7250
  try {
@@ -6114,10 +7274,13 @@ function isTransforming(_schema, _ctx) {
6114
7274
  if (def.type === "array") return isTransforming(def.element, ctx);
6115
7275
  if (def.type === "set") return isTransforming(def.valueType, ctx);
6116
7276
  if (def.type === "lazy") return isTransforming(def.getter(), ctx);
6117
- if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") return isTransforming(def.innerType, ctx);
7277
+ if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault" || def.type === "catch") return isTransforming(def.innerType, ctx);
6118
7278
  if (def.type === "intersection") return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
6119
7279
  if (def.type === "record" || def.type === "map") return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
6120
- if (def.type === "pipe") return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
7280
+ if (def.type === "pipe") {
7281
+ if (_schema._zod.traits.has("$ZodCodec")) return true;
7282
+ return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
7283
+ }
6121
7284
  if (def.type === "object") {
6122
7285
  for (const key in def.shape) if (isTransforming(def.shape[key], ctx)) return true;
6123
7286
  return false;
@@ -6142,7 +7305,7 @@ const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
6142
7305
  ...params,
6143
7306
  processors
6144
7307
  });
6145
- process$1(schema, ctx);
7308
+ processSchema(schema, ctx);
6146
7309
  extractDefs(ctx, schema);
6147
7310
  return finalize(ctx, schema);
6148
7311
  };
@@ -6154,10 +7317,82 @@ const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params)
6154
7317
  io,
6155
7318
  processors
6156
7319
  });
6157
- process$1(schema, ctx);
7320
+ processSchema(schema, ctx);
6158
7321
  extractDefs(ctx, schema);
6159
7322
  return finalize(ctx, schema);
6160
7323
  };
7324
+ const narrowMin = (agg, key, value) => {
7325
+ if (agg[key] === void 0 || value > agg[key]) agg[key] = value;
7326
+ };
7327
+ const narrowMax = (agg, key, value) => {
7328
+ if (agg[key] === void 0 || value < agg[key]) agg[key] = value;
7329
+ };
7330
+ const narrowBoth = (agg, value) => {
7331
+ narrowMin(agg, "minimum", value);
7332
+ narrowMax(agg, "maximum", value);
7333
+ };
7334
+ const addDivisor = (agg, value) => {
7335
+ agg.multipleOf ?? (agg.multipleOf = []);
7336
+ if (!agg.multipleOf.includes(value)) agg.multipleOf.push(value);
7337
+ };
7338
+ const addPattern = (agg, pattern) => {
7339
+ agg.patterns ?? (agg.patterns = /* @__PURE__ */ new Set());
7340
+ agg.patterns.add(pattern);
7341
+ };
7342
+ const intersectMime = (agg, mime) => {
7343
+ agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];
7344
+ };
7345
+ const setFormat = (agg, format) => {
7346
+ agg.format = format;
7347
+ if (format.includes("int")) agg.isInt = true;
7348
+ };
7349
+ const minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum);
7350
+ const maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum);
7351
+ const formatContributor = (ranges) => (agg, def) => {
7352
+ setFormat(agg, def.format);
7353
+ const [minimum, maximum] = ranges[def.format];
7354
+ narrowMin(agg, "minimum", minimum);
7355
+ narrowMax(agg, "maximum", maximum);
7356
+ };
7357
+ const contributors = {
7358
+ greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value),
7359
+ less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value),
7360
+ multiple_of: (agg, def) => addDivisor(agg, def.value),
7361
+ number_format: formatContributor(NUMBER_FORMAT_RANGES),
7362
+ bigint_format: formatContributor(BIGINT_FORMAT_RANGES),
7363
+ min_length: minContributor,
7364
+ max_length: maxContributor,
7365
+ length_equals: (agg, def) => narrowBoth(agg, def.length),
7366
+ min_size: minContributor,
7367
+ max_size: maxContributor,
7368
+ size_equals: (agg, def) => narrowBoth(agg, def.size),
7369
+ string_format: (agg, def) => {
7370
+ setFormat(agg, def.format);
7371
+ if (def.pattern) addPattern(agg, def.pattern);
7372
+ if (def.format === "base64" || def.format === "base64url") agg.contentEncoding = def.format;
7373
+ if (def.local || def.precision === -1) agg.laxFormat = true;
7374
+ },
7375
+ mime_type: (agg, def) => intersectMime(agg, def.mime)
7376
+ };
7377
+ function aggregateChecks(schema) {
7378
+ const agg = {};
7379
+ const def = schema._zod.def;
7380
+ const list = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? [];
7381
+ for (const ch of list) contributors[ch._zod.def.check]?.(agg, ch._zod.def);
7382
+ const bag = schema._zod.bag;
7383
+ if (bag.minimum !== void 0) narrowMin(agg, "minimum", bag.minimum);
7384
+ if (bag.exclusiveMinimum !== void 0) narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum);
7385
+ if (bag.maximum !== void 0) narrowMax(agg, "maximum", bag.maximum);
7386
+ if (bag.exclusiveMaximum !== void 0) narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum);
7387
+ if (bag.multipleOf !== void 0) addDivisor(agg, bag.multipleOf);
7388
+ if (bag.format !== void 0) {
7389
+ agg.format ?? (agg.format = bag.format);
7390
+ if (bag.format.includes("int")) agg.isInt = true;
7391
+ }
7392
+ if (bag.mime) intersectMime(agg, bag.mime);
7393
+ for (const pattern of bag.patterns ?? []) addPattern(agg, pattern);
7394
+ return agg;
7395
+ }
6161
7396
  const formatMap = {
6162
7397
  guid: "uuid",
6163
7398
  url: "uri",
@@ -6165,51 +7400,54 @@ const formatMap = {
6165
7400
  json_string: "json-string",
6166
7401
  regex: ""
6167
7402
  };
7403
+ const exactPatterns = new Map([[base64Charset, base64], [base64urlCharset, base64url]]);
7404
+ const exactPattern = (p) => exactPatterns.get(p) ?? p;
6168
7405
  const stringProcessor = (schema, ctx, _json, _params) => {
6169
7406
  const json = _json;
6170
7407
  json.type = "string";
6171
- const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag;
7408
+ const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);
6172
7409
  if (typeof minimum === "number") json.minLength = minimum;
6173
7410
  if (typeof maximum === "number") json.maxLength = maximum;
6174
7411
  if (format) {
6175
7412
  json.format = formatMap[format] ?? format;
6176
7413
  if (json.format === "") delete json.format;
6177
- if (format === "time") delete json.format;
7414
+ if (format === "time" || laxFormat) delete json.format;
6178
7415
  }
6179
7416
  if (contentEncoding) json.contentEncoding = contentEncoding;
6180
7417
  if (patterns && patterns.size > 0) {
6181
- const regexes = [...patterns];
6182
- if (regexes.length === 1) json.pattern = regexes[0].source;
6183
- else if (regexes.length > 1) json.allOf = [...regexes.map((regex) => ({
7418
+ const patternList = [...patterns].map(exactPattern);
7419
+ if (patternList.length === 1) json.pattern = patternList[0].source;
7420
+ else if (patternList.length > 1) json.allOf = [...patternList.map((regex) => ({
6184
7421
  ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
6185
7422
  pattern: regex.source
6186
7423
  }))];
6187
7424
  }
6188
7425
  };
6189
- const numberProcessor = (schema, ctx, _json, _params) => {
7426
+ const numberProcessor = (schema, ctx, _json, params) => {
6190
7427
  const json = _json;
6191
- const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
6192
- if (typeof format === "string" && format.includes("int")) json.type = "integer";
6193
- else json.type = "number";
6194
- if (typeof exclusiveMinimum === "number") if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
7428
+ const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);
7429
+ json.type = isInt ? "integer" : "number";
7430
+ const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
7431
+ const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
7432
+ const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
7433
+ if (exMin) if (legacy) {
6195
7434
  json.minimum = exclusiveMinimum;
6196
7435
  json.exclusiveMinimum = true;
6197
7436
  } else json.exclusiveMinimum = exclusiveMinimum;
6198
- if (typeof minimum === "number") {
6199
- json.minimum = minimum;
6200
- if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") if (exclusiveMinimum >= minimum) delete json.minimum;
6201
- else delete json.exclusiveMinimum;
6202
- }
6203
- if (typeof exclusiveMaximum === "number") if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
7437
+ else if (typeof minimum === "number") json.minimum = minimum;
7438
+ if (exMax) if (legacy) {
6204
7439
  json.maximum = exclusiveMaximum;
6205
7440
  json.exclusiveMaximum = true;
6206
7441
  } else json.exclusiveMaximum = exclusiveMaximum;
6207
- if (typeof maximum === "number") {
6208
- json.maximum = maximum;
6209
- if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") if (exclusiveMaximum <= maximum) delete json.maximum;
6210
- else delete json.exclusiveMaximum;
7442
+ else if (typeof maximum === "number") json.maximum = maximum;
7443
+ if (multipleOf) {
7444
+ const divisors = /* @__PURE__ */ new Set();
7445
+ for (const divisor of multipleOf) if (Number.isFinite(divisor) && divisor !== 0) divisors.add(Math.abs(divisor));
7446
+ else handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);
7447
+ const [first, ...rest] = divisors;
7448
+ if (first !== void 0) json.multipleOf = first;
7449
+ if (rest.length) json.allOf = [...json.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))];
6211
7450
  }
6212
- if (typeof multipleOf === "number") json.multipleOf = multipleOf;
6213
7451
  };
6214
7452
  const booleanProcessor = (_schema, _ctx, json, _params) => {
6215
7453
  json.type = "boolean";
@@ -6221,18 +7459,27 @@ const unknownProcessor = (_schema, _ctx, _json, _params) => {};
6221
7459
  const enumProcessor = (schema, _ctx, json, _params) => {
6222
7460
  const def = schema._zod.def;
6223
7461
  const values = getEnumValues(def.entries);
7462
+ if (values.length === 0) {
7463
+ json.not = {};
7464
+ return;
7465
+ }
6224
7466
  if (values.every((v) => typeof v === "number")) json.type = "number";
6225
7467
  if (values.every((v) => typeof v === "string")) json.type = "string";
6226
7468
  json.enum = values;
6227
7469
  };
6228
- const literalProcessor = (schema, ctx, json, _params) => {
7470
+ const literalProcessor = (schema, ctx, json, params) => {
6229
7471
  const def = schema._zod.def;
7472
+ if (def.values.length === 0) {
7473
+ json.not = {};
7474
+ return;
7475
+ }
6230
7476
  const vals = [];
6231
7477
  for (const val of def.values) if (val === void 0) {
6232
- if (ctx.unrepresentable === "throw") throw new Error("Literal `undefined` cannot be represented in JSON Schema");
6233
- } else if (typeof val === "bigint") if (ctx.unrepresentable === "throw") throw new Error("BigInt literals cannot be represented in JSON Schema");
6234
- else vals.push(Number(val));
6235
- else vals.push(val);
7478
+ if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema")) return;
7479
+ } else if (typeof val === "bigint") {
7480
+ if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema")) return;
7481
+ vals.push(Number(val));
7482
+ } else vals.push(val);
6236
7483
  if (vals.length === 0) {} else if (vals.length === 1) {
6237
7484
  const val = vals[0];
6238
7485
  json.type = val === null ? "null" : typeof val;
@@ -6246,49 +7493,55 @@ const literalProcessor = (schema, ctx, json, _params) => {
6246
7493
  json.enum = vals;
6247
7494
  }
6248
7495
  };
6249
- const customProcessor = (_schema, ctx, _json, _params) => {
6250
- if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
7496
+ const customProcessor = (schema, ctx, json, params) => {
7497
+ handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema");
6251
7498
  };
6252
- const transformProcessor = (_schema, ctx, _json, _params) => {
6253
- if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
7499
+ const transformProcessor = (schema, ctx, json, params) => {
7500
+ handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema");
6254
7501
  };
6255
7502
  const arrayProcessor = (schema, ctx, _json, params) => {
6256
7503
  const json = _json;
6257
7504
  const def = schema._zod.def;
6258
- const { minimum, maximum } = schema._zod.bag;
7505
+ const { minimum, maximum } = aggregateChecks(schema);
6259
7506
  if (typeof minimum === "number") json.minItems = minimum;
6260
7507
  if (typeof maximum === "number") json.maxItems = maximum;
6261
7508
  json.type = "array";
6262
- json.items = process$1(def.element, ctx, {
7509
+ json.items = processSchema(def.element, ctx, {
6263
7510
  ...params,
6264
7511
  path: [...params.path, "items"]
6265
7512
  });
6266
7513
  };
7514
+ function inputOptin(schema) {
7515
+ const def = schema._zod.def;
7516
+ if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) return inputOptin(def.out);
7517
+ if (def.type === "catch") return inputOptin(def.innerType);
7518
+ return schema._zod.optin;
7519
+ }
6267
7520
  const objectProcessor = (schema, ctx, _json, params) => {
6268
7521
  const json = _json;
6269
7522
  const def = schema._zod.def;
7523
+ const shape = def.shape;
7524
+ if (Object.getOwnPropertySymbols(shape).length && handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) return;
6270
7525
  json.type = "object";
6271
7526
  json.properties = {};
6272
- const shape = def.shape;
6273
- for (const key in shape) json.properties[key] = process$1(shape[key], ctx, {
7527
+ for (const key in shape) assignProp(json.properties, key, processSchema(shape[key], ctx, {
6274
7528
  ...params,
6275
7529
  path: [
6276
7530
  ...params.path,
6277
7531
  "properties",
6278
7532
  key
6279
7533
  ]
6280
- });
6281
- const allKeys = new Set(Object.keys(shape));
6282
- const requiredKeys = new Set([...allKeys].filter((key) => {
6283
- const v = def.shape[key]._zod;
6284
- if (ctx.io === "input") return v.optin === void 0;
6285
- else return v.optout === void 0;
6286
7534
  }));
6287
- if (requiredKeys.size > 0) json.required = Array.from(requiredKeys);
7535
+ const requiredKeys = [];
7536
+ for (const key of Object.keys(shape)) {
7537
+ const field = def.shape[key];
7538
+ if (ctx.io === "input" ? inputOptin(field) === void 0 : field._zod.optout === void 0) requiredKeys.push(key);
7539
+ }
7540
+ if (requiredKeys.length > 0) json.required = requiredKeys;
6288
7541
  if (def.catchall?._zod.def.type === "never") json.additionalProperties = false;
6289
7542
  else if (!def.catchall) {
6290
7543
  if (ctx.io === "output") json.additionalProperties = false;
6291
- } else if (def.catchall) json.additionalProperties = process$1(def.catchall, ctx, {
7544
+ } else if (def.catchall) json.additionalProperties = processSchema(def.catchall, ctx, {
6292
7545
  ...params,
6293
7546
  path: [...params.path, "additionalProperties"]
6294
7547
  });
@@ -6296,7 +7549,7 @@ const objectProcessor = (schema, ctx, _json, params) => {
6296
7549
  const unionProcessor = (schema, ctx, json, params) => {
6297
7550
  const def = schema._zod.def;
6298
7551
  const isExclusive = def.inclusive === false;
6299
- const options = def.options.map((x, i) => process$1(x, ctx, {
7552
+ const options = def.options.map((x, i) => processSchema(x, ctx, {
6300
7553
  ...params,
6301
7554
  path: [
6302
7555
  ...params.path,
@@ -6309,7 +7562,7 @@ const unionProcessor = (schema, ctx, json, params) => {
6309
7562
  };
6310
7563
  const intersectionProcessor = (schema, ctx, json, params) => {
6311
7564
  const def = schema._zod.def;
6312
- const a = process$1(def.left, ctx, {
7565
+ const a = processSchema(def.left, ctx, {
6313
7566
  ...params,
6314
7567
  path: [
6315
7568
  ...params.path,
@@ -6317,7 +7570,7 @@ const intersectionProcessor = (schema, ctx, json, params) => {
6317
7570
  0
6318
7571
  ]
6319
7572
  });
6320
- const b = process$1(def.right, ctx, {
7573
+ const b = processSchema(def.right, ctx, {
6321
7574
  ...params,
6322
7575
  path: [
6323
7576
  ...params.path,
@@ -6326,16 +7579,76 @@ const intersectionProcessor = (schema, ctx, json, params) => {
6326
7579
  ]
6327
7580
  });
6328
7581
  const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
6329
- json.allOf = [...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b]];
7582
+ const allOf = [...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b]];
7583
+ json.allOf = allOf;
7584
+ ctx.intersections.push(allOf);
6330
7585
  };
7586
+ /** JSON object keys are always strings, so a numeric record key schema is re-expressed over the
7587
+ * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key
7588
+ * behind a wrapper only carries its own `type` before then, and a union key only has its branches.
7589
+ *
7590
+ * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather
7591
+ * than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this
7592
+ * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)`
7593
+ * accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema
7594
+ * outright. */
7595
+ function stringifyKeyNames(bySchema, json, visited) {
7596
+ if (json.$ref) {
7597
+ if (visited.has(json)) return json;
7598
+ visited.add(json);
7599
+ const def = bySchema.get(json)?.def;
7600
+ if (!def) return json;
7601
+ const inlined = stringifyKeyNames(bySchema, def, visited);
7602
+ return inlined === def ? json : inlined;
7603
+ }
7604
+ for (const keyword of ["anyOf", "oneOf"]) {
7605
+ const branches = json[keyword];
7606
+ if (!Array.isArray(branches)) continue;
7607
+ const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));
7608
+ if (mapped.some((branch, i) => branch !== branches[i])) json = {
7609
+ ...json,
7610
+ [keyword]: mapped
7611
+ };
7612
+ }
7613
+ const types = Array.isArray(json.type) ? json.type : [json.type];
7614
+ const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer");
7615
+ const values = json.enum ?? (json.const !== void 0 ? [json.const] : void 0);
7616
+ if (!numericType && !values?.some((v) => typeof v === "number")) return json;
7617
+ const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;
7618
+ if (rest.enum) rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v);
7619
+ else if (typeof rest.const === "number") rest.const = String(rest.const);
7620
+ if (!numericType) return rest;
7621
+ rest.type = "string";
7622
+ if (!values) rest.pattern = (types.includes("number") ? number$1 : integer).source;
7623
+ return rest;
7624
+ }
7625
+ /** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */
7626
+ const pendingRecords = /* @__PURE__ */ new WeakMap();
7627
+ function rewriteKeyNames(ctx) {
7628
+ const bySchema = /* @__PURE__ */ new Map();
7629
+ for (const entry of ctx.seen.values()) if (entry.def && !bySchema.has(entry.schema)) bySchema.set(entry.schema, entry);
7630
+ const rewrites = /* @__PURE__ */ new Map();
7631
+ for (const record of pendingRecords.get(ctx) ?? []) {
7632
+ const seen = ctx.seen.get(record);
7633
+ const names = (seen?.def ?? seen?.schema)?.propertyNames;
7634
+ if (!names || names === true || rewrites.has(names)) continue;
7635
+ const rewritten = stringifyKeyNames(bySchema, names, /* @__PURE__ */ new Set());
7636
+ if (rewritten !== names) rewrites.set(names, rewritten);
7637
+ }
7638
+ if (!rewrites.size) return;
7639
+ for (const entry of ctx.seen.values()) for (const carrier of [entry.schema, entry.def]) {
7640
+ const rewritten = carrier && rewrites.get(carrier.propertyNames);
7641
+ if (rewritten) carrier.propertyNames = rewritten;
7642
+ }
7643
+ }
6331
7644
  const recordProcessor = (schema, ctx, _json, params) => {
6332
7645
  const json = _json;
6333
7646
  const def = schema._zod.def;
6334
7647
  json.type = "object";
6335
7648
  const keyType = def.keyType;
6336
- const patterns = keyType._zod.bag?.patterns;
7649
+ const patterns = aggregateChecks(keyType).patterns;
6337
7650
  if (def.mode === "loose" && patterns && patterns.size > 0) {
6338
- const valueSchema = process$1(def.valueType, ctx, {
7651
+ const valueSchema = processSchema(def.valueType, ctx, {
6339
7652
  ...params,
6340
7653
  path: [
6341
7654
  ...params.path,
@@ -6344,26 +7657,36 @@ const recordProcessor = (schema, ctx, _json, params) => {
6344
7657
  ]
6345
7658
  });
6346
7659
  json.patternProperties = {};
6347
- for (const pattern of patterns) json.patternProperties[pattern.source] = valueSchema;
7660
+ for (const pattern of patterns) assignProp(json.patternProperties, exactPattern(pattern).source, valueSchema);
6348
7661
  } else {
6349
- if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") json.propertyNames = process$1(def.keyType, ctx, {
6350
- ...params,
6351
- path: [...params.path, "propertyNames"]
6352
- });
6353
- json.additionalProperties = process$1(def.valueType, ctx, {
7662
+ if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
7663
+ json.propertyNames = processSchema(def.keyType, ctx, {
7664
+ ...params,
7665
+ path: [...params.path, "propertyNames"]
7666
+ });
7667
+ let pending = pendingRecords.get(ctx);
7668
+ if (!pending) {
7669
+ pending = [];
7670
+ pendingRecords.set(ctx, pending);
7671
+ ctx.deferred.push(() => rewriteKeyNames(ctx));
7672
+ }
7673
+ pending.push(schema);
7674
+ }
7675
+ json.additionalProperties = processSchema(def.valueType, ctx, {
6354
7676
  ...params,
6355
7677
  path: [...params.path, "additionalProperties"]
6356
7678
  });
6357
7679
  }
6358
7680
  const keyValues = keyType._zod.values;
6359
- if (keyValues) {
7681
+ const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== void 0;
7682
+ if (keyValues && !def.partial && !omittableOnInput) {
6360
7683
  const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
6361
- if (validKeyValues.length > 0) json.required = validKeyValues;
7684
+ if (validKeyValues.length > 0) json.required = validKeyValues.map(String);
6362
7685
  }
6363
7686
  };
6364
7687
  const nullableProcessor = (schema, ctx, json, params) => {
6365
7688
  const def = schema._zod.def;
6366
- const inner = process$1(def.innerType, ctx, params);
7689
+ const inner = processSchema(def.innerType, ctx, params);
6367
7690
  const seen = ctx.seen.get(schema);
6368
7691
  if (ctx.target === "openapi-3.0") {
6369
7692
  seen.ref = def.innerType;
@@ -6372,106 +7695,125 @@ const nullableProcessor = (schema, ctx, json, params) => {
6372
7695
  };
6373
7696
  const nonoptionalProcessor = (schema, ctx, _json, params) => {
6374
7697
  const def = schema._zod.def;
6375
- process$1(def.innerType, ctx, params);
7698
+ processSchema(def.innerType, ctx, params);
6376
7699
  const seen = ctx.seen.get(schema);
6377
7700
  seen.ref = def.innerType;
6378
7701
  };
7702
+ /** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON.
7703
+ * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other
7704
+ * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */
7705
+ const UNREPRESENTABLE_DEFAULT = Symbol();
7706
+ function serializeDefaultValue(value, schema, ctx, json, params) {
7707
+ let unrepresentable = false;
7708
+ const serialized = JSON.stringify(value, (_, val) => {
7709
+ if (typeof val !== "bigint") return val;
7710
+ unrepresentable = true;
7711
+ return null;
7712
+ });
7713
+ if (!unrepresentable) return JSON.parse(serialized);
7714
+ handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema");
7715
+ return UNREPRESENTABLE_DEFAULT;
7716
+ }
6379
7717
  const defaultProcessor = (schema, ctx, json, params) => {
6380
7718
  const def = schema._zod.def;
6381
- process$1(def.innerType, ctx, params);
7719
+ processSchema(def.innerType, ctx, params);
6382
7720
  const seen = ctx.seen.get(schema);
6383
7721
  seen.ref = def.innerType;
6384
- json.default = JSON.parse(JSON.stringify(def.defaultValue));
7722
+ const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);
7723
+ if (value !== UNREPRESENTABLE_DEFAULT) json.default = value;
6385
7724
  };
6386
7725
  const prefaultProcessor = (schema, ctx, json, params) => {
6387
7726
  const def = schema._zod.def;
6388
- process$1(def.innerType, ctx, params);
7727
+ processSchema(def.innerType, ctx, params);
6389
7728
  const seen = ctx.seen.get(schema);
6390
7729
  seen.ref = def.innerType;
6391
- if (ctx.io === "input") json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
7730
+ if (ctx.io !== "input") return;
7731
+ const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);
7732
+ if (value !== UNREPRESENTABLE_DEFAULT) json._prefault = value;
6392
7733
  };
6393
7734
  const catchProcessor = (schema, ctx, json, params) => {
6394
7735
  const def = schema._zod.def;
6395
- process$1(def.innerType, ctx, params);
7736
+ processSchema(def.innerType, ctx, params);
6396
7737
  const seen = ctx.seen.get(schema);
6397
7738
  seen.ref = def.innerType;
6398
7739
  let catchValue;
6399
7740
  try {
6400
7741
  catchValue = def.catchValue(void 0);
6401
7742
  } catch {
6402
- throw new Error("Dynamic catch values are not supported in JSON Schema");
7743
+ handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema");
7744
+ return;
6403
7745
  }
6404
7746
  json.default = catchValue;
6405
7747
  };
6406
7748
  const pipeProcessor = (schema, ctx, _json, params) => {
6407
7749
  const def = schema._zod.def;
6408
- const innerType = ctx.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out;
6409
- process$1(innerType, ctx, params);
7750
+ const inIsTransform = def.in._zod.traits.has("$ZodTransform");
7751
+ const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out;
7752
+ processSchema(innerType, ctx, params);
6410
7753
  const seen = ctx.seen.get(schema);
6411
7754
  seen.ref = innerType;
6412
7755
  };
6413
7756
  const readonlyProcessor = (schema, ctx, json, params) => {
6414
7757
  const def = schema._zod.def;
6415
- process$1(def.innerType, ctx, params);
7758
+ processSchema(def.innerType, ctx, params);
6416
7759
  const seen = ctx.seen.get(schema);
6417
7760
  seen.ref = def.innerType;
6418
7761
  json.readOnly = true;
6419
7762
  };
6420
7763
  const optionalProcessor = (schema, ctx, _json, params) => {
6421
7764
  const def = schema._zod.def;
6422
- process$1(def.innerType, ctx, params);
7765
+ processSchema(def.innerType, ctx, params);
6423
7766
  const seen = ctx.seen.get(schema);
6424
7767
  seen.ref = def.innerType;
6425
7768
  };
6426
- const ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
6427
- $ZodISODateTime.init(inst, def);
6428
- ZodStringFormat.init(inst, def);
6429
- });
6430
- function datetime(params) {
6431
- return /* @__PURE__ */ _isoDateTime(ZodISODateTime, params);
6432
- }
6433
- const ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
6434
- $ZodISODate.init(inst, def);
6435
- ZodStringFormat.init(inst, def);
6436
- });
6437
- function date(params) {
6438
- return /* @__PURE__ */ _isoDate(ZodISODate, params);
6439
- }
6440
- const ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
6441
- $ZodISOTime.init(inst, def);
6442
- ZodStringFormat.init(inst, def);
6443
- });
6444
- function time(params) {
6445
- return /* @__PURE__ */ _isoTime(ZodISOTime, params);
6446
- }
6447
- const ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
6448
- $ZodISODuration.init(inst, def);
6449
- ZodStringFormat.init(inst, def);
6450
- });
6451
- function duration(params) {
6452
- return /* @__PURE__ */ _isoDuration(ZodISODuration, params);
7769
+ const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
7770
+ function _lazyMethod(proto, key, make) {
7771
+ Object.defineProperty(proto, key, {
7772
+ configurable: true,
7773
+ enumerable: false,
7774
+ get() {
7775
+ const value = make(this);
7776
+ Object.defineProperty(this, key, {
7777
+ value,
7778
+ configurable: true,
7779
+ writable: true
7780
+ });
7781
+ return value;
7782
+ },
7783
+ set(value) {
7784
+ Object.defineProperty(this, key, {
7785
+ value,
7786
+ configurable: true,
7787
+ writable: true
7788
+ });
7789
+ }
7790
+ });
6453
7791
  }
6454
7792
  const initializer = (inst, issues) => {
6455
7793
  $ZodError.init(inst, issues);
6456
7794
  inst.name = "ZodError";
6457
- Object.defineProperties(inst, {
6458
- format: { value: (mapper) => formatError(inst, mapper) },
6459
- flatten: { value: (mapper) => flattenError(inst, mapper) },
6460
- addIssue: { value: (issue) => {
6461
- inst.issues.push(issue);
6462
- inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
6463
- } },
6464
- addIssues: { value: (issues) => {
6465
- inst.issues.push(...issues);
6466
- inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
6467
- } },
6468
- isEmpty: { get() {
6469
- return inst.issues.length === 0;
6470
- } }
7795
+ const proto = Object.getPrototypeOf(inst);
7796
+ if (_installedErrorProtos.has(proto)) return;
7797
+ _installedErrorProtos.add(proto);
7798
+ _lazyMethod(proto, "format", (self) => (mapper) => formatError(self, mapper));
7799
+ _lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper));
7800
+ _lazyMethod(proto, "addIssue", (self) => (issue) => {
7801
+ self.issues.push(issue);
7802
+ self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2);
7803
+ });
7804
+ _lazyMethod(proto, "addIssues", (self) => (issues) => {
7805
+ self.issues.push(...issues);
7806
+ self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2);
7807
+ });
7808
+ Object.defineProperty(proto, "isEmpty", {
7809
+ configurable: true,
7810
+ enumerable: false,
7811
+ get() {
7812
+ return this.issues.length === 0;
7813
+ }
6471
7814
  });
6472
7815
  };
6473
- $constructor("ZodError", initializer);
6474
- const ZodRealError = $constructor("ZodError", initializer, { Parent: Error });
7816
+ const ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer, void 0, { Parent: Error });
6475
7817
  const parse = /* @__PURE__ */ _parse(ZodRealError);
6476
7818
  const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
6477
7819
  const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
@@ -6484,137 +7826,319 @@ const safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError);
6484
7826
  const safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
6485
7827
  const safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
6486
7828
  const safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
7829
+ function _ensureDefaultLocale() {
7830
+ if (!globalConfig.localeError) config(en_default());
7831
+ }
7832
+ function _ensureDefaultMemoizer() {
7833
+ if (!globalConfig.memoizer) config({ memoizer: memoizer() });
7834
+ }
6487
7835
  const ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
7836
+ _ensureDefaultLocale();
6488
7837
  $ZodType.init(inst, def);
6489
- Object.assign(inst["~standard"], { jsonSchema: {
6490
- input: createStandardJSONSchemaMethod(inst, "input"),
6491
- output: createStandardJSONSchemaMethod(inst, "output")
6492
- } });
6493
- inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
6494
7838
  inst.def = def;
6495
7839
  inst.type = def.type;
6496
- Object.defineProperty(inst, "_def", { value: def });
6497
- inst.check = (...checks) => {
6498
- return inst.clone(mergeDefs(def, { checks: [...def.checks ?? [], ...checks.map((ch) => typeof ch === "function" ? { _zod: {
7840
+ return inst;
7841
+ }, {
7842
+ check(...chks) {
7843
+ const def = this.def;
7844
+ return this.clone(mergeDefs(def, { checks: [...def.checks ?? [], ...chks.map((ch) => typeof ch === "function" ? { _zod: {
6499
7845
  check: ch,
6500
7846
  def: { check: "custom" },
6501
7847
  onattach: []
6502
7848
  } } : ch)] }), { parent: true });
6503
- };
6504
- inst.with = inst.check;
6505
- inst.clone = (def, params) => clone(inst, def, params);
6506
- inst.brand = () => inst;
6507
- inst.register = ((reg, meta) => {
6508
- reg.add(inst, meta);
6509
- return inst;
6510
- });
6511
- inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
6512
- inst.safeParse = (data, params) => safeParse(inst, data, params);
6513
- inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
6514
- inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
6515
- inst.spa = inst.safeParseAsync;
6516
- inst.encode = (data, params) => encode(inst, data, params);
6517
- inst.decode = (data, params) => decode(inst, data, params);
6518
- inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
6519
- inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
6520
- inst.safeEncode = (data, params) => safeEncode(inst, data, params);
6521
- inst.safeDecode = (data, params) => safeDecode(inst, data, params);
6522
- inst.safeEncodeAsync = async (data, params) => safeEncodeAsync(inst, data, params);
6523
- inst.safeDecodeAsync = async (data, params) => safeDecodeAsync(inst, data, params);
6524
- inst.refine = (check, params) => inst.check(refine(check, params));
6525
- inst.superRefine = (refinement) => inst.check(superRefine(refinement));
6526
- inst.overwrite = (fn) => inst.check(/* @__PURE__ */ _overwrite(fn));
6527
- inst.optional = () => optional(inst);
6528
- inst.exactOptional = () => exactOptional(inst);
6529
- inst.nullable = () => nullable(inst);
6530
- inst.nullish = () => optional(nullable(inst));
6531
- inst.nonoptional = (params) => nonoptional(inst, params);
6532
- inst.array = () => array(inst);
6533
- inst.or = (arg) => union([inst, arg]);
6534
- inst.and = (arg) => intersection(inst, arg);
6535
- inst.transform = (tx) => pipe(inst, transform(tx));
6536
- inst.default = (def) => _default(inst, def);
6537
- inst.prefault = (def) => prefault(inst, def);
6538
- inst.catch = (params) => _catch(inst, params);
6539
- inst.pipe = (target) => pipe(inst, target);
6540
- inst.readonly = () => readonly(inst);
6541
- inst.describe = (description) => {
6542
- const cl = inst.clone();
7849
+ },
7850
+ with(...chks) {
7851
+ return this.check(...chks);
7852
+ },
7853
+ clone(def, params) {
7854
+ return clone(this, def, params);
7855
+ },
7856
+ brand() {
7857
+ return this;
7858
+ },
7859
+ register(reg, meta) {
7860
+ reg.add(this, meta);
7861
+ return this;
7862
+ },
7863
+ refine(check, params) {
7864
+ return this.check(refine(check, params));
7865
+ },
7866
+ superRefine(refinement, params) {
7867
+ return this.check(superRefine(refinement, params));
7868
+ },
7869
+ overwrite(fn) {
7870
+ return this.check(/* @__PURE__ */ _overwrite(fn));
7871
+ },
7872
+ optional() {
7873
+ return optional(this);
7874
+ },
7875
+ exactOptional() {
7876
+ return exactOptional(this);
7877
+ },
7878
+ nullable() {
7879
+ return nullable(this);
7880
+ },
7881
+ nullish() {
7882
+ return optional(nullable(this));
7883
+ },
7884
+ nonoptional(params) {
7885
+ return nonoptional(this, params);
7886
+ },
7887
+ array() {
7888
+ return array(this);
7889
+ },
7890
+ or(arg) {
7891
+ return union([this, arg]);
7892
+ },
7893
+ and(arg) {
7894
+ return intersection(this, arg);
7895
+ },
7896
+ transform(tx) {
7897
+ return pipe(this, transform(tx));
7898
+ },
7899
+ default(d) {
7900
+ return _default(this, d);
7901
+ },
7902
+ prefault(d) {
7903
+ return prefault(this, d);
7904
+ },
7905
+ catch(params) {
7906
+ return _catch(this, params);
7907
+ },
7908
+ pipe(target) {
7909
+ return pipe(this, target);
7910
+ },
7911
+ readonly() {
7912
+ return readonly(this);
7913
+ },
7914
+ describe(description) {
7915
+ const cl = this.clone();
6543
7916
  globalRegistry.add(cl, { description });
6544
7917
  return cl;
6545
- };
6546
- Object.defineProperty(inst, "description", {
6547
- get() {
6548
- return globalRegistry.get(inst)?.description;
6549
- },
6550
- configurable: true
6551
- });
6552
- inst.meta = (...args) => {
6553
- if (args.length === 0) return globalRegistry.get(inst);
6554
- const cl = inst.clone();
7918
+ },
7919
+ meta(...args) {
7920
+ if (args.length === 0) return globalRegistry.get(this);
7921
+ const cl = this.clone();
6555
7922
  globalRegistry.add(cl, args[0]);
6556
7923
  return cl;
6557
- };
6558
- inst.isOptional = () => inst.safeParse(void 0).success;
6559
- inst.isNullable = () => inst.safeParse(null).success;
6560
- inst.apply = (fn) => fn(inst);
6561
- return inst;
7924
+ },
7925
+ isOptional() {
7926
+ return this.safeParse(void 0).success;
7927
+ },
7928
+ isNullable() {
7929
+ return this.safeParse(null).success;
7930
+ },
7931
+ apply(fn, ...args) {
7932
+ return args.length === 0 ? fn(this) : fn(this, ...args);
7933
+ },
7934
+ get "~standard"() {
7935
+ return hide(this, "~standard", {
7936
+ ...standardProps(this),
7937
+ jsonSchema: {
7938
+ input: createStandardJSONSchemaMethod(this, "input"),
7939
+ output: createStandardJSONSchemaMethod(this, "output")
7940
+ }
7941
+ });
7942
+ },
7943
+ set "~standard"(value) {
7944
+ own(this, "~standard", value);
7945
+ },
7946
+ parse: function _parse(data, params) {
7947
+ return parse(this, data, params, { callee: _parse });
7948
+ },
7949
+ parseAsync: async function _parseAsync(data, params) {
7950
+ return await parseAsync(this, data, params, { callee: _parseAsync });
7951
+ },
7952
+ safeParse(data, params) {
7953
+ return safeParse(this, data, params);
7954
+ },
7955
+ async safeParseAsync(data, params) {
7956
+ return safeParseAsync(this, data, params);
7957
+ },
7958
+ get spa() {
7959
+ return this?.safeParseAsync;
7960
+ },
7961
+ set spa(value) {
7962
+ own(this, "spa", value);
7963
+ },
7964
+ validate(data, params) {
7965
+ return validate(this, data, params);
7966
+ },
7967
+ validateAsync(data, params) {
7968
+ return validateAsync$1(this, data, params);
7969
+ },
7970
+ encode: function _encode(data, params) {
7971
+ return encode(this, data, params, { callee: _encode });
7972
+ },
7973
+ decode: function _decode(data, params) {
7974
+ return decode(this, data, params, { callee: _decode });
7975
+ },
7976
+ encodeAsync: async function _encodeAsync(data, params) {
7977
+ return await encodeAsync(this, data, params, { callee: _encodeAsync });
7978
+ },
7979
+ decodeAsync: async function _decodeAsync(data, params) {
7980
+ return await decodeAsync(this, data, params, { callee: _decodeAsync });
7981
+ },
7982
+ safeEncode(data, params) {
7983
+ return safeEncode(this, data, params);
7984
+ },
7985
+ safeDecode(data, params) {
7986
+ return safeDecode(this, data, params);
7987
+ },
7988
+ async safeEncodeAsync(data, params) {
7989
+ return safeEncodeAsync(this, data, params);
7990
+ },
7991
+ async safeDecodeAsync(data, params) {
7992
+ return safeDecodeAsync(this, data, params);
7993
+ },
7994
+ toJSONSchema(params) {
7995
+ return createToJSONSchemaMethod(this, {})(params);
7996
+ },
7997
+ get description() {
7998
+ return globalRegistry.get(this)?.description;
7999
+ },
8000
+ get _def() {
8001
+ return this._zod.def;
8002
+ }
6562
8003
  });
6563
8004
  /** @internal */
6564
8005
  const _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
6565
8006
  $ZodString.init(inst, def);
6566
8007
  ZodType.init(inst, def);
6567
8008
  inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params);
6568
- const bag = inst._zod.bag;
6569
- inst.format = bag.format ?? null;
6570
- inst.minLength = bag.minimum ?? null;
6571
- inst.maxLength = bag.maximum ?? null;
6572
- inst.regex = (...args) => inst.check(/* @__PURE__ */ _regex(...args));
6573
- inst.includes = (...args) => inst.check(/* @__PURE__ */ _includes(...args));
6574
- inst.startsWith = (...args) => inst.check(/* @__PURE__ */ _startsWith(...args));
6575
- inst.endsWith = (...args) => inst.check(/* @__PURE__ */ _endsWith(...args));
6576
- inst.min = (...args) => inst.check(/* @__PURE__ */ _minLength(...args));
6577
- inst.max = (...args) => inst.check(/* @__PURE__ */ _maxLength(...args));
6578
- inst.length = (...args) => inst.check(/* @__PURE__ */ _length(...args));
6579
- inst.nonempty = (...args) => inst.check(/* @__PURE__ */ _minLength(1, ...args));
6580
- inst.lowercase = (params) => inst.check(/* @__PURE__ */ _lowercase(params));
6581
- inst.uppercase = (params) => inst.check(/* @__PURE__ */ _uppercase(params));
6582
- inst.trim = () => inst.check(/* @__PURE__ */ _trim());
6583
- inst.normalize = (...args) => inst.check(/* @__PURE__ */ _normalize(...args));
6584
- inst.toLowerCase = () => inst.check(/* @__PURE__ */ _toLowerCase());
6585
- inst.toUpperCase = () => inst.check(/* @__PURE__ */ _toUpperCase());
6586
- inst.slugify = () => inst.check(/* @__PURE__ */ _slugify());
6587
- });
8009
+ }, /* @__PURE__ */ derived({
8010
+ format: (inst) => aggregateChecks(inst).format ?? null,
8011
+ minLength: (inst) => aggregateChecks(inst).minimum ?? null,
8012
+ maxLength: (inst) => aggregateChecks(inst).maximum ?? null
8013
+ }, {
8014
+ regex(...args) {
8015
+ return this.check(/* @__PURE__ */ _regex(...args));
8016
+ },
8017
+ includes(...args) {
8018
+ return this.check(/* @__PURE__ */ _includes(...args));
8019
+ },
8020
+ startsWith(...args) {
8021
+ return this.check(/* @__PURE__ */ _startsWith(...args));
8022
+ },
8023
+ endsWith(...args) {
8024
+ return this.check(/* @__PURE__ */ _endsWith(...args));
8025
+ },
8026
+ min(...args) {
8027
+ return this.check(/* @__PURE__ */ _minLength(...args));
8028
+ },
8029
+ max(...args) {
8030
+ return this.check(/* @__PURE__ */ _maxLength(...args));
8031
+ },
8032
+ length(...args) {
8033
+ return this.check(/* @__PURE__ */ _length(...args));
8034
+ },
8035
+ nonempty(...args) {
8036
+ return this.check(/* @__PURE__ */ _minLength(1, ...args));
8037
+ },
8038
+ lowercase(params) {
8039
+ return this.check(/* @__PURE__ */ _lowercase(params));
8040
+ },
8041
+ uppercase(params) {
8042
+ return this.check(/* @__PURE__ */ _uppercase(params));
8043
+ },
8044
+ trim() {
8045
+ return this.check(/* @__PURE__ */ _trim());
8046
+ },
8047
+ normalize(...args) {
8048
+ return this.check(/* @__PURE__ */ _normalize(...args));
8049
+ },
8050
+ toLowerCase() {
8051
+ return this.check(/* @__PURE__ */ _toLowerCase());
8052
+ },
8053
+ toUpperCase() {
8054
+ return this.check(/* @__PURE__ */ _toUpperCase());
8055
+ },
8056
+ slugify() {
8057
+ return this.check(/* @__PURE__ */ _slugify());
8058
+ }
8059
+ }));
6588
8060
  const ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
6589
8061
  $ZodString.init(inst, def);
6590
8062
  _ZodString.init(inst, def);
6591
- inst.email = (params) => inst.check(/* @__PURE__ */ _email(ZodEmail, params));
6592
- inst.url = (params) => inst.check(/* @__PURE__ */ _url(ZodURL, params));
6593
- inst.jwt = (params) => inst.check(/* @__PURE__ */ _jwt(ZodJWT, params));
6594
- inst.emoji = (params) => inst.check(/* @__PURE__ */ _emoji(ZodEmoji, params));
6595
- inst.guid = (params) => inst.check(/* @__PURE__ */ _guid(ZodGUID, params));
6596
- inst.uuid = (params) => inst.check(/* @__PURE__ */ _uuid(ZodUUID, params));
6597
- inst.uuidv4 = (params) => inst.check(/* @__PURE__ */ _uuidv4(ZodUUID, params));
6598
- inst.uuidv6 = (params) => inst.check(/* @__PURE__ */ _uuidv6(ZodUUID, params));
6599
- inst.uuidv7 = (params) => inst.check(/* @__PURE__ */ _uuidv7(ZodUUID, params));
6600
- inst.nanoid = (params) => inst.check(/* @__PURE__ */ _nanoid(ZodNanoID, params));
6601
- inst.guid = (params) => inst.check(/* @__PURE__ */ _guid(ZodGUID, params));
6602
- inst.cuid = (params) => inst.check(/* @__PURE__ */ _cuid(ZodCUID, params));
6603
- inst.cuid2 = (params) => inst.check(/* @__PURE__ */ _cuid2(ZodCUID2, params));
6604
- inst.ulid = (params) => inst.check(/* @__PURE__ */ _ulid(ZodULID, params));
6605
- inst.base64 = (params) => inst.check(/* @__PURE__ */ _base64(ZodBase64, params));
6606
- inst.base64url = (params) => inst.check(/* @__PURE__ */ _base64url(ZodBase64URL, params));
6607
- inst.xid = (params) => inst.check(/* @__PURE__ */ _xid(ZodXID, params));
6608
- inst.ksuid = (params) => inst.check(/* @__PURE__ */ _ksuid(ZodKSUID, params));
6609
- inst.ipv4 = (params) => inst.check(/* @__PURE__ */ _ipv4(ZodIPv4, params));
6610
- inst.ipv6 = (params) => inst.check(/* @__PURE__ */ _ipv6(ZodIPv6, params));
6611
- inst.cidrv4 = (params) => inst.check(/* @__PURE__ */ _cidrv4(ZodCIDRv4, params));
6612
- inst.cidrv6 = (params) => inst.check(/* @__PURE__ */ _cidrv6(ZodCIDRv6, params));
6613
- inst.e164 = (params) => inst.check(/* @__PURE__ */ _e164(ZodE164, params));
6614
- inst.datetime = (params) => inst.check(datetime(params));
6615
- inst.date = (params) => inst.check(date(params));
6616
- inst.time = (params) => inst.check(time(params));
6617
- inst.duration = (params) => inst.check(duration(params));
8063
+ }, {
8064
+ email(params) {
8065
+ return this.check(/* @__PURE__ */ _email(ZodEmail, params));
8066
+ },
8067
+ url(params) {
8068
+ return this.check(/* @__PURE__ */ _url(ZodURL, params));
8069
+ },
8070
+ jwt(params) {
8071
+ return this.check(/* @__PURE__ */ _jwt(ZodJWT, params));
8072
+ },
8073
+ emoji(params) {
8074
+ return this.check(/* @__PURE__ */ _emoji(ZodEmoji, params));
8075
+ },
8076
+ guid(params) {
8077
+ return this.check(/* @__PURE__ */ _guid(ZodGUID, params));
8078
+ },
8079
+ uuid(params) {
8080
+ return this.check(/* @__PURE__ */ _uuid(ZodUUID, params));
8081
+ },
8082
+ uuidv4(params) {
8083
+ return this.check(/* @__PURE__ */ _uuidv4(ZodUUID, params));
8084
+ },
8085
+ uuidv6(params) {
8086
+ return this.check(/* @__PURE__ */ _uuidv6(ZodUUID, params));
8087
+ },
8088
+ uuidv7(params) {
8089
+ return this.check(/* @__PURE__ */ _uuidv7(ZodUUID, params));
8090
+ },
8091
+ nanoid(params) {
8092
+ return this.check(/* @__PURE__ */ _nanoid(ZodNanoID, params));
8093
+ },
8094
+ cuid(params) {
8095
+ return this.check(/* @__PURE__ */ _cuid(ZodCUID, params));
8096
+ },
8097
+ cuid2(params) {
8098
+ return this.check(/* @__PURE__ */ _cuid2(ZodCUID2, params));
8099
+ },
8100
+ ulid(params) {
8101
+ return this.check(/* @__PURE__ */ _ulid(ZodULID, params));
8102
+ },
8103
+ base64(params) {
8104
+ return this.check(/* @__PURE__ */ _base64(ZodBase64, params));
8105
+ },
8106
+ base64url(params) {
8107
+ return this.check(/* @__PURE__ */ _base64url(ZodBase64URL, params));
8108
+ },
8109
+ xid(params) {
8110
+ return this.check(/* @__PURE__ */ _xid(ZodXID, params));
8111
+ },
8112
+ ksuid(params) {
8113
+ return this.check(/* @__PURE__ */ _ksuid(ZodKSUID, params));
8114
+ },
8115
+ ipv4(params) {
8116
+ return this.check(/* @__PURE__ */ _ipv4(ZodIPv4, params));
8117
+ },
8118
+ ipv6(params) {
8119
+ return this.check(/* @__PURE__ */ _ipv6(ZodIPv6, params));
8120
+ },
8121
+ cidrv4(params) {
8122
+ return this.check(/* @__PURE__ */ _cidrv4(ZodCIDRv4, params));
8123
+ },
8124
+ cidrv6(params) {
8125
+ return this.check(/* @__PURE__ */ _cidrv6(ZodCIDRv6, params));
8126
+ },
8127
+ e164(params) {
8128
+ return this.check(/* @__PURE__ */ _e164(ZodE164, params));
8129
+ },
8130
+ datetime(params) {
8131
+ return this.check(/* @__PURE__ */ _isoDateTime(ZodISODateTime, params));
8132
+ },
8133
+ date(params) {
8134
+ return this.check(/* @__PURE__ */ _isoDate(ZodISODate, params));
8135
+ },
8136
+ time(params) {
8137
+ return this.check(/* @__PURE__ */ _isoTime(ZodISOTime, params));
8138
+ },
8139
+ duration(params) {
8140
+ return this.check(/* @__PURE__ */ _isoDuration(ZodISODuration, params));
8141
+ }
6618
8142
  });
6619
8143
  function string(params) {
6620
8144
  return /* @__PURE__ */ _string(ZodString, params);
@@ -6623,6 +8147,22 @@ const ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, d
6623
8147
  $ZodStringFormat.init(inst, def);
6624
8148
  _ZodString.init(inst, def);
6625
8149
  });
8150
+ const ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
8151
+ $ZodISODateTime.init(inst, def);
8152
+ ZodStringFormat.init(inst, def);
8153
+ });
8154
+ const ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
8155
+ $ZodISODate.init(inst, def);
8156
+ ZodStringFormat.init(inst, def);
8157
+ });
8158
+ const ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
8159
+ $ZodISOTime.init(inst, def);
8160
+ ZodStringFormat.init(inst, def);
8161
+ });
8162
+ const ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
8163
+ $ZodISODuration.init(inst, def);
8164
+ ZodStringFormat.init(inst, def);
8165
+ });
6626
8166
  const ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
6627
8167
  $ZodEmail.init(inst, def);
6628
8168
  ZodStringFormat.init(inst, def);
@@ -6647,6 +8187,11 @@ const ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
6647
8187
  $ZodNanoID.init(inst, def);
6648
8188
  ZodStringFormat.init(inst, def);
6649
8189
  });
8190
+ /**
8191
+ * @deprecated CUID v1 is deprecated by its authors due to information leakage
8192
+ * (timestamps embedded in the id). Use {@link ZodCUID2} instead.
8193
+ * See https://github.com/paralleldrive/cuid.
8194
+ */
6650
8195
  const ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
6651
8196
  $ZodCUID.init(inst, def);
6652
8197
  ZodStringFormat.init(inst, def);
@@ -6703,28 +8248,68 @@ const ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
6703
8248
  $ZodNumber.init(inst, def);
6704
8249
  ZodType.init(inst, def);
6705
8250
  inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params);
6706
- inst.gt = (value, params) => inst.check(/* @__PURE__ */ _gt(value, params));
6707
- inst.gte = (value, params) => inst.check(/* @__PURE__ */ _gte(value, params));
6708
- inst.min = (value, params) => inst.check(/* @__PURE__ */ _gte(value, params));
6709
- inst.lt = (value, params) => inst.check(/* @__PURE__ */ _lt(value, params));
6710
- inst.lte = (value, params) => inst.check(/* @__PURE__ */ _lte(value, params));
6711
- inst.max = (value, params) => inst.check(/* @__PURE__ */ _lte(value, params));
6712
- inst.int = (params) => inst.check(int(params));
6713
- inst.safe = (params) => inst.check(int(params));
6714
- inst.positive = (params) => inst.check(/* @__PURE__ */ _gt(0, params));
6715
- inst.nonnegative = (params) => inst.check(/* @__PURE__ */ _gte(0, params));
6716
- inst.negative = (params) => inst.check(/* @__PURE__ */ _lt(0, params));
6717
- inst.nonpositive = (params) => inst.check(/* @__PURE__ */ _lte(0, params));
6718
- inst.multipleOf = (value, params) => inst.check(/* @__PURE__ */ _multipleOf(value, params));
6719
- inst.step = (value, params) => inst.check(/* @__PURE__ */ _multipleOf(value, params));
6720
- inst.finite = () => inst;
6721
- const bag = inst._zod.bag;
6722
- inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
6723
- inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
6724
- inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? .5);
6725
8251
  inst.isFinite = true;
6726
- inst.format = bag.format ?? null;
6727
- });
8252
+ }, /* @__PURE__ */ derived({
8253
+ minValue: (inst) => {
8254
+ const { minimum, exclusiveMinimum } = aggregateChecks(inst);
8255
+ return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY);
8256
+ },
8257
+ maxValue: (inst) => {
8258
+ const { maximum, exclusiveMaximum } = aggregateChecks(inst);
8259
+ return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY);
8260
+ },
8261
+ isInt: (inst) => {
8262
+ const { isInt, multipleOf } = aggregateChecks(inst);
8263
+ return !!isInt || !!multipleOf?.some(Number.isSafeInteger);
8264
+ },
8265
+ format: (inst) => aggregateChecks(inst).format ?? null
8266
+ }, {
8267
+ gt(value, params) {
8268
+ return this.check(/* @__PURE__ */ _gt(value, params));
8269
+ },
8270
+ gte(value, params) {
8271
+ return this.check(/* @__PURE__ */ _gte(value, params));
8272
+ },
8273
+ min(value, params) {
8274
+ return this.check(/* @__PURE__ */ _gte(value, params));
8275
+ },
8276
+ lt(value, params) {
8277
+ return this.check(/* @__PURE__ */ _lt(value, params));
8278
+ },
8279
+ lte(value, params) {
8280
+ return this.check(/* @__PURE__ */ _lte(value, params));
8281
+ },
8282
+ max(value, params) {
8283
+ return this.check(/* @__PURE__ */ _lte(value, params));
8284
+ },
8285
+ int(params) {
8286
+ return this.check(int(params));
8287
+ },
8288
+ safe(params) {
8289
+ return this.check(int(params));
8290
+ },
8291
+ positive(params) {
8292
+ return this.check(/* @__PURE__ */ _gt(0, params));
8293
+ },
8294
+ nonnegative(params) {
8295
+ return this.check(/* @__PURE__ */ _gte(0, params));
8296
+ },
8297
+ negative(params) {
8298
+ return this.check(/* @__PURE__ */ _lt(0, params));
8299
+ },
8300
+ nonpositive(params) {
8301
+ return this.check(/* @__PURE__ */ _lte(0, params));
8302
+ },
8303
+ multipleOf(value, params) {
8304
+ return this.check(/* @__PURE__ */ _multipleOf(value, params));
8305
+ },
8306
+ step(value, params) {
8307
+ return this.check(/* @__PURE__ */ _multipleOf(value, params));
8308
+ },
8309
+ finite() {
8310
+ return this;
8311
+ }
8312
+ }));
6728
8313
  function number(params) {
6729
8314
  return /* @__PURE__ */ _number(ZodNumber, params);
6730
8315
  }
@@ -6760,58 +8345,80 @@ function never(params) {
6760
8345
  return /* @__PURE__ */ _never(ZodNever, params);
6761
8346
  }
6762
8347
  const ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
8348
+ _ensureDefaultMemoizer();
6763
8349
  $ZodArray.init(inst, def);
6764
8350
  ZodType.init(inst, def);
6765
8351
  inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params);
6766
8352
  inst.element = def.element;
6767
- inst.min = (minLength, params) => inst.check(/* @__PURE__ */ _minLength(minLength, params));
6768
- inst.nonempty = (params) => inst.check(/* @__PURE__ */ _minLength(1, params));
6769
- inst.max = (maxLength, params) => inst.check(/* @__PURE__ */ _maxLength(maxLength, params));
6770
- inst.length = (len, params) => inst.check(/* @__PURE__ */ _length(len, params));
6771
- inst.unwrap = () => inst.element;
8353
+ }, {
8354
+ min(n, params) {
8355
+ return this.check(/* @__PURE__ */ _minLength(n, params));
8356
+ },
8357
+ nonempty(params) {
8358
+ return this.check(/* @__PURE__ */ _minLength(1, params));
8359
+ },
8360
+ max(n, params) {
8361
+ return this.check(/* @__PURE__ */ _maxLength(n, params));
8362
+ },
8363
+ length(n, params) {
8364
+ return this.check(/* @__PURE__ */ _length(n, params));
8365
+ },
8366
+ unwrap() {
8367
+ return this.element;
8368
+ }
6772
8369
  });
6773
8370
  function array(element, params) {
6774
8371
  return /* @__PURE__ */ _array(ZodArray, element, params);
6775
8372
  }
6776
8373
  const ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
8374
+ _ensureDefaultMemoizer();
6777
8375
  $ZodObjectJIT.init(inst, def);
6778
8376
  ZodType.init(inst, def);
6779
8377
  inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params);
6780
- defineLazy(inst, "shape", () => {
6781
- return def.shape;
6782
- });
6783
- inst.keyof = () => _enum(Object.keys(inst._zod.def.shape));
6784
- inst.catchall = (catchall) => inst.clone({
6785
- ...inst._zod.def,
6786
- catchall
6787
- });
6788
- inst.passthrough = () => inst.clone({
6789
- ...inst._zod.def,
6790
- catchall: unknown()
6791
- });
6792
- inst.loose = () => inst.clone({
6793
- ...inst._zod.def,
6794
- catchall: unknown()
6795
- });
6796
- inst.strict = () => inst.clone({
6797
- ...inst._zod.def,
6798
- catchall: never()
6799
- });
6800
- inst.strip = () => inst.clone({
6801
- ...inst._zod.def,
6802
- catchall: void 0
6803
- });
6804
- inst.extend = (incoming) => {
6805
- return extend(inst, incoming);
6806
- };
6807
- inst.safeExtend = (incoming) => {
6808
- return safeExtend(inst, incoming);
6809
- };
6810
- inst.merge = (other) => merge(inst, other);
6811
- inst.pick = (mask) => pick(inst, mask);
6812
- inst.omit = (mask) => omit(inst, mask);
6813
- inst.partial = (...args) => partial(ZodOptional, inst, args[0]);
6814
- inst.required = (...args) => required(ZodNonOptional, inst, args[0]);
8378
+ installLazyProp(inst, "shape", (self) => self._zod.def.shape, false);
8379
+ }, {
8380
+ keyof() {
8381
+ return _enum(Object.keys(this._zod.def.shape));
8382
+ },
8383
+ catchall(catchall) {
8384
+ return this.clone(mergeDefs(this._zod.def, { catchall }));
8385
+ },
8386
+ passthrough() {
8387
+ return this.clone(mergeDefs(this._zod.def, { catchall: unknown() }));
8388
+ },
8389
+ loose() {
8390
+ return this.clone(mergeDefs(this._zod.def, { catchall: unknown() }));
8391
+ },
8392
+ strict() {
8393
+ return this.clone(mergeDefs(this._zod.def, { catchall: never() }));
8394
+ },
8395
+ strip() {
8396
+ return this.clone(mergeDefs(this._zod.def, { catchall: void 0 }));
8397
+ },
8398
+ extend(incoming) {
8399
+ return extend(this, incoming);
8400
+ },
8401
+ safeExtend(incoming) {
8402
+ return safeExtend(this, incoming);
8403
+ },
8404
+ merge(other) {
8405
+ return merge(this, other);
8406
+ },
8407
+ pick(mask) {
8408
+ return pick(this, mask);
8409
+ },
8410
+ omit(mask) {
8411
+ return omit(this, mask);
8412
+ },
8413
+ partial(...args) {
8414
+ return partial(ZodOptional, this, args[0]);
8415
+ },
8416
+ exactPartial(...args) {
8417
+ return partial(ZodExactOptional, this, args[0], "exactPartial");
8418
+ },
8419
+ required(...args) {
8420
+ return required(ZodNonOptional, this, args[0]);
8421
+ }
6815
8422
  });
6816
8423
  function object(shape, params) {
6817
8424
  return new ZodObject({
@@ -6858,6 +8465,7 @@ function intersection(left, right) {
6858
8465
  });
6859
8466
  }
6860
8467
  const ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
8468
+ _ensureDefaultMemoizer();
6861
8469
  $ZodRecord.init(inst, def);
6862
8470
  ZodType.init(inst, def);
6863
8471
  inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params);
@@ -6865,6 +8473,12 @@ const ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
6865
8473
  inst.valueType = def.valueType;
6866
8474
  });
6867
8475
  function record(keyType, valueType, params) {
8476
+ if (!valueType || !valueType._zod) return new ZodRecord({
8477
+ type: "record",
8478
+ keyType: string(),
8479
+ valueType: keyType,
8480
+ ...normalizeParams(valueType)
8481
+ });
6868
8482
  return new ZodRecord({
6869
8483
  type: "record",
6870
8484
  keyType,
@@ -6877,7 +8491,7 @@ const ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
6877
8491
  ZodType.init(inst, def);
6878
8492
  inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params);
6879
8493
  inst.enum = def.entries;
6880
- inst.options = Object.values(def.entries);
8494
+ inst.options = [...inst._zod.values];
6881
8495
  const keys = new Set(Object.keys(def.entries));
6882
8496
  inst.extract = (values, params) => {
6883
8497
  const newEntries = {};
@@ -6927,6 +8541,7 @@ function literal(value, params) {
6927
8541
  });
6928
8542
  }
6929
8543
  const ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
8544
+ _ensureDefaultMemoizer();
6930
8545
  $ZodTransform.init(inst, def);
6931
8546
  ZodType.init(inst, def);
6932
8547
  inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params);
@@ -6938,7 +8553,7 @@ const ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) =>
6938
8553
  const _issue = issue$1;
6939
8554
  if (_issue.fatal) _issue.continue = false;
6940
8555
  _issue.code ?? (_issue.code = "custom");
6941
- _issue.input ?? (_issue.input = payload.value);
8556
+ if (!("input" in _issue)) _issue.input = payload.value;
6942
8557
  _issue.inst ?? (_issue.inst = inst);
6943
8558
  payload.issues.push(issue(_issue));
6944
8559
  }
@@ -7049,7 +8664,7 @@ function _catch(innerType, catchValue) {
7049
8664
  return new ZodCatch({
7050
8665
  type: "catch",
7051
8666
  innerType,
7052
- catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
8667
+ catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue)
7053
8668
  });
7054
8669
  }
7055
8670
  const ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
@@ -7086,8 +8701,8 @@ const ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
7086
8701
  function refine(fn, _params = {}) {
7087
8702
  return /* @__PURE__ */ _refine(ZodCustom, fn, _params);
7088
8703
  }
7089
- function superRefine(fn) {
7090
- return /* @__PURE__ */ _superRefine(fn);
8704
+ function superRefine(fn, params) {
8705
+ return /* @__PURE__ */ _superRefine(fn, params);
7091
8706
  }
7092
8707
  process.env.TANK_REGISTRY_URL;
7093
8708
  const MANIFEST_FILENAME = "tank.json";
@@ -11932,7 +13547,6 @@ function resolveCurrentBinary() {
11932
13547
  function replaceBinary(tmpBin, currentBinaryPath) {
11933
13548
  if (process.platform !== "win32") {
11934
13549
  fs.renameSync(tmpBin, currentBinaryPath);
11935
- fs.chmodSync(currentBinaryPath, 493);
11936
13550
  return;
11937
13551
  }
11938
13552
  fs.copyFileSync(tmpBin, currentBinaryPath);
@@ -11964,7 +13578,8 @@ async function upgradeCommand(opts) {
11964
13578
  return;
11965
13579
  }
11966
13580
  console.log(chalk.cyan(`Upgrading tank ${VERSION} → ${targetVersion}...`));
11967
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "tank-upgrade-"));
13581
+ const stagingDir = process.platform === "win32" ? os.tmpdir() : path.dirname(currentBinaryPath);
13582
+ const tmpDir = fs.mkdtempSync(path.join(stagingDir, ".tank-upgrade-"));
11968
13583
  try {
11969
13584
  const binaryUrl = `https://github.com/tankpkg/tank/releases/download/v${targetVersion}/${binaryName}`;
11970
13585
  const tmpBin = path.join(tmpDir, binaryName);
@@ -11998,10 +13613,14 @@ async function upgradeCommand(opts) {
11998
13613
  console.log(chalk.green(`✓ Upgraded tank ${VERSION} → ${targetVersion}`));
11999
13614
  console.log(chalk.gray(`Release notes: https://github.com/tankpkg/tank/releases/tag/v${targetVersion}`));
12000
13615
  } finally {
12001
- fs.rmSync(tmpDir, {
12002
- recursive: true,
12003
- force: true
12004
- });
13616
+ try {
13617
+ fs.rmSync(tmpDir, {
13618
+ recursive: true,
13619
+ force: true
13620
+ });
13621
+ } catch (err) {
13622
+ console.error(`Could not remove temporary upgrade files at ${tmpDir}: ${err instanceof Error ? err.message : err}`);
13623
+ }
12005
13624
  }
12006
13625
  }
12007
13626
  //#endregion