From 051e9c1aa8a9ac6199ef48cc328d965398df6c99 Mon Sep 17 00:00:00 2001 From: cdeust Date: Mon, 1 Jun 2026 10:17:05 +0200 Subject: [PATCH] =?UTF-8?q?fix(benchmark):=20stop=20MCP=20startup=20deadlo?= =?UTF-8?q?ck=20=E2=80=94=20drop=20script-only=20runners=20from=20the=20ca?= =?UTF-8?q?libration=20library=20barrel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The calibration barrel (packages/benchmark/calibration/index.ts) re-exported the script-only runners (runCalibration, selectModeFromArgv, runProductionCalibration, runProductionFromCli) alongside its library-safe oracle/stats seams. Those runner modules are script-only — top-level await + FS writes, per the §2.2 layer-contract banner in calibrate-gates-production.ts. @prd-gen/mcp-server imports this barrel (via build-conclude-opts) only for the library-safe oracle dispatch (invokeOracle / OracleUnavailableError). But esbuild, bundling the server, must initialise every statically-reachable module — so the script island's top-level await was awaited at server startup and never settled. The MCP `initialize` handshake never completed because server.connect() was never reached: the plugin's MCP server hung on every launch. Import chain (esbuild metafile): mcp-server/index -> pipeline-tools -> build-conclude-opts -> @prd-gen/benchmark/calibration (barrel) -> calibrate-gates-production (TLA island) Fix: stop the library barrel from re-exporting the script-only runners. They have no barrel consumers — the CLIs and their tests already import them directly from their own modules — so this is non-breaking and simply honours the §2.2 script/library boundary those modules already document. The library-safe oracle/stats seams the server actually needs are unchanged. Verification: - esbuild metafile: script island no longer in the server graph - regenerated bundle (mcp-server/index.js) has zero top-level await - MCP server now answers `initialize` immediately (was: deadlock) - pnpm vitest packages/benchmark packages/mcp-server: 339 passed Co-Authored-By: Claude Opus 4.8 (1M context) --- mcp-server/index.js | 64544 +++++++++++----------- packages/benchmark/calibration/index.ts | 51 +- 2 files changed, 31304 insertions(+), 33291 deletions(-) diff --git a/mcp-server/index.js b/mcp-server/index.js index 7079624..5b99750 100755 --- a/mcp-server/index.js +++ b/mcp-server/index.js @@ -11,9 +11,6 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require if (typeof require !== "undefined") return require.apply(this, arguments); throw Error('Dynamic require of "' + x + '" is not supported'); }); -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; -}; var __commonJS = (cb, mod3) => function __require2() { return mod3 || (0, cb[__getOwnPropNames(cb)[0]])((mod3 = { exports: {} }).exports, mod3), mod3.exports; }; @@ -38,34928 +35,33078 @@ var __toESM = (mod3, isNodeMode, target) => (target = mod3 != null ? __create(__ mod3 )); -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js -var util, objectUtil, ZodParsedType, getParsedType; -var init_util = __esm({ - "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js"() { - (function(util2) { - util2.assertEqual = (_) => { - }; - function assertIs2(_arg) { +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js +var require_code = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + var _CodeOrName = class { + }; + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + var Name = class extends _CodeOrName { + constructor(s) { + super(); + if (!exports.IDENTIFIER.test(s)) + throw new Error("CodeGen: name must be a valid identifier"); + this.str = s; } - util2.assertIs = assertIs2; - function assertNever2(_x) { - throw new Error(); + toString() { + return this.str; } - util2.assertNever = assertNever2; - util2.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util2.getValidEnumValues = (obj) => { - const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util2.objectValues(filtered); - }; - util2.objectValues = (obj) => { - return util2.objectKeys(obj).map(function(e3) { - return obj[e3]; - }); - }; - util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object3) => { - const keys = []; - for (const key in object3) { - if (Object.prototype.hasOwnProperty.call(object3, key)) { - keys.push(key); + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + }; + exports.Name = Name; + var _Code = class extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) + return false; + const item = this._items[0]; + return item === "" || item === '""'; + } + get str() { + var _a; + return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); + } + get names() { + var _a; + return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { + if (c instanceof Name) + names[c.str] = (names[c.str] || 0) + 1; + return names; + }, {}); + } + }; + exports._Code = _Code; + exports.nil = new _Code(""); + function _(strs, ...args) { + const code = [strs[0]]; + let i2 = 0; + while (i2 < args.length) { + addCodeArg(code, args[i2]); + code.push(strs[++i2]); + } + return new _Code(code); + } + exports._ = _; + var plus = new _Code("+"); + function str2(strs, ...args) { + const expr = [safeStringify(strs[0])]; + let i2 = 0; + while (i2 < args.length) { + expr.push(plus); + addCodeArg(expr, args[i2]); + expr.push(plus, safeStringify(strs[++i2])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str2; + function addCodeArg(code, arg2) { + if (arg2 instanceof _Code) + code.push(...arg2._items); + else if (arg2 instanceof Name) + code.push(arg2); + else + code.push(interpolate(arg2)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i2 = 1; + while (i2 < expr.length - 1) { + if (expr[i2] === plus) { + const res = mergeExprItems(expr[i2 - 1], expr[i2 + 1]); + if (res !== void 0) { + expr.splice(i2 - 1, 3, res); + continue; } + expr[i2++] = "+"; } - return keys; - }; - util2.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return void 0; - }; - util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues2(array2, separator = " | ") { - return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); + i2++; } - util2.joinValues = joinValues2; - util2.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; - })(util || (util = {})); - (function(objectUtil2) { - objectUtil2.mergeShapes = (first, second) => { - return { - ...first, - ...second - // second overwrites first - }; - }; - })(objectUtil || (objectUtil = {})); - ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set" - ]); - getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType.undefined; - case "string": - return ZodParsedType.string; - case "number": - return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; - case "boolean": - return ZodParsedType.boolean; - case "function": - return ZodParsedType.function; - case "bigint": - return ZodParsedType.bigint; - case "symbol": - return ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType.array; - } - if (data === null) { - return ZodParsedType.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType.date; - } - return ZodParsedType.object; - default: - return ZodParsedType.unknown; + } + function mergeExprItems(a, b) { + if (b === '""') + return a; + if (a === '""') + return b; + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== '"') + return; + if (typeof b != "string") + return `${a.slice(0, -1)}${b}"`; + if (b[0] === '"') + return a.slice(0, -1) + b.slice(1); + return; } - }; + if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) + return `"${a}${b.slice(1)}`; + return; + } + function strConcat(c1, c2) { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str2`${c1}${c2}`; + } + exports.strConcat = strConcat; + function interpolate(x) { + return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); + } + function stringify2(x) { + return new _Code(safeStringify(x)); + } + exports.stringify = stringify2; + function safeStringify(x) { + return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; + } + exports.getProperty = getProperty; + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) { + return new _Code(`${key}`); + } + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; } }); -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js -var ZodIssueCode, quotelessJson, ZodError; -var init_ZodError = __esm({ - "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js"() { - init_util(); - ZodIssueCode = util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite" - ]); - quotelessJson = (obj) => { - const json2 = JSON.stringify(obj, null, 2); - return json2.replace(/"([^"]+)":/g, "$1:"); +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js +var require_scope = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + var code_1 = require_code(); + var ValueError = class extends Error { + constructor(name315) { + super(`CodeGen: "code" for ${name315} not defined`); + this.value = name315.value; + } + }; + var UsedValueState; + (function(UsedValueState2) { + UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; + UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; + })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var") }; - ZodError = class _ZodError extends Error { - get errors() { - return this.issues; + var Scope = class { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub2) => { - this.issues = [...this.issues, sub2]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(this, actualProto); - } else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); } - format(_mapper) { - const mapper = _mapper || function(issue2) { - return issue2.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error2) => { - for (const issue2 of error2.issues) { - if (issue2.code === "invalid_union") { - issue2.unionErrors.map(processError); - } else if (issue2.code === "invalid_return_type") { - processError(issue2.returnTypeError); - } else if (issue2.code === "invalid_arguments") { - processError(issue2.argumentsError); - } else if (issue2.path.length === 0) { - fieldErrors._errors.push(mapper(issue2)); - } else { - let curr = fieldErrors; - let i2 = 0; - while (i2 < issue2.path.length) { - const el = issue2.path[i2]; - const terminal = i2 === issue2.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); - } - curr = curr[el]; - i2++; - } - } - } - }; - processError(this); - return fieldErrors; + name(prefix) { + return new code_1.Name(this._newName(prefix)); } - static assert(value) { - if (!(value instanceof _ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue2) => issue2.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub2 of this.issues) { - if (sub2.path.length > 0) { - const firstEl = sub2.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub2)); - } else { - formErrors.push(mapper(sub2)); - } + _nameGroup(prefix) { + var _a, _b; + if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { + throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); + return this._names[prefix] = { prefix, index: 0 }; } }; - ZodError.create = (issues) => { - const error2 = new ZodError(issues); - return error2; + exports.Scope = Scope; + var ValueScopeName = class extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; + } }; - } -}); - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js -var errorMap, en_default; -var init_en = __esm({ - "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js"() { - init_ZodError(); - init_util(); - errorMap = (issue2, _ctx) => { - let message; - switch (issue2.code) { - case ZodIssueCode.invalid_type: - if (issue2.received === ZodParsedType.undefined) { - message = "Required"; - } else { - message = `Expected ${issue2.expected}, received ${issue2.received}`; - } - break; - case ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`; - break; - case ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`; - break; - case ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`; - break; - case ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`; - break; - case ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode.invalid_string: - if (typeof issue2.validation === "object") { - if ("includes" in issue2.validation) { - message = `Invalid input: must include "${issue2.validation.includes}"`; - if (typeof issue2.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`; - } - } else if ("startsWith" in issue2.validation) { - message = `Invalid input: must start with "${issue2.validation.startsWith}"`; - } else if ("endsWith" in issue2.validation) { - message = `Invalid input: must end with "${issue2.validation.endsWith}"`; + exports.ValueScopeName = ValueScopeName; + var line = (0, code_1._)`\n`; + var ValueScope = class extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a; + if (value.ref === void 0) + throw new Error("CodeGen: ref must be passed in value"); + const name315 = this.toName(nameOrPrefix); + const { prefix } = name315; + const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) + return _name; + } else { + vs = this._values[prefix] = /* @__PURE__ */ new Map(); + } + vs.set(valueKey, name315); + const s = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s.length; + s[itemIndex] = value.ref; + name315.setValue(value, { property: prefix, itemIndex }); + return name315; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) + return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values = this._values) { + return this._reduceValues(values, (name315) => { + if (name315.scopePath === void 0) + throw new Error(`CodeGen: name "${name315}" has no value`); + return (0, code_1._)`${scopeName}${name315.scopePath}`; + }); + } + scopeCode(values = this._values, usedValues, getCode) { + return this._reduceValues(values, (name315) => { + if (name315.value === void 0) + throw new Error(`CodeGen: name "${name315}" has no value`); + return name315.value.code; + }, usedValues, getCode); + } + _reduceValues(values, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values) { + const vs = values[prefix]; + if (!vs) + continue; + const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + vs.forEach((name315) => { + if (nameSet.has(name315)) + return; + nameSet.set(name315, UsedValueState.Started); + let c = valueCode(name315); + if (c) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._)`${code}${def} ${name315} = ${c};${this.opts._n}`; + } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name315)) { + code = (0, code_1._)`${code}${c}${this.opts._n}`; } else { - util.assertNever(issue2.validation); + throw new ValueError(name315); } - } else if (issue2.validation !== "regex") { - message = `Invalid ${issue2.validation}`; - } else { - message = "Invalid"; - } - break; - case ZodIssueCode.too_small: - if (issue2.type === "array") - message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`; - else if (issue2.type === "string") - message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`; - else if (issue2.type === "number") - message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; - else if (issue2.type === "bigint") - message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; - else if (issue2.type === "date") - message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.too_big: - if (issue2.type === "array") - message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`; - else if (issue2.type === "string") - message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`; - else if (issue2.type === "number") - message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; - else if (issue2.type === "bigint") - message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; - else if (issue2.type === "date") - message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue2.multipleOf}`; - break; - case ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util.assertNever(issue2); + nameSet.set(name315, UsedValueState.Completed); + }); + } + return code; } - return { message }; }; - en_default = errorMap; - } -}); - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js -function setErrorMap(map4) { - overrideErrorMap = map4; -} -function getErrorMap() { - return overrideErrorMap; -} -var overrideErrorMap; -var init_errors = __esm({ - "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js"() { - init_en(); - overrideErrorMap = en_default; + exports.ValueScope = ValueScope; } }); -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js -function addIssueToContext(ctx, issueData) { - const overrideMap = getErrorMap(); - const issue2 = makeIssue({ - issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - // contextual error map is first priority - ctx.schemaErrorMap, - // then schema-bound map if available - overrideMap, - // then global override map - overrideMap === en_default ? void 0 : en_default - // then global default map - ].filter((x) => !!x) - }); - ctx.common.issues.push(issue2); -} -var makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync; -var init_parseUtil = __esm({ - "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js"() { - init_errors(); - init_en(); - makeIssue = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...issueData.path || []]; - const fullIssue = { - ...issueData, - path: fullPath - }; - if (issueData.message !== void 0) { - return { - ...issueData, - path: fullPath, - message: issueData.message - }; +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js +var require_codegen = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + var code_1 = require_code(); + var scope_1 = require_scope(); + var code_2 = require_code(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return code_2._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return code_2.str; + } }); + Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() { + return code_2.strConcat; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return code_2.nil; + } }); + Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() { + return code_2.getProperty; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return code_2.stringify; + } }); + Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() { + return code_2.regexpCode; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return code_2.Name; + } }); + var scope_2 = require_scope(); + Object.defineProperty(exports, "Scope", { enumerable: true, get: function() { + return scope_2.Scope; + } }); + Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() { + return scope_2.ValueScope; + } }); + Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() { + return scope_2.ValueScopeName; + } }); + Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() { + return scope_2.varKinds; + } }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+") + }; + var Node2 = class { + optimizeNodes() { + return this; } - let errorMessage = ""; - const maps = errorMaps.filter((m) => !!m).slice().reverse(); - for (const map4 of maps) { - errorMessage = map4(fullIssue, { data, defaultError: errorMessage }).message; + optimizeNames(_names, _constants) { + return this; } - return { - ...issueData, - path: fullPath, - message: errorMessage - }; }; - EMPTY_PATH = []; - ParseStatus = class _ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; + var Def = class extends Node2 { + constructor(varKind, name315, rhs) { + super(); + this.varKind = varKind; + this.name = name315; + this.rhs = rhs; } - static async mergeObjectAsync(status, pairs2) { - const syncPairs = []; - for (const pair of pairs2) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value - }); - } - return _ParseStatus.mergeObjectSync(status, syncPairs); + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; } - static mergeObjectSync(status, pairs2) { - const finalObject = {}; - for (const pair of pairs2) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID; - if (value.status === "aborted") - return INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; + optimizeNames(names, constants) { + if (!names[this.name.str]) + return; + if (this.rhs) + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; } }; - INVALID = Object.freeze({ - status: "aborted" - }); - DIRTY = (value) => ({ status: "dirty", value }); - OK = (value) => ({ status: "valid", value }); - isAborted = (x) => x.status === "aborted"; - isDirty = (x) => x.status === "dirty"; - isValid = (x) => x.status === "valid"; - isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; - } -}); - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/typeAliases.js -var init_typeAliases = __esm({ - "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/typeAliases.js"() { - } -}); - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js -var errorUtil; -var init_errorUtil = __esm({ - "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js"() { - (function(errorUtil2) { - errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; - })(errorUtil || (errorUtil = {})); - } -}); - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; - if (errorMap2 && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap2) - return { errorMap: errorMap2, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} -function timeRegexSource(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); -} -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP(ip, version4) { - if ((version4 === "v4" || !version4) && ipv4Regex.test(ip)) { - return true; - } - if ((version4 === "v6" || !version4) && ipv6Regex.test(ip)) { - return true; - } - return false; -} -function isValidJWT(jwt, alg) { - if (!jwtRegex.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - if (!header) - return false; - const base642 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); - const decoded = JSON.parse(atob(base642)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } catch { - return false; - } -} -function isValidCidr(ip, version4) { - if ((version4 === "v4" || !version4) && ipv4CidrRegex.test(ip)) { - return true; - } - if ((version4 === "v6" || !version4) && ipv6CidrRegex.test(ip)) { - return true; - } - return false; -} -function floatSafeRemainder(val, step2) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step2.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step2.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} -function deepPartialify(schema2) { - if (schema2 instanceof ZodObject) { - const newShape = {}; - for (const key in schema2.shape) { - const fieldSchema = schema2.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema2._def, - shape: () => newShape - }); - } else if (schema2 instanceof ZodArray) { - return new ZodArray({ - ...schema2._def, - type: deepPartialify(schema2.element) - }); - } else if (schema2 instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema2.unwrap())); - } else if (schema2 instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema2.unwrap())); - } else if (schema2 instanceof ZodTuple) { - return ZodTuple.create(schema2.items.map((item) => deepPartialify(item))); - } else { - return schema2; - } -} -function mergeValues(a, b) { - const aType = getParsedType(a); - const bType = getParsedType(b); - if (a === b) { - return { valid: true, data: a }; - } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util.objectKeys(b); - const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index2 = 0; index2 < a.length; index2++) { - const itemA = a[index2]; - const itemB = b[index2]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { - return { valid: true, data: a }; - } else { - return { valid: false }; - } -} -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params) - }); -} -function cleanParams(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom(check2, _params = {}, fatal) { - if (check2) - return ZodAny.create().superRefine((data, ctx) => { - const r = check2(data); - if (r instanceof Promise) { - return r.then((r2) => { - if (!r2) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); + var Assign = class extends Node2 { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; } - if (!r) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; } - return; - }); - return ZodAny.create(); -} -var ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER; -var init_types = __esm({ - "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js"() { - init_ZodError(); - init_errors(); - init_errorUtil(); - init_parseUtil(); - init_util(); - ParseInputLazyPath = class { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) + return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; + get names() { + const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; + return addExprNames(names, this.rhs); } }; - handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; - } else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error2 = new ZodError(ctx.common.issues); - this._error = error2; - return this._error; - } - }; + var AssignOp = class extends Assign { + constructor(lhs, op, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op; } - }; - ZodType = class { - get description() { - return this._def.description; - } - _getType(input) { - return getParsedType(input.data); - } - _getOrReturnCtx(input, ctx) { - return ctx || { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - }; + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; } - _processInputParams(input) { - return { - status: new ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent - } - }; + }; + var Label = class extends Node2 { + constructor(label) { + super(); + this.label = label; + this.names = {}; } - _parseSync(input) { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; + render({ _n }) { + return `${this.label}:` + _n; } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); + }; + var Break = class extends Node2 { + constructor(label) { + super(); + this.label = label; + this.names = {}; } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; + render({ _n }) { + const label = this.label ? ` ${this.label}` : ""; + return `break${label};` + _n; } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); + }; + var Throw = class extends Node2 { + constructor(error2) { + super(); + this.error = error2; } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }; - } catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { - value: result.value - } : { - issues: ctx.common.issues - }); + render({ _n }) { + return `throw ${this.error};` + _n; } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; + get names() { + return this.error.names; } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: getParsedType(data) - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check2, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } else if (typeof message === "function") { - return message(val); - } else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check2(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode.custom, - ...getIssueProperties(val) - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } else { - return true; - } - }); + }; + var AnyCode = class extends Node2 { + constructor(code) { + super(); + this.code = code; } - refinement(check2, refinementData) { - return this._refinement((val, ctx) => { - if (!check2(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } else { - return true; - } - }); + render({ _n }) { + return `${this.code};` + _n; } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement } - }); + optimizeNodes() { + return `${this.code}` ? this : void 0; } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data) - }; + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; } - optional() { - return ZodOptional.create(this, this._def); + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; } - nullable() { - return ZodNullable.create(this, this._def); + }; + var ParentNode = class extends Node2 { + constructor(nodes = []) { + super(); + this.nodes = nodes; } - nullish() { - return this.nullable().optional(); + render(opts) { + return this.nodes.reduce((code, n) => code + n.render(opts), ""); } - array() { - return ZodArray.create(this); + optimizeNodes() { + const { nodes } = this; + let i2 = nodes.length; + while (i2--) { + const n = nodes[i2].optimizeNodes(); + if (Array.isArray(n)) + nodes.splice(i2, 1, ...n); + else if (n) + nodes[i2] = n; + else + nodes.splice(i2, 1); + } + return nodes.length > 0 ? this : void 0; } - promise() { - return ZodPromise.create(this, this._def); + optimizeNames(names, constants) { + const { nodes } = this; + let i2 = nodes.length; + while (i2--) { + const n = nodes[i2]; + if (n.optimizeNames(names, constants)) + continue; + subtractNames(names, n.names); + nodes.splice(i2, 1); + } + return nodes.length > 0 ? this : void 0; } - or(option) { - return ZodUnion.create([this, option], this._def); + get names() { + return this.nodes.reduce((names, n) => addNames(names, n.names), {}); } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); + }; + var BlockNode2 = class extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; } - transform(transform2) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform: transform2 } - }); + }; + var Root = class extends ParentNode { + }; + var Else = class extends BlockNode2 { + }; + Else.kind = "else"; + var If = class _If extends BlockNode2 { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault - }); + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) + code += "else " + this.else.render(opts); + return code; } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def) - }); + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) + return this.nodes; + let e3 = this.else; + if (e3) { + const ns = e3.optimizeNodes(); + e3 = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e3) { + if (cond === false) + return e3 instanceof _If ? e3 : e3.nodes; + if (this.nodes.length) + return this; + return new _If(not2(cond), e3 instanceof _If ? [e3] : e3.nodes); + } + if (cond === false || !this.nodes.length) + return void 0; + return this; } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch - }); + optimizeNames(names, constants) { + var _a; + this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) + return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description - }); + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) + addNames(names, this.else.names); + return names; } - pipe(target) { - return ZodPipeline.create(this, target); + }; + If.kind = "if"; + var For = class extends BlockNode2 { + }; + For.kind = "for"; + var ForLoop = class extends For { + constructor(iteration) { + super(); + this.iteration = iteration; } - readonly() { - return ZodReadonly.create(this); + render(opts) { + return `for(${this.iteration})` + super.render(opts); } - isOptional() { - return this.safeParse(void 0).success; + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; } - isNullable() { - return this.safeParse(null).success; + get names() { + return addNames(super.names, this.iteration.names); } }; - cuidRegex = /^c[^\s-]{8,}$/i; - cuid2Regex = /^[0-9a-z]+$/; - ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; - uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; - nanoidRegex = /^[a-z0-9_-]{21}$/i; - jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; - durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; - emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; - _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; - ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; - ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; - ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; - ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; - base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; - base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; - dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; - dateRegex = new RegExp(`^${dateRegexSource}$`); - ZodString = class _ZodString2 extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.string) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx2.parsedType - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - if (input.data.length < check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check2.value, - type: "string", - inclusive: true, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "max") { - if (input.data.length > check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check2.value, - type: "string", - inclusive: true, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "length") { - const tooBig = input.data.length > check2.value; - const tooSmall = input.data.length < check2.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check2.value, - type: "string", - inclusive: true, - exact: true, - message: check2.message - }); - } else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check2.value, - type: "string", - inclusive: true, - exact: true, - message: check2.message - }); - } - status.dirty(); - } - } else if (check2.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "nanoid", - code: ZodIssueCode.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "url") { - try { - new URL(input.data); - } catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "regex") { - check2.regex.lastIndex = 0; - const testResult = check2.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "trim") { - input.data = input.data.trim(); - } else if (check2.kind === "includes") { - if (!input.data.includes(check2.value, check2.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { includes: check2.value, position: check2.position }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } else if (check2.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } else if (check2.kind === "startsWith") { - if (!input.data.startsWith(check2.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { startsWith: check2.value }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "endsWith") { - if (!input.data.endsWith(check2.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { endsWith: check2.value }, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "datetime") { - const regex = datetimeRegex(check2); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "datetime", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "date", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "time") { - const regex = timeRegex(check2); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "time", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "duration", - code: ZodIssueCode.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "ip") { - if (!isValidIP(input.data, check2.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "jwt") { - if (!isValidJWT(input.data, check2.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "jwt", - code: ZodIssueCode.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "cidr") { - if (!isValidCidr(input.data, check2.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cidr", - code: ZodIssueCode.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64", - code: ZodIssueCode.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64url", - code: ZodIssueCode.invalid_string, - message: check2.message - }); - status.dirty(); - } - } else { - util.assertNever(check2); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode.invalid_string, - ...errorUtil.errToObj(message) - }); - } - _addCheck(check2) { - return new _ZodString2({ - ...this._def, - checks: [...this._def.checks, check2] - }); + var ForRange = class extends For { + constructor(varKind, name315, from, to2) { + super(); + this.varKind = varKind; + this.name = name315; + this.from = from; + this.to = to2; } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name: name315, from, to: to2 } = this; + return `for(${varKind} ${name315}=${from}; ${name315}<${to2}; ${name315}++)` + super.render(opts); } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + get names() { + const names = addExprNames(super.names, this.from); + return addExprNames(names, this.to); } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + }; + var ForIter = class extends For { + constructor(loop, varKind, name315, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name315; + this.iterable = iterable; } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + get names() { + return addNames(super.names, this.iterable.names); } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); - } - base64url(message) { - return this._addCheck({ - kind: "base64url", - ...errorUtil.errToObj(message) - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil.errToObj(options?.message) - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil.errToObj(options?.message) - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex, - ...errorUtil.errToObj(message) - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value, - position: options?.position, - ...errorUtil.errToObj(options?.message) - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value, - ...errorUtil.errToObj(message) - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value, - ...errorUtil.errToObj(message) - }); + }; + var Func = class extends BlockNode2 { + constructor(name315, args, async) { + super(); + this.name = name315; + this.args = args; + this.async = async; } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message) - }); + render(opts) { + const _async = this.async ? "async " : ""; + return `${_async}function ${this.name}(${this.args})` + super.render(opts); } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message) - }); + }; + Func.kind = "func"; + var Return = class extends ParentNode { + render(opts) { + return "return " + super.render(opts); } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message) - }); + }; + Return.kind = "return"; + var Try = class extends BlockNode2 { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) + code += this.catch.render(opts); + if (this.finally) + code += this.finally.render(opts); + return code; } - /** - * Equivalent to `.min(1)` - */ - nonempty(message) { - return this.min(1, errorUtil.errToObj(message)); + optimizeNodes() { + var _a, _b; + super.optimizeNodes(); + (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); + return this; } - trim() { - return new _ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }] - }); + optimizeNames(names, constants) { + var _a, _b; + super.optimizeNames(names, constants); + (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); + return this; } - toLowerCase() { - return new _ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }] - }); + get names() { + const names = super.names; + if (this.catch) + addNames(names, this.catch.names); + if (this.finally) + addNames(names, this.finally.names); + return names; } - toUpperCase() { - return new _ZodString2({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }] - }); + }; + var Catch = class extends BlockNode2 { + constructor(error2) { + super(); + this.error = error2; } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); + render(opts) { + return `catch(${this.error})` + super.render(opts); } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); + }; + Catch.kind = "catch"; + var Finally = class extends BlockNode2 { + render(opts) { + return "finally" + super.render(opts); } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); + }; + Finally.kind = "finally"; + var CodeGen = class { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); + toString() { + return this._root.render(this.opts); } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); + // returns unique name in the internal scope + name(prefix) { + return this._scope.name(prefix); } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); + // reserves unique name in the external scope + scopeName(prefix) { + return this._extScope.name(prefix); } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); + // reserves unique name in the external scope and assigns value to it + scopeValue(prefixOrName, value) { + const name315 = this._extScope.value(prefixOrName, value); + const vs = this._values[name315.prefix] || (this._values[name315.prefix] = /* @__PURE__ */ new Set()); + vs.add(name315); + return name315; } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + // return code that assigns values in the external scope to the names that are used internally + // (same names that were returned by gen.scopeName or gen.scopeValue) + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); + scopeCode() { + return this._extScope.scopeCode(this._values); } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + _def(varKind, nameOrPrefix, rhs, constant) { + const name315 = this._scope.toName(nameOrPrefix); + if (rhs !== void 0 && constant) + this._constants[name315.str] = rhs; + this._leafNode(new Def(varKind, name315, rhs)); + return name315; } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); + // `const` declaration (`var` in es5 mode) + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); + // `let` declaration with optional assignment (`var` in es5 mode) + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); + // `var` declaration with optional assignment + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); + // assignment code + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); } - get isBase64url() { - return !!this._def.checks.find((ch) => ch.kind === "base64url"); + // `+=` code + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); } - get minLength() { - let min3 = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min3 === null || ch.value > min3) - min3 = ch.value; - } - } - return min3; + // appends passed SafeExpr to code or executes Block + code(c) { + if (typeof c == "function") + c(); + else if (c !== code_1.nil) + this._leafNode(new AnyCode(c)); + return this; } - get maxLength() { - let max3 = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max3 === null || ch.value < max3) - max3 = ch.value; + // returns code for object literal for the passed argument list of key-value pairs + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) + code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); } } - return max3; + code.push("}"); + return new code_1._Code(code); } - }; - ZodString.create = (params) => { - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); - }; - ZodNumber = class _ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.number) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.number, - received: ctx2.parsedType - }); - return INVALID; - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check2 of this._def.checks) { - if (check2.kind === "int") { - if (!util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "min") { - const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check2.value, - type: "number", - inclusive: check2.inclusive, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "max") { - const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check2.value, - type: "number", - inclusive: check2.inclusive, - exact: false, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check2.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check2.value, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check2.message - }); - status.dirty(); - } - } else { - util.assertNever(check2); - } + // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) { + this.code(thenBody).else().code(elseBody).endIf(); + } else if (thenBody) { + this.code(thenBody).endIf(); + } else if (elseBody) { + throw new Error('CodeGen: "else" body without "then" body'); } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new _ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check2) { - return new _ZodNumber({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message) - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message) - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message) - }); + return this; } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); + // `else if` clause - invalid without `if` or after `else` clauses + elseIf(condition) { + return this._elseNode(new If(condition)); } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message) - }); + // `else` clause - only valid after `if` or `else if` clauses + else() { + return this._elseNode(new Else()); } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message) - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message) - }); + // end `if` statement (needed if gen.if was used only with condition) + endIf() { + return this._endBlockNode(If, Else); } - get minValue() { - let min3 = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min3 === null || ch.value > min3) - min3 = ch.value; - } - } - return min3; + _for(node, forBody) { + this._blockNode(node); + if (forBody) + this.code(forBody).endFor(); + return this; } - get maxValue() { - let max3 = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max3 === null || ch.value < max3) - max3 = ch.value; - } - } - return max3; + // a generic `for` clause (or statement if `forBody` is passed) + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); + // `for` statement for a range of values + forRange(nameOrPrefix, from, to2, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name315 = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name315, from, to2), () => forBody(name315)); } - get isFinite() { - let max3 = null; - let min3 = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } else if (ch.kind === "min") { - if (min3 === null || ch.value > min3) - min3 = ch.value; - } else if (ch.kind === "max") { - if (max3 === null || ch.value < max3) - max3 = ch.value; - } + // `for-of` statement (in es5 mode replace with a normal for loop) + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name315 = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i2) => { + this.var(name315, (0, code_1._)`${arr}[${i2}]`); + forBody(name315); + }); } - return Number.isFinite(min3) && Number.isFinite(max3); + return this._for(new ForIter("of", varKind, name315, iterable), () => forBody(name315)); } - }; - ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); - }; - ZodBigInt = class _ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } catch { - return this._getInvalidInput(input); - } - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.bigint) { - return this._getInvalidInput(input); - } - let ctx = void 0; - const status = new ParseStatus(); - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check2.value, - inclusive: check2.inclusive, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "max") { - const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check2.value, - inclusive: check2.inclusive, - message: check2.message - }); - status.dirty(); - } - } else if (check2.kind === "multipleOf") { - if (input.data % check2.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check2.value, - message: check2.message - }); - status.dirty(); - } - } else { - util.assertNever(check2); - } + // `for-in` statement. + // With option `ownProperties` replaced with a `for-of` loop for object keys + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) { + return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType - }); - return INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new _ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message) - } - ] - }); - } - _addCheck(check2) { - return new _ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check2] - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); + const name315 = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name315, obj), () => forBody(name315)); } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message) - }); + // end `for` loop + endFor() { + return this._endBlockNode(For); } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); + // `label` statement + label(label) { + return this._leafNode(new Label(label)); } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message) - }); + // `break` statement + break(label) { + return this._leafNode(new Break(label)); } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message) - }); + // `return` statement + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) + throw new Error('CodeGen: "return" should have one node'); + return this._endBlockNode(Return); } - get minValue() { - let min3 = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min3 === null || ch.value > min3) - min3 = ch.value; - } + // `try` statement + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) + throw new Error('CodeGen: "try" without "catch" and "finally"'); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error2 = this.name("e"); + this._currNode = node.catch = new Catch(error2); + catchCode(error2); } - return min3; - } - get maxValue() { - let max3 = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max3 === null || ch.value < max3) - max3 = ch.value; - } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); } - return max3; + return this._endBlockNode(Catch, Finally); } - }; - ZodBigInt.create = (params) => { - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams(params) - }); - }; - ZodBoolean = class extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); + // `throw` statement + throw(error2) { + return this._leafNode(new Throw(error2)); } - }; - ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams(params) - }); - }; - ZodDate = class _ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.date) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, - received: ctx2.parsedType - }); - return INVALID; - } - if (Number.isNaN(input.data.getTime())) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_date - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = void 0; - for (const check2 of this._def.checks) { - if (check2.kind === "min") { - if (input.data.getTime() < check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check2.message, - inclusive: true, - exact: false, - minimum: check2.value, - type: "date" - }); - status.dirty(); - } - } else if (check2.kind === "max") { - if (input.data.getTime() > check2.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check2.message, - inclusive: true, - exact: false, - maximum: check2.value, - type: "date" - }); - status.dirty(); - } - } else { - util.assertNever(check2); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()) - }; + // start self-balancing block + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) + this.code(body).endBlock(nodeCount); + return this; } - _addCheck(check2) { - return new _ZodDate({ - ...this._def, - checks: [...this._def.checks, check2] - }); + // end the current self-balancing block + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === void 0) + throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { + throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + } + this._nodes.length = len; + return this; } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message) - }); + // `function` heading (or definition if funcBody is passed) + func(name315, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name315, args, async)); + if (funcBody) + this.code(funcBody).endFunc(); + return this; } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message) - }); + // end function definition + endFunc() { + return this._endBlockNode(Func); } - get minDate() { - let min3 = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min3 === null || ch.value > min3) - min3 = ch.value; - } + optimize(n = 1) { + while (n-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); } - return min3 != null ? new Date(min3) : null; } - get maxDate() { - let max3 = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max3 === null || ch.value < max3) - max3 = ch.value; - } - } - return max3 != null ? new Date(max3) : null; + _leafNode(node) { + this._currNode.nodes.push(node); + return this; } - }; - ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params) - }); - }; - ZodSymbol = class extends ZodType { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); } - }; - ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params) - }); - }; - ZodUndefined = class extends ZodType { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType - }); - return INVALID; + _endBlockNode(N1, N2) { + const n = this._currNode; + if (n instanceof N1 || N2 && n instanceof N2) { + this._nodes.pop(); + return this; } - return OK(input.data); + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } - }; - ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params) - }); - }; - ZodNull = class extends ZodType { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType - }); - return INVALID; + _elseNode(node) { + const n = this._currNode; + if (!(n instanceof If)) { + throw new Error('CodeGen: "else" without "if"'); } - return OK(input.data); - } - }; - ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params) - }); - }; - ZodAny = class extends ZodType { - constructor() { - super(...arguments); - this._any = true; + this._currNode = n.else = node; + return this; } - _parse(input) { - return OK(input.data); + get _root() { + return this._nodes[0]; } - }; - ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params) - }); - }; - ZodUnknown = class extends ZodType { - constructor() { - super(...arguments); - this._unknown = true; + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; } - _parse(input) { - return OK(input.data); + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; } }; - ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params) - }); - }; - ZodNever = class extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType - }); - return INVALID; + exports.CodeGen = CodeGen; + function addNames(names, from) { + for (const n in from) + names[n] = (names[n] || 0) + (from[n] || 0); + return names; + } + function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + } + function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) + return replaceName(expr); + if (!canOptimize(expr)) + return expr; + return new code_1._Code(expr._items.reduce((items, c) => { + if (c instanceof code_1.Name) + c = replaceName(c); + if (c instanceof code_1._Code) + items.push(...c._items); + else + items.push(c); + return items; + }, [])); + function replaceName(n) { + const c = constants[n.str]; + if (c === void 0 || names[n.str] !== 1) + return n; + delete names[n.str]; + return c; } - }; - ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params) - }); - }; - ZodVoid = class extends ZodType { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType - }); - return INVALID; - } - return OK(input.data); - } - }; - ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params) - }); - }; - ZodArray = class _ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: tooSmall ? def.exactLength.value : void 0, - maximum: tooBig ? def.exactLength.value : void 0, - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i2) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i2)); - })).then((result2) => { - return ParseStatus.mergeArray(status, result2); - }); - } - const result = [...ctx.data].map((item, i2) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i2)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new _ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) } - }); - } - max(maxLength, message) { - return new _ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) } - }); - } - length(len, message) { - return new _ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) } - }); - } - nonempty(message) { - return this.min(1, message); - } - }; - ZodArray.create = (schema2, params) => { - return new ZodArray({ - type: schema2, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params) - }); - }; - ZodObject = class _ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - this.nonstrict = this.passthrough; - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.object) { - const ctx2 = this._getOrReturnCtx(input); - addIssueToContext(ctx2, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx2.parsedType - }); - return INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs2 = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs2.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs2.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] } - }); - } - } else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys - }); - status.dirty(); - } - } else if (unknownKeys === "strip") { - } else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } else { - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs2.push({ - key: { status: "valid", value: key }, - value: catchall._parse( - new ParseInputLazyPath(ctx, value, ctx.path, key) - //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data - }); - } - } - if (ctx.common.async) { - return Promise.resolve().then(async () => { - const syncPairs = []; - for (const pair of pairs2) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet - }); - } - return syncPairs; - }).then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } else { - return ParseStatus.mergeObjectSync(status, pairs2); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil.errToObj; - return new _ZodObject({ - ...this._def, - unknownKeys: "strict", - ...message !== void 0 ? { - errorMap: (issue2, ctx) => { - const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError; - if (issue2.code === "unrecognized_keys") - return { - message: errorUtil.errToObj(message).message ?? defaultError - }; - return { - message: defaultError - }; - } - } : {} - }); - } - strip() { - return new _ZodObject({ - ...this._def, - unknownKeys: "strip" - }); - } - passthrough() { - return new _ZodObject({ - ...this._def, - unknownKeys: "passthrough" - }); - } - // const AugmentFactory = - // (def: Def) => - // ( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, Augmentation>, - // Def["unknownKeys"], - // Def["catchall"] - // > => { - // return new ZodObject({ - // ...def, - // shape: () => ({ - // ...def.shape(), - // ...augmentation, - // }), - // }) as any; - // }; - extend(augmentation) { - return new _ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation - }) - }); - } - /** - * Prior to zod@1.0.12 there was a bug in the - * inferred type of merged objects. Please - * upgrade if you are experiencing issues. - */ - merge(merging) { - const merged = new _ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape() - }), - typeName: ZodFirstPartyTypeKind.ZodObject - }); - return merged; - } - // merge< - // Incoming extends AnyZodObject, - // Augmentation extends Incoming["shape"], - // NewOutput extends { - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }, - // NewInput extends { - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // } - // >( - // merging: Incoming - // ): ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"], - // NewOutput, - // NewInput - // > { - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - setKey(key, schema2) { - return this.augment({ [key]: schema2 }); - } - // merge( - // merging: Incoming - // ): //ZodObject = (merging) => { - // ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - catchall(index2) { - return new _ZodObject({ - ...this._def, - catchall: index2 - }); + function canOptimize(e3) { + return e3 instanceof code_1._Code && e3._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); } - pick(mask) { - const shape = {}; - for (const key of util.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new _ZodObject({ - ...this._def, - shape: () => shape - }); + } + function subtractNames(names, from) { + for (const n in from) + names[n] = (names[n] || 0) - (from[n] || 0); + } + function not2(x) { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; + } + exports.not = not2; + var andCode = mappend(exports.operators.AND); + function and2(...args) { + return args.reduce(andCode); + } + exports.and = and2; + var orCode = mappend(exports.operators.OR); + function or2(...args) { + return args.reduce(orCode); + } + exports.or = or2; + function mappend(op) { + return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; + } + function par(x) { + return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; + } + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js +var require_util = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + var codegen_1 = require_codegen(); + var code_1 = require_code(); + function toHash(arr) { + const hash = {}; + for (const item of arr) + hash[item] = true; + return hash; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema2) { + if (typeof schema2 == "boolean") + return schema2; + if (Object.keys(schema2).length === 0) + return true; + checkUnknownRules(it, schema2); + return !schemaHasRules(schema2, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema2 = it.schema) { + const { opts, self: self2 } = it; + if (!opts.strictSchema) + return; + if (typeof schema2 === "boolean") + return; + const rules = self2.RULES.keywords; + for (const key in schema2) { + if (!rules[key]) + checkStrictMode(it, `unknown keyword: "${key}"`); } - omit(mask) { - const shape = {}; - for (const key of util.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new _ZodObject({ - ...this._def, - shape: () => shape - }); + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema2, rules) { + if (typeof schema2 == "boolean") + return !schema2; + for (const key in schema2) + if (rules[key]) + return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema2, RULES2) { + if (typeof schema2 == "boolean") + return !schema2; + for (const key in schema2) + if (key !== "$ref" && RULES2.all[key]) + return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema2, keyword, $data) { + if (!$data) { + if (typeof schema2 == "number" || typeof schema2 == "boolean") + return schema2; + if (typeof schema2 == "string") + return (0, codegen_1._)`${schema2}`; } - /** - * @deprecated - */ - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } else { - newShape[key] = fieldSchema.optional(); - } - } - return new _ZodObject({ - ...this._def, - shape: () => newShape - }); + return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str2) { + return unescapeJsonPointer(decodeURIComponent(str2)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str2) { + return encodeURIComponent(escapeJsonPointer(str2)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str2) { + if (typeof str2 == "number") + return `${str2}`; + return str2.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str2) { + return str2.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f) { + if (Array.isArray(xs)) { + for (const x of xs) + f(x); + } else { + f(xs); } - required(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) { + return (gen, from, to2, toName) => { + const res = to2 === void 0 ? from : to2 instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to2) : mergeToName(gen, from, to2), to2) : from instanceof codegen_1.Name ? (mergeToName(gen, to2, from), from) : mergeValues3(from, to2); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to2) => gen.if((0, codegen_1._)`${to2} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to2, true), () => gen.assign(to2, (0, codegen_1._)`${to2} || {}`).code((0, codegen_1._)`Object.assign(${to2}, ${from})`)); + }), + mergeToName: (gen, from, to2) => gen.if((0, codegen_1._)`${to2} !== true`, () => { + if (from === true) { + gen.assign(to2, true); } else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; + gen.assign(to2, (0, codegen_1._)`${to2} || {}`); + setEvaluated(gen, to2, from); } - } - return new _ZodObject({ - ...this._def, - shape: () => newShape - }); - } - keyof() { - return createZodEnum(util.objectKeys(this.shape)); - } + }), + mergeValues: (from, to2) => from === true ? true : { ...from, ...to2 }, + resultToName: evaluatedPropsToName + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to2) => gen.if((0, codegen_1._)`${to2} !== true && ${from} !== undefined`, () => gen.assign(to2, (0, codegen_1._)`${from} === true ? true : ${to2} > ${from} ? ${to2} : ${from}`)), + mergeToName: (gen, from, to2) => gen.if((0, codegen_1._)`${to2} !== true`, () => gen.assign(to2, from === true ? true : (0, codegen_1._)`${to2} > ${from} ? ${to2} : ${from}`)), + mergeValues: (from, to2) => from === true ? true : Math.max(from, to2), + resultToName: (gen, items) => gen.var("items", items) + }) }; - ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) + function evaluatedPropsToName(gen, ps) { + if (ps === true) + return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._)`{}`); + if (ps !== void 0) + setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); + } + exports.setEvaluated = setEvaluated; + var snippets = {}; + function useFunc(gen, f) { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) }); + } + exports.useFunc = useFunc; + var Type; + (function(Type2) { + Type2[Type2["Num"] = 0] = "Num"; + Type2[Type2["Str"] = 1] = "Str"; + })(Type || (exports.Type = Type = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + if (dataProp instanceof codegen_1.Name) { + const isNumber2 = dataPropType === Type.Num; + return jsPropertySyntax ? isNumber2 ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber2 ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode2 = it.opts.strictSchema) { + if (!mode2) + return; + msg = `strict mode: ${msg}`; + if (mode2 === true) + throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js +var require_names = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var names = { + // validation function arguments + data: new codegen_1.Name("data"), + // data passed to validation function + // args passed from referencing schema + valCxt: new codegen_1.Name("valCxt"), + // validation/data context - should not be used directly, it is destructured to the names below + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + // root data - same as the data passed to the first/top validation function + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + // used to support recursiveRef and dynamicRef + // function scoped variables + vErrors: new codegen_1.Name("vErrors"), + // null or array of validation errors + errors: new codegen_1.Name("errors"), + // counter of validation errors + this: new codegen_1.Name("this"), + // "globals" + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + // JTD serialize/parse name for JSON string and position + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart") }; - ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); + exports.default = names; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js +var require_errors = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var names_1 = require_names(); + exports.keywordError = { + message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; - ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params) - }); + exports.keyword$DataError = { + message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; - ZodUnion = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }), - ctx: childCtx - }; - })).then(handleResults); - } else { - let dirty = void 0; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - }, - parent: null - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx - }); - if (result.status === "valid") { - return result; - } else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues2) => new ZodError(issues2)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors - }); - return INVALID; - } + function reportError(cxt, error2 = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error2, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { + addError(gen, errObj); + } else { + returnErrors(it, (0, codegen_1._)`[${errObj}]`); } - get options() { - return this._def.options; + } + exports.reportError = reportError; + function reportExtraError(cxt, error2 = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error2, errorPaths); + addError(gen, errObj); + if (!(compositeRule || allErrors)) { + returnErrors(it, names_1.default.vErrors); } - }; - ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params) + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { + if (errsCount === void 0) + throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i2) => { + gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i2}]`); + gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); + gen.assign((0, codegen_1._)`${err}.data`, data); + } }); - }; - getDiscriminator = (type2) => { - if (type2 instanceof ZodLazy) { - return getDiscriminator(type2.schema); - } else if (type2 instanceof ZodEffects) { - return getDiscriminator(type2.innerType()); - } else if (type2 instanceof ZodLiteral) { - return [type2.value]; - } else if (type2 instanceof ZodEnum) { - return type2.options; - } else if (type2 instanceof ZodNativeEnum) { - return util.objectValues(type2.enum); - } else if (type2 instanceof ZodDefault) { - return getDiscriminator(type2._def.innerType); - } else if (type2 instanceof ZodUndefined) { - return [void 0]; - } else if (type2 instanceof ZodNull) { - return [null]; - } else if (type2 instanceof ZodOptional) { - return [void 0, ...getDiscriminator(type2.unwrap())]; - } else if (type2 instanceof ZodNullable) { - return [null, ...getDiscriminator(type2.unwrap())]; - } else if (type2 instanceof ZodBranded) { - return getDiscriminator(type2.unwrap()); - } else if (type2 instanceof ZodReadonly) { - return getDiscriminator(type2.unwrap()); - } else if (type2 instanceof ZodCatch) { - return getDiscriminator(type2._def.innerType); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._)`${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) { + gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); } else { - return []; + gen.assign((0, codegen_1._)`${validateName}.errors`, errs); + gen.return(false); } + } + var E = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + // also used in JTD errors + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema") }; - ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator] - }); - return INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - } + function errorObjectCode(cxt, error2, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) + return (0, codegen_1._)`{}`; + return errorObject(cxt, error2, errorPaths); + } + function errorObject(cxt, error2, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [ + errorInstancePath(it, errorPaths), + errorSchemaPath(cxt, errorPaths) + ]; + extraErrorProps(cxt, error2, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; + if (schemaPath) { + schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create(discriminator, options, params) { - const optionsMap = /* @__PURE__ */ new Map(); - for (const type2 of options) { - const discriminatorValues = getDiscriminator(type2.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type2); - } - } - return new _ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params) - }); + return [E.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); + if (opts.messages) { + keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); } - }; - ZodIntersection = class extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }) - ]).then(([left, right]) => handleParsed(left, right)); - } else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - })); - } - } - }; - ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left, - right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params) - }); - }; - ZodTuple = class _ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType - }); - return INVALID; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - return INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array" - }); - status.dirty(); - } - const items = [...ctx.data].map((item, itemIndex) => { - const schema2 = this._def.items[itemIndex] || this._def.rest; - if (!schema2) - return null; - return schema2._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }).filter((x) => !!x); - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } else { - return ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new _ZodTuple({ - ...this._def, - rest - }); + if (opts.verbose) { + keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); } + if (propertyName) + keyValues.push([E.propertyName, propertyName]); + } + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js +var require_boolSchema = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; + var errors_1 = require_errors(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var boolError = { + message: "boolean schema is false" }; - ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params) - }); - }; - ZodRecord = class _ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; + function topBoolOrEmptySchema(it) { + const { gen, schema: schema2, validateName } = it; + if (schema2 === false) { + falseSchemaError(it, false); + } else if (typeof schema2 == "object" && schema2.$async === true) { + gen.return(names_1.default.data); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, null); + gen.return(true); } - get valueSchema() { - return this._def.valueType; + } + exports.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema: schema2 } = it; + if (schema2 === false) { + gen.var(valid, false); + falseSchemaError(it); + } else { + gen.var(valid, true); } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType - }); - return INVALID; - } - const pairs2 = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs2.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data - }); - } - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs2); - } else { - return ParseStatus.mergeObjectSync(status, pairs2); + } + exports.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it + }; + (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); + } + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js +var require_rules = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; + var jsonTypes = new Set(_jsonTypes); + function isJSONType(x) { + return typeof x == "string" && jsonTypes.has(x); + } + exports.isJSONType = isJSONType; + function getRules() { + const groups = { + number: { type: "number", rules: [] }, + string: { type: "string", rules: [] }, + array: { type: "array", rules: [] }, + object: { type: "object", rules: [] } + }; + return { + types: { ...groups, integer: true, boolean: true, null: true }, + rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], + post: { rules: [] }, + all: {}, + keywords: {} + }; + } + exports.getRules = getRules; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js +var require_applicability = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema: schema2, self: self2 }, type2) { + const group = self2.RULES.types[type2]; + return group && group !== true && shouldUseGroup(schema2, group); + } + exports.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema2, group) { + return group.rules.some((rule) => shouldUseRule(schema2, rule)); + } + exports.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema2, rule) { + var _a; + return schema2[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema2[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js +var require_dataType = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + var rules_1 = require_rules(); + var applicability_1 = require_applicability(); + var errors_1 = require_errors(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var DataType; + (function(DataType2) { + DataType2[DataType2["Correct"] = 0] = "Correct"; + DataType2[DataType2["Wrong"] = 1] = "Wrong"; + })(DataType || (exports.DataType = DataType = {})); + function getSchemaTypes(schema2) { + const types = getJSONTypes(schema2.type); + const hasNull = types.includes("null"); + if (hasNull) { + if (schema2.nullable === false) + throw new Error("type: null contradicts nullable: false"); + } else { + if (!types.length && schema2.nullable !== void 0) { + throw new Error('"nullable" cannot be used without "type"'); } + if (schema2.nullable === true) + types.push("null"); } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType) { - return new _ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third) - }); - } - return new _ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second) + return types; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts) { + const types = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types.every(rules_1.isJSONType)) + return types; + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types, opts.coerceTypes); + const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) + coerceData(it, types, coerceTo); + else + reportTypeError(it); }); } - }; - ZodMap = class extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); + function coerceToTypes(types, coerceTypes) { + return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; + } + function coerceData(it, types, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); + if (opts.coerceTypes === "array") { + gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType - }); - return INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs2 = [...ctx.data.entries()].map(([key, value], index2) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"])) - }; - }); - if (ctx.common.async) { - const finalMap = /* @__PURE__ */ new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs2) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } else { - const finalMap = /* @__PURE__ */ new Map(); - for (const pair of pairs2) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; + gen.if((0, codegen_1._)`${coerced} !== undefined`); + for (const t of coerceTo) { + if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") { + coerceSpecificType(t); } } - }; - ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params) + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); }); - }; - ZodSet = class _ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType - }); - return INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements2) { - const parsedSet = /* @__PURE__ */ new Set(); - for (const element of elements2) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i2) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i2))); - if (ctx.common.async) { - return Promise.all(elements).then((elements2) => finalizeSet(elements2)); - } else { - return finalizeSet(elements); + function coerceSpecificType(t) { + switch (t) { + case "string": + gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); + return; + case "number": + gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "integer": + gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "boolean": + gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": + gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); } } - min(minSize, message) { - return new _ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) } - }); + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": + return (0, codegen_1._)`${data} ${EQ} null`; + case "array": + cond = (0, codegen_1._)`Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: + return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; } - max(maxSize, message) { - return new _ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) } - }); + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); } - size(size2, message) { - return this.min(size2, message).max(size2, message); + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) { + return checkDataType(dataTypes[0], data, strictNums, correct); } - nonempty(message) { - return this.min(1, message); + let cond; + const types = (0, util_1.toHash)(dataTypes); + if (types.array && types.object) { + const notObj = (0, codegen_1._)`typeof ${data} != "object"`; + cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; + delete types.null; + delete types.array; + delete types.object; + } else { + cond = codegen_1.nil; } + if (types.number) + delete types.integer; + for (const t in types) + cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + var typeError = { + message: ({ schema: schema2 }) => `must be ${schema2}`, + params: ({ schema: schema2, schemaValue }) => typeof schema2 == "string" ? (0, codegen_1._)`{type: ${schema2}}` : (0, codegen_1._)`{type: ${schemaValue}}` }; - ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params) - }); - }; - ZodFunction = class _ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType - }); - return INVALID; - } - function makeArgsIssue(args, error2) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_arguments, - argumentsError: error2 - } - }); - } - function makeReturnsIssue(returns, error2) { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_return_type, - returnTypeError: error2 - } - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - const me = this; - return OK(async function(...args) { - const error2 = new ZodError([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e3) => { - error2.addIssue(makeArgsIssue(args, e3)); - throw error2; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e3) => { - error2.addIssue(makeReturnsIssue(result, e3)); - throw error2; - }); - return parsedReturns; - }); - } else { - const me = this; - return OK(function(...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data, schema: schema2 } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema2, "type"); + return { + gen, + keyword: "type", + data, + schema: schema2.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema2, + params: {}, + it + }; + } + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js +var require_defaults = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assignDefaults = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + function assignDefaults(it, ty) { + const { properties: properties2, items } = it.schema; + if (ty === "object" && properties2) { + for (const key in properties2) { + assignDefault(it, key, properties2[key].default); } + } else if (ty === "array" && Array.isArray(items)) { + items.forEach((sch, i2) => assignDefault(it, i2, sch.default)); } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new _ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()) - }); - } - returns(returnType) { - return new _ZodFunction({ - ...this._def, - returns: returnType - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new _ZodFunction({ - args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params) - }); - } - }; - ZodLazy = class extends ZodType { - get schema() { - return this._def.getter(); + } + exports.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === void 0) + return; + const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + let condition = (0, codegen_1._)`${childData} === undefined`; + if (opts.useDefaults === "empty") { + condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; } - }; - ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params) + gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js +var require_code2 = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var names_1 = require_names(); + var util_2 = require_util(); + function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); + cxt.error(); }); - }; - ZodLiteral = class extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } - }; - ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params) + } + exports.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data, it: { opts } }, properties2, missing) { + return (0, codegen_1.or)(...properties2.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); + } + exports.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + exports.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + // eslint-disable-next-line @typescript-eslint/unbound-method + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._)`Object.prototype.hasOwnProperty` }); - }; - ZodEnum = class _ZodEnum extends ZodType { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return _ZodEnum.create(values, { - ...this._def, - ...newDef - }); - } - exclude(values, newDef = this._def) { - return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef - }); - } - }; - ZodEnum.create = createZodEnum; - ZodNativeEnum = class extends ZodType { - _parse(input) { - const nativeEnumValues = util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(util.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues - }); - return INVALID; - } - return OK(input.data); - } - get enum() { - return this._def.values; - } - }; - ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params) + } + exports.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data, property) { + return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; + } + exports.isOwnProperty = isOwnProperty; + function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; + } + exports.propertyInData = propertyInData; + function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; + } + exports.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; + } + exports.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); + } + exports.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData] + ]; + if (it.opts.dynamicRef) + valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; + } + exports.callValidateCode = callValidateCode; + var newRegExp = (0, codegen_1._)`new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` }); - }; - ZodPromise = class extends ZodType { - unwrap() { - return this._def.type; + } + exports.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType - }); - return INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap - }); - })); + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + gen.forRange("i", 0, len, (i2) => { + cxt.subschema({ + keyword, + dataProp: i2, + dataPropType: util_1.Type.Num + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); } - }; - ZodPromise.create = (schema2, params) => { - return new ZodPromise({ - type: schema2, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params) - }); - }; - ZodEffects = class extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg2) => { - addIssueToContext(ctx, arg2); - if (arg2.fatal) { - status.abort(); - } else { - status.dirty(); - } - }, - get path() { - return ctx.path; - } - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed2) => { - if (status.value === "aborted") - return INVALID; - const result = await this._def.schema._parseAsync({ - data: processed2, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } else { - if (status.value === "aborted") - return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (!isValid(base)) - return INVALID; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid(base)) - return INVALID; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result - })); - }); - } + } + exports.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema: schema2, keyword, it } = cxt; + if (!Array.isArray(schema2)) + throw new Error("ajv implementation error"); + const alwaysValid = schema2.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); + if (alwaysValid && !it.opts.unevaluated) + return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema2.forEach((_sch, i2) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i2, + compositeRule: true + }, schValid); + gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); + const merged = cxt.mergeValidEvaluated(schCxt, schValid); + if (!merged) + gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + exports.validateUnion = validateUnion; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js +var require_keyword = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var code_1 = require_code2(); + var errors_1 = require_errors(); + function macroKeywordCode(cxt, def) { + const { gen, keyword, schema: schema2, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema2, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) + it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + exports.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def) { + var _a; + const { gen, keyword, schema: schema2, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validate2 = !$data && def.compile ? def.compile.call(it.self, schema2, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate2); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => cxt.error()); + } else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); } - util.assertNever(effect); } - }; - ZodEffects.create = (schema2, effect, params) => { - return new ZodEffects({ - schema: schema2, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params) - }); - }; - ZodEffects.createWithPreprocess = (preprocess2, schema2, params) => { - return new ZodEffects({ - schema: schema2, - effect: { type: "preprocess", transform: preprocess2 }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params) - }); - }; - ZodOptional = class extends ZodType { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 === ZodParsedType.undefined) { - return OK(void 0); - } - return this._def.innerType._parse(input); + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._)`await `), (e3) => gen.assign(valid, false).if((0, codegen_1._)`${e3} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e3}.errors`), () => gen.throw(e3))); + return ruleErrs; } - unwrap() { - return this._def.innerType; + function validateSync() { + const validateErrs = (0, codegen_1._)`${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; } - }; - ZodOptional.create = (type2, params) => { - return new ZodOptional({ - innerType: type2, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params) - }); - }; - ZodNullable = class extends ZodType { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); + function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !("compile" in def && !$data || def.schema === false); + gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); } - unwrap() { - return this._def.innerType; + function reportErrs(errors) { + var _a2; + gen.if((0, codegen_1.not)((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid), errors); } - }; - ZodNullable.create = (type2, params) => { - return new ZodNullable({ - innerType: type2, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params) - }); - }; - ZodDefault = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx - }); + } + exports.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) + throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === void 0) + throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); + } + function validSchemaType(schema2, schemaType, allowUndefined = false) { + return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema2) : st === "object" ? schema2 && typeof schema2 == "object" && !Array.isArray(schema2) : typeof schema2 == st || allowUndefined && typeof schema2 == "undefined"); + } + exports.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema: schema2, opts, self: self2, errSchemaPath }, def, keyword) { + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { + throw new Error("ajv implementation error"); } - removeDefault() { - return this._def.innerType; + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema2, kwd))) { + throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); } - }; - ZodDefault.create = (type2, params) => { - return new ZodDefault({ - innerType: type2, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams(params) - }); - }; - ZodCatch = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [] - } - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx - } - }); - if (isAsync(result)) { - return result.then((result2) => { - return { - status: "valid", - value: result2.status === "valid" ? result2.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; - }); - } else { - return { - status: "valid", - value: result.status === "valid" ? result.value : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data - }) - }; + if (def.validateSchema) { + const valid = def.validateSchema(schema2[keyword]); + if (!valid) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") + self2.logger.error(msg); + else + throw new Error(msg); } } - removeCatch() { - return this._def.innerType; + } + exports.validateKeywordUsage = validateKeywordUsage; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js +var require_subschema = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + function getSubschema(it, { keyword, schemaProp, schema: schema2, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== void 0 && schema2 !== void 0) { + throw new Error('both "keyword" and "schema" passed, only one allowed'); + } + if (keyword !== void 0) { + const sch = it.schema[keyword]; + return schemaProp === void 0 ? { + schema: sch, + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}` + } : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` + }; } - }; - ZodCatch.create = (type2, params) => { - return new ZodCatch({ - innerType: type2, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params) - }); - }; - ZodNaN = class extends ZodType { - _parse(input) { - const parsedType2 = this._getType(input); - if (parsedType2 !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType - }); - return INVALID; + if (schema2 !== void 0) { + if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { + throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); } - return { status: "valid", value: input.data }; + return { + schema: schema2, + schemaPath, + topSchemaRef, + errSchemaPath + }; } - }; - ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params) - }); - }; - BRAND = /* @__PURE__ */ Symbol("zod_brand"); - ZodBranded = class extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx - }); + throw new Error('either "keyword" or "schema" must be passed'); + } + exports.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== void 0 && dataProp !== void 0) { + throw new Error('both "data" and "dataProp" passed, only one allowed'); } - unwrap() { - return this._def.type; + const { gen } = it; + if (dataProp !== void 0) { + const { errorPath, dataPathArr, opts } = it; + const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); + dataContextProps(nextData); + subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; } - }; - ZodPipeline = class _ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - }; - return handleAsync(); - } else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value - }; - } else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx - }); - } - } + if (data !== void 0) { + const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); + dataContextProps(nextData); + if (propertyName !== void 0) + subschema.propertyName = propertyName; } - static create(a, b) { - return new _ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline - }); + if (dataTypes) + subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = /* @__PURE__ */ new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; } - }; - ZodReadonly = class extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); + } + exports.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== void 0) + subschema.compositeRule = compositeRule; + if (createErrors !== void 0) + subschema.createErrors = createErrors; + if (allErrors !== void 0) + subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; + subschema.jtdMetadata = jtdMetadata; + } + exports.extendSubschemaMode = extendSubschemaMode; + } +}); + +// node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports, module) { + "use strict"; + module.exports = function equal2(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i2, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i2 = length; i2-- !== 0; ) + if (!equal2(a[i2], b[i2])) return false; + return true; + } + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i2 = length; i2-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b, keys[i2])) return false; + for (i2 = length; i2-- !== 0; ) { + var key = keys[i2]; + if (!equal2(a[key], b[key])) return false; + } + return true; } - unwrap() { - return this._def.innerType; + return a !== a && b !== b; + }; + } +}); + +// node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js +var require_json_schema_traverse = __commonJS({ + "node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js"(exports, module) { + "use strict"; + var traverse = module.exports = function(schema2, opts, cb) { + if (typeof opts == "function") { + cb = opts; + opts = {}; } + cb = opts.cb || cb; + var pre = typeof cb == "function" ? cb : cb.pre || function() { + }; + var post = cb.post || function() { + }; + _traverse(opts, pre, post, schema2, "", schema2); }; - ZodReadonly.create = (type2, params) => { - return new ZodReadonly({ - innerType: type2, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params) - }); + traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true }; - late = { - object: ZodObject.lazycreate + traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true }; - (function(ZodFirstPartyTypeKind2) { - ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; - })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); - instanceOfType = (cls, params = { - message: `Input not instance of ${cls.name}` - }) => custom((data) => data instanceof cls, params); - stringType = ZodString.create; - numberType = ZodNumber.create; - nanType = ZodNaN.create; - bigIntType = ZodBigInt.create; - booleanType = ZodBoolean.create; - dateType = ZodDate.create; - symbolType = ZodSymbol.create; - undefinedType = ZodUndefined.create; - nullType = ZodNull.create; - anyType = ZodAny.create; - unknownType = ZodUnknown.create; - neverType = ZodNever.create; - voidType = ZodVoid.create; - arrayType = ZodArray.create; - objectType = ZodObject.create; - strictObjectType = ZodObject.strictCreate; - unionType = ZodUnion.create; - discriminatedUnionType = ZodDiscriminatedUnion.create; - intersectionType = ZodIntersection.create; - tupleType = ZodTuple.create; - recordType = ZodRecord.create; - mapType = ZodMap.create; - setType = ZodSet.create; - functionType = ZodFunction.create; - lazyType = ZodLazy.create; - literalType = ZodLiteral.create; - enumType = ZodEnum.create; - nativeEnumType = ZodNativeEnum.create; - promiseType = ZodPromise.create; - effectsType = ZodEffects.create; - optionalType = ZodOptional.create; - nullableType = ZodNullable.create; - preprocessType = ZodEffects.createWithPreprocess; - pipelineType = ZodPipeline.create; - ostring = () => stringType().optional(); - onumber = () => numberType().optional(); - oboolean = () => booleanType().optional(); - coerce = { - string: ((arg2) => ZodString.create({ ...arg2, coerce: true })), - number: ((arg2) => ZodNumber.create({ ...arg2, coerce: true })), - boolean: ((arg2) => ZodBoolean.create({ - ...arg2, - coerce: true - })), - bigint: ((arg2) => ZodBigInt.create({ ...arg2, coerce: true })), - date: ((arg2) => ZodDate.create({ ...arg2, coerce: true })) + traverse.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true }; - NEVER = INVALID; - } -}); - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js -var external_exports = {}; -__export(external_exports, { - BRAND: () => BRAND, - DIRTY: () => DIRTY, - EMPTY_PATH: () => EMPTY_PATH, - INVALID: () => INVALID, - NEVER: () => NEVER, - OK: () => OK, - ParseStatus: () => ParseStatus, - Schema: () => ZodType, - ZodAny: () => ZodAny, - ZodArray: () => ZodArray, - ZodBigInt: () => ZodBigInt, - ZodBoolean: () => ZodBoolean, - ZodBranded: () => ZodBranded, - ZodCatch: () => ZodCatch, - ZodDate: () => ZodDate, - ZodDefault: () => ZodDefault, - ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, - ZodEffects: () => ZodEffects, - ZodEnum: () => ZodEnum, - ZodError: () => ZodError, - ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, - ZodFunction: () => ZodFunction, - ZodIntersection: () => ZodIntersection, - ZodIssueCode: () => ZodIssueCode, - ZodLazy: () => ZodLazy, - ZodLiteral: () => ZodLiteral, - ZodMap: () => ZodMap, - ZodNaN: () => ZodNaN, - ZodNativeEnum: () => ZodNativeEnum, - ZodNever: () => ZodNever, - ZodNull: () => ZodNull, - ZodNullable: () => ZodNullable, - ZodNumber: () => ZodNumber, - ZodObject: () => ZodObject, - ZodOptional: () => ZodOptional, - ZodParsedType: () => ZodParsedType, - ZodPipeline: () => ZodPipeline, - ZodPromise: () => ZodPromise, - ZodReadonly: () => ZodReadonly, - ZodRecord: () => ZodRecord, - ZodSchema: () => ZodType, - ZodSet: () => ZodSet, - ZodString: () => ZodString, - ZodSymbol: () => ZodSymbol, - ZodTransformer: () => ZodEffects, - ZodTuple: () => ZodTuple, - ZodType: () => ZodType, - ZodUndefined: () => ZodUndefined, - ZodUnion: () => ZodUnion, - ZodUnknown: () => ZodUnknown, - ZodVoid: () => ZodVoid, - addIssueToContext: () => addIssueToContext, - any: () => anyType, - array: () => arrayType, - bigint: () => bigIntType, - boolean: () => booleanType, - coerce: () => coerce, - custom: () => custom, - date: () => dateType, - datetimeRegex: () => datetimeRegex, - defaultErrorMap: () => en_default, - discriminatedUnion: () => discriminatedUnionType, - effect: () => effectsType, - enum: () => enumType, - function: () => functionType, - getErrorMap: () => getErrorMap, - getParsedType: () => getParsedType, - instanceof: () => instanceOfType, - intersection: () => intersectionType, - isAborted: () => isAborted, - isAsync: () => isAsync, - isDirty: () => isDirty, - isValid: () => isValid, - late: () => late, - lazy: () => lazyType, - literal: () => literalType, - makeIssue: () => makeIssue, - map: () => mapType, - nan: () => nanType, - nativeEnum: () => nativeEnumType, - never: () => neverType, - null: () => nullType, - nullable: () => nullableType, - number: () => numberType, - object: () => objectType, - objectUtil: () => objectUtil, - oboolean: () => oboolean, - onumber: () => onumber, - optional: () => optionalType, - ostring: () => ostring, - pipeline: () => pipelineType, - preprocess: () => preprocessType, - promise: () => promiseType, - quotelessJson: () => quotelessJson, - record: () => recordType, - set: () => setType, - setErrorMap: () => setErrorMap, - strictObject: () => strictObjectType, - string: () => stringType, - symbol: () => symbolType, - transformer: () => effectsType, - tuple: () => tupleType, - undefined: () => undefinedType, - union: () => unionType, - unknown: () => unknownType, - util: () => util, - void: () => voidType -}); -var init_external = __esm({ - "node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js"() { - init_errors(); - init_parseUtil(); - init_typeAliases(); - init_util(); - init_types(); - init_ZodError(); + traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true + }; + function _traverse(opts, pre, post, schema2, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema2 && typeof schema2 == "object" && !Array.isArray(schema2)) { + pre(schema2, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema2) { + var sch = schema2[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) { + for (var i2 = 0; i2 < sch.length; i2++) + _traverse(opts, pre, post, sch[i2], jsonPtr + "/" + key + "/" + i2, rootSchema, jsonPtr, key, schema2, i2); + } + } else if (key in traverse.propsKeywords) { + if (sch && typeof sch == "object") { + for (var prop in sch) + _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema2, prop); + } + } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { + _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema2); + } + } + post(schema2, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } + } + function escapeJsonPtr(str2) { + return str2.replace(/~/g, "~0").replace(/\//g, "~1"); + } } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js -var require_code = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js"(exports) { +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js +var require_resolve = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); - exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; - var _CodeOrName = class { - }; - exports._CodeOrName = _CodeOrName; - exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; - var Name = class extends _CodeOrName { - constructor(s) { - super(); - if (!exports.IDENTIFIER.test(s)) - throw new Error("CodeGen: name must be a valid identifier"); - this.str = s; - } - toString() { - return this.str; - } - emptyStr() { + exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; + var util_1 = require_util(); + var equal2 = require_fast_deep_equal(); + var traverse = require_json_schema_traverse(); + var SIMPLE_INLINED = /* @__PURE__ */ new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const" + ]); + function inlineRef(schema2, limit = true) { + if (typeof schema2 == "boolean") + return true; + if (limit === true) + return !hasRef(schema2); + if (!limit) return false; - } - get names() { - return { [this.str]: 1 }; - } - }; - exports.Name = Name; - var _Code = class extends _CodeOrName { - constructor(code) { - super(); - this._items = typeof code === "string" ? [code] : code; - } - toString() { - return this.str; - } - emptyStr() { - if (this._items.length > 1) - return false; - const item = this._items[0]; - return item === "" || item === '""'; - } - get str() { - var _a; - return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); - } - get names() { - var _a; - return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { - if (c instanceof Name) - names[c.str] = (names[c.str] || 0) + 1; - return names; - }, {}); - } - }; - exports._Code = _Code; - exports.nil = new _Code(""); - function _(strs, ...args) { - const code = [strs[0]]; - let i2 = 0; - while (i2 < args.length) { - addCodeArg(code, args[i2]); - code.push(strs[++i2]); - } - return new _Code(code); + return countKeys(schema2) <= limit; } - exports._ = _; - var plus = new _Code("+"); - function str2(strs, ...args) { - const expr = [safeStringify(strs[0])]; - let i2 = 0; - while (i2 < args.length) { - expr.push(plus); - addCodeArg(expr, args[i2]); - expr.push(plus, safeStringify(strs[++i2])); + exports.inlineRef = inlineRef; + var REF_KEYWORDS = /* @__PURE__ */ new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor" + ]); + function hasRef(schema2) { + for (const key in schema2) { + if (REF_KEYWORDS.has(key)) + return true; + const sch = schema2[key]; + if (Array.isArray(sch) && sch.some(hasRef)) + return true; + if (typeof sch == "object" && hasRef(sch)) + return true; } - optimize(expr); - return new _Code(expr); - } - exports.str = str2; - function addCodeArg(code, arg2) { - if (arg2 instanceof _Code) - code.push(...arg2._items); - else if (arg2 instanceof Name) - code.push(arg2); - else - code.push(interpolate(arg2)); + return false; } - exports.addCodeArg = addCodeArg; - function optimize(expr) { - let i2 = 1; - while (i2 < expr.length - 1) { - if (expr[i2] === plus) { - const res = mergeExprItems(expr[i2 - 1], expr[i2 + 1]); - if (res !== void 0) { - expr.splice(i2 - 1, 3, res); - continue; - } - expr[i2++] = "+"; + function countKeys(schema2) { + let count2 = 0; + for (const key in schema2) { + if (key === "$ref") + return Infinity; + count2++; + if (SIMPLE_INLINED.has(key)) + continue; + if (typeof schema2[key] == "object") { + (0, util_1.eachItem)(schema2[key], (sch) => count2 += countKeys(sch)); } - i2++; - } - } - function mergeExprItems(a, b) { - if (b === '""') - return a; - if (a === '""') - return b; - if (typeof a == "string") { - if (b instanceof Name || a[a.length - 1] !== '"') - return; - if (typeof b != "string") - return `${a.slice(0, -1)}${b}"`; - if (b[0] === '"') - return a.slice(0, -1) + b.slice(1); - return; + if (count2 === Infinity) + return Infinity; } - if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) - return `"${a}${b.slice(1)}`; - return; - } - function strConcat(c1, c2) { - return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str2`${c1}${c2}`; + return count2; } - exports.strConcat = strConcat; - function interpolate(x) { - return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); + function getFullPath(resolver, id = "", normalize) { + if (normalize !== false) + id = normalizeId(id); + const p = resolver.parse(id); + return _getFullPath(resolver, p); } - function stringify2(x) { - return new _Code(safeStringify(x)); + exports.getFullPath = getFullPath; + function _getFullPath(resolver, p) { + const serialized = resolver.serialize(p); + return serialized.split("#")[0] + "#"; } - exports.stringify = stringify2; - function safeStringify(x) { - return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + exports._getFullPath = _getFullPath; + var TRAILING_SLASH_HASH = /#\/?$/; + function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; } - exports.safeStringify = safeStringify; - function getProperty(key) { - return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; + exports.normalizeId = normalizeId; + function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); } - exports.getProperty = getProperty; - function getEsmExportName(key) { - if (typeof key == "string" && exports.IDENTIFIER.test(key)) { - return new _Code(`${key}`); + exports.resolveUrl = resolveUrl; + var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; + function getSchemaRefs(schema2, baseId) { + if (typeof schema2 == "boolean") + return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema2[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = /* @__PURE__ */ new Set(); + traverse(schema2, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === void 0) + return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") + innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) + throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") + schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") { + checkAmbiguosRef(sch, schOrRef.schema, ref); + } else if (ref !== normalizeId(fullPath)) { + if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } else { + this.refs[ref] = fullPath; + } + } + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) + throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== void 0 && !equal2(sch1, sch2)) + throw ambiguos(ref); + } + function ambiguos(ref) { + return new Error(`reference "${ref}" resolves to more than one schema`); } - throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); - } - exports.getEsmExportName = getEsmExportName; - function regexpCode(rx) { - return new _Code(rx.toString()); } - exports.regexpCode = regexpCode; + exports.getSchemaRefs = getSchemaRefs; } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js -var require_scope = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js"(exports) { +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js +var require_validate = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); - exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; - var code_1 = require_code(); - var ValueError = class extends Error { - constructor(name315) { - super(`CodeGen: "code" for ${name315} not defined`); - this.value = name315.value; - } - }; - var UsedValueState; - (function(UsedValueState2) { - UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; - UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; - })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); - exports.varKinds = { - const: new code_1.Name("const"), - let: new code_1.Name("let"), - var: new code_1.Name("var") - }; - var Scope = class { - constructor({ prefixes, parent } = {}) { - this._names = {}; - this._prefixes = prefixes; - this._parent = parent; - } - toName(nameOrPrefix) { - return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); - } - name(prefix) { - return new code_1.Name(this._newName(prefix)); - } - _newName(prefix) { - const ng = this._names[prefix] || this._nameGroup(prefix); - return `${prefix}${ng.index++}`; - } - _nameGroup(prefix) { - var _a, _b; - if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { - throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; + var boolSchema_1 = require_boolSchema(); + var dataType_1 = require_dataType(); + var applicability_1 = require_applicability(); + var dataType_2 = require_dataType(); + var defaults_1 = require_defaults(); + var keyword_1 = require_keyword(); + var subschema_1 = require_subschema(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var resolve_1 = require_resolve(); + var util_1 = require_util(); + var errors_1 = require_errors(); + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; } - return this._names[prefix] = { prefix, index: 0 }; - } - }; - exports.Scope = Scope; - var ValueScopeName = class extends code_1.Name { - constructor(prefix, nameStr) { - super(nameStr); - this.prefix = prefix; - } - setValue(value, { property, itemIndex }) { - this.value = value; - this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; - } - }; - exports.ValueScopeName = ValueScopeName; - var line = (0, code_1._)`\n`; - var ValueScope = class extends Scope { - constructor(opts) { - super(opts); - this._values = {}; - this._scope = opts.scope; - this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; - } - get() { - return this._scope; } - name(prefix) { - return new ValueScopeName(prefix, this._newName(prefix)); + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + exports.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema: schema2, schemaEnv, opts }, body) { + if (opts.code.es5) { + gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema2, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + } else { + gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema2, opts)).code(body)); } - value(nameOrPrefix, value) { - var _a; - if (value.ref === void 0) - throw new Error("CodeGen: ref must be passed in value"); - const name315 = this.toName(nameOrPrefix); - const { prefix } = name315; - const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; - let vs = this._values[prefix]; - if (vs) { - const _name = vs.get(valueKey); - if (_name) - return _name; - } else { - vs = this._values[prefix] = /* @__PURE__ */ new Map(); - } - vs.set(valueKey, name315); - const s = this._scope[prefix] || (this._scope[prefix] = []); - const itemIndex = s.length; - s[itemIndex] = value.ref; - name315.setValue(value, { property: prefix, itemIndex }); - return name315; - } - getValue(prefix, keyOrRef) { - const vs = this._values[prefix]; - if (!vs) + } + function destructureValCxt(opts) { + return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); + gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); + }); + } + function topSchemaObjCode(it) { + const { schema: schema2, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema2.$comment) + commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) + resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + return; + } + function resetEvaluated(it) { + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); + } + function funcSourceUrl(schema2, opts) { + const schId = typeof schema2 == "object" && schema2[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; + } + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); return; - return vs.get(keyOrRef); - } - scopeRefs(scopeName, values = this._values) { - return this._reduceValues(values, (name315) => { - if (name315.scopePath === void 0) - throw new Error(`CodeGen: name "${name315}" has no value`); - return (0, code_1._)`${scopeName}${name315.scopePath}`; - }); - } - scopeCode(values = this._values, usedValues, getCode) { - return this._reduceValues(values, (name315) => { - if (name315.value === void 0) - throw new Error(`CodeGen: name "${name315}" has no value`); - return name315.value.code; - }, usedValues, getCode); - } - _reduceValues(values, valueCode, usedValues = {}, getCode) { - let code = code_1.nil; - for (const prefix in values) { - const vs = values[prefix]; - if (!vs) - continue; - const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); - vs.forEach((name315) => { - if (nameSet.has(name315)) - return; - nameSet.set(name315, UsedValueState.Started); - let c = valueCode(name315); - if (c) { - const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; - code = (0, code_1._)`${code}${def} ${name315} = ${c};${this.opts._n}`; - } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name315)) { - code = (0, code_1._)`${code}${c}${this.opts._n}`; - } else { - throw new ValueError(name315); - } - nameSet.set(name315, UsedValueState.Completed); - }); } - return code; - } - }; - exports.ValueScope = ValueScope; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js -var require_codegen = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; - var code_1 = require_code(); - var scope_1 = require_scope(); - var code_2 = require_code(); - Object.defineProperty(exports, "_", { enumerable: true, get: function() { - return code_2._; - } }); - Object.defineProperty(exports, "str", { enumerable: true, get: function() { - return code_2.str; - } }); - Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() { - return code_2.strConcat; - } }); - Object.defineProperty(exports, "nil", { enumerable: true, get: function() { - return code_2.nil; - } }); - Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() { - return code_2.getProperty; - } }); - Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { - return code_2.stringify; - } }); - Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() { - return code_2.regexpCode; - } }); - Object.defineProperty(exports, "Name", { enumerable: true, get: function() { - return code_2.Name; - } }); - var scope_2 = require_scope(); - Object.defineProperty(exports, "Scope", { enumerable: true, get: function() { - return scope_2.Scope; - } }); - Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() { - return scope_2.ValueScope; - } }); - Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() { - return scope_2.ValueScopeName; - } }); - Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() { - return scope_2.varKinds; - } }); - exports.operators = { - GT: new code_1._Code(">"), - GTE: new code_1._Code(">="), - LT: new code_1._Code("<"), - LTE: new code_1._Code("<="), - EQ: new code_1._Code("==="), - NEQ: new code_1._Code("!=="), - NOT: new code_1._Code("!"), - OR: new code_1._Code("||"), - AND: new code_1._Code("&&"), - ADD: new code_1._Code("+") - }; - var Node2 = class { - optimizeNodes() { - return this; - } - optimizeNames(_names, _constants) { - return this; - } - }; - var Def = class extends Node2 { - constructor(varKind, name315, rhs) { - super(); - this.varKind = varKind; - this.name = name315; - this.rhs = rhs; } - render({ es5, _n }) { - const varKind = es5 ? scope_1.varKinds.var : this.varKind; - const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; - return `${varKind} ${this.name}${rhs};` + _n; + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema: schema2, self: self2 }) { + if (typeof schema2 == "boolean") + return !schema2; + for (const key in schema2) + if (self2.RULES.all[key]) + return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema: schema2, gen, opts } = it; + if (opts.$comment && schema2.$comment) + commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) + return schemaKeywords(it, [], false, errsCount); + const types = (0, dataType_1.getSchemaTypes)(it.schema); + const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); + schemaKeywords(it, types, !checkedTypes, errsCount); + } + function checkRefsAndKeywords(it) { + const { schema: schema2, errSchemaPath, opts, self: self2 } = it; + if (schema2.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema2, self2.RULES)) { + self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); } - optimizeNames(names, constants) { - if (!names[this.name.str]) - return; - if (this.rhs) - this.rhs = optimizeExpr(this.rhs, names, constants); - return this; + } + function checkNoDefault(it) { + const { schema: schema2, opts } = it; + if (schema2.default !== void 0 && opts.useDefaults && opts.strictSchema) { + (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); } - get names() { - return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) + it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) + throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema: schema2, errSchemaPath, opts }) { + const msg = schema2.$comment; + if (opts.$comment === true) { + gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); + } else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); } - }; - var Assign = class extends Node2 { - constructor(lhs, rhs, sideEffects) { - super(); - this.lhs = lhs; - this.rhs = rhs; - this.sideEffects = sideEffects; + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) { + gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) + assignEvaluated(it); + gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); } - render({ _n }) { - return `${this.lhs} = ${this.rhs};` + _n; + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) + gen.assign((0, codegen_1._)`${evaluated}.props`, props); + if (items instanceof codegen_1.Name) + gen.assign((0, codegen_1._)`${evaluated}.items`, items); + } + function schemaKeywords(it, types, typeErrors, errsCount) { + const { gen, schema: schema2, data, allErrors, opts, self: self2 } = it; + const { RULES: RULES2 } = self2; + if (schema2.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema2, RULES2))) { + gen.block(() => keywordCode(it, "$ref", RULES2.all.$ref.definition)); + return; } - optimizeNames(names, constants) { - if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) + if (!opts.jtd) + checkStrictTypes(it, types); + gen.block(() => { + for (const group of RULES2.rules) + groupKeywords(group); + groupKeywords(RULES2.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema2, group)) return; - this.rhs = optimizeExpr(this.rhs, names, constants); - return this; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } else { + iterateKeywords(it, group); + } + if (!allErrors) + gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); } - get names() { - const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; - return addExprNames(names, this.rhs); + } + function iterateKeywords(it, group) { + const { gen, schema: schema2, opts: { useDefaults } } = it; + if (useDefaults) + (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) { + if ((0, applicability_1.shouldUseRule)(schema2, rule)) { + keywordCode(it, rule.keyword, rule.definition, group.type); + } + } + }); + } + function checkStrictTypes(it, types) { + if (it.schemaEnv.meta || !it.opts.strictTypes) + return; + checkContextTypes(it, types); + if (!it.opts.allowUnionTypes) + checkMultipleTypes(it, types); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types) { + if (!types.length) + return; + if (!it.dataTypes.length) { + it.dataTypes = types; + return; } - }; - var AssignOp = class extends Assign { - constructor(lhs, op, rhs, sideEffects) { - super(lhs, rhs, sideEffects); - this.op = op; + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) { + strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); + } + }); + narrowSchemaTypes(it, types); + } + function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { + strictTypesError(it, "use allowUnionTypes to allow union type keyword"); } - render({ _n }) { - return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type: type2 } = rule.definition; + if (type2.length && !type2.some((t) => hasApplicableType(ts, t))) { + strictTypesError(it, `missing type "${type2.join(",")}" for keyword "${keyword}"`); + } + } } - }; - var Label = class extends Node2 { - constructor(label) { - super(); - this.label = label; - this.names = {}; + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); + } + function includesType(ts, t) { + return ts.includes(t) || t === "integer" && ts.includes("number"); + } + function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t of it.dataTypes) { + if (includesType(withTypes, t)) + ts.push(t); + else if (withTypes.includes("integer") && t === "number") + ts.push("integer"); } - render({ _n }) { - return `${this.label}:` + _n; + it.dataTypes = ts; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + var KeywordCxt = class { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) { + this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + } else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { + throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + } + if ("code" in def ? def.trackErrors : def.errors !== false) { + this.errsCount = it.gen.const("_errs", names_1.default.errors); + } } - }; - var Break = class extends Node2 { - constructor(label) { - super(); - this.label = label; - this.names = {}; + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); } - render({ _n }) { - const label = this.label ? ` ${this.label}` : ""; - return `break${label};` + _n; + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) + failAction(); + else + this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) + this.gen.endIf(); + } else { + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } } - }; - var Throw = class extends Node2 { - constructor(error2) { - super(); - this.error = error2; + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), void 0, failAction); } - render({ _n }) { - return `throw ${this.error};` + _n; + fail(condition) { + if (condition === void 0) { + this.error(); + if (!this.allErrors) + this.gen.if(false); + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); } - get names() { - return this.error.names; + fail$data(condition) { + if (!this.$data) + return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); } - }; - var AnyCode = class extends Node2 { - constructor(code) { - super(); - this.code = code; + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); } - render({ _n }) { - return `${this.code};` + _n; + _error(append, errorPaths) { + ; + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); } - optimizeNodes() { - return `${this.code}` ? this : void 0; + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); } - optimizeNames(names, constants) { - this.code = optimizeExpr(this.code, names, constants); - return this; + reset() { + if (this.errsCount === void 0) + throw new Error('add "trackErrors" to keyword definition'); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); } - get names() { - return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + ok(cond) { + if (!this.allErrors) + this.gen.if(cond); } - }; - var ParentNode = class extends Node2 { - constructor(nodes = []) { - super(); - this.nodes = nodes; - } - render(opts) { - return this.nodes.reduce((code, n) => code + n.render(opts), ""); + setParams(obj, assign2) { + if (assign2) + Object.assign(this.params, obj); + else + this.params = obj; } - optimizeNodes() { - const { nodes } = this; - let i2 = nodes.length; - while (i2--) { - const n = nodes[i2].optimizeNodes(); - if (Array.isArray(n)) - nodes.splice(i2, 1, ...n); - else if (n) - nodes[i2] = n; - else - nodes.splice(i2, 1); - } - return nodes.length > 0 ? this : void 0; + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); } - optimizeNames(names, constants) { - const { nodes } = this; - let i2 = nodes.length; - while (i2--) { - const n = nodes[i2]; - if (n.optimizeNames(names, constants)) - continue; - subtractNames(names, n.names); - nodes.splice(i2, 1); + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) + return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) + gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) + gen.assign(valid, false); } - return nodes.length > 0 ? this : void 0; - } - get names() { - return this.nodes.reduce((names, n) => addNames(names, n.names), {}); - } - }; - var BlockNode2 = class extends ParentNode { - render(opts) { - return "{" + opts._n + super.render(opts) + "}" + opts._n; - } - }; - var Root = class extends ParentNode { - }; - var Else = class extends BlockNode2 { - }; - Else.kind = "else"; - var If = class _If extends BlockNode2 { - constructor(condition, nodes) { - super(nodes); - this.condition = condition; - } - render(opts) { - let code = `if(${this.condition})` + super.render(opts); - if (this.else) - code += "else " + this.else.render(opts); - return code; + gen.else(); } - optimizeNodes() { - super.optimizeNodes(); - const cond = this.condition; - if (cond === true) - return this.nodes; - let e3 = this.else; - if (e3) { - const ns = e3.optimizeNodes(); - e3 = this.else = Array.isArray(ns) ? new Else(ns) : ns; + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + if (!(schemaCode instanceof codegen_1.Name)) + throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; } - if (e3) { - if (cond === false) - return e3 instanceof _If ? e3 : e3.nodes; - if (this.nodes.length) - return this; - return new _If(not2(cond), e3 instanceof _If ? [e3] : e3.nodes); + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); + return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; } - if (cond === false || !this.nodes.length) - return void 0; - return this; - } - optimizeNames(names, constants) { - var _a; - this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); - if (!(super.optimizeNames(names, constants) || this.else)) - return; - this.condition = optimizeExpr(this.condition, names, constants); - return this; - } - get names() { - const names = super.names; - addExprNames(names, this.condition); - if (this.else) - addNames(names, this.else.names); - return names; } - }; - If.kind = "if"; - var For = class extends BlockNode2 { - }; - For.kind = "for"; - var ForLoop = class extends For { - constructor(iteration) { - super(); - this.iteration = iteration; - } - render(opts) { - return `for(${this.iteration})` + super.render(opts); + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; + subschemaCode(nextContext, valid); + return nextContext; } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) return; - this.iteration = optimizeExpr(this.iteration, names, constants); - return this; + if (it.props !== true && schemaCxt.props !== void 0) { + it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + } + if (it.items !== true && schemaCxt.items !== void 0) { + it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } } - get names() { - return addNames(super.names, this.iteration.names); + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } } }; - var ForRange = class extends For { - constructor(varKind, name315, from, to2) { - super(); - this.varKind = varKind; - this.name = name315; - this.from = from; - this.to = to2; - } - render(opts) { - const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; - const { name: name315, from, to: to2 } = this; - return `for(${varKind} ${name315}=${from}; ${name315}<${to2}; ${name315}++)` + super.render(opts); - } - get names() { - const names = addExprNames(super.names, this.from); - return addExprNames(names, this.to); + exports.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) { + def.code(cxt, ruleType); + } else if (cxt.$data && def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } else if ("macro" in def) { + (0, keyword_1.macroKeywordCode)(cxt, def); + } else if (def.compile || def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); } - }; - var ForIter = class extends For { - constructor(loop, varKind, name315, iterable) { - super(); - this.loop = loop; - this.varKind = varKind; - this.name = name315; - this.iterable = iterable; + } + var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") + return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) + throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) + throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) + throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) + throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) + return data; } - render(opts) { - return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) { + if (segment) { + data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._)`${expr} && ${data}`; + } } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) - return; - this.iterable = optimizeExpr(this.iterable, names, constants); - return this; + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; } - get names() { - return addNames(super.names, this.iterable.names); + } + exports.getData = getData; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js +var require_validation_error = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var ValidationError = class extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; } }; - var Func = class extends BlockNode2 { - constructor(name315, args, async) { - super(); - this.name = name315; - this.args = args; - this.async = async; - } - render(opts) { - const _async = this.async ? "async " : ""; - return `${_async}function ${this.name}(${this.args})` + super.render(opts); + exports.default = ValidationError; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js +var require_ref_error = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var resolve_1 = require_resolve(); + var MissingRefError = class extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); } }; - Func.kind = "func"; - var Return = class extends ParentNode { - render(opts) { - return "return " + super.render(opts); + exports.default = MissingRefError; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js +var require_compile = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; + var codegen_1 = require_codegen(); + var validation_error_1 = require_validation_error(); + var names_1 = require_names(); + var resolve_1 = require_resolve(); + var util_1 = require_util(); + var validate_1 = require_validate(); + var SchemaEnv = class { + constructor(env) { + var _a; + this.refs = {}; + this.dynamicAnchors = {}; + let schema2; + if (typeof env.schema == "object") + schema2 = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema2 === null || schema2 === void 0 ? void 0 : schema2[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema2 === null || schema2 === void 0 ? void 0 : schema2.$async; + this.refs = {}; } }; - Return.kind = "return"; - var Try = class extends BlockNode2 { - render(opts) { - let code = "try" + super.render(opts); - if (this.catch) - code += this.catch.render(opts); - if (this.finally) - code += this.finally.render(opts); - return code; + exports.SchemaEnv = SchemaEnv; + function compileSchema(sch) { + const _sch = getCompilingSchema.call(this, sch); + if (_sch) + return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); + let _ValidationError; + if (sch.$async) { + _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` + }); } - optimizeNodes() { - var _a, _b; - super.optimizeNodes(); - (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes(); - (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); - return this; + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + // TODO can its length be used as dataLevel if nil is removed? + dataLevel: 0, + dataTypes: [], + definedProperties: /* @__PURE__ */ new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._)`""`, + opts: this.opts, + self: this + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + if (this.opts.code.process) + sourceCode = this.opts.code.process(sourceCode, sch); + const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); + const validate2 = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate2 }); + validate2.errors = null; + validate2.schema = sch.schema; + validate2.schemaEnv = sch; + if (sch.$async) + validate2.$async = true; + if (this.opts.code.source === true) { + validate2.source = { validateName, validateCode, scopeValues: gen._values }; + } + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate2.evaluated = { + props: props instanceof codegen_1.Name ? void 0 : props, + items: items instanceof codegen_1.Name ? void 0 : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name + }; + if (validate2.source) + validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated); + } + sch.validate = validate2; + return sch; + } catch (e3) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) + this.logger.error("Error compiling schema, function code:", sourceCode); + throw e3; + } finally { + this._compilations.delete(sch); } - optimizeNames(names, constants) { - var _a, _b; - super.optimizeNames(names, constants); - (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); - (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); - return this; + } + exports.compileSchema = compileSchema; + function resolveRef(root, baseId, ref) { + var _a; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) + return schOrFunc; + let _sch = resolve2.call(this, root, ref); + if (_sch === void 0) { + const schema2 = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; + const { schemaId } = this.opts; + if (schema2) + _sch = new SchemaEnv({ schema: schema2, schemaId, root, baseId }); } - get names() { - const names = super.names; - if (this.catch) - addNames(names, this.catch.names); - if (this.finally) - addNames(names, this.finally.names); - return names; + if (_sch === void 0) + return; + return root.refs[ref] = inlineOrCompile.call(this, _sch); + } + exports.resolveRef = resolveRef; + function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) + return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); + } + function getCompilingSchema(schEnv) { + for (const sch of this._compilations) { + if (sameSchemaEnv(sch, schEnv)) + return sch; } - }; - var Catch = class extends BlockNode2 { - constructor(error2) { - super(); - this.error = error2; + } + exports.getCompilingSchema = getCompilingSchema; + function sameSchemaEnv(s1, s2) { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; + } + function resolve2(root, ref) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") + ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); + } + function resolveSchema(root, ref) { + const p = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); + if (Object.keys(root.schema).length > 0 && refPath === baseId) { + return getJsonPointer.call(this, p, root); } - render(opts) { - return `catch(${this.error})` + super.render(opts); + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") + return; + return getJsonPointer.call(this, p, sch); } - }; - Catch.kind = "catch"; - var Finally = class extends BlockNode2 { - render(opts) { - return "finally" + super.render(opts); + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") + return; + if (!schOrRef.validate) + compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema: schema2 } = schOrRef; + const { schemaId } = this.opts; + const schId = schema2[schemaId]; + if (schId) + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ schema: schema2, schemaId, root, baseId }); } + return getJsonPointer.call(this, p, schOrRef); + } + exports.resolveSchema = resolveSchema; + var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema: schema2, root }) { + var _a; + if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") + return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema2 === "boolean") + return; + const partSchema = schema2[(0, util_1.unescapeFragment)(part)]; + if (partSchema === void 0) + return; + schema2 = partSchema; + const schId = typeof schema2 === "object" && schema2[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + } + let env; + if (typeof schema2 != "boolean" && schema2.$ref && !(0, util_1.schemaHasRulesButRef)(schema2, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema2.$ref); + env = resolveSchema.call(this, root, $ref); + } + const { schemaId } = this.opts; + env = env || new SchemaEnv({ schema: schema2, schemaId, root, baseId }); + if (env.schema !== env.root.schema) + return env; + return void 0; + } + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json +var require_data = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json"(exports, module) { + module.exports = { + $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", + type: "object", + required: ["$data"], + properties: { + $data: { + type: "string", + anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] + } + }, + additionalProperties: false }; - Finally.kind = "finally"; - var CodeGen = class { - constructor(extScope, opts = {}) { - this._values = {}; - this._blockStarts = []; - this._constants = {}; - this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; - this._extScope = extScope; - this._scope = new scope_1.Scope({ parent: extScope }); - this._nodes = [new Root()]; + } +}); + +// node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js +var require_utils = __commonJS({ + "node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js"(exports, module) { + "use strict"; + var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); + var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); + function stringArrayToHexStripped(input) { + let acc = ""; + let code = 0; + let i2 = 0; + for (i2 = 0; i2 < input.length; i2++) { + code = input[i2].charCodeAt(0); + if (code === 48) { + continue; + } + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { + return ""; + } + acc += input[i2]; + break; } - toString() { - return this._root.render(this.opts); + for (i2 += 1; i2 < input.length; i2++) { + code = input[i2].charCodeAt(0); + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { + return ""; + } + acc += input[i2]; } - // returns unique name in the internal scope - name(prefix) { - return this._scope.name(prefix); + return acc; + } + var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); + function consumeIsZone(buffer) { + buffer.length = 0; + return true; + } + function consumeHextets(buffer, address, output) { + if (buffer.length) { + const hex2 = stringArrayToHexStripped(buffer); + if (hex2 !== "") { + address.push(hex2); + } else { + output.error = true; + return false; + } + buffer.length = 0; } - // reserves unique name in the external scope - scopeName(prefix) { - return this._extScope.name(prefix); + return true; + } + function getIPV6(input) { + let tokenCount = 0; + const output = { error: false, address: "", zone: "" }; + const address = []; + const buffer = []; + let endipv6Encountered = false; + let endIpv6 = false; + let consume = consumeHextets; + for (let i2 = 0; i2 < input.length; i2++) { + const cursor = input[i2]; + if (cursor === "[" || cursor === "]") { + continue; + } + if (cursor === ":") { + if (endipv6Encountered === true) { + endIpv6 = true; + } + if (!consume(buffer, address, output)) { + break; + } + if (++tokenCount > 7) { + output.error = true; + break; + } + if (i2 > 0 && input[i2 - 1] === ":") { + endipv6Encountered = true; + } + address.push(":"); + continue; + } else if (cursor === "%") { + if (!consume(buffer, address, output)) { + break; + } + consume = consumeIsZone; + } else { + buffer.push(cursor); + continue; + } } - // reserves unique name in the external scope and assigns value to it - scopeValue(prefixOrName, value) { - const name315 = this._extScope.value(prefixOrName, value); - const vs = this._values[name315.prefix] || (this._values[name315.prefix] = /* @__PURE__ */ new Set()); - vs.add(name315); - return name315; + if (buffer.length) { + if (consume === consumeIsZone) { + output.zone = buffer.join(""); + } else if (endIpv6) { + address.push(buffer.join("")); + } else { + address.push(stringArrayToHexStripped(buffer)); + } } - getScopeValue(prefix, keyOrRef) { - return this._extScope.getValue(prefix, keyOrRef); + output.address = address.join(""); + return output; + } + function normalizeIPv6(host) { + if (findToken(host, ":") < 2) { + return { host, isIPV6: false }; } - // return code that assigns values in the external scope to the names that are used internally - // (same names that were returned by gen.scopeName or gen.scopeValue) - scopeRefs(scopeName) { - return this._extScope.scopeRefs(scopeName, this._values); + const ipv62 = getIPV6(host); + if (!ipv62.error) { + let newHost = ipv62.address; + let escapedHost = ipv62.address; + if (ipv62.zone) { + newHost += "%" + ipv62.zone; + escapedHost += "%25" + ipv62.zone; + } + return { host: newHost, isIPV6: true, escapedHost }; + } else { + return { host, isIPV6: false }; } - scopeCode() { - return this._extScope.scopeCode(this._values); + } + function findToken(str2, token) { + let ind = 0; + for (let i2 = 0; i2 < str2.length; i2++) { + if (str2[i2] === token) ind++; } - _def(varKind, nameOrPrefix, rhs, constant) { - const name315 = this._scope.toName(nameOrPrefix); - if (rhs !== void 0 && constant) - this._constants[name315.str] = rhs; - this._leafNode(new Def(varKind, name315, rhs)); - return name315; + return ind; + } + function removeDotSegments(path) { + let input = path; + const output = []; + let nextSlash = -1; + let len = 0; + while (len = input.length) { + if (len === 1) { + if (input === ".") { + break; + } else if (input === "/") { + output.push("/"); + break; + } else { + output.push(input); + break; + } + } else if (len === 2) { + if (input[0] === ".") { + if (input[1] === ".") { + break; + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === "." || input[1] === "/") { + output.push("/"); + break; + } + } + } else if (len === 3) { + if (input === "/..") { + if (output.length !== 0) { + output.pop(); + } + output.push("/"); + break; + } + } + if (input[0] === ".") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(3); + continue; + } + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(2); + continue; + } else if (input[2] === ".") { + if (input[3] === "/") { + input = input.slice(3); + if (output.length !== 0) { + output.pop(); + } + continue; + } + } + } + } + if ((nextSlash = input.indexOf("/", 1)) === -1) { + output.push(input); + break; + } else { + output.push(input.slice(0, nextSlash)); + input = input.slice(nextSlash); + } } - // `const` declaration (`var` in es5 mode) - const(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + return output.join(""); + } + function normalizeComponentEncoding(component, esc2) { + const func = esc2 !== true ? escape : unescape; + if (component.scheme !== void 0) { + component.scheme = func(component.scheme); } - // `let` declaration with optional assignment (`var` in es5 mode) - let(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + if (component.userinfo !== void 0) { + component.userinfo = func(component.userinfo); } - // `var` declaration with optional assignment - var(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + if (component.host !== void 0) { + component.host = func(component.host); } - // assignment code - assign(lhs, rhs, sideEffects) { - return this._leafNode(new Assign(lhs, rhs, sideEffects)); + if (component.path !== void 0) { + component.path = func(component.path); } - // `+=` code - add(lhs, rhs) { - return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + if (component.query !== void 0) { + component.query = func(component.query); } - // appends passed SafeExpr to code or executes Block - code(c) { - if (typeof c == "function") - c(); - else if (c !== code_1.nil) - this._leafNode(new AnyCode(c)); - return this; + if (component.fragment !== void 0) { + component.fragment = func(component.fragment); } - // returns code for object literal for the passed argument list of key-value pairs - object(...keyValues) { - const code = ["{"]; - for (const [key, value] of keyValues) { - if (code.length > 1) - code.push(","); - code.push(key); - if (key !== value || this.opts.es5) { - code.push(":"); - (0, code_1.addCodeArg)(code, value); + return component; + } + function recomposeAuthority(component) { + const uriTokens = []; + if (component.userinfo !== void 0) { + uriTokens.push(component.userinfo); + uriTokens.push("@"); + } + if (component.host !== void 0) { + let host = unescape(component.host); + if (!isIPv4(host)) { + const ipV6res = normalizeIPv6(host); + if (ipV6res.isIPV6 === true) { + host = `[${ipV6res.escapedHost}]`; + } else { + host = component.host; } } - code.push("}"); - return new code_1._Code(code); + uriTokens.push(host); } - // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) - if(condition, thenBody, elseBody) { - this._blockNode(new If(condition)); - if (thenBody && elseBody) { - this.code(thenBody).else().code(elseBody).endIf(); - } else if (thenBody) { - this.code(thenBody).endIf(); - } else if (elseBody) { - throw new Error('CodeGen: "else" body without "then" body'); - } - return this; + if (typeof component.port === "number" || typeof component.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(component.port)); } - // `else if` clause - invalid without `if` or after `else` clauses - elseIf(condition) { - return this._elseNode(new If(condition)); + return uriTokens.length ? uriTokens.join("") : void 0; + } + module.exports = { + nonSimpleDomain, + recomposeAuthority, + normalizeComponentEncoding, + removeDotSegments, + isIPv4, + isUUID, + normalizeIPv6, + stringArrayToHexStripped + }; + } +}); + +// node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js +var require_schemes = __commonJS({ + "node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js"(exports, module) { + "use strict"; + var { isUUID } = require_utils(); + var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; + var supportedSchemeNames = ( + /** @type {const} */ + [ + "http", + "https", + "ws", + "wss", + "urn", + "urn:uuid" + ] + ); + function isValidSchemeName(name315) { + return supportedSchemeNames.indexOf( + /** @type {*} */ + name315 + ) !== -1; + } + function wsIsSecure(wsComponent) { + if (wsComponent.secure === true) { + return true; + } else if (wsComponent.secure === false) { + return false; + } else if (wsComponent.scheme) { + return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); + } else { + return false; } - // `else` clause - only valid after `if` or `else if` clauses - else() { - return this._elseNode(new Else()); + } + function httpParse(component) { + if (!component.host) { + component.error = component.error || "HTTP URIs must have a host."; } - // end `if` statement (needed if gen.if was used only with condition) - endIf() { - return this._endBlockNode(If, Else); + return component; + } + function httpSerialize(component) { + const secure = String(component.scheme).toLowerCase() === "https"; + if (component.port === (secure ? 443 : 80) || component.port === "") { + component.port = void 0; } - _for(node, forBody) { - this._blockNode(node); - if (forBody) - this.code(forBody).endFor(); - return this; + if (!component.path) { + component.path = "/"; } - // a generic `for` clause (or statement if `forBody` is passed) - for(iteration, forBody) { - return this._for(new ForLoop(iteration), forBody); + return component; + } + function wsParse(wsComponent) { + wsComponent.secure = wsIsSecure(wsComponent); + wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); + wsComponent.path = void 0; + wsComponent.query = void 0; + return wsComponent; + } + function wsSerialize(wsComponent) { + if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") { + wsComponent.port = void 0; } - // `for` statement for a range of values - forRange(nameOrPrefix, from, to2, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { - const name315 = this._scope.toName(nameOrPrefix); - return this._for(new ForRange(varKind, name315, from, to2), () => forBody(name315)); + if (typeof wsComponent.secure === "boolean") { + wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; + wsComponent.secure = void 0; } - // `for-of` statement (in es5 mode replace with a normal for loop) - forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { - const name315 = this._scope.toName(nameOrPrefix); - if (this.opts.es5) { - const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); - return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i2) => { - this.var(name315, (0, code_1._)`${arr}[${i2}]`); - forBody(name315); - }); - } - return this._for(new ForIter("of", varKind, name315, iterable), () => forBody(name315)); + if (wsComponent.resourceName) { + const [path, query] = wsComponent.resourceName.split("?"); + wsComponent.path = path && path !== "/" ? path : void 0; + wsComponent.query = query; + wsComponent.resourceName = void 0; } - // `for-in` statement. - // With option `ownProperties` replaced with a `for-of` loop for object keys - forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { - if (this.opts.ownProperties) { - return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); + wsComponent.fragment = void 0; + return wsComponent; + } + function urnParse(urnComponent, options) { + if (!urnComponent.path) { + urnComponent.error = "URN can not be parsed"; + return urnComponent; + } + const matches = urnComponent.path.match(URN_REG); + if (matches) { + const scheme = options.scheme || urnComponent.scheme || "urn"; + urnComponent.nid = matches[1].toLowerCase(); + urnComponent.nss = matches[2]; + const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`; + const schemeHandler = getSchemeHandler(urnScheme); + urnComponent.path = void 0; + if (schemeHandler) { + urnComponent = schemeHandler.parse(urnComponent, options); } - const name315 = this._scope.toName(nameOrPrefix); - return this._for(new ForIter("in", varKind, name315, obj), () => forBody(name315)); + } else { + urnComponent.error = urnComponent.error || "URN can not be parsed."; } - // end `for` loop - endFor() { - return this._endBlockNode(For); + return urnComponent; + } + function urnSerialize(urnComponent, options) { + if (urnComponent.nid === void 0) { + throw new Error("URN without nid cannot be serialized"); } - // `label` statement - label(label) { - return this._leafNode(new Label(label)); + const scheme = options.scheme || urnComponent.scheme || "urn"; + const nid = urnComponent.nid.toLowerCase(); + const urnScheme = `${scheme}:${options.nid || nid}`; + const schemeHandler = getSchemeHandler(urnScheme); + if (schemeHandler) { + urnComponent = schemeHandler.serialize(urnComponent, options); } - // `break` statement - break(label) { - return this._leafNode(new Break(label)); + const uriComponent = urnComponent; + const nss = urnComponent.nss; + uriComponent.path = `${nid || options.nid}:${nss}`; + options.skipEscape = true; + return uriComponent; + } + function urnuuidParse(urnComponent, options) { + const uuidComponent = urnComponent; + uuidComponent.uuid = uuidComponent.nss; + uuidComponent.nss = void 0; + if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) { + uuidComponent.error = uuidComponent.error || "UUID is not valid."; } - // `return` statement - return(value) { - const node = new Return(); - this._blockNode(node); - this.code(value); - if (node.nodes.length !== 1) - throw new Error('CodeGen: "return" should have one node'); - return this._endBlockNode(Return); + return uuidComponent; + } + function urnuuidSerialize(uuidComponent) { + const urnComponent = uuidComponent; + urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); + return urnComponent; + } + var http = ( + /** @type {SchemeHandler} */ + { + scheme: "http", + domainHost: true, + parse: httpParse, + serialize: httpSerialize } - // `try` statement - try(tryBody, catchCode, finallyCode) { - if (!catchCode && !finallyCode) - throw new Error('CodeGen: "try" without "catch" and "finally"'); - const node = new Try(); - this._blockNode(node); - this.code(tryBody); - if (catchCode) { - const error2 = this.name("e"); - this._currNode = node.catch = new Catch(error2); - catchCode(error2); - } - if (finallyCode) { - this._currNode = node.finally = new Finally(); - this.code(finallyCode); - } - return this._endBlockNode(Catch, Finally); + ); + var https = ( + /** @type {SchemeHandler} */ + { + scheme: "https", + domainHost: http.domainHost, + parse: httpParse, + serialize: httpSerialize } - // `throw` statement - throw(error2) { - return this._leafNode(new Throw(error2)); + ); + var ws = ( + /** @type {SchemeHandler} */ + { + scheme: "ws", + domainHost: true, + parse: wsParse, + serialize: wsSerialize } - // start self-balancing block - block(body, nodeCount) { - this._blockStarts.push(this._nodes.length); - if (body) - this.code(body).endBlock(nodeCount); - return this; + ); + var wss = ( + /** @type {SchemeHandler} */ + { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize } - // end the current self-balancing block - endBlock(nodeCount) { - const len = this._blockStarts.pop(); - if (len === void 0) - throw new Error("CodeGen: not in self-balancing block"); - const toClose = this._nodes.length - len; - if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { - throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); - } - this._nodes.length = len; - return this; + ); + var urn = ( + /** @type {SchemeHandler} */ + { + scheme: "urn", + parse: urnParse, + serialize: urnSerialize, + skipNormalize: true } - // `function` heading (or definition if funcBody is passed) - func(name315, args = code_1.nil, async, funcBody) { - this._blockNode(new Func(name315, args, async)); - if (funcBody) - this.code(funcBody).endFunc(); - return this; + ); + var urnuuid = ( + /** @type {SchemeHandler} */ + { + scheme: "urn:uuid", + parse: urnuuidParse, + serialize: urnuuidSerialize, + skipNormalize: true } - // end function definition - endFunc() { - return this._endBlockNode(Func); + ); + var SCHEMES = ( + /** @type {Record} */ + { + http, + https, + ws, + wss, + urn, + "urn:uuid": urnuuid } - optimize(n = 1) { - while (n-- > 0) { - this._root.optimizeNodes(); - this._root.optimizeNames(this._root.names, this._constants); + ); + Object.setPrototypeOf(SCHEMES, null); + function getSchemeHandler(scheme) { + return scheme && (SCHEMES[ + /** @type {SchemeName} */ + scheme + ] || SCHEMES[ + /** @type {SchemeName} */ + scheme.toLowerCase() + ]) || void 0; + } + module.exports = { + wsIsSecure, + SCHEMES, + isValidSchemeName, + getSchemeHandler + }; + } +}); + +// node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js +var require_fast_uri = __commonJS({ + "node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js"(exports, module) { + "use strict"; + var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); + var { SCHEMES, getSchemeHandler } = require_schemes(); + function normalize(uri, options) { + if (typeof uri === "string") { + uri = /** @type {T} */ + serialize(parse6(uri, options), options); + } else if (typeof uri === "object") { + uri = /** @type {T} */ + parse6(serialize(uri, options), options); + } + return uri; + } + function resolve2(baseURI, relativeURI, options) { + const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; + const resolved = resolveComponent(parse6(baseURI, schemelessOptions), parse6(relativeURI, schemelessOptions), schemelessOptions, true); + schemelessOptions.skipEscape = true; + return serialize(resolved, schemelessOptions); + } + function resolveComponent(base, relative, options, skipNormalization) { + const target = {}; + if (!skipNormalization) { + base = parse6(serialize(base, options), options); + relative = parse6(serialize(relative, options), options); + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== void 0) { + target.query = relative.query; + } else { + target.query = base.query; + } + } else { + if (relative.path[0] === "/") { + target.path = removeDotSegments(relative.path); + } else { + if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) { + target.path = "/" + relative.path; + } else if (!base.path) { + target.path = relative.path; + } else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; } + target.scheme = base.scheme; } - _leafNode(node) { - this._currNode.nodes.push(node); - return this; + target.fragment = relative.fragment; + return target; + } + function equal2(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = unescape(uriA); + uriA = serialize(normalizeComponentEncoding(parse6(uriA, options), true), { ...options, skipEscape: true }); + } else if (typeof uriA === "object") { + uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true }); } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); + if (typeof uriB === "string") { + uriB = unescape(uriB); + uriB = serialize(normalizeComponentEncoding(parse6(uriB, options), true), { ...options, skipEscape: true }); + } else if (typeof uriB === "object") { + uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true }); } - _endBlockNode(N1, N2) { - const n = this._currNode; - if (n instanceof N1 || N2 && n instanceof N2) { - this._nodes.pop(); - return this; + return uriA.toLowerCase() === uriB.toLowerCase(); + } + function serialize(cmpts, opts) { + const component = { + host: cmpts.host, + scheme: cmpts.scheme, + userinfo: cmpts.userinfo, + port: cmpts.port, + path: cmpts.path, + query: cmpts.query, + nid: cmpts.nid, + nss: cmpts.nss, + uuid: cmpts.uuid, + fragment: cmpts.fragment, + reference: cmpts.reference, + resourceName: cmpts.resourceName, + secure: cmpts.secure, + error: "" + }; + const options = Object.assign({}, opts); + const uriTokens = []; + const schemeHandler = getSchemeHandler(options.scheme || component.scheme); + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); + if (component.path !== void 0) { + if (!options.skipEscape) { + component.path = escape(component.path); + if (component.scheme !== void 0) { + component.path = component.path.split("%3A").join(":"); + } + } else { + component.path = unescape(component.path); } - throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); } - _elseNode(node) { - const n = this._currNode; - if (!(n instanceof If)) { - throw new Error('CodeGen: "else" without "if"'); + if (options.reference !== "suffix" && component.scheme) { + uriTokens.push(component.scheme, ":"); + } + const authority = recomposeAuthority(component); + if (authority !== void 0) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (component.path && component.path[0] !== "/") { + uriTokens.push("/"); } - this._currNode = n.else = node; - return this; } - get _root() { - return this._nodes[0]; + if (component.path !== void 0) { + let s = component.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s = removeDotSegments(s); + } + if (authority === void 0 && s[0] === "/" && s[1] === "/") { + s = "/%2F" + s.slice(2); + } + uriTokens.push(s); } - get _currNode() { - const ns = this._nodes; - return ns[ns.length - 1]; + if (component.query !== void 0) { + uriTokens.push("?", component.query); } - set _currNode(node) { - const ns = this._nodes; - ns[ns.length - 1] = node; + if (component.fragment !== void 0) { + uriTokens.push("#", component.fragment); } - }; - exports.CodeGen = CodeGen; - function addNames(names, from) { - for (const n in from) - names[n] = (names[n] || 0) + (from[n] || 0); - return names; - } - function addExprNames(names, from) { - return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + return uriTokens.join(""); } - function optimizeExpr(expr, names, constants) { - if (expr instanceof code_1.Name) - return replaceName(expr); - if (!canOptimize(expr)) - return expr; - return new code_1._Code(expr._items.reduce((items, c) => { - if (c instanceof code_1.Name) - c = replaceName(c); - if (c instanceof code_1._Code) - items.push(...c._items); - else - items.push(c); - return items; - }, [])); - function replaceName(n) { - const c = constants[n.str]; - if (c === void 0 || names[n.str] !== 1) - return n; - delete names[n.str]; - return c; + var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; + function parse6(uri, opts) { + const options = Object.assign({}, opts); + const parsed = { + scheme: void 0, + userinfo: void 0, + host: "", + port: void 0, + path: "", + query: void 0, + fragment: void 0 + }; + let isIP = false; + if (options.reference === "suffix") { + if (options.scheme) { + uri = options.scheme + ":" + uri; + } else { + uri = "//" + uri; + } } - function canOptimize(e3) { - return e3 instanceof code_1._Code && e3._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); + const matches = uri.match(URI_PARSE); + if (matches) { + parsed.scheme = matches[1]; + parsed.userinfo = matches[3]; + parsed.host = matches[4]; + parsed.port = parseInt(matches[5], 10); + parsed.path = matches[6] || ""; + parsed.query = matches[7]; + parsed.fragment = matches[8]; + if (isNaN(parsed.port)) { + parsed.port = matches[5]; + } + if (parsed.host) { + const ipv4result = isIPv4(parsed.host); + if (ipv4result === false) { + const ipv6result = normalizeIPv6(parsed.host); + parsed.host = ipv6result.host.toLowerCase(); + isIP = ipv6result.isIPV6; + } else { + isIP = true; + } + } + if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) { + parsed.reference = "same-document"; + } else if (parsed.scheme === void 0) { + parsed.reference = "relative"; + } else if (parsed.fragment === void 0) { + parsed.reference = "absolute"; + } else { + parsed.reference = "uri"; + } + if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) { + parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; + } + const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) { + try { + parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); + } catch (e3) { + parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e3; + } + } + } + if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { + if (uri.indexOf("%") !== -1) { + if (parsed.scheme !== void 0) { + parsed.scheme = unescape(parsed.scheme); + } + if (parsed.host !== void 0) { + parsed.host = unescape(parsed.host); + } + } + if (parsed.path) { + parsed.path = escape(unescape(parsed.path)); + } + if (parsed.fragment) { + parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); + } + } + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(parsed, options); + } + } else { + parsed.error = parsed.error || "URI can not be parsed."; } + return parsed; } - function subtractNames(names, from) { - for (const n in from) - names[n] = (names[n] || 0) - (from[n] || 0); - } - function not2(x) { - return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; - } - exports.not = not2; - var andCode = mappend(exports.operators.AND); - function and2(...args) { - return args.reduce(andCode); - } - exports.and = and2; - var orCode = mappend(exports.operators.OR); - function or2(...args) { - return args.reduce(orCode); - } - exports.or = or2; - function mappend(op) { - return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; - } - function par(x) { - return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; - } + var fastUri = { + SCHEMES, + normalize, + resolve: resolve2, + resolveComponent, + equal: equal2, + serialize, + parse: parse6 + }; + module.exports = fastUri; + module.exports.default = fastUri; + module.exports.fastUri = fastUri; } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js -var require_util = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js"(exports) { +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js +var require_uri = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); - exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; - var codegen_1 = require_codegen(); - var code_1 = require_code(); - function toHash(arr) { - const hash = {}; - for (const item of arr) - hash[item] = true; - return hash; - } - exports.toHash = toHash; - function alwaysValidSchema(it, schema2) { - if (typeof schema2 == "boolean") - return schema2; - if (Object.keys(schema2).length === 0) - return true; - checkUnknownRules(it, schema2); - return !schemaHasRules(schema2, it.self.RULES.all); - } - exports.alwaysValidSchema = alwaysValidSchema; - function checkUnknownRules(it, schema2 = it.schema) { - const { opts, self: self2 } = it; - if (!opts.strictSchema) - return; - if (typeof schema2 === "boolean") - return; - const rules = self2.RULES.keywords; - for (const key in schema2) { - if (!rules[key]) - checkStrictMode(it, `unknown keyword: "${key}"`); - } - } - exports.checkUnknownRules = checkUnknownRules; - function schemaHasRules(schema2, rules) { - if (typeof schema2 == "boolean") - return !schema2; - for (const key in schema2) - if (rules[key]) - return true; - return false; - } - exports.schemaHasRules = schemaHasRules; - function schemaHasRulesButRef(schema2, RULES2) { - if (typeof schema2 == "boolean") - return !schema2; - for (const key in schema2) - if (key !== "$ref" && RULES2.all[key]) - return true; - return false; - } - exports.schemaHasRulesButRef = schemaHasRulesButRef; - function schemaRefOrVal({ topSchemaRef, schemaPath }, schema2, keyword, $data) { - if (!$data) { - if (typeof schema2 == "number" || typeof schema2 == "boolean") - return schema2; - if (typeof schema2 == "string") - return (0, codegen_1._)`${schema2}`; - } - return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; - } - exports.schemaRefOrVal = schemaRefOrVal; - function unescapeFragment(str2) { - return unescapeJsonPointer(decodeURIComponent(str2)); - } - exports.unescapeFragment = unescapeFragment; - function escapeFragment(str2) { - return encodeURIComponent(escapeJsonPointer(str2)); - } - exports.escapeFragment = escapeFragment; - function escapeJsonPointer(str2) { - if (typeof str2 == "number") - return `${str2}`; - return str2.replace(/~/g, "~0").replace(/\//g, "~1"); - } - exports.escapeJsonPointer = escapeJsonPointer; - function unescapeJsonPointer(str2) { - return str2.replace(/~1/g, "/").replace(/~0/g, "~"); - } - exports.unescapeJsonPointer = unescapeJsonPointer; - function eachItem(xs, f) { - if (Array.isArray(xs)) { - for (const x of xs) - f(x); - } else { - f(xs); - } - } - exports.eachItem = eachItem; - function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) { - return (gen, from, to2, toName) => { - const res = to2 === void 0 ? from : to2 instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to2) : mergeToName(gen, from, to2), to2) : from instanceof codegen_1.Name ? (mergeToName(gen, to2, from), from) : mergeValues3(from, to2); - return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; - }; - } - exports.mergeEvaluated = { - props: makeMergeEvaluated({ - mergeNames: (gen, from, to2) => gen.if((0, codegen_1._)`${to2} !== true && ${from} !== undefined`, () => { - gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to2, true), () => gen.assign(to2, (0, codegen_1._)`${to2} || {}`).code((0, codegen_1._)`Object.assign(${to2}, ${from})`)); - }), - mergeToName: (gen, from, to2) => gen.if((0, codegen_1._)`${to2} !== true`, () => { - if (from === true) { - gen.assign(to2, true); - } else { - gen.assign(to2, (0, codegen_1._)`${to2} || {}`); - setEvaluated(gen, to2, from); - } - }), - mergeValues: (from, to2) => from === true ? true : { ...from, ...to2 }, - resultToName: evaluatedPropsToName - }), - items: makeMergeEvaluated({ - mergeNames: (gen, from, to2) => gen.if((0, codegen_1._)`${to2} !== true && ${from} !== undefined`, () => gen.assign(to2, (0, codegen_1._)`${from} === true ? true : ${to2} > ${from} ? ${to2} : ${from}`)), - mergeToName: (gen, from, to2) => gen.if((0, codegen_1._)`${to2} !== true`, () => gen.assign(to2, from === true ? true : (0, codegen_1._)`${to2} > ${from} ? ${to2} : ${from}`)), - mergeValues: (from, to2) => from === true ? true : Math.max(from, to2), - resultToName: (gen, items) => gen.var("items", items) - }) - }; - function evaluatedPropsToName(gen, ps) { - if (ps === true) - return gen.var("props", true); - const props = gen.var("props", (0, codegen_1._)`{}`); - if (ps !== void 0) - setEvaluated(gen, props, ps); - return props; - } - exports.evaluatedPropsToName = evaluatedPropsToName; - function setEvaluated(gen, props, ps) { - Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); - } - exports.setEvaluated = setEvaluated; - var snippets = {}; - function useFunc(gen, f) { - return gen.scopeValue("func", { - ref: f, - code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) - }); - } - exports.useFunc = useFunc; - var Type; - (function(Type2) { - Type2[Type2["Num"] = 0] = "Num"; - Type2[Type2["Str"] = 1] = "Str"; - })(Type || (exports.Type = Type = {})); - function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { - if (dataProp instanceof codegen_1.Name) { - const isNumber2 = dataPropType === Type.Num; - return jsPropertySyntax ? isNumber2 ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber2 ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; - } - return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); - } - exports.getErrorPath = getErrorPath; - function checkStrictMode(it, msg, mode2 = it.opts.strictSchema) { - if (!mode2) - return; - msg = `strict mode: ${msg}`; - if (mode2 === true) - throw new Error(msg); - it.self.logger.warn(msg); - } - exports.checkStrictMode = checkStrictMode; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js -var require_names = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var names = { - // validation function arguments - data: new codegen_1.Name("data"), - // data passed to validation function - // args passed from referencing schema - valCxt: new codegen_1.Name("valCxt"), - // validation/data context - should not be used directly, it is destructured to the names below - instancePath: new codegen_1.Name("instancePath"), - parentData: new codegen_1.Name("parentData"), - parentDataProperty: new codegen_1.Name("parentDataProperty"), - rootData: new codegen_1.Name("rootData"), - // root data - same as the data passed to the first/top validation function - dynamicAnchors: new codegen_1.Name("dynamicAnchors"), - // used to support recursiveRef and dynamicRef - // function scoped variables - vErrors: new codegen_1.Name("vErrors"), - // null or array of validation errors - errors: new codegen_1.Name("errors"), - // counter of validation errors - this: new codegen_1.Name("this"), - // "globals" - self: new codegen_1.Name("self"), - scope: new codegen_1.Name("scope"), - // JTD serialize/parse name for JSON string and position - json: new codegen_1.Name("json"), - jsonPos: new codegen_1.Name("jsonPos"), - jsonLen: new codegen_1.Name("jsonLen"), - jsonPart: new codegen_1.Name("jsonPart") - }; - exports.default = names; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js -var require_errors = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + var uri = require_fast_uri(); + uri.code = 'require("ajv/dist/runtime/uri").default'; + exports.default = uri; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js +var require_core = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { + return validate_1.KeywordCxt; + } }); var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return codegen_1._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return codegen_1.str; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return codegen_1.stringify; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return codegen_1.nil; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return codegen_1.Name; + } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { + return codegen_1.CodeGen; + } }); + var validation_error_1 = require_validation_error(); + var ref_error_1 = require_ref_error(); + var rules_1 = require_rules(); + var compile_1 = require_compile(); + var codegen_2 = require_codegen(); + var resolve_1 = require_resolve(); + var dataType_1 = require_dataType(); var util_1 = require_util(); - var names_1 = require_names(); - exports.keywordError = { - message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` + var $dataRefSchema = require_data(); + var uri_1 = require_uri(); + var defaultRegExp = (str2, flags) => new RegExp(str2, flags); + defaultRegExp.code = "new RegExp"; + var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; + var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error" + ]); + var removedOptions = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: '"nullable" keyword is supported by default.', + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: '"uniqueItems" keyword is always validated.', + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now." }; - exports.keyword$DataError = { - message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` + var deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: '"minLength"/"maxLength" account for unicode characters by default.' }; - function reportError(cxt, error2 = exports.keywordError, errorPaths, overrideAllErrors) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error2, errorPaths); - if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { - addError(gen, errObj); - } else { - returnErrors(it, (0, codegen_1._)`[${errObj}]`); - } - } - exports.reportError = reportError; - function reportExtraError(cxt, error2 = exports.keywordError, errorPaths) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error2, errorPaths); - addError(gen, errObj); - if (!(compositeRule || allErrors)) { - returnErrors(it, names_1.default.vErrors); - } - } - exports.reportExtraError = reportExtraError; - function resetErrorsCount(gen, errsCount) { - gen.assign(names_1.default.errors, errsCount); - gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); - } - exports.resetErrorsCount = resetErrorsCount; - function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { - if (errsCount === void 0) - throw new Error("ajv implementation error"); - const err = gen.name("err"); - gen.forRange("i", errsCount, names_1.default.errors, (i2) => { - gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i2}]`); - gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); - gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); - if (it.opts.verbose) { - gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); - gen.assign((0, codegen_1._)`${err}.data`, data); - } - }); - } - exports.extendErrors = extendErrors; - function addError(gen, errObj) { - const err = gen.const("err", errObj); - gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); - gen.code((0, codegen_1._)`${names_1.default.errors}++`); + var MAX_EXPRESSION = 200; + function requiredOptions(o) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; + const s = o.strict; + const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; + const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; + const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, + code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, + loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver + }; } - function returnErrors(it, errs) { - const { gen, validateName, schemaEnv } = it; - if (schemaEnv.$async) { - gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); - } else { - gen.assign((0, codegen_1._)`${validateName}.errors`, errs); - gen.return(false); + var Ajv2 = class { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = {}; + this._compilations = /* @__PURE__ */ new Set(); + this._loading = {}; + this._cache = /* @__PURE__ */ new Map(); + opts = this.opts = { ...opts, ...requiredOptions(opts) }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) + addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) + addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") + this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; } - } - var E = { - keyword: new codegen_1.Name("keyword"), - schemaPath: new codegen_1.Name("schemaPath"), - // also used in JTD errors - params: new codegen_1.Name("params"), - propertyName: new codegen_1.Name("propertyName"), - message: new codegen_1.Name("message"), - schema: new codegen_1.Name("schema"), - parentSchema: new codegen_1.Name("parentSchema") - }; - function errorObjectCode(cxt, error2, errorPaths) { - const { createErrors } = cxt.it; - if (createErrors === false) - return (0, codegen_1._)`{}`; - return errorObject(cxt, error2, errorPaths); - } - function errorObject(cxt, error2, errorPaths = {}) { - const { gen, it } = cxt; - const keyValues = [ - errorInstancePath(it, errorPaths), - errorSchemaPath(cxt, errorPaths) - ]; - extraErrorProps(cxt, error2, keyValues); - return gen.object(...keyValues); - } - function errorInstancePath({ errorPath }, { instancePath }) { - const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; - return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; - } - function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { - let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; - if (schemaPath) { - schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + _addVocabularies() { + this.addKeyword("$async"); } - return [E.schemaPath, schPath]; - } - function extraErrorProps(cxt, { params, message }, keyValues) { - const { keyword, data, schemaValue, it } = cxt; - const { opts, propertyName, topSchemaRef, schemaPath } = it; - keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); - if (opts.messages) { - keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); + _addDefaultMetaSchema() { + const { $data, meta, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta && $data) + this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); } - if (opts.verbose) { - keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + defaultMeta() { + const { meta, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; } - if (propertyName) - keyValues.push([E.propertyName, propertyName]); - } - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js -var require_boolSchema = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; - var errors_1 = require_errors(); - var codegen_1 = require_codegen(); - var names_1 = require_names(); - var boolError = { - message: "boolean schema is false" - }; - function topBoolOrEmptySchema(it) { - const { gen, schema: schema2, validateName } = it; - if (schema2 === false) { - falseSchemaError(it, false); - } else if (typeof schema2 == "object" && schema2.$async === true) { - gen.return(names_1.default.data); - } else { - gen.assign((0, codegen_1._)`${validateName}.errors`, null); - gen.return(true); + validate(schemaKeyRef, data) { + let v; + if (typeof schemaKeyRef == "string") { + v = this.getSchema(schemaKeyRef); + if (!v) + throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } else { + v = this.compile(schemaKeyRef); + } + const valid = v(data); + if (!("$async" in v)) + this.errors = v.errors; + return valid; } - } - exports.topBoolOrEmptySchema = topBoolOrEmptySchema; - function boolOrEmptySchema(it, valid) { - const { gen, schema: schema2 } = it; - if (schema2 === false) { - gen.var(valid, false); - falseSchemaError(it); - } else { - gen.var(valid, true); + compile(schema2, _meta) { + const sch = this._addSchema(schema2, _meta); + return sch.validate || this._compileSchemaEnv(sch); } - } - exports.boolOrEmptySchema = boolOrEmptySchema; - function falseSchemaError(it, overrideAllErrors) { - const { gen, data } = it; - const cxt = { - gen, - keyword: "false schema", - data, - schema: false, - schemaCode: false, - schemaValue: false, - params: {}, - it - }; - (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); - } - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js -var require_rules = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getRules = exports.isJSONType = void 0; - var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; - var jsonTypes = new Set(_jsonTypes); - function isJSONType(x) { - return typeof x == "string" && jsonTypes.has(x); - } - exports.isJSONType = isJSONType; - function getRules() { - const groups = { - number: { type: "number", rules: [] }, - string: { type: "string", rules: [] }, - array: { type: "array", rules: [] }, - object: { type: "object", rules: [] } - }; - return { - types: { ...groups, integer: true, boolean: true, null: true }, - rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], - post: { rules: [] }, - all: {}, - keywords: {} - }; - } - exports.getRules = getRules; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js -var require_applicability = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; - function schemaHasRulesForType({ schema: schema2, self: self2 }, type2) { - const group = self2.RULES.types[type2]; - return group && group !== true && shouldUseGroup(schema2, group); - } - exports.schemaHasRulesForType = schemaHasRulesForType; - function shouldUseGroup(schema2, group) { - return group.rules.some((rule) => shouldUseRule(schema2, rule)); - } - exports.shouldUseGroup = shouldUseGroup; - function shouldUseRule(schema2, rule) { - var _a; - return schema2[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema2[kwd] !== void 0)); - } - exports.shouldUseRule = shouldUseRule; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js -var require_dataType = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; - var rules_1 = require_rules(); - var applicability_1 = require_applicability(); - var errors_1 = require_errors(); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var DataType; - (function(DataType2) { - DataType2[DataType2["Correct"] = 0] = "Correct"; - DataType2[DataType2["Wrong"] = 1] = "Wrong"; - })(DataType || (exports.DataType = DataType = {})); - function getSchemaTypes(schema2) { - const types = getJSONTypes(schema2.type); - const hasNull = types.includes("null"); - if (hasNull) { - if (schema2.nullable === false) - throw new Error("type: null contradicts nullable: false"); - } else { - if (!types.length && schema2.nullable !== void 0) { - throw new Error('"nullable" cannot be used without "type"'); + compileAsync(schema2, meta) { + if (typeof this.opts.loadSchema != "function") { + throw new Error("options.loadSchema should be a function"); + } + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema2, meta); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) { + await runCompileAsync.call(this, { $ref }, true); + } + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } catch (e3) { + if (!(e3 instanceof ref_error_1.default)) + throw e3; + checkLoaded.call(this, e3); + await loadMissingSchema.call(this, e3.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) { + throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) + await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) + this.addSchema(_schema, ref, meta); + } + async function _loadSchema(ref) { + const p = this._loading[ref]; + if (p) + return p; + try { + return await (this._loading[ref] = loadSchema(ref)); + } finally { + delete this._loading[ref]; + } } - if (schema2.nullable === true) - types.push("null"); } - return types; - } - exports.getSchemaTypes = getSchemaTypes; - function getJSONTypes(ts) { - const types = Array.isArray(ts) ? ts : ts ? [ts] : []; - if (types.every(rules_1.isJSONType)) - return types; - throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); - } - exports.getJSONTypes = getJSONTypes; - function coerceAndCheckDataType(it, types) { - const { gen, data, opts } = it; - const coerceTo = coerceToTypes(types, opts.coerceTypes); - const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); - if (checkTypes) { - const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); - gen.if(wrongType, () => { - if (coerceTo.length) - coerceData(it, types, coerceTo); - else - reportTypeError(it); - }); + // Adds schema to the instance + addSchema(schema2, key, _meta, _validateSchema = this.opts.validateSchema) { + if (Array.isArray(schema2)) { + for (const sch of schema2) + this.addSchema(sch, void 0, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema2 === "object") { + const { schemaId } = this.opts; + id = schema2[schemaId]; + if (id !== void 0 && typeof id != "string") { + throw new Error(`schema ${schemaId} must be string`); + } + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema2, _meta, key, _validateSchema, true); + return this; } - return checkTypes; - } - exports.coerceAndCheckDataType = coerceAndCheckDataType; - var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); - function coerceToTypes(types, coerceTypes) { - return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; - } - function coerceData(it, types, coerceTo) { - const { gen, data, opts } = it; - const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); - const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); - if (opts.coerceTypes === "array") { - gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); + // Add schema that will be used to validate other schemas + // options in META_IGNORE_OPTIONS are alway set to false + addMetaSchema(schema2, key, _validateSchema = this.opts.validateSchema) { + this.addSchema(schema2, key, true, _validateSchema); + return this; } - gen.if((0, codegen_1._)`${coerced} !== undefined`); - for (const t of coerceTo) { - if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") { - coerceSpecificType(t); + // Validate schema against its meta-schema + validateSchema(schema2, throwOrLogError) { + if (typeof schema2 == "boolean") + return true; + let $schema; + $schema = schema2.$schema; + if ($schema !== void 0 && typeof $schema != "string") { + throw new Error("$schema must be a string"); + } + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema2); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") + this.logger.error(message); + else + throw new Error(message); } + return valid; } - gen.else(); - reportTypeError(it); - gen.endIf(); - gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { - gen.assign(data, coerced); - assignParentData(it, coerced); - }); - function coerceSpecificType(t) { - switch (t) { - case "string": - gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); - return; - case "number": - gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null - || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "integer": - gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null - || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "boolean": - gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); - return; - case "null": - gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); - gen.assign(coerced, null); + // Get compiled schema by `key` or `ref`. + // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") + keyRef = sch; + if (sch === void 0) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) return; - case "array": - gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" - || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); + this.refs[keyRef] = sch; } + return sch.validate || this._compileSchemaEnv(sch); } - } - function assignParentData({ gen, parentData, parentDataProperty }, expr) { - gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); - } - function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { - const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; - let cond; - switch (dataType) { - case "null": - return (0, codegen_1._)`${data} ${EQ} null`; - case "array": - cond = (0, codegen_1._)`Array.isArray(${data})`; - break; - case "object": - cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; - break; - case "integer": - cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); - break; - case "number": - cond = numCond(); - break; - default: - return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; + // Remove cached schema(s). + // If no parameter is passed all schemas but meta-schemas are removed. + // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") + this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: + throw new Error("ajv.removeSchema: invalid parameter"); + } } - return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); - function numCond(_cond = codegen_1.nil) { - return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); + // add "vocabulary" - a collection of keywords + addVocabulary(definitions) { + for (const def of definitions) + this.addKeyword(def); + return this; } - } - exports.checkDataType = checkDataType; - function checkDataTypes(dataTypes, data, strictNums, correct) { - if (dataTypes.length === 1) { - return checkDataType(dataTypes[0], data, strictNums, correct); + addKeyword(kwdOrDef, def) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } else if (typeof kwdOrDef == "object" && def === void 0) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) { + throw new Error("addKeywords: keyword must be string or non-empty array"); + } + } else { + throw new Error("invalid addKeywords parameters"); + } + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); + return this; } - let cond; - const types = (0, util_1.toHash)(dataTypes); - if (types.array && types.object) { - const notObj = (0, codegen_1._)`typeof ${data} != "object"`; - cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; - delete types.null; - delete types.array; - delete types.object; - } else { - cond = codegen_1.nil; + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; } - if (types.number) - delete types.integer; - for (const t in types) - cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); - return cond; - } - exports.checkDataTypes = checkDataTypes; - var typeError = { - message: ({ schema: schema2 }) => `must be ${schema2}`, - params: ({ schema: schema2, schemaValue }) => typeof schema2 == "string" ? (0, codegen_1._)`{type: ${schema2}}` : (0, codegen_1._)`{type: ${schemaValue}}` - }; - function reportTypeError(it) { - const cxt = getTypeErrorContext(it); - (0, errors_1.reportError)(cxt, typeError); - } - exports.reportTypeError = reportTypeError; - function getTypeErrorContext(it) { - const { gen, data, schema: schema2 } = it; - const schemaCode = (0, util_1.schemaRefOrVal)(it, schema2, "type"); - return { - gen, - keyword: "type", - data, - schema: schema2.type, - schemaCode, - schemaValue: schemaCode, - parentSchema: schema2, - params: {}, - it - }; - } - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js -var require_defaults = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.assignDefaults = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - function assignDefaults(it, ty) { - const { properties: properties2, items } = it.schema; - if (ty === "object" && properties2) { - for (const key in properties2) { - assignDefault(it, key, properties2[key].default); + // Remove keyword + removeKeyword(keyword) { + const { RULES: RULES2 } = this; + delete RULES2.keywords[keyword]; + delete RULES2.all[keyword]; + for (const group of RULES2.rules) { + const i2 = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i2 >= 0) + group.rules.splice(i2, 1); } - } else if (ty === "array" && Array.isArray(items)) { - items.forEach((sch, i2) => assignDefault(it, i2, sch.default)); + return this; } - } - exports.assignDefaults = assignDefaults; - function assignDefault(it, prop, defaultValue) { - const { gen, compositeRule, data, opts } = it; - if (defaultValue === void 0) - return; - const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; - if (compositeRule) { - (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); - return; + // Add format + addFormat(name315, format5) { + if (typeof format5 == "string") + format5 = new RegExp(format5); + this.formats[name315] = format5; + return this; } - let condition = (0, codegen_1._)`${childData} === undefined`; - if (opts.useDefaults === "empty") { - condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; + errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { + if (!errors || errors.length === 0) + return "No errors"; + return errors.map((e3) => `${dataVar}${e3.instancePath} ${e3.message}`).reduce((text, msg) => text + separator + msg); } - gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); - } - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js -var require_code2 = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var names_1 = require_names(); - var util_2 = require_util(); - function checkReportMissingProp(cxt, prop) { - const { gen, data, it } = cxt; - gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { - cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); - cxt.error(); - }); - } - exports.checkReportMissingProp = checkReportMissingProp; - function checkMissingProp({ gen, data, it: { opts } }, properties2, missing) { - return (0, codegen_1.or)(...properties2.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); - } - exports.checkMissingProp = checkMissingProp; - function reportMissingProp(cxt, missing) { - cxt.setParams({ missingProperty: missing }, true); - cxt.error(); - } - exports.reportMissingProp = reportMissingProp; - function hasPropFunc(gen) { - return gen.scopeValue("func", { - // eslint-disable-next-line @typescript-eslint/unbound-method - ref: Object.prototype.hasOwnProperty, - code: (0, codegen_1._)`Object.prototype.hasOwnProperty` - }); - } - exports.hasPropFunc = hasPropFunc; - function isOwnProperty(gen, data, property) { - return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; - } - exports.isOwnProperty = isOwnProperty; - function propertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; - return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; - } - exports.propertyInData = propertyInData; - function noPropertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; - return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; - } - exports.noPropertyInData = noPropertyInData; - function allSchemaProperties(schemaMap) { - return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; - } - exports.allSchemaProperties = allSchemaProperties; - function schemaProperties(it, schemaMap) { - return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); - } - exports.schemaProperties = schemaProperties; - function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { - const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; - const valCxt = [ - [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], - [names_1.default.parentData, it.parentData], - [names_1.default.parentDataProperty, it.parentDataProperty], - [names_1.default.rootData, names_1.default.rootData] - ]; - if (it.opts.dynamicRef) - valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); - const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; - return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; - } - exports.callValidateCode = callValidateCode; - var newRegExp = (0, codegen_1._)`new RegExp`; - function usePattern({ gen, it: { opts } }, pattern) { - const u = opts.unicodeRegExp ? "u" : ""; - const { regExp } = opts.code; - const rx = regExp(pattern, u); - return gen.scopeValue("pattern", { - key: rx.toString(), - ref: rx, - code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` - }); - } - exports.usePattern = usePattern; - function validateArray(cxt) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - if (it.allErrors) { - const validArr = gen.let("valid", true); - validateItems(() => gen.assign(validArr, false)); - return validArr; + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); + let keywords2 = metaSchema; + for (const seg of segments) + keywords2 = keywords2[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") + continue; + const { $data } = rule.definition; + const schema2 = keywords2[key]; + if ($data && schema2) + keywords2[key] = schemaOrData(schema2); + } + } + return metaSchema; } - gen.var(valid, true); - validateItems(() => gen.break()); - return valid; - function validateItems(notValid) { - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - gen.forRange("i", 0, len, (i2) => { - cxt.subschema({ - keyword, - dataProp: i2, - dataPropType: util_1.Type.Num - }, valid); - gen.if((0, codegen_1.not)(valid), notValid); - }); + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") { + delete schemas[keyRef]; + } else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } } - } - exports.validateArray = validateArray; - function validateUnion(cxt) { - const { gen, schema: schema2, keyword, it } = cxt; - if (!Array.isArray(schema2)) - throw new Error("ajv implementation error"); - const alwaysValid = schema2.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); - if (alwaysValid && !it.opts.unevaluated) - return; - const valid = gen.let("valid", false); - const schValid = gen.name("_valid"); - gen.block(() => schema2.forEach((_sch, i2) => { - const schCxt = cxt.subschema({ - keyword, - schemaProp: i2, - compositeRule: true - }, schValid); - gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); - const merged = cxt.mergeValidEvaluated(schCxt, schValid); - if (!merged) - gen.if((0, codegen_1.not)(valid)); - })); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - } - exports.validateUnion = validateUnion; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js -var require_keyword = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; - var codegen_1 = require_codegen(); - var names_1 = require_names(); - var code_1 = require_code2(); - var errors_1 = require_errors(); - function macroKeywordCode(cxt, def) { - const { gen, keyword, schema: schema2, parentSchema, it } = cxt; - const macroSchema = def.macro.call(it.self, schema2, parentSchema, it); - const schemaRef = useKeyword(gen, keyword, macroSchema); - if (it.opts.validateSchema !== false) - it.self.validateSchema(macroSchema, true); - const valid = gen.name("valid"); - cxt.subschema({ - schema: macroSchema, - schemaPath: codegen_1.nil, - errSchemaPath: `${it.errSchemaPath}/${keyword}`, - topSchemaRef: schemaRef, - compositeRule: true - }, valid); - cxt.pass(valid, () => cxt.error(true)); - } - exports.macroKeywordCode = macroKeywordCode; - function funcKeywordCode(cxt, def) { - var _a; - const { gen, keyword, schema: schema2, parentSchema, $data, it } = cxt; - checkAsyncKeyword(it, def); - const validate2 = !$data && def.compile ? def.compile.call(it.self, schema2, parentSchema, it) : def.validate; - const validateRef = useKeyword(gen, keyword, validate2); - const valid = gen.let("valid"); - cxt.block$data(valid, validateKeyword); - cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); - function validateKeyword() { - if (def.errors === false) { - assignValid(); - if (def.modifying) - modifyData(cxt); - reportErrs(() => cxt.error()); + _addSchema(schema2, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema2 == "object") { + id = schema2[schemaId]; } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); - if (def.modifying) - modifyData(cxt); - reportErrs(() => addErrs(cxt, ruleErrs)); + if (this.opts.jtd) + throw new Error("schema must be object"); + else if (typeof schema2 != "boolean") + throw new Error("schema must be object or boolean"); } + let sch = this._cache.get(schema2); + if (sch !== void 0) + return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema2, baseId); + sch = new compile_1.SchemaEnv({ schema: schema2, schemaId, meta, baseId, localRefs }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + if (baseId) + this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) + this.validateSchema(schema2, true); + return sch; } - function validateAsync() { - const ruleErrs = gen.let("ruleErrs", null); - gen.try(() => assignValid((0, codegen_1._)`await `), (e3) => gen.assign(valid, false).if((0, codegen_1._)`${e3} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e3}.errors`), () => gen.throw(e3))); - return ruleErrs; + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) { + throw new Error(`schema with key or id "${id}" already exists`); + } } - function validateSync() { - const validateErrs = (0, codegen_1._)`${validateRef}.errors`; - gen.assign(validateErrs, null); - assignValid(codegen_1.nil); - return validateErrs; + _compileSchemaEnv(sch) { + if (sch.meta) + this._compileMetaSchema(sch); + else + compile_1.compileSchema.call(this, sch); + if (!sch.validate) + throw new Error("ajv implementation error"); + return sch.validate; } - function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { - const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; - const passSchema = !("compile" in def && !$data || def.schema === false); - gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } finally { + this.opts = currentOpts; + } } - function reportErrs(errors) { - var _a2; - gen.if((0, codegen_1.not)((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid), errors); + }; + Ajv2.ValidationError = validation_error_1.default; + Ajv2.MissingRefError = ref_error_1.default; + exports.default = Ajv2; + function checkOptions(checkOpts, options, msg, log4 = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) + this.logger[log4](`${msg}: option ${key}. ${checkOpts[opt]}`); } } - exports.funcKeywordCode = funcKeywordCode; - function modifyData(cxt) { - const { gen, data, it } = cxt; - gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); - } - function addErrs(cxt, errs) { - const { gen } = cxt; - gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - (0, errors_1.extendErrors)(cxt); - }, () => cxt.error()); - } - function checkAsyncKeyword({ schemaEnv }, def) { - if (def.async && !schemaEnv.$async) - throw new Error("async keyword in sync schema"); - } - function useKeyword(gen, keyword, result) { - if (result === void 0) - throw new Error(`keyword "${keyword}" failed to compile`); - return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); + return this.schemas[keyRef] || this.refs[keyRef]; } - function validSchemaType(schema2, schemaType, allowUndefined = false) { - return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema2) : st === "object" ? schema2 && typeof schema2 == "object" && !Array.isArray(schema2) : typeof schema2 == st || allowUndefined && typeof schema2 == "undefined"); + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) + return; + if (Array.isArray(optsSchemas)) + this.addSchema(optsSchemas); + else + for (const key in optsSchemas) + this.addSchema(optsSchemas[key], key); } - exports.validSchemaType = validSchemaType; - function validateKeywordUsage({ schema: schema2, opts, self: self2, errSchemaPath }, def, keyword) { - if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { - throw new Error("ajv implementation error"); + function addInitialFormats() { + for (const name315 in this.opts.formats) { + const format5 = this.opts.formats[name315]; + if (format5) + this.addFormat(name315, format5); } - const deps = def.dependencies; - if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema2, kwd))) { - throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; } - if (def.validateSchema) { - const valid = def.validateSchema(schema2[keyword]); - if (!valid) { - const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors); - if (opts.validateSchema === "log") - self2.logger.error(msg); - else - throw new Error(msg); - } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) + def.keyword = keyword; + this.addKeyword(def); } } - exports.validateKeywordUsage = validateKeywordUsage; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js -var require_subschema = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - function getSubschema(it, { keyword, schemaProp, schema: schema2, schemaPath, errSchemaPath, topSchemaRef }) { - if (keyword !== void 0 && schema2 !== void 0) { - throw new Error('both "keyword" and "schema" passed, only one allowed'); + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) + delete metaOpts[opt]; + return metaOpts; + } + var noLogs = { log() { + }, warn() { + }, error() { + } }; + function getLogger(logger) { + if (logger === false) + return noLogs; + if (logger === void 0) + return console; + if (logger.log && logger.warn && logger.error) + return logger; + throw new Error("logger must implement log, warn and error methods"); + } + var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def) { + const { RULES: RULES2 } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES2.keywords[kwd]) + throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) + throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) + return; + if (def.$data && !("code" in def || "validate" in def)) { + throw new Error('$data keyword must have "code" or "validate" function'); } - if (keyword !== void 0) { - const sch = it.schema[keyword]; - return schemaProp === void 0 ? { - schema: sch, - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}` - } : { - schema: sch[schemaProp], - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` - }; + } + function addRule(keyword, definition, dataType) { + var _a; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) + throw new Error('keyword with "post" flag cannot have "type"'); + const { RULES: RULES2 } = this; + let ruleGroup = post ? RULES2.post : RULES2.rules.find(({ type: t }) => t === dataType); + if (!ruleGroup) { + ruleGroup = { type: dataType, rules: [] }; + RULES2.rules.push(ruleGroup); } - if (schema2 !== void 0) { - if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { - throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); + RULES2.keywords[keyword] = true; + if (!definition) + return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) } - return { - schema: schema2, - schemaPath, - topSchemaRef, - errSchemaPath - }; - } - throw new Error('either "keyword" or "schema" must be passed'); + }; + if (definition.before) + addBeforeRule.call(this, ruleGroup, rule, definition.before); + else + ruleGroup.rules.push(rule); + RULES2.all[keyword] = rule; + (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd)); } - exports.getSubschema = getSubschema; - function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { - if (data !== void 0 && dataProp !== void 0) { - throw new Error('both "data" and "dataProp" passed, only one allowed'); - } - const { gen } = it; - if (dataProp !== void 0) { - const { errorPath, dataPathArr, opts } = it; - const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); - dataContextProps(nextData); - subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; - subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; - subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; - } - if (data !== void 0) { - const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); - dataContextProps(nextData); - if (propertyName !== void 0) - subschema.propertyName = propertyName; - } - if (dataTypes) - subschema.dataTypes = dataTypes; - function dataContextProps(_nextData) { - subschema.data = _nextData; - subschema.dataLevel = it.dataLevel + 1; - subschema.dataTypes = []; - it.definedProperties = /* @__PURE__ */ new Set(); - subschema.parentData = it.data; - subschema.dataNames = [...it.dataNames, _nextData]; + function addBeforeRule(ruleGroup, rule, before) { + const i2 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i2 >= 0) { + ruleGroup.rules.splice(i2, 0, rule); + } else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); } } - exports.extendSubschemaData = extendSubschemaData; - function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { - if (compositeRule !== void 0) - subschema.compositeRule = compositeRule; - if (createErrors !== void 0) - subschema.createErrors = createErrors; - if (allErrors !== void 0) - subschema.allErrors = allErrors; - subschema.jtdDiscriminator = jtdDiscriminator; - subschema.jtdMetadata = jtdMetadata; + function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === void 0) + return; + if (def.$data && this.opts.$data) + metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); + } + var $dataRef = { + $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" + }; + function schemaOrData(schema2) { + return { anyOf: [schema2, $dataRef] }; } - exports.extendSubschemaMode = extendSubschemaMode; } }); -// node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = __commonJS({ - "node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports, module) { +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js +var require_id = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js"(exports) { "use strict"; - module.exports = function equal2(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i2, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i2 = length; i2-- !== 0; ) - if (!equal2(a[i2], b[i2])) return false; - return true; - } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i2 = length; i2-- !== 0; ) - if (!Object.prototype.hasOwnProperty.call(b, keys[i2])) return false; - for (i2 = length; i2-- !== 0; ) { - var key = keys[i2]; - if (!equal2(a[key], b[key])) return false; - } - return true; + Object.defineProperty(exports, "__esModule", { value: true }); + var def = { + keyword: "id", + code() { + throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); } - return a !== a && b !== b; }; + exports.default = def; } }); -// node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js -var require_json_schema_traverse = __commonJS({ - "node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js"(exports, module) { +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js +var require_ref = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js"(exports) { "use strict"; - var traverse = module.exports = function(schema2, opts, cb) { - if (typeof opts == "function") { - cb = opts; - opts = {}; - } - cb = opts.cb || cb; - var pre = typeof cb == "function" ? cb : cb.pre || function() { - }; - var post = cb.post || function() { - }; - _traverse(opts, pre, post, schema2, "", schema2); - }; - traverse.keywords = { - additionalItems: true, - items: true, - contains: true, - additionalProperties: true, - propertyNames: true, - not: true, - if: true, - then: true, - else: true - }; - traverse.arrayKeywords = { - items: true, - allOf: true, - anyOf: true, - oneOf: true - }; - traverse.propsKeywords = { - $defs: true, - definitions: true, - properties: true, - patternProperties: true, - dependencies: true - }; - traverse.skipKeywords = { - default: true, - enum: true, - const: true, - required: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callRef = exports.getValidate = void 0; + var ref_error_1 = require_ref_error(); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var compile_1 = require_compile(); + var util_1 = require_util(); + var def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) + return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref); + if (schOrEnv === void 0) + throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) + return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) + return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + const v = getValidate(cxt, sch); + callRef(cxt, v, sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + } }; - function _traverse(opts, pre, post, schema2, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { - if (schema2 && typeof schema2 == "object" && !Array.isArray(schema2)) { - pre(schema2, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - for (var key in schema2) { - var sch = schema2[key]; - if (Array.isArray(sch)) { - if (key in traverse.arrayKeywords) { - for (var i2 = 0; i2 < sch.length; i2++) - _traverse(opts, pre, post, sch[i2], jsonPtr + "/" + key + "/" + i2, rootSchema, jsonPtr, key, schema2, i2); + function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + } + exports.getValidate = getValidate; + function callRef(cxt, v, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) + callAsyncRef(); + else + callSyncRef(); + function callAsyncRef() { + if (!env.$async) + throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); + addEvaluatedFrom(v); + if (!allErrors) + gen.assign(valid, true); + }, (e3) => { + gen.if((0, codegen_1._)`!(${e3} instanceof ${it.ValidationError})`, () => gen.throw(e3)); + addErrorsFrom(e3); + if (!allErrors) + gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._)`${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); + gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a; + if (!it.opts.unevaluated) + return; + const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; + if (it.props !== true) { + if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== void 0) { + it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); } - } else if (key in traverse.propsKeywords) { - if (sch && typeof sch == "object") { - for (var prop in sch) - _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema2, prop); + } else { + const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + } + if (it.items !== true) { + if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== void 0) { + it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); } - } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { - _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema2); + } else { + const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); } } - post(schema2, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); } } - function escapeJsonPtr(str2) { - return str2.replace(/~/g, "~0").replace(/\//g, "~1"); - } + exports.callRef = callRef; + exports.default = def; } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js -var require_resolve = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js"(exports) { +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js +var require_core2 = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); - exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; - var util_1 = require_util(); - var equal2 = require_fast_deep_equal(); - var traverse = require_json_schema_traverse(); - var SIMPLE_INLINED = /* @__PURE__ */ new Set([ - "type", - "format", - "pattern", - "maxLength", - "minLength", - "maxProperties", - "minProperties", - "maxItems", - "minItems", - "maximum", - "minimum", - "uniqueItems", - "multipleOf", - "required", - "enum", - "const" - ]); - function inlineRef(schema2, limit = true) { - if (typeof schema2 == "boolean") - return true; - if (limit === true) - return !hasRef(schema2); - if (!limit) - return false; - return countKeys(schema2) <= limit; - } - exports.inlineRef = inlineRef; - var REF_KEYWORDS = /* @__PURE__ */ new Set([ - "$ref", - "$recursiveRef", - "$recursiveAnchor", - "$dynamicRef", - "$dynamicAnchor" - ]); - function hasRef(schema2) { - for (const key in schema2) { - if (REF_KEYWORDS.has(key)) - return true; - const sch = schema2[key]; - if (Array.isArray(sch) && sch.some(hasRef)) - return true; - if (typeof sch == "object" && hasRef(sch)) - return true; + var id_1 = require_id(); + var ref_1 = require_ref(); + var core2 = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default + ]; + exports.default = core2; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js +var require_limitNumber = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var ops = codegen_1.operators; + var KWDs = { + maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } + }; + var error2 = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + var def = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error: error2, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); } - return false; - } - function countKeys(schema2) { - let count2 = 0; - for (const key in schema2) { - if (key === "$ref") - return Infinity; - count2++; - if (SIMPLE_INLINED.has(key)) - continue; - if (typeof schema2[key] == "object") { - (0, util_1.eachItem)(schema2[key], (sch) => count2 += countKeys(sch)); - } - if (count2 === Infinity) - return Infinity; + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js +var require_multipleOf = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error2 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` + }; + var def = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error: error2, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); } - return count2; - } - function getFullPath(resolver, id = "", normalize) { - if (normalize !== false) - id = normalizeId(id); - const p = resolver.parse(id); - return _getFullPath(resolver, p); - } - exports.getFullPath = getFullPath; - function _getFullPath(resolver, p) { - const serialized = resolver.serialize(p); - return serialized.split("#")[0] + "#"; - } - exports._getFullPath = _getFullPath; - var TRAILING_SLASH_HASH = /#\/?$/; - function normalizeId(id) { - return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; - } - exports.normalizeId = normalizeId; - function resolveUrl(resolver, baseId, id) { - id = normalizeId(id); - return resolver.resolve(baseId, id); - } - exports.resolveUrl = resolveUrl; - var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; - function getSchemaRefs(schema2, baseId) { - if (typeof schema2 == "boolean") - return {}; - const { schemaId, uriResolver } = this.opts; - const schId = normalizeId(schema2[schemaId] || baseId); - const baseIds = { "": schId }; - const pathPrefix = getFullPath(uriResolver, schId, false); - const localRefs = {}; - const schemaRefs = /* @__PURE__ */ new Set(); - traverse(schema2, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { - if (parentJsonPtr === void 0) - return; - const fullPath = pathPrefix + jsonPtr; - let innerBaseId = baseIds[parentJsonPtr]; - if (typeof sch[schemaId] == "string") - innerBaseId = addRef.call(this, sch[schemaId]); - addAnchor.call(this, sch.$anchor); - addAnchor.call(this, sch.$dynamicAnchor); - baseIds[jsonPtr] = innerBaseId; - function addRef(ref) { - const _resolve = this.opts.uriResolver.resolve; - ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); - if (schemaRefs.has(ref)) - throw ambiguos(ref); - schemaRefs.add(ref); - let schOrRef = this.refs[ref]; - if (typeof schOrRef == "string") - schOrRef = this.refs[schOrRef]; - if (typeof schOrRef == "object") { - checkAmbiguosRef(sch, schOrRef.schema, ref); - } else if (ref !== normalizeId(fullPath)) { - if (ref[0] === "#") { - checkAmbiguosRef(sch, localRefs[ref], ref); - localRefs[ref] = sch; - } else { - this.refs[ref] = fullPath; - } - } - return ref; - } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) - throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); - } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js +var require_ucs2length = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + function ucs2length(str2) { + const len = str2.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str2.charCodeAt(pos++); + if (value >= 55296 && value <= 56319 && pos < len) { + value = str2.charCodeAt(pos); + if ((value & 64512) === 56320) + pos++; } - }); - return localRefs; - function checkAmbiguosRef(sch1, sch2, ref) { - if (sch2 !== void 0 && !equal2(sch1, sch2)) - throw ambiguos(ref); - } - function ambiguos(ref) { - return new Error(`reference "${ref}" resolves to more than one schema`); } + return length; } - exports.getSchemaRefs = getSchemaRefs; + exports.default = ucs2length; + ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js -var require_validate = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js"(exports) { +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js +var require_limitLength = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); - exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; - var boolSchema_1 = require_boolSchema(); - var dataType_1 = require_dataType(); - var applicability_1 = require_applicability(); - var dataType_2 = require_dataType(); - var defaults_1 = require_defaults(); - var keyword_1 = require_keyword(); - var subschema_1 = require_subschema(); var codegen_1 = require_codegen(); - var names_1 = require_names(); - var resolve_1 = require_resolve(); var util_1 = require_util(); - var errors_1 = require_errors(); - function validateFunctionCode(it) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - topSchemaObjCode(it); - return; - } + var ucs2length_1 = require_ucs2length(); + var error2 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error: error2, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); } - validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); - } - exports.validateFunctionCode = validateFunctionCode; - function validateFunction({ gen, validateName, schema: schema2, schemaEnv, opts }, body) { - if (opts.code.es5) { - gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { - gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema2, opts)}`); - destructureValCxtES5(gen, opts); - gen.code(body); - }); - } else { - gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema2, opts)).code(body)); + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js +var require_pattern = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var util_1 = require_util(); + var codegen_1 = require_codegen(); + var error2 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` + }; + var def = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error: error2, + code(cxt) { + const { gen, data, $data, schema: schema2, schemaCode, it } = cxt; + const u = it.opts.unicodeRegExp ? "u" : ""; + if ($data) { + const { regExp } = it.opts.code; + const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); + const valid = gen.let("valid"); + gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); + cxt.fail$data((0, codegen_1._)`!${valid}`); + } else { + const regExp = (0, code_1.usePattern)(cxt, schema2); + cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); + } } - } - function destructureValCxt(opts) { - return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; - } - function destructureValCxtES5(gen, opts) { - gen.if(names_1.default.valCxt, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); - gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); - gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); - if (opts.dynamicRef) - gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); - }, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); - gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); - gen.var(names_1.default.rootData, names_1.default.data); - if (opts.dynamicRef) - gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); - }); - } - function topSchemaObjCode(it) { - const { schema: schema2, opts, gen } = it; - validateFunction(it, () => { - if (opts.$comment && schema2.$comment) - commentKeyword(it); - checkNoDefault(it); - gen.let(names_1.default.vErrors, null); - gen.let(names_1.default.errors, 0); - if (opts.unevaluated) - resetEvaluated(it); - typeAndKeywords(it); - returnResults(it); - }); - return; - } - function resetEvaluated(it) { - const { gen, validateName } = it; - it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); - } - function funcSourceUrl(schema2, opts) { - const schId = typeof schema2 == "object" && schema2[opts.schemaId]; - return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; - } - function subschemaCode(it, valid) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - subSchemaObjCode(it, valid); - return; - } - } - (0, boolSchema_1.boolOrEmptySchema)(it, valid); - } - function schemaCxtHasRules({ schema: schema2, self: self2 }) { - if (typeof schema2 == "boolean") - return !schema2; - for (const key in schema2) - if (self2.RULES.all[key]) - return true; - return false; - } - function isSchemaObj(it) { - return typeof it.schema != "boolean"; - } - function subSchemaObjCode(it, valid) { - const { schema: schema2, gen, opts } = it; - if (opts.$comment && schema2.$comment) - commentKeyword(it); - updateContext(it); - checkAsyncSchema(it); - const errsCount = gen.const("_errs", names_1.default.errors); - typeAndKeywords(it, errsCount); - gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - } - function checkKeywords(it) { - (0, util_1.checkUnknownRules)(it); - checkRefsAndKeywords(it); - } - function typeAndKeywords(it, errsCount) { - if (it.opts.jtd) - return schemaKeywords(it, [], false, errsCount); - const types = (0, dataType_1.getSchemaTypes)(it.schema); - const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); - schemaKeywords(it, types, !checkedTypes, errsCount); - } - function checkRefsAndKeywords(it) { - const { schema: schema2, errSchemaPath, opts, self: self2 } = it; - if (schema2.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema2, self2.RULES)) { - self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); - } - } - function checkNoDefault(it) { - const { schema: schema2, opts } = it; - if (schema2.default !== void 0 && opts.useDefaults && opts.strictSchema) { - (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); - } - } - function updateContext(it) { - const schId = it.schema[it.opts.schemaId]; - if (schId) - it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); - } - function checkAsyncSchema(it) { - if (it.schema.$async && !it.schemaEnv.$async) - throw new Error("async schema in sync schema"); - } - function commentKeyword({ gen, schemaEnv, schema: schema2, errSchemaPath, opts }) { - const msg = schema2.$comment; - if (opts.$comment === true) { - gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); - } else if (typeof opts.$comment == "function") { - const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; - const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); - gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); - } - } - function returnResults(it) { - const { gen, schemaEnv, validateName, ValidationError, opts } = it; - if (schemaEnv.$async) { - gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); - } else { - gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); - if (opts.unevaluated) - assignEvaluated(it); - gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); - } - } - function assignEvaluated({ gen, evaluated, props, items }) { - if (props instanceof codegen_1.Name) - gen.assign((0, codegen_1._)`${evaluated}.props`, props); - if (items instanceof codegen_1.Name) - gen.assign((0, codegen_1._)`${evaluated}.items`, items); - } - function schemaKeywords(it, types, typeErrors, errsCount) { - const { gen, schema: schema2, data, allErrors, opts, self: self2 } = it; - const { RULES: RULES2 } = self2; - if (schema2.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema2, RULES2))) { - gen.block(() => keywordCode(it, "$ref", RULES2.all.$ref.definition)); - return; + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js +var require_limitProperties = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error2 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error: error2, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); } - if (!opts.jtd) - checkStrictTypes(it, types); - gen.block(() => { - for (const group of RULES2.rules) - groupKeywords(group); - groupKeywords(RULES2.post); - }); - function groupKeywords(group) { - if (!(0, applicability_1.shouldUseGroup)(schema2, group)) + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js +var require_required = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error2 = { + message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` + }; + var def = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error: error2, + code(cxt) { + const { gen, schema: schema2, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema2.length === 0) return; - if (group.type) { - gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); - iterateKeywords(it, group); - if (types.length === 1 && types[0] === group.type && typeErrors) { - gen.else(); - (0, dataType_2.reportTypeError)(it); - } - gen.endIf(); - } else { - iterateKeywords(it, group); - } - if (!allErrors) - gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); - } - } - function iterateKeywords(it, group) { - const { gen, schema: schema2, opts: { useDefaults } } = it; - if (useDefaults) - (0, defaults_1.assignDefaults)(it, group.type); - gen.block(() => { - for (const rule of group.rules) { - if ((0, applicability_1.shouldUseRule)(schema2, rule)) { - keywordCode(it, rule.keyword, rule.definition, group.type); + const useLoop = schema2.length >= opts.loopRequired; + if (it.allErrors) + allErrorsMode(); + else + exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema2) { + if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } } } - }); - } - function checkStrictTypes(it, types) { - if (it.schemaEnv.meta || !it.opts.strictTypes) - return; - checkContextTypes(it, types); - if (!it.opts.allowUnionTypes) - checkMultipleTypes(it, types); - checkKeywordTypes(it, it.dataTypes); - } - function checkContextTypes(it, types) { - if (!types.length) - return; - if (!it.dataTypes.length) { - it.dataTypes = types; - return; - } - types.forEach((t) => { - if (!includesType(it.dataTypes, t)) { - strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); - } - }); - narrowSchemaTypes(it, types); - } - function checkMultipleTypes(it, ts) { - if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { - strictTypesError(it, "use allowUnionTypes to allow union type keyword"); - } - } - function checkKeywordTypes(it, ts) { - const rules = it.self.RULES.all; - for (const keyword in rules) { - const rule = rules[keyword]; - if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { - const { type: type2 } = rule.definition; - if (type2.length && !type2.some((t) => hasApplicableType(ts, t))) { - strictTypesError(it, `missing type "${type2.join(",")}" for keyword "${keyword}"`); + function allErrorsMode() { + if (useLoop || $data) { + cxt.block$data(codegen_1.nil, loopAllRequired); + } else { + for (const prop of schema2) { + (0, code_1.checkReportMissingProp)(cxt, prop); + } } } - } - } - function hasApplicableType(schTs, kwdT) { - return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); - } - function includesType(ts, t) { - return ts.includes(t) || t === "integer" && ts.includes("number"); - } - function narrowSchemaTypes(it, withTypes) { - const ts = []; - for (const t of it.dataTypes) { - if (includesType(withTypes, t)) - ts.push(t); - else if (withTypes.includes("integer") && t === "number") - ts.push("integer"); - } - it.dataTypes = ts; - } - function strictTypesError(it, msg) { - const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; - msg += ` at "${schemaPath}" (strictTypes)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); - } - var KeywordCxt = class { - constructor(it, def, keyword) { - (0, keyword_1.validateKeywordUsage)(it, def, keyword); - this.gen = it.gen; - this.allErrors = it.allErrors; - this.keyword = keyword; - this.data = it.data; - this.schema = it.schema[keyword]; - this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; - this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); - this.schemaType = def.schemaType; - this.parentSchema = it.schema; - this.params = {}; - this.it = it; - this.def = def; - if (this.$data) { - this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); - } else { - this.schemaCode = this.schemaValue; - if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { - throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } else { + gen.if((0, code_1.checkMissingProp)(cxt, schema2, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); } } - if ("code" in def ? def.trackErrors : def.errors !== false) { - this.errsCount = it.gen.const("_errs", names_1.default.errors); + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); } - } - result(condition, successAction, failAction) { - this.failResult((0, codegen_1.not)(condition), successAction, failAction); - } - failResult(condition, successAction, failAction) { - this.gen.if(condition); - if (failAction) - failAction(); - else - this.error(); - if (successAction) { - this.gen.else(); - successAction(); - if (this.allErrors) - this.gen.endIf(); - } else { - if (this.allErrors) - this.gen.endIf(); - else - this.gen.else(); + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); } } - pass(condition, failAction) { - this.failResult((0, codegen_1.not)(condition), void 0, failAction); + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js +var require_limitItems = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error2 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error: error2, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); } - fail(condition) { - if (condition === void 0) { - this.error(); - if (!this.allErrors) - this.gen.if(false); + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js +var require_equal = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var equal2 = require_fast_deep_equal(); + equal2.code = 'require("ajv/dist/runtime/equal").default'; + exports.default = equal2; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js +var require_uniqueItems = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var dataType_1 = require_dataType(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + var error2 = { + message: ({ params: { i: i2, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i2} are identical)`, + params: ({ params: { i: i2, j } }) => (0, codegen_1._)`{i: ${i2}, j: ${j}}` + }; + var def = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error: error2, + code(cxt) { + const { gen, data, $data, schema: schema2, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema2) return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i2 = gen.let("i", (0, codegen_1._)`${data}.length`); + const j = gen.let("j"); + cxt.setParams({ i: i2, j }); + gen.assign(valid, true); + gen.if((0, codegen_1._)`${i2} > 1`, () => (canOptimize() ? loopN : loopN2)(i2, j)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); + } + function loopN(i2, j) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._)`{}`); + gen.for((0, codegen_1._)`;${i2}--;`, () => { + gen.let(item, (0, codegen_1._)`${data}[${i2}]`); + gen.if(wrongType, (0, codegen_1._)`continue`); + if (itemTypes.length > 1) + gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); + gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }).code((0, codegen_1._)`${indices}[${item}] = ${i2}`); + }); + } + function loopN2(i2, j) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._)`;${i2}--;`, () => gen.for((0, codegen_1._)`${j} = ${i2}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i2}], ${data}[${j}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); } - this.gen.if(condition); - this.error(); - if (this.allErrors) - this.gen.endIf(); - else - this.gen.else(); - } - fail$data(condition) { - if (!this.$data) - return this.fail(condition); - const { schemaCode } = this; - this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); } - error(append, errorParams, errorPaths) { - if (errorParams) { - this.setParams(errorParams); - this._error(append, errorPaths); - this.setParams({}); - return; + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js +var require_const = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + var error2 = { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` + }; + var def = { + keyword: "const", + $data: true, + error: error2, + code(cxt) { + const { gen, data, $data, schemaCode, schema: schema2 } = cxt; + if ($data || schema2 && typeof schema2 == "object") { + cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + } else { + cxt.fail((0, codegen_1._)`${schema2} !== ${data}`); } - this._error(append, errorPaths); } - _error(append, errorPaths) { - ; - (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); - } - $dataError() { - (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); - } - reset() { - if (this.errsCount === void 0) - throw new Error('add "trackErrors" to keyword definition'); - (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); - } - ok(cond) { - if (!this.allErrors) - this.gen.if(cond); - } - setParams(obj, assign2) { - if (assign2) - Object.assign(this.params, obj); - else - this.params = obj; - } - block$data(valid, codeBlock, $dataValid = codegen_1.nil) { - this.gen.block(() => { - this.check$data(valid, $dataValid); - codeBlock(); - }); - } - check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { - if (!this.$data) - return; - const { gen, schemaCode, schemaType, def } = this; - gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); - if (valid !== codegen_1.nil) - gen.assign(valid, true); - if (schemaType.length || def.validateSchema) { - gen.elseIf(this.invalid$data()); - this.$dataError(); - if (valid !== codegen_1.nil) - gen.assign(valid, false); + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js +var require_enum = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + var error2 = { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }; + var def = { + keyword: "enum", + schemaType: "array", + $data: true, + error: error2, + code(cxt) { + const { gen, data, $data, schema: schema2, schemaCode, it } = cxt; + if (!$data && schema2.length === 0) + throw new Error("enum must have non-empty array"); + const useLoop = schema2.length >= it.opts.loopEnum; + let eql; + const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } else { + if (!Array.isArray(schema2)) + throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema2.map((_x, i2) => equalCode(vSchema, i2))); } - gen.else(); - } - invalid$data() { - const { gen, schemaCode, schemaType, def, it } = this; - return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); - function wrong$DataType() { - if (schemaType.length) { - if (!(schemaCode instanceof codegen_1.Name)) - throw new Error("ajv implementation error"); - const st = Array.isArray(schemaType) ? schemaType : [schemaType]; - return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; - } - return codegen_1.nil; + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); } - function invalid$DataSchema() { - if (def.validateSchema) { - const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); - return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; - } - return codegen_1.nil; + function equalCode(vSchema, i2) { + const sch = schema2[i2]; + return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i2}])` : (0, codegen_1._)`${data} === ${sch}`; } } - subschema(appl, valid) { - const subschema = (0, subschema_1.getSubschema)(this.it, appl); - (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); - (0, subschema_1.extendSubschemaMode)(subschema, appl); - const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; - subschemaCode(nextContext, valid); - return nextContext; - } - mergeEvaluated(schemaCxt, toName) { - const { it, gen } = this; - if (!it.opts.unevaluated) + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js +var require_validation = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var limitNumber_1 = require_limitNumber(); + var multipleOf_1 = require_multipleOf(); + var limitLength_1 = require_limitLength(); + var pattern_1 = require_pattern(); + var limitProperties_1 = require_limitProperties(); + var required_1 = require_required(); + var limitItems_1 = require_limitItems(); + var uniqueItems_1 = require_uniqueItems(); + var const_1 = require_const(); + var enum_1 = require_enum(); + var validation = [ + // number + limitNumber_1.default, + multipleOf_1.default, + // string + limitLength_1.default, + pattern_1.default, + // object + limitProperties_1.default, + required_1.default, + // array + limitItems_1.default, + uniqueItems_1.default, + // any + { keyword: "type", schemaType: ["string", "array"] }, + { keyword: "nullable", schemaType: "boolean" }, + const_1.default, + enum_1.default + ]; + exports.default = validation; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js +var require_additionalItems = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAdditionalItems = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error2 = { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }; + var def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error: error2, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); return; - if (it.props !== true && schemaCxt.props !== void 0) { - it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); - } - if (it.items !== true && schemaCxt.items !== void 0) { - it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); - } - } - mergeValidEvaluated(schemaCxt, valid) { - const { it, gen } = this; - if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { - gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); - return true; } + validateAdditionalItems(cxt, items); } }; - exports.KeywordCxt = KeywordCxt; - function keywordCode(it, keyword, def, ruleType) { - const cxt = new KeywordCxt(it, def, keyword); - if ("code" in def) { - def.code(cxt, ruleType); - } else if (cxt.$data && def.validate) { - (0, keyword_1.funcKeywordCode)(cxt, def); - } else if ("macro" in def) { - (0, keyword_1.macroKeywordCode)(cxt, def); - } else if (def.compile || def.validate) { - (0, keyword_1.funcKeywordCode)(cxt, def); + function validateAdditionalItems(cxt, items) { + const { gen, schema: schema2, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema2 === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); + } else if (typeof schema2 == "object" && !(0, util_1.alwaysValidSchema)(it, schema2)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i2) => { + cxt.subschema({ keyword, dataProp: i2, dataPropType: util_1.Type.Num }, valid); + if (!it.allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); } } - var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; - var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; - function getData($data, { dataLevel, dataNames, dataPathArr }) { - let jsonPointer; - let data; - if ($data === "") - return names_1.default.rootData; - if ($data[0] === "/") { - if (!JSON_POINTER.test($data)) - throw new Error(`Invalid JSON-pointer: ${$data}`); - jsonPointer = $data; - data = names_1.default.rootData; - } else { - const matches = RELATIVE_JSON_POINTER.exec($data); - if (!matches) - throw new Error(`Invalid JSON-pointer: ${$data}`); - const up = +matches[1]; - jsonPointer = matches[2]; - if (jsonPointer === "#") { - if (up >= dataLevel) - throw new Error(errorMsg("property/index", up)); - return dataPathArr[dataLevel - up]; - } - if (up > dataLevel) - throw new Error(errorMsg("data", up)); - data = dataNames[dataLevel - up]; - if (!jsonPointer) - return data; + exports.validateAdditionalItems = validateAdditionalItems; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js +var require_items = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTuple = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code2(); + var def = { + keyword: "items", + type: "array", + schemaType: ["object", "array", "boolean"], + before: "uniqueItems", + code(cxt) { + const { schema: schema2, it } = cxt; + if (Array.isArray(schema2)) + return validateTuple(cxt, "additionalItems", schema2); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema2)) + return; + cxt.ok((0, code_1.validateArray)(cxt)); } - let expr = data; - const segments = jsonPointer.split("/"); - for (const segment of segments) { - if (segment) { - data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; - expr = (0, codegen_1._)`${expr} && ${data}`; - } + }; + function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) { + it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); } - return expr; - function errorMsg(pointerType, up) { - return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + schArr.forEach((sch, i2) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + gen.if((0, codegen_1._)`${len} > ${i2}`, () => cxt.subschema({ + keyword, + schemaProp: i2, + dataProp: i2 + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l = schArr.length; + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } } } - exports.getData = getData; + exports.validateTuple = validateTuple; + exports.default = def; } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js -var require_validation_error = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js"(exports) { +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js +var require_prefixItems = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); - var ValidationError = class extends Error { - constructor(errors) { - super("validation failed"); - this.errors = errors; - this.ajv = this.validation = true; - } + var items_1 = require_items(); + var def = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items") }; - exports.default = ValidationError; + exports.default = def; } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js -var require_ref_error = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js"(exports) { +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js +var require_items2020 = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); - var resolve_1 = require_resolve(); - var MissingRefError = class extends Error { - constructor(resolver, baseId, ref, msg) { - super(msg || `can't resolve reference ${ref} from id ${baseId}`); - this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); - this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code2(); + var additionalItems_1 = require_additionalItems(); + var error2 = { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }; + var def = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error: error2, + code(cxt) { + const { schema: schema2, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema2)) + return; + if (prefixItems) + (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else + cxt.ok((0, code_1.validateArray)(cxt)); } }; - exports.default = MissingRefError; + exports.default = def; } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js -var require_compile = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js"(exports) { +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js +var require_contains = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); - exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; var codegen_1 = require_codegen(); - var validation_error_1 = require_validation_error(); - var names_1 = require_names(); - var resolve_1 = require_resolve(); var util_1 = require_util(); - var validate_1 = require_validate(); - var SchemaEnv = class { - constructor(env) { - var _a; - this.refs = {}; - this.dynamicAnchors = {}; - let schema2; - if (typeof env.schema == "object") - schema2 = env.schema; - this.schema = env.schema; - this.schemaId = env.schemaId; - this.root = env.root || this; - this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema2 === null || schema2 === void 0 ? void 0 : schema2[env.schemaId || "$id"]); - this.schemaPath = env.schemaPath; - this.localRefs = env.localRefs; - this.meta = env.meta; - this.$async = schema2 === null || schema2 === void 0 ? void 0 : schema2.$async; - this.refs = {}; - } + var error2 = { + message: ({ params: { min: min3, max: max3 } }) => max3 === void 0 ? (0, codegen_1.str)`must contain at least ${min3} valid item(s)` : (0, codegen_1.str)`must contain at least ${min3} and no more than ${max3} valid item(s)`, + params: ({ params: { min: min3, max: max3 } }) => max3 === void 0 ? (0, codegen_1._)`{minContains: ${min3}}` : (0, codegen_1._)`{minContains: ${min3}, maxContains: ${max3}}` }; - exports.SchemaEnv = SchemaEnv; - function compileSchema(sch) { - const _sch = getCompilingSchema.call(this, sch); - if (_sch) - return _sch; - const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); - const { es5, lines } = this.opts.code; - const { ownProperties } = this.opts; - const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); - let _ValidationError; - if (sch.$async) { - _ValidationError = gen.scopeValue("Error", { - ref: validation_error_1.default, - code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` - }); - } - const validateName = gen.scopeName("validate"); - sch.validateName = validateName; - const schemaCxt = { - gen, - allErrors: this.opts.allErrors, - data: names_1.default.data, - parentData: names_1.default.parentData, - parentDataProperty: names_1.default.parentDataProperty, - dataNames: [names_1.default.data], - dataPathArr: [codegen_1.nil], - // TODO can its length be used as dataLevel if nil is removed? - dataLevel: 0, - dataTypes: [], - definedProperties: /* @__PURE__ */ new Set(), - topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), - validateName, - ValidationError: _ValidationError, - schema: sch.schema, - schemaEnv: sch, - rootId, - baseId: sch.baseId || rootId, - schemaPath: codegen_1.nil, - errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), - errorPath: (0, codegen_1._)`""`, - opts: this.opts, - self: this - }; - let sourceCode; - try { - this._compilations.add(sch); - (0, validate_1.validateFunctionCode)(schemaCxt); - gen.optimize(this.opts.code.optimize); - const validateCode = gen.toString(); - sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; - if (this.opts.code.process) - sourceCode = this.opts.code.process(sourceCode, sch); - const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); - const validate2 = makeValidate(this, this.scope.get()); - this.scope.value(validateName, { ref: validate2 }); - validate2.errors = null; - validate2.schema = sch.schema; - validate2.schemaEnv = sch; - if (sch.$async) - validate2.$async = true; - if (this.opts.code.source === true) { - validate2.source = { validateName, validateCode, scopeValues: gen._values }; + var def = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error: error2, + code(cxt) { + const { gen, schema: schema2, parentSchema, data, it } = cxt; + let min3; + let max3; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min3 = minContains === void 0 ? 1 : minContains; + max3 = maxContains; + } else { + min3 = 1; } - if (this.opts.unevaluated) { - const { props, items } = schemaCxt; - validate2.evaluated = { - props: props instanceof codegen_1.Name ? void 0 : props, - items: items instanceof codegen_1.Name ? void 0 : items, - dynamicProps: props instanceof codegen_1.Name, - dynamicItems: items instanceof codegen_1.Name - }; - if (validate2.source) - validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated); + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + cxt.setParams({ min: min3, max: max3 }); + if (max3 === void 0 && min3 === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; } - sch.validate = validate2; - return sch; - } catch (e3) { - delete sch.validate; - delete sch.validateName; - if (sourceCode) - this.logger.error("Error compiling schema, function code:", sourceCode); - throw e3; - } finally { - this._compilations.delete(sch); - } - } - exports.compileSchema = compileSchema; - function resolveRef(root, baseId, ref) { - var _a; - ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); - const schOrFunc = root.refs[ref]; - if (schOrFunc) - return schOrFunc; - let _sch = resolve3.call(this, root, ref); - if (_sch === void 0) { - const schema2 = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; - const { schemaId } = this.opts; - if (schema2) - _sch = new SchemaEnv({ schema: schema2, schemaId, root, baseId }); - } - if (_sch === void 0) - return; - return root.refs[ref] = inlineOrCompile.call(this, _sch); - } - exports.resolveRef = resolveRef; - function inlineOrCompile(sch) { - if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) - return sch.schema; - return sch.validate ? sch : compileSchema.call(this, sch); - } - function getCompilingSchema(schEnv) { - for (const sch of this._compilations) { - if (sameSchemaEnv(sch, schEnv)) - return sch; - } - } - exports.getCompilingSchema = getCompilingSchema; - function sameSchemaEnv(s1, s2) { - return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; - } - function resolve3(root, ref) { - let sch; - while (typeof (sch = this.refs[ref]) == "string") - ref = sch; - return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); - } - function resolveSchema(root, ref) { - const p = this.opts.uriResolver.parse(ref); - const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); - let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); - if (Object.keys(root.schema).length > 0 && refPath === baseId) { - return getJsonPointer.call(this, p, root); - } - const id = (0, resolve_1.normalizeId)(refPath); - const schOrRef = this.refs[id] || this.schemas[id]; - if (typeof schOrRef == "string") { - const sch = resolveSchema.call(this, root, schOrRef); - if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") + if (max3 !== void 0 && min3 > max3) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); return; - return getJsonPointer.call(this, p, sch); + } + if ((0, util_1.alwaysValidSchema)(it, schema2)) { + let cond = (0, codegen_1._)`${len} >= ${min3}`; + if (max3 !== void 0) + cond = (0, codegen_1._)`${cond} && ${len} <= ${max3}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max3 === void 0 && min3 === 1) { + validateItems(valid, () => gen.if(valid, () => gen.break())); + } else if (min3 === 0) { + gen.let(valid, true); + if (max3 !== void 0) + gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); + } else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count2 = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count2))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i2) => { + cxt.subschema({ + keyword: "contains", + dataProp: i2, + dataPropType: util_1.Type.Num, + compositeRule: true + }, _valid); + block(); + }); + } + function checkLimits(count2) { + gen.code((0, codegen_1._)`${count2}++`); + if (max3 === void 0) { + gen.if((0, codegen_1._)`${count2} >= ${min3}`, () => gen.assign(valid, true).break()); + } else { + gen.if((0, codegen_1._)`${count2} > ${max3}`, () => gen.assign(valid, false).break()); + if (min3 === 1) + gen.assign(valid, true); + else + gen.if((0, codegen_1._)`${count2} >= ${min3}`, () => gen.assign(valid, true)); + } + } } - if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") - return; - if (!schOrRef.validate) - compileSchema.call(this, schOrRef); - if (id === (0, resolve_1.normalizeId)(ref)) { - const { schema: schema2 } = schOrRef; - const { schemaId } = this.opts; - const schId = schema2[schemaId]; - if (schId) - baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - return new SchemaEnv({ schema: schema2, schemaId, root, baseId }); + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js +var require_dependencies = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code2(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}` + // TODO change to reference + }; + var def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); } - return getJsonPointer.call(this, p, schOrRef); + }; + function splitDependencies({ schema: schema2 }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema2) { + if (key === "__proto__") + continue; + const deps = Array.isArray(schema2[key]) ? propertyDeps : schemaDeps; + deps[key] = schema2[key]; + } + return [propertyDeps, schemaDeps]; } - exports.resolveSchema = resolveSchema; - var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ - "properties", - "patternProperties", - "enum", - "dependencies", - "definitions" - ]); - function getJsonPointer(parsedRef, { baseId, schema: schema2, root }) { - var _a; - if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) return; - for (const part of parsedRef.fragment.slice(1).split("/")) { - if (typeof schema2 === "boolean") - return; - const partSchema = schema2[(0, util_1.unescapeFragment)(part)]; - if (partSchema === void 0) - return; - schema2 = partSchema; - const schId = typeof schema2 === "object" && schema2[this.opts.schemaId]; - if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { - baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) + continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", ") + }); + if (it.allErrors) { + gen.if(hasProperty, () => { + for (const depProp of deps) { + (0, code_1.checkReportMissingProp)(cxt, depProp); + } + }); + } else { + gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); } } - let env; - if (typeof schema2 != "boolean" && schema2.$ref && !(0, util_1.schemaHasRulesButRef)(schema2, this.RULES)) { - const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema2.$ref); - env = resolveSchema.call(this, root, $ref); + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) + continue; + gen.if( + (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), + () => { + const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, + () => gen.var(valid, true) + // TODO var + ); + cxt.ok(valid); } - const { schemaId } = this.opts; - env = env || new SchemaEnv({ schema: schema2, schemaId, root, baseId }); - if (env.schema !== env.root.schema) - return env; - return void 0; } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def; } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json -var require_data = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json"(exports, module) { - module.exports = { - $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", - description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js +var require_propertyNames = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error2 = { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` + }; + var def = { + keyword: "propertyNames", type: "object", - required: ["$data"], - properties: { - $data: { - type: "string", - anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] - } - }, - additionalProperties: false + schemaType: ["object", "boolean"], + error: error2, + code(cxt) { + const { gen, schema: schema2, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema2)) + return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) + gen.break(); + }); + }); + cxt.ok(valid); + } }; + exports.default = def; } }); -// node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js -var require_utils = __commonJS({ - "node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js"(exports, module) { +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js +var require_additionalProperties = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) { "use strict"; - var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); - var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); - function stringArrayToHexStripped(input) { - let acc = ""; - let code = 0; - let i2 = 0; - for (i2 = 0; i2 < input.length; i2++) { - code = input[i2].charCodeAt(0); - if (code === 48) { - continue; - } - if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { - return ""; - } - acc += input[i2]; - break; - } - for (i2 += 1; i2 < input.length; i2++) { - code = input[i2].charCodeAt(0); - if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { - return ""; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var util_1 = require_util(); + var error2 = { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` + }; + var def = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error: error2, + code(cxt) { + const { gen, schema: schema2, parentSchema, data, errsCount, it } = cxt; + if (!errsCount) + throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema2)) + return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) + additionalPropertyCode(key); + else + gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); } - acc += input[i2]; - } - return acc; - } - var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); - function consumeIsZone(buffer) { - buffer.length = 0; - return true; - } - function consumeHextets(buffer, address, output) { - if (buffer.length) { - const hex2 = stringArrayToHexStripped(buffer); - if (hex2 !== "") { - address.push(hex2); - } else { - output.error = true; - return false; + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } else if (props.length) { + definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); + } else { + definedProp = codegen_1.nil; + } + if (patProps.length) { + definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); + } + return (0, codegen_1.not)(definedProp); } - buffer.length = 0; - } - return true; - } - function getIPV6(input) { - let tokenCount = 0; - const output = { error: false, address: "", zone: "" }; - const address = []; - const buffer = []; - let endipv6Encountered = false; - let endIpv6 = false; - let consume = consumeHextets; - for (let i2 = 0; i2 < input.length; i2++) { - const cursor = input[i2]; - if (cursor === "[" || cursor === "]") { - continue; + function deleteAdditional(key) { + gen.code((0, codegen_1._)`delete ${data}[${key}]`); } - if (cursor === ":") { - if (endipv6Encountered === true) { - endIpv6 = true; - } - if (!consume(buffer, address, output)) { - break; + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || opts.removeAdditional && schema2 === false) { + deleteAdditional(key); + return; } - if (++tokenCount > 7) { - output.error = true; - break; + if (schema2 === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) + gen.break(); + return; } - if (i2 > 0 && input[i2 - 1] === ":") { - endipv6Encountered = true; + if (typeof schema2 == "object" && !(0, util_1.alwaysValidSchema)(it, schema2)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } else { + applyAdditionalSchema(key, valid); + if (!allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } } - address.push(":"); - continue; - } else if (cursor === "%") { - if (!consume(buffer, address, output)) { - break; + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }; + if (errors === false) { + Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false + }); } - consume = consumeIsZone; - } else { - buffer.push(cursor); - continue; + cxt.subschema(subschema, valid); } } - if (buffer.length) { - if (consume === consumeIsZone) { - output.zone = buffer.join(""); - } else if (endIpv6) { - address.push(buffer.join("")); - } else { - address.push(stringArrayToHexStripped(buffer)); + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js +var require_properties = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var validate_1 = require_validate(); + var code_1 = require_code2(); + var util_1 = require_util(); + var additionalProperties_1 = require_additionalProperties(); + var def = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema: schema2, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { + additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); } - } - output.address = address.join(""); - return output; - } - function normalizeIPv6(host) { - if (findToken(host, ":") < 2) { - return { host, isIPV6: false }; - } - const ipv62 = getIPV6(host); - if (!ipv62.error) { - let newHost = ipv62.address; - let escapedHost = ipv62.address; - if (ipv62.zone) { - newHost += "%" + ipv62.zone; - escapedHost += "%25" + ipv62.zone; + const allProps = (0, code_1.allSchemaProperties)(schema2); + for (const prop of allProps) { + it.definedProperties.add(prop); } - return { host: newHost, isIPV6: true, escapedHost }; - } else { - return { host, isIPV6: false }; - } - } - function findToken(str2, token) { - let ind = 0; - for (let i2 = 0; i2 < str2.length; i2++) { - if (str2[i2] === token) ind++; - } - return ind; - } - function removeDotSegments(path) { - let input = path; - const output = []; - let nextSlash = -1; - let len = 0; - while (len = input.length) { - if (len === 1) { - if (input === ".") { - break; - } else if (input === "/") { - output.push("/"); - break; + if (it.opts.unevaluated && allProps.length && it.props !== true) { + it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + } + const properties2 = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema2[p])); + if (properties2.length === 0) + return; + const valid = gen.name("valid"); + for (const prop of properties2) { + if (hasDefault(prop)) { + applyPropertySchema(prop); } else { - output.push(input); - break; - } - } else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") { - break; - } else if (input[1] === "/") { - input = input.slice(2); - continue; - } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); - break; - } - } - } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) { - output.pop(); - } - output.push("/"); - break; + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) + gen.else().var(valid, true); + gen.endIf(); } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); - continue; + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema2[prop].default !== void 0; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop + }, valid); + } + } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js +var require_patternProperties = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var util_2 = require_util(); + var def = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema: schema2, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema2); + const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema2[p])); + if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { + return; + } + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) { + it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + } + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) + checkMatchingProperties(pat); + if (it.allErrors) { + validateProperties(pat); + } else { + gen.var(valid, true); + validateProperties(pat); + gen.if(valid); } - } else if (input[1] === "/") { - input = input.slice(2); - continue; } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); - continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) { - output.pop(); - } - continue; - } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) { + if (new RegExp(pat).test(prop)) { + (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); } } } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); - break; - } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) { + cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str + }, valid); + } + if (it.opts.unevaluated && props !== true) { + gen.assign((0, codegen_1._)`${props}[${key}]`, true); + } else if (!alwaysValid && !it.allErrors) { + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + }); + }); } } - return output.join(""); - } - function normalizeComponentEncoding(component, esc2) { - const func = esc2 !== true ? escape : unescape; - if (component.scheme !== void 0) { - component.scheme = func(component.scheme); - } - if (component.userinfo !== void 0) { - component.userinfo = func(component.userinfo); - } - if (component.host !== void 0) { - component.host = func(component.host); - } - if (component.path !== void 0) { - component.path = func(component.path); - } - if (component.query !== void 0) { - component.query = func(component.query); - } - if (component.fragment !== void 0) { - component.fragment = func(component.fragment); - } - return component; - } - function recomposeAuthority(component) { - const uriTokens = []; - if (component.userinfo !== void 0) { - uriTokens.push(component.userinfo); - uriTokens.push("@"); - } - if (component.host !== void 0) { - let host = unescape(component.host); - if (!isIPv4(host)) { - const ipV6res = normalizeIPv6(host); - if (ipV6res.isIPV6 === true) { - host = `[${ipV6res.escapedHost}]`; - } else { - host = component.host; - } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js +var require_not = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + var def = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema: schema2, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema2)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js +var require_anyOf = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var def = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: code_1.validateUnion, + error: { message: "must match a schema in anyOf" } + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js +var require_oneOf = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error2 = { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` + }; + var def = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error: error2, + code(cxt) { + const { gen, schema: schema2, parentSchema, it } = cxt; + if (!Array.isArray(schema2)) + throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) + return; + const schArr = schema2; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i2) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) { + gen.var(schValid, true); + } else { + schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i2, + compositeRule: true + }, schValid); + } + if (i2 > 0) { + gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i2}]`).else(); + } + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i2); + if (schCxt) + cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); } - uriTokens.push(host); } - if (typeof component.port === "number" || typeof component.port === "string") { - uriTokens.push(":"); - uriTokens.push(String(component.port)); + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js +var require_allOf = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + var def = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema: schema2, it } = cxt; + if (!Array.isArray(schema2)) + throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema2.forEach((sch, i2) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i2 }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); } - return uriTokens.length ? uriTokens.join("") : void 0; - } - module.exports = { - nonSimpleDomain, - recomposeAuthority, - normalizeComponentEncoding, - removeDotSegments, - isIPv4, - isUUID, - normalizeIPv6, - stringArrayToHexStripped }; + exports.default = def; } }); -// node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js -var require_schemes = __commonJS({ - "node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js"(exports, module) { +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js +var require_if = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) { "use strict"; - var { isUUID } = require_utils(); - var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; - var supportedSchemeNames = ( - /** @type {const} */ - [ - "http", - "https", - "ws", - "wss", - "urn", - "urn:uuid" - ] - ); - function isValidSchemeName(name315) { - return supportedSchemeNames.indexOf( - /** @type {*} */ - name315 - ) !== -1; - } - function wsIsSecure(wsComponent) { - if (wsComponent.secure === true) { - return true; - } else if (wsComponent.secure === false) { - return false; - } else if (wsComponent.scheme) { - return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); - } else { - return false; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error2 = { + message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` + }; + var def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error: error2, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === void 0 && parentSchema.else === void 0) { + (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); + } + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) + return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } else if (hasThen) { + gen.if(schValid, validateClause("then")); + } else { + gen.if((0, codegen_1.not)(schValid), validateClause("else")); + } + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) + gen.assign(ifClause, (0, codegen_1._)`${keyword}`); + else + cxt.setParams({ ifClause: keyword }); + }; + } } + }; + function hasSchema(it, keyword) { + const schema2 = it.schema[keyword]; + return schema2 !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema2); } - function httpParse(component) { - if (!component.host) { - component.error = component.error || "HTTP URIs must have a host."; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js +var require_thenElse = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + var def = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === void 0) + (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); } - return component; + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js +var require_applicator = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var additionalItems_1 = require_additionalItems(); + var prefixItems_1 = require_prefixItems(); + var items_1 = require_items(); + var items2020_1 = require_items2020(); + var contains_1 = require_contains(); + var dependencies_1 = require_dependencies(); + var propertyNames_1 = require_propertyNames(); + var additionalProperties_1 = require_additionalProperties(); + var properties_1 = require_properties(); + var patternProperties_1 = require_patternProperties(); + var not_1 = require_not(); + var anyOf_1 = require_anyOf(); + var oneOf_1 = require_oneOf(); + var allOf_1 = require_allOf(); + var if_1 = require_if(); + var thenElse_1 = require_thenElse(); + function getApplicator(draft2020 = false) { + const applicator = [ + // any + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + // object + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default + ]; + if (draft2020) + applicator.push(prefixItems_1.default, items2020_1.default); + else + applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; } - function httpSerialize(component) { - const secure = String(component.scheme).toLowerCase() === "https"; - if (component.port === (secure ? 443 : 80) || component.port === "") { - component.port = void 0; - } - if (!component.path) { - component.path = "/"; - } - return component; - } - function wsParse(wsComponent) { - wsComponent.secure = wsIsSecure(wsComponent); - wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); - wsComponent.path = void 0; - wsComponent.query = void 0; - return wsComponent; - } - function wsSerialize(wsComponent) { - if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") { - wsComponent.port = void 0; - } - if (typeof wsComponent.secure === "boolean") { - wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; - wsComponent.secure = void 0; - } - if (wsComponent.resourceName) { - const [path, query] = wsComponent.resourceName.split("?"); - wsComponent.path = path && path !== "/" ? path : void 0; - wsComponent.query = query; - wsComponent.resourceName = void 0; - } - wsComponent.fragment = void 0; - return wsComponent; - } - function urnParse(urnComponent, options) { - if (!urnComponent.path) { - urnComponent.error = "URN can not be parsed"; - return urnComponent; - } - const matches = urnComponent.path.match(URN_REG); - if (matches) { - const scheme = options.scheme || urnComponent.scheme || "urn"; - urnComponent.nid = matches[1].toLowerCase(); - urnComponent.nss = matches[2]; - const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`; - const schemeHandler = getSchemeHandler(urnScheme); - urnComponent.path = void 0; - if (schemeHandler) { - urnComponent = schemeHandler.parse(urnComponent, options); - } - } else { - urnComponent.error = urnComponent.error || "URN can not be parsed."; - } - return urnComponent; - } - function urnSerialize(urnComponent, options) { - if (urnComponent.nid === void 0) { - throw new Error("URN without nid cannot be serialized"); - } - const scheme = options.scheme || urnComponent.scheme || "urn"; - const nid = urnComponent.nid.toLowerCase(); - const urnScheme = `${scheme}:${options.nid || nid}`; - const schemeHandler = getSchemeHandler(urnScheme); - if (schemeHandler) { - urnComponent = schemeHandler.serialize(urnComponent, options); - } - const uriComponent = urnComponent; - const nss = urnComponent.nss; - uriComponent.path = `${nid || options.nid}:${nss}`; - options.skipEscape = true; - return uriComponent; - } - function urnuuidParse(urnComponent, options) { - const uuidComponent = urnComponent; - uuidComponent.uuid = uuidComponent.nss; - uuidComponent.nss = void 0; - if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) { - uuidComponent.error = uuidComponent.error || "UUID is not valid."; - } - return uuidComponent; - } - function urnuuidSerialize(uuidComponent) { - const urnComponent = uuidComponent; - urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); - return urnComponent; - } - var http = ( - /** @type {SchemeHandler} */ - { - scheme: "http", - domainHost: true, - parse: httpParse, - serialize: httpSerialize - } - ); - var https = ( - /** @type {SchemeHandler} */ - { - scheme: "https", - domainHost: http.domainHost, - parse: httpParse, - serialize: httpSerialize - } - ); - var ws = ( - /** @type {SchemeHandler} */ - { - scheme: "ws", - domainHost: true, - parse: wsParse, - serialize: wsSerialize - } - ); - var wss = ( - /** @type {SchemeHandler} */ - { - scheme: "wss", - domainHost: ws.domainHost, - parse: ws.parse, - serialize: ws.serialize - } - ); - var urn = ( - /** @type {SchemeHandler} */ - { - scheme: "urn", - parse: urnParse, - serialize: urnSerialize, - skipNormalize: true - } - ); - var urnuuid = ( - /** @type {SchemeHandler} */ - { - scheme: "urn:uuid", - parse: urnuuidParse, - serialize: urnuuidSerialize, - skipNormalize: true - } - ); - var SCHEMES = ( - /** @type {Record} */ - { - http, - https, - ws, - wss, - urn, - "urn:uuid": urnuuid - } - ); - Object.setPrototypeOf(SCHEMES, null); - function getSchemeHandler(scheme) { - return scheme && (SCHEMES[ - /** @type {SchemeName} */ - scheme - ] || SCHEMES[ - /** @type {SchemeName} */ - scheme.toLowerCase() - ]) || void 0; - } - module.exports = { - wsIsSecure, - SCHEMES, - isValidSchemeName, - getSchemeHandler - }; + exports.default = getApplicator; } }); -// node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js -var require_fast_uri = __commonJS({ - "node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js"(exports, module) { +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js +var require_format = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js"(exports) { "use strict"; - var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); - var { SCHEMES, getSchemeHandler } = require_schemes(); - function normalize(uri, options) { - if (typeof uri === "string") { - uri = /** @type {T} */ - serialize(parse6(uri, options), options); - } else if (typeof uri === "object") { - uri = /** @type {T} */ - parse6(serialize(uri, options), options); - } - return uri; - } - function resolve3(baseURI, relativeURI, options) { - const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; - const resolved = resolveComponent(parse6(baseURI, schemelessOptions), parse6(relativeURI, schemelessOptions), schemelessOptions, true); - schemelessOptions.skipEscape = true; - return serialize(resolved, schemelessOptions); - } - function resolveComponent(base, relative, options, skipNormalization) { - const target = {}; - if (!skipNormalization) { - base = parse6(serialize(base, options), options); - relative = parse6(serialize(relative, options), options); - } - options = options || {}; - if (!options.tolerant && relative.scheme) { - target.scheme = relative.scheme; - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (!relative.path) { - target.path = base.path; - if (relative.query !== void 0) { - target.query = relative.query; - } else { - target.query = base.query; - } - } else { - if (relative.path[0] === "/") { - target.path = removeDotSegments(relative.path); - } else { - if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) { - target.path = "/" + relative.path; - } else if (!base.path) { - target.path = relative.path; - } else { - target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; - } - target.path = removeDotSegments(target.path); - } - target.query = relative.query; - } - target.userinfo = base.userinfo; - target.host = base.host; - target.port = base.port; - } - target.scheme = base.scheme; - } - target.fragment = relative.fragment; - return target; - } - function equal2(uriA, uriB, options) { - if (typeof uriA === "string") { - uriA = unescape(uriA); - uriA = serialize(normalizeComponentEncoding(parse6(uriA, options), true), { ...options, skipEscape: true }); - } else if (typeof uriA === "object") { - uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true }); - } - if (typeof uriB === "string") { - uriB = unescape(uriB); - uriB = serialize(normalizeComponentEncoding(parse6(uriB, options), true), { ...options, skipEscape: true }); - } else if (typeof uriB === "object") { - uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true }); - } - return uriA.toLowerCase() === uriB.toLowerCase(); - } - function serialize(cmpts, opts) { - const component = { - host: cmpts.host, - scheme: cmpts.scheme, - userinfo: cmpts.userinfo, - port: cmpts.port, - path: cmpts.path, - query: cmpts.query, - nid: cmpts.nid, - nss: cmpts.nss, - uuid: cmpts.uuid, - fragment: cmpts.fragment, - reference: cmpts.reference, - resourceName: cmpts.resourceName, - secure: cmpts.secure, - error: "" - }; - const options = Object.assign({}, opts); - const uriTokens = []; - const schemeHandler = getSchemeHandler(options.scheme || component.scheme); - if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); - if (component.path !== void 0) { - if (!options.skipEscape) { - component.path = escape(component.path); - if (component.scheme !== void 0) { - component.path = component.path.split("%3A").join(":"); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error2 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` + }; + var def = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error: error2, + code(cxt, ruleType) { + const { gen, data, $data, schema: schema2, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self: self2 } = it; + if (!opts.validateFormats) + return; + if ($data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self2.formats, + code: opts.code.formats + }); + const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format5 = gen.let("format"); + gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format5, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format5, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) + return codegen_1.nil; + return (0, codegen_1._)`${schemaCode} && !${format5}`; } - } else { - component.path = unescape(component.path); - } - } - if (options.reference !== "suffix" && component.scheme) { - uriTokens.push(component.scheme, ":"); - } - const authority = recomposeAuthority(component); - if (authority !== void 0) { - if (options.reference !== "suffix") { - uriTokens.push("//"); - } - uriTokens.push(authority); - if (component.path && component.path[0] !== "/") { - uriTokens.push("/"); - } - } - if (component.path !== void 0) { - let s = component.path; - if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { - s = removeDotSegments(s); - } - if (authority === void 0 && s[0] === "/" && s[1] === "/") { - s = "/%2F" + s.slice(2); - } - uriTokens.push(s); - } - if (component.query !== void 0) { - uriTokens.push("?", component.query); - } - if (component.fragment !== void 0) { - uriTokens.push("#", component.fragment); - } - return uriTokens.join(""); - } - var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; - function parse6(uri, opts) { - const options = Object.assign({}, opts); - const parsed = { - scheme: void 0, - userinfo: void 0, - host: "", - port: void 0, - path: "", - query: void 0, - fragment: void 0 - }; - let isIP = false; - if (options.reference === "suffix") { - if (options.scheme) { - uri = options.scheme + ":" + uri; - } else { - uri = "//" + uri; - } - } - const matches = uri.match(URI_PARSE); - if (matches) { - parsed.scheme = matches[1]; - parsed.userinfo = matches[3]; - parsed.host = matches[4]; - parsed.port = parseInt(matches[5], 10); - parsed.path = matches[6] || ""; - parsed.query = matches[7]; - parsed.fragment = matches[8]; - if (isNaN(parsed.port)) { - parsed.port = matches[5]; - } - if (parsed.host) { - const ipv4result = isIPv4(parsed.host); - if (ipv4result === false) { - const ipv6result = normalizeIPv6(parsed.host); - parsed.host = ipv6result.host.toLowerCase(); - isIP = ipv6result.isIPV6; - } else { - isIP = true; + function invalidFmt() { + const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format5}(${data}) : ${format5}(${data}))` : (0, codegen_1._)`${format5}(${data})`; + const validData = (0, codegen_1._)`(typeof ${format5} == "function" ? ${callFormat} : ${format5}.test(${data}))`; + return (0, codegen_1._)`${format5} && ${format5} !== true && ${fType} === ${ruleType} && !${validData}`; } } - if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) { - parsed.reference = "same-document"; - } else if (parsed.scheme === void 0) { - parsed.reference = "relative"; - } else if (parsed.fragment === void 0) { - parsed.reference = "absolute"; - } else { - parsed.reference = "uri"; - } - if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) { - parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; - } - const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); - if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { - if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) { - try { - parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); - } catch (e3) { - parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e3; - } + function validateFormat() { + const formatDef = self2.formats[schema2]; + if (!formatDef) { + unknownFormat(); + return; } - } - if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { - if (uri.indexOf("%") !== -1) { - if (parsed.scheme !== void 0) { - parsed.scheme = unescape(parsed.scheme); + if (formatDef === true) + return; + const [fmtType, format5, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) + cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self2.logger.warn(unknownMsg()); + return; } - if (parsed.host !== void 0) { - parsed.host = unescape(parsed.host); + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema2}" ignored in schema at path "${errSchemaPath}"`; } } - if (parsed.path) { - parsed.path = escape(unescape(parsed.path)); + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema2)}` : void 0; + const fmt = gen.scopeValue("formats", { key: schema2, ref: fmtDef, code }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { + return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; + } + return ["string", fmtDef, fmt]; } - if (parsed.fragment) { - parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) + throw new Error("async format in sync schema"); + return (0, codegen_1._)`await ${fmtRef}(${data})`; + } + return typeof format5 == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; } } - if (schemeHandler && schemeHandler.parse) { - schemeHandler.parse(parsed, options); - } - } else { - parsed.error = parsed.error || "URI can not be parsed."; } - return parsed; - } - var fastUri = { - SCHEMES, - normalize, - resolve: resolve3, - resolveComponent, - equal: equal2, - serialize, - parse: parse6 }; - module.exports = fastUri; - module.exports.default = fastUri; - module.exports.fastUri = fastUri; + exports.default = def; } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js -var require_uri = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js"(exports) { +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js +var require_format2 = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); - var uri = require_fast_uri(); - uri.code = 'require("ajv/dist/runtime/uri").default'; - exports.default = uri; + var format_1 = require_format(); + var format5 = [format_1.default]; + exports.default = format5; } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js -var require_core = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js"(exports) { +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js +var require_metadata = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); - exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { - return validate_1.KeywordCxt; - } }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { enumerable: true, get: function() { - return codegen_1._; - } }); - Object.defineProperty(exports, "str", { enumerable: true, get: function() { - return codegen_1.str; - } }); - Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { - return codegen_1.stringify; - } }); - Object.defineProperty(exports, "nil", { enumerable: true, get: function() { - return codegen_1.nil; - } }); - Object.defineProperty(exports, "Name", { enumerable: true, get: function() { - return codegen_1.Name; - } }); - Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { - return codegen_1.CodeGen; - } }); - var validation_error_1 = require_validation_error(); - var ref_error_1 = require_ref_error(); - var rules_1 = require_rules(); + exports.contentVocabulary = exports.metadataVocabulary = void 0; + exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples" + ]; + exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema" + ]; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js +var require_draft7 = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var core_1 = require_core2(); + var validation_1 = require_validation(); + var applicator_1 = require_applicator(); + var format_1 = require_format2(); + var metadata_1 = require_metadata(); + var draft7Vocabularies = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary + ]; + exports.default = draft7Vocabularies; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js +var require_types = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError2) { + DiscrError2["Tag"] = "tag"; + DiscrError2["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js +var require_discriminator = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var types_1 = require_types(); var compile_1 = require_compile(); - var codegen_2 = require_codegen(); - var resolve_1 = require_resolve(); - var dataType_1 = require_dataType(); + var ref_error_1 = require_ref_error(); var util_1 = require_util(); - var $dataRefSchema = require_data(); - var uri_1 = require_uri(); - var defaultRegExp = (str2, flags) => new RegExp(str2, flags); - defaultRegExp.code = "new RegExp"; - var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; - var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ - "validate", - "serialize", - "parse", - "wrapper", - "root", - "schema", - "keyword", - "pattern", - "formats", - "validate$data", - "func", - "obj", - "Error" - ]); - var removedOptions = { - errorDataPath: "", - format: "`validateFormats: false` can be used instead.", - nullable: '"nullable" keyword is supported by default.', - jsonPointers: "Deprecated jsPropertySyntax can be used instead.", - extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", - missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", - processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", - sourceCode: "Use option `code: {source: true}`", - strictDefaults: "It is default now, see option `strict`.", - strictKeywords: "It is default now, see option `strict`.", - uniqueItems: '"uniqueItems" keyword is always validated.', - unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", - cache: "Map is used as cache, schema object as key.", - serialize: "Map is used as cache, schema object as key.", - ajvErrors: "It is default now." - }; - var deprecatedOptions = { - ignoreKeywordsWithRef: "", - jsPropertySyntax: "", - unicode: '"minLength"/"maxLength" account for unicode characters by default.' + var error2 = { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag: tag2, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag2}}` }; - var MAX_EXPRESSION = 200; - function requiredOptions(o) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; - const s = o.strict; - const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; - const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; - const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; - const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; - return { - strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, - strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, - strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", - strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", - strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, - code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, - loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, - loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, - meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, - messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, - inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, - schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", - addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, - validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, - validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, - unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, - int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, - uriResolver - }; - } - var Ajv2 = class { - constructor(opts = {}) { - this.schemas = {}; - this.refs = {}; - this.formats = {}; - this._compilations = /* @__PURE__ */ new Set(); - this._loading = {}; - this._cache = /* @__PURE__ */ new Map(); - opts = this.opts = { ...opts, ...requiredOptions(opts) }; - const { es5, lines } = this.opts.code; - this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); - this.logger = getLogger(opts.logger); - const formatOpt = opts.validateFormats; - opts.validateFormats = false; - this.RULES = (0, rules_1.getRules)(); - checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); - checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); - this._metaOpts = getMetaSchemaOptions.call(this); - if (opts.formats) - addInitialFormats.call(this); - this._addVocabularies(); - this._addDefaultMetaSchema(); - if (opts.keywords) - addInitialKeywords.call(this, opts.keywords); - if (typeof opts.meta == "object") - this.addMetaSchema(opts.meta); - addInitialSchemas.call(this); - opts.validateFormats = formatOpt; - } - _addVocabularies() { - this.addKeyword("$async"); - } - _addDefaultMetaSchema() { - const { $data, meta, schemaId } = this.opts; - let _dataRefSchema = $dataRefSchema; - if (schemaId === "id") { - _dataRefSchema = { ...$dataRefSchema }; - _dataRefSchema.id = _dataRefSchema.$id; - delete _dataRefSchema.$id; - } - if (meta && $data) - this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); - } - defaultMeta() { - const { meta, schemaId } = this.opts; - return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; - } - validate(schemaKeyRef, data) { - let v; - if (typeof schemaKeyRef == "string") { - v = this.getSchema(schemaKeyRef); - if (!v) - throw new Error(`no schema with key or ref "${schemaKeyRef}"`); - } else { - v = this.compile(schemaKeyRef); - } - const valid = v(data); - if (!("$async" in v)) - this.errors = v.errors; - return valid; - } - compile(schema2, _meta) { - const sch = this._addSchema(schema2, _meta); - return sch.validate || this._compileSchemaEnv(sch); - } - compileAsync(schema2, meta) { - if (typeof this.opts.loadSchema != "function") { - throw new Error("options.loadSchema should be a function"); - } - const { loadSchema } = this.opts; - return runCompileAsync.call(this, schema2, meta); - async function runCompileAsync(_schema, _meta) { - await loadMetaSchema.call(this, _schema.$schema); - const sch = this._addSchema(_schema, _meta); - return sch.validate || _compileAsync.call(this, sch); - } - async function loadMetaSchema($ref) { - if ($ref && !this.getSchema($ref)) { - await runCompileAsync.call(this, { $ref }, true); - } - } - async function _compileAsync(sch) { - try { - return this._compileSchemaEnv(sch); - } catch (e3) { - if (!(e3 instanceof ref_error_1.default)) - throw e3; - checkLoaded.call(this, e3); - await loadMissingSchema.call(this, e3.missingSchema); - return _compileAsync.call(this, sch); - } - } - function checkLoaded({ missingSchema: ref, missingRef }) { - if (this.refs[ref]) { - throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); - } - } - async function loadMissingSchema(ref) { - const _schema = await _loadSchema.call(this, ref); - if (!this.refs[ref]) - await loadMetaSchema.call(this, _schema.$schema); - if (!this.refs[ref]) - this.addSchema(_schema, ref, meta); + var def = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error: error2, + code(cxt) { + const { gen, data, schema: schema2, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) { + throw new Error("discriminator: requires discriminator option"); } - async function _loadSchema(ref) { - const p = this._loading[ref]; - if (p) - return p; - try { - return await (this._loading[ref] = loadSchema(ref)); - } finally { - delete this._loading[ref]; + const tagName = schema2.propertyName; + if (typeof tagName != "string") + throw new Error("discriminator: requires propertyName"); + if (schema2.mapping) + throw new Error("discriminator: mapping is not supported"); + if (!oneOf) + throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag2 = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag2} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag: tag2, tagName })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag2} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); } + gen.else(); + cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag: tag2, tagName }); + gen.endIf(); } - } - // Adds schema to the instance - addSchema(schema2, key, _meta, _validateSchema = this.opts.validateSchema) { - if (Array.isArray(schema2)) { - for (const sch of schema2) - this.addSchema(sch, void 0, _meta, _validateSchema); - return this; + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; } - let id; - if (typeof schema2 === "object") { - const { schemaId } = this.opts; - id = schema2[schemaId]; - if (id !== void 0 && typeof id != "string") { - throw new Error(`schema ${schemaId} must be string`); + function getMapping() { + var _a; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i2 = 0; i2 < oneOf.length; i2++) { + let sch = oneOf[i2]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) + sch = sch.schema; + if (sch === void 0) + throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; + if (typeof propSch != "object") { + throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + } + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i2); } - } - key = (0, resolve_1.normalizeId)(key || id); - this._checkUnique(key); - this.schemas[key] = this._addSchema(schema2, _meta, key, _validateSchema, true); - return this; - } - // Add schema that will be used to validate other schemas - // options in META_IGNORE_OPTIONS are alway set to false - addMetaSchema(schema2, key, _validateSchema = this.opts.validateSchema) { - this.addSchema(schema2, key, true, _validateSchema); - return this; - } - // Validate schema against its meta-schema - validateSchema(schema2, throwOrLogError) { - if (typeof schema2 == "boolean") - return true; - let $schema; - $schema = schema2.$schema; - if ($schema !== void 0 && typeof $schema != "string") { - throw new Error("$schema must be a string"); - } - $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); - if (!$schema) { - this.logger.warn("meta-schema not available"); - this.errors = null; - return true; - } - const valid = this.validate($schema, schema2); - if (!valid && throwOrLogError) { - const message = "schema is invalid: " + this.errorsText(); - if (this.opts.validateSchema === "log") - this.logger.error(message); - else - throw new Error(message); - } - return valid; - } - // Get compiled schema by `key` or `ref`. - // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) - getSchema(keyRef) { - let sch; - while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") - keyRef = sch; - if (sch === void 0) { - const { schemaId } = this.opts; - const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); - sch = compile_1.resolveSchema.call(this, root, keyRef); - if (!sch) - return; - this.refs[keyRef] = sch; - } - return sch.validate || this._compileSchemaEnv(sch); - } - // Remove cached schema(s). - // If no parameter is passed all schemas but meta-schemas are removed. - // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. - // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. - removeSchema(schemaKeyRef) { - if (schemaKeyRef instanceof RegExp) { - this._removeAllSchemas(this.schemas, schemaKeyRef); - this._removeAllSchemas(this.refs, schemaKeyRef); - return this; - } - switch (typeof schemaKeyRef) { - case "undefined": - this._removeAllSchemas(this.schemas); - this._removeAllSchemas(this.refs); - this._cache.clear(); - return this; - case "string": { - const sch = getSchEnv.call(this, schemaKeyRef); - if (typeof sch == "object") - this._cache.delete(sch.schema); - delete this.schemas[schemaKeyRef]; - delete this.refs[schemaKeyRef]; - return this; + if (!tagRequired) + throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required: required2 }) { + return Array.isArray(required2) && required2.includes(tagName); } - case "object": { - const cacheKey = schemaKeyRef; - this._cache.delete(cacheKey); - let id = schemaKeyRef[this.opts.schemaId]; - if (id) { - id = (0, resolve_1.normalizeId)(id); - delete this.schemas[id]; - delete this.refs[id]; + function addMappings(sch, i2) { + if (sch.const) { + addMapping(sch.const, i2); + } else if (sch.enum) { + for (const tagValue of sch.enum) { + addMapping(tagValue, i2); + } + } else { + throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); } - return this; - } - default: - throw new Error("ajv.removeSchema: invalid parameter"); - } - } - // add "vocabulary" - a collection of keywords - addVocabulary(definitions) { - for (const def of definitions) - this.addKeyword(def); - return this; - } - addKeyword(kwdOrDef, def) { - let keyword; - if (typeof kwdOrDef == "string") { - keyword = kwdOrDef; - if (typeof def == "object") { - this.logger.warn("these parameters are deprecated, see docs for addKeyword"); - def.keyword = keyword; } - } else if (typeof kwdOrDef == "object" && def === void 0) { - def = kwdOrDef; - keyword = def.keyword; - if (Array.isArray(keyword) && !keyword.length) { - throw new Error("addKeywords: keyword must be string or non-empty array"); + function addMapping(tagValue, i2) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) { + throw new Error(`discriminator: "${tagName}" values must be unique strings`); + } + oneOfMapping[tagValue] = i2; } - } else { - throw new Error("invalid addKeywords parameters"); - } - checkKeyword.call(this, keyword, def); - if (!def) { - (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); - return this; } - keywordMetaschema.call(this, def); - const definition = { - ...def, - type: (0, dataType_1.getJSONTypes)(def.type), - schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) - }; - (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); - return this; - } - getKeyword(keyword) { - const rule = this.RULES.all[keyword]; - return typeof rule == "object" ? rule.definition : !!rule; } - // Remove keyword - removeKeyword(keyword) { - const { RULES: RULES2 } = this; - delete RULES2.keywords[keyword]; - delete RULES2.all[keyword]; - for (const group of RULES2.rules) { - const i2 = group.rules.findIndex((rule) => rule.keyword === keyword); - if (i2 >= 0) - group.rules.splice(i2, 1); + }; + exports.default = def; + } +}); + +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json +var require_json_schema_draft_07 = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module) { + module.exports = { + $schema: "http://json-schema.org/draft-07/schema#", + $id: "http://json-schema.org/draft-07/schema#", + title: "Core schema meta-schema", + definitions: { + schemaArray: { + type: "array", + minItems: 1, + items: { $ref: "#" } + }, + nonNegativeInteger: { + type: "integer", + minimum: 0 + }, + nonNegativeIntegerDefault0: { + allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] + }, + simpleTypes: { + enum: ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + stringArray: { + type: "array", + items: { type: "string" }, + uniqueItems: true, + default: [] } - return this; - } - // Add format - addFormat(name315, format5) { - if (typeof format5 == "string") - format5 = new RegExp(format5); - this.formats[name315] = format5; - return this; - } - errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { - if (!errors || errors.length === 0) - return "No errors"; - return errors.map((e3) => `${dataVar}${e3.instancePath} ${e3.message}`).reduce((text, msg) => text + separator + msg); - } - $dataMetaSchema(metaSchema, keywordsJsonPointers) { - const rules = this.RULES.all; - metaSchema = JSON.parse(JSON.stringify(metaSchema)); - for (const jsonPointer of keywordsJsonPointers) { - const segments = jsonPointer.split("/").slice(1); - let keywords2 = metaSchema; - for (const seg of segments) - keywords2 = keywords2[seg]; - for (const key in rules) { - const rule = rules[key]; - if (typeof rule != "object") - continue; - const { $data } = rule.definition; - const schema2 = keywords2[key]; - if ($data && schema2) - keywords2[key] = schemaOrData(schema2); + }, + type: ["object", "boolean"], + properties: { + $id: { + type: "string", + format: "uri-reference" + }, + $schema: { + type: "string", + format: "uri" + }, + $ref: { + type: "string", + format: "uri-reference" + }, + $comment: { + type: "string" + }, + title: { + type: "string" + }, + description: { + type: "string" + }, + default: true, + readOnly: { + type: "boolean", + default: false + }, + examples: { + type: "array", + items: true + }, + multipleOf: { + type: "number", + exclusiveMinimum: 0 + }, + maximum: { + type: "number" + }, + exclusiveMaximum: { + type: "number" + }, + minimum: { + type: "number" + }, + exclusiveMinimum: { + type: "number" + }, + maxLength: { $ref: "#/definitions/nonNegativeInteger" }, + minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + pattern: { + type: "string", + format: "regex" + }, + additionalItems: { $ref: "#" }, + items: { + anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], + default: true + }, + maxItems: { $ref: "#/definitions/nonNegativeInteger" }, + minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + uniqueItems: { + type: "boolean", + default: false + }, + contains: { $ref: "#" }, + maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, + minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + required: { $ref: "#/definitions/stringArray" }, + additionalProperties: { $ref: "#" }, + definitions: { + type: "object", + additionalProperties: { $ref: "#" }, + default: {} + }, + properties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: {} + }, + patternProperties: { + type: "object", + additionalProperties: { $ref: "#" }, + propertyNames: { format: "regex" }, + default: {} + }, + dependencies: { + type: "object", + additionalProperties: { + anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] } - } - return metaSchema; - } - _removeAllSchemas(schemas, regex) { - for (const keyRef in schemas) { - const sch = schemas[keyRef]; - if (!regex || regex.test(keyRef)) { - if (typeof sch == "string") { - delete schemas[keyRef]; - } else if (sch && !sch.meta) { - this._cache.delete(sch.schema); - delete schemas[keyRef]; + }, + propertyNames: { $ref: "#" }, + const: true, + enum: { + type: "array", + items: true, + minItems: 1, + uniqueItems: true + }, + type: { + anyOf: [ + { $ref: "#/definitions/simpleTypes" }, + { + type: "array", + items: { $ref: "#/definitions/simpleTypes" }, + minItems: 1, + uniqueItems: true } - } - } - } - _addSchema(schema2, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { - let id; - const { schemaId } = this.opts; - if (typeof schema2 == "object") { - id = schema2[schemaId]; - } else { - if (this.opts.jtd) - throw new Error("schema must be object"); - else if (typeof schema2 != "boolean") - throw new Error("schema must be object or boolean"); - } - let sch = this._cache.get(schema2); - if (sch !== void 0) - return sch; - baseId = (0, resolve_1.normalizeId)(id || baseId); - const localRefs = resolve_1.getSchemaRefs.call(this, schema2, baseId); - sch = new compile_1.SchemaEnv({ schema: schema2, schemaId, meta, baseId, localRefs }); - this._cache.set(sch.schema, sch); - if (addSchema && !baseId.startsWith("#")) { - if (baseId) - this._checkUnique(baseId); - this.refs[baseId] = sch; - } - if (validateSchema) - this.validateSchema(schema2, true); - return sch; - } - _checkUnique(id) { - if (this.schemas[id] || this.refs[id]) { - throw new Error(`schema with key or id "${id}" already exists`); - } - } - _compileSchemaEnv(sch) { - if (sch.meta) - this._compileMetaSchema(sch); - else - compile_1.compileSchema.call(this, sch); - if (!sch.validate) - throw new Error("ajv implementation error"); - return sch.validate; - } - _compileMetaSchema(sch) { - const currentOpts = this.opts; - this.opts = this._metaOpts; - try { - compile_1.compileSchema.call(this, sch); - } finally { - this.opts = currentOpts; - } - } - }; - Ajv2.ValidationError = validation_error_1.default; - Ajv2.MissingRefError = ref_error_1.default; - exports.default = Ajv2; - function checkOptions(checkOpts, options, msg, log4 = "error") { - for (const key in checkOpts) { - const opt = key; - if (opt in options) - this.logger[log4](`${msg}: option ${key}. ${checkOpts[opt]}`); - } - } - function getSchEnv(keyRef) { - keyRef = (0, resolve_1.normalizeId)(keyRef); - return this.schemas[keyRef] || this.refs[keyRef]; - } - function addInitialSchemas() { - const optsSchemas = this.opts.schemas; - if (!optsSchemas) - return; - if (Array.isArray(optsSchemas)) - this.addSchema(optsSchemas); - else - for (const key in optsSchemas) - this.addSchema(optsSchemas[key], key); - } - function addInitialFormats() { - for (const name315 in this.opts.formats) { - const format5 = this.opts.formats[name315]; - if (format5) - this.addFormat(name315, format5); - } - } - function addInitialKeywords(defs) { - if (Array.isArray(defs)) { - this.addVocabulary(defs); - return; - } - this.logger.warn("keywords option as map is deprecated, pass array"); - for (const keyword in defs) { - const def = defs[keyword]; - if (!def.keyword) - def.keyword = keyword; - this.addKeyword(def); - } - } - function getMetaSchemaOptions() { - const metaOpts = { ...this.opts }; - for (const opt of META_IGNORE_OPTIONS) - delete metaOpts[opt]; - return metaOpts; - } - var noLogs = { log() { - }, warn() { - }, error() { - } }; - function getLogger(logger) { - if (logger === false) - return noLogs; - if (logger === void 0) - return console; - if (logger.log && logger.warn && logger.error) - return logger; - throw new Error("logger must implement log, warn and error methods"); - } - var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; - function checkKeyword(keyword, def) { - const { RULES: RULES2 } = this; - (0, util_1.eachItem)(keyword, (kwd) => { - if (RULES2.keywords[kwd]) - throw new Error(`Keyword ${kwd} is already defined`); - if (!KEYWORD_NAME.test(kwd)) - throw new Error(`Keyword ${kwd} has invalid name`); - }); - if (!def) - return; - if (def.$data && !("code" in def || "validate" in def)) { - throw new Error('$data keyword must have "code" or "validate" function'); - } - } - function addRule(keyword, definition, dataType) { - var _a; - const post = definition === null || definition === void 0 ? void 0 : definition.post; - if (dataType && post) - throw new Error('keyword with "post" flag cannot have "type"'); - const { RULES: RULES2 } = this; - let ruleGroup = post ? RULES2.post : RULES2.rules.find(({ type: t }) => t === dataType); - if (!ruleGroup) { - ruleGroup = { type: dataType, rules: [] }; - RULES2.rules.push(ruleGroup); - } - RULES2.keywords[keyword] = true; - if (!definition) - return; - const rule = { - keyword, - definition: { - ...definition, - type: (0, dataType_1.getJSONTypes)(definition.type), - schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) - } - }; - if (definition.before) - addBeforeRule.call(this, ruleGroup, rule, definition.before); - else - ruleGroup.rules.push(rule); - RULES2.all[keyword] = rule; - (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd)); - } - function addBeforeRule(ruleGroup, rule, before) { - const i2 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); - if (i2 >= 0) { - ruleGroup.rules.splice(i2, 0, rule); - } else { - ruleGroup.rules.push(rule); - this.logger.warn(`rule ${before} is not defined`); - } - } - function keywordMetaschema(def) { - let { metaSchema } = def; - if (metaSchema === void 0) - return; - if (def.$data && this.opts.$data) - metaSchema = schemaOrData(metaSchema); - def.validateSchema = this.compile(metaSchema, true); - } - var $dataRef = { - $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" + ] + }, + format: { type: "string" }, + contentMediaType: { type: "string" }, + contentEncoding: { type: "string" }, + if: { $ref: "#" }, + then: { $ref: "#" }, + else: { $ref: "#" }, + allOf: { $ref: "#/definitions/schemaArray" }, + anyOf: { $ref: "#/definitions/schemaArray" }, + oneOf: { $ref: "#/definitions/schemaArray" }, + not: { $ref: "#" } + }, + default: true }; - function schemaOrData(schema2) { - return { anyOf: [schema2, $dataRef] }; - } } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js -var require_id = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js"(exports) { +// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js +var require_ajv = __commonJS({ + "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js"(exports, module) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); - var def = { - keyword: "id", - code() { - throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + var core_1 = require_core(); + var draft7_1 = require_draft7(); + var discriminator_1 = require_discriminator(); + var draft7MetaSchema = require_json_schema_draft_07(); + var META_SUPPORT_DATA = ["/properties"]; + var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; + var Ajv2 = class extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) + this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) + return; + const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); } }; - exports.default = def; + exports.Ajv = Ajv2; + module.exports = exports = Ajv2; + module.exports.Ajv = Ajv2; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { + return validate_1.KeywordCxt; + } }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return codegen_1._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return codegen_1.str; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return codegen_1.stringify; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return codegen_1.nil; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return codegen_1.Name; + } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { + return codegen_1.CodeGen; + } }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { + return validation_error_1.default; + } }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { + return ref_error_1.default; + } }); } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js -var require_ref = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js"(exports) { +// node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js +var require_formats = __commonJS({ + "node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); - exports.callRef = exports.getValidate = void 0; - var ref_error_1 = require_ref_error(); - var code_1 = require_code2(); - var codegen_1 = require_codegen(); - var names_1 = require_names(); - var compile_1 = require_compile(); - var util_1 = require_util(); - var def = { - keyword: "$ref", - schemaType: "string", - code(cxt) { - const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it; - const { root } = env; - if (($ref === "#" || $ref === "#/") && baseId === root.baseId) - return callRootRef(); - const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref); - if (schOrEnv === void 0) - throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); - if (schOrEnv instanceof compile_1.SchemaEnv) - return callValidate(schOrEnv); - return inlineRefSchema(schOrEnv); - function callRootRef() { - if (env === root) - return callRef(cxt, validateName, env, env.$async); - const rootName = gen.scopeValue("root", { ref: root }); - return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); - } - function callValidate(sch) { - const v = getValidate(cxt, sch); - callRef(cxt, v, sch, sch.$async); - } - function inlineRefSchema(sch) { - const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); - const valid = gen.name("valid"); - const schCxt = cxt.subschema({ - schema: sch, - dataTypes: [], - schemaPath: codegen_1.nil, - topSchemaRef: schName, - errSchemaPath: $ref - }, valid); - cxt.mergeEvaluated(schCxt); - cxt.ok(valid); - } - } - }; - function getValidate(cxt, sch) { - const { gen } = cxt; - return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; + function fmtDef(validate2, compare2) { + return { validate: validate2, compare: compare2 }; } - exports.getValidate = getValidate; - function callRef(cxt, v, sch, $async) { - const { gen, it } = cxt; - const { allErrors, schemaEnv: env, opts } = it; - const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; - if ($async) - callAsyncRef(); - else - callSyncRef(); - function callAsyncRef() { - if (!env.$async) - throw new Error("async schema referenced by sync schema"); - const valid = gen.let("valid"); - gen.try(() => { - gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); - addEvaluatedFrom(v); - if (!allErrors) - gen.assign(valid, true); - }, (e3) => { - gen.if((0, codegen_1._)`!(${e3} instanceof ${it.ValidationError})`, () => gen.throw(e3)); - addErrorsFrom(e3); - if (!allErrors) - gen.assign(valid, false); - }); - cxt.ok(valid); - } - function callSyncRef() { - cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); - } - function addErrorsFrom(source) { - const errs = (0, codegen_1._)`${source}.errors`; - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); - gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - } - function addEvaluatedFrom(source) { - var _a; - if (!it.opts.unevaluated) - return; - const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; - if (it.props !== true) { - if (schEvaluated && !schEvaluated.dynamicProps) { - if (schEvaluated.props !== void 0) { - it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); - } - } else { - const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); - it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); - } - } - if (it.items !== true) { - if (schEvaluated && !schEvaluated.dynamicItems) { - if (schEvaluated.items !== void 0) { - it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); - } - } else { - const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); - it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); - } - } + exports.fullFormats = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: fmtDef(date3, compareDate), + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + // duration: https://tools.ietf.org/html/rfc3339#appendix-A + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, + // uri-template: https://tools.ietf.org/html/rfc6570 + "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, + // For the source: https://gist.github.com/dperini/729294 + // For test cases: https://mathiasbynens.be/demo/url-regex + url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, + ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, + regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, + "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, + // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types + // byte: https://github.com/miguelmota/is-base64 + byte, + // signed 32 bit integer + int32: { type: "number", validate: validateInt32 }, + // signed 64 bit integer + int64: { type: "number", validate: validateInt64 }, + // C-type float + float: { type: "number", validate: validateNumber }, + // C-type double + double: { type: "number", validate: validateNumber }, + // hint to the UI to hide input strings + password: true, + // unchecked string payload + binary: true + }; + exports.fastFormats = { + ...exports.fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), + "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), + "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), + "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i + }; + exports.formatNames = Object.keys(exports.fullFormats); + function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + } + var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + function date3(str2) { + const matches = DATE.exec(str2); + if (!matches) + return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); + } + function compareDate(d1, d2) { + if (!(d1 && d2)) + return void 0; + if (d1 > d2) + return 1; + if (d1 < d2) + return -1; + return 0; + } + var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; + function getTime(strictTimeZone) { + return function time3(str2) { + const matches = TIME.exec(str2); + if (!matches) + return false; + const hr = +matches[1]; + const min3 = +matches[2]; + const sec2 = +matches[3]; + const tz = matches[4]; + const tzSign = matches[5] === "-" ? -1 : 1; + const tzH = +(matches[6] || 0); + const tzM = +(matches[7] || 0); + if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) + return false; + if (hr <= 23 && min3 <= 59 && sec2 < 60) + return true; + const utcMin = min3 - tzM * tzSign; + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec2 < 61; + }; + } + function compareTime(s1, s2) { + if (!(s1 && s2)) + return void 0; + const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); + const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); + if (!(t1 && t2)) + return void 0; + return t1 - t2; + } + function compareIsoTime(t1, t2) { + if (!(t1 && t2)) + return void 0; + const a1 = TIME.exec(t1); + const a2 = TIME.exec(t2); + if (!(a1 && a2)) + return void 0; + t1 = a1[1] + a1[2] + a1[3]; + t2 = a2[1] + a2[2] + a2[3]; + if (t1 > t2) + return 1; + if (t1 < t2) + return -1; + return 0; + } + var DATE_TIME_SEPARATOR = /t|\s/i; + function getDateTime(strictTimeZone) { + const time3 = getTime(strictTimeZone); + return function date_time(str2) { + const dateTime = str2.split(DATE_TIME_SEPARATOR); + return dateTime.length === 2 && date3(dateTime[0]) && time3(dateTime[1]); + }; + } + function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) + return void 0; + const d1 = new Date(dt1).valueOf(); + const d2 = new Date(dt2).valueOf(); + if (!(d1 && d2)) + return void 0; + return d1 - d2; + } + function compareIsoDateTime(dt1, dt2) { + if (!(dt1 && dt2)) + return void 0; + const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); + const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); + const res = compareDate(d1, d2); + if (res === void 0) + return void 0; + return res || compareTime(t1, t2); + } + var NOT_URI_FRAGMENT = /\/|:/; + var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + function uri(str2) { + return NOT_URI_FRAGMENT.test(str2) && URI.test(str2); + } + var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; + function byte(str2) { + BYTE.lastIndex = 0; + return BYTE.test(str2); + } + var MIN_INT32 = -(2 ** 31); + var MAX_INT32 = 2 ** 31 - 1; + function validateInt32(value) { + return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; + } + function validateInt64(value) { + return Number.isInteger(value); + } + function validateNumber() { + return true; + } + var Z_ANCHOR = /[^\\]\\Z/; + function regex(str2) { + if (Z_ANCHOR.test(str2)) + return false; + try { + new RegExp(str2); + return true; + } catch (e3) { + return false; } } - exports.callRef = callRef; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js -var require_core2 = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var id_1 = require_id(); - var ref_1 = require_ref(); - var core2 = [ - "$schema", - "$id", - "$defs", - "$vocabulary", - { keyword: "$comment" }, - "definitions", - id_1.default, - ref_1.default - ]; - exports.default = core2; } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js -var require_limitNumber = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) { +// node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js +var require_limit = __commonJS({ + "node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatLimitDefinition = void 0; + var ajv_1 = require_ajv(); var codegen_1 = require_codegen(); var ops = codegen_1.operators; var KWDs = { - maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, - minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, - exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, - exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } + formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } }; var error2 = { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` }; - var def = { + exports.formatLimitDefinition = { keyword: Object.keys(KWDs), - type: "number", - schemaType: "number", + type: "string", + schemaType: "string", $data: true, error: error2, code(cxt) { - const { keyword, data, schemaCode } = cxt; - cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); - } + const { gen, data, schemaCode, keyword, it } = cxt; + const { opts, self: self2 } = it; + if (!opts.validateFormats) + return; + const fCxt = new ajv_1.KeywordCxt(it, self2.RULES.all.format.definition, "format"); + if (fCxt.$data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self2.formats, + code: opts.code.formats + }); + const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); + cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); + } + function validateFormat() { + const format5 = fCxt.schema; + const fmtDef = self2.formats[format5]; + if (!fmtDef || fmtDef === true) + return; + if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") { + throw new Error(`"${keyword}": format "${format5}" does not define "compare" function`); + } + const fmt = gen.scopeValue("formats", { + key: format5, + ref: fmtDef, + code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format5)}` : void 0 + }); + cxt.fail$data(compareCode(fmt)); + } + function compareCode(fmt) { + return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; + } + }, + dependencies: ["format"] }; - exports.default = def; + var formatLimitPlugin = (ajv2) => { + ajv2.addKeyword(exports.formatLimitDefinition); + return ajv2; + }; + exports.default = formatLimitPlugin; } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js -var require_multipleOf = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) { +// node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js +var require_dist = __commonJS({ + "node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js"(exports, module) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); + var formats_1 = require_formats(); + var limit_1 = require_limit(); var codegen_1 = require_codegen(); - var error2 = { - message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, - params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` - }; - var def = { - keyword: "multipleOf", - type: "number", - schemaType: "number", - $data: true, - error: error2, - code(cxt) { - const { gen, data, schemaCode, it } = cxt; - const prec = it.opts.multipleOfPrecision; - const res = gen.let("res"); - const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; - cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + var fullName = new codegen_1.Name("fullFormats"); + var fastName = new codegen_1.Name("fastFormats"); + var formatsPlugin = (ajv2, opts = { keywords: true }) => { + if (Array.isArray(opts)) { + addFormats(ajv2, opts, formats_1.fullFormats, fullName); + return ajv2; } + const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; + const list = opts.formats || formats_1.formatNames; + addFormats(ajv2, list, formats, exportName); + if (opts.keywords) + (0, limit_1.default)(ajv2); + return ajv2; }; - exports.default = def; + formatsPlugin.get = (name315, mode2 = "full") => { + const formats = mode2 === "fast" ? formats_1.fastFormats : formats_1.fullFormats; + const f = formats[name315]; + if (!f) + throw new Error(`Unknown format "${name315}"`); + return f; + }; + function addFormats(ajv2, list, fs, exportName) { + var _a; + var _b; + (_a = (_b = ajv2.opts.code).formats) !== null && _a !== void 0 ? _a : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`; + for (const f of list) + ajv2.addFormat(f, fs[f]); + } + module.exports = exports = formatsPlugin; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = formatsPlugin; } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js -var require_ucs2length = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - function ucs2length(str2) { - const len = str2.length; - let length = 0; - let pos = 0; - let value; - while (pos < len) { - length++; - value = str2.charCodeAt(pos++); - if (value >= 55296 && value <= 56319 && pos < len) { - value = str2.charCodeAt(pos); - if ((value & 64512) === 56320) - pos++; +// node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/extends.js +var require_extends = __commonJS({ + "node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/extends.js"(exports, module) { + function _extends8() { + return module.exports = _extends8 = Object.assign ? Object.assign.bind() : function(n) { + for (var e3 = 1; e3 < arguments.length; e3++) { + var t = arguments[e3]; + for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } - } - return length; + return n; + }, module.exports.__esModule = true, module.exports["default"] = module.exports, _extends8.apply(null, arguments); } - exports.default = ucs2length; - ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; + module.exports = _extends8, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js -var require_limitLength = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var ucs2length_1 = require_ucs2length(); - var error2 = { - message({ keyword, schemaCode }) { - const comp = keyword === "maxLength" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }; - var def = { - keyword: ["maxLength", "minLength"], - type: "string", - schemaType: "number", - $data: true, - error: error2, - code(cxt) { - const { keyword, data, schemaCode, it } = cxt; - const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; - const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; - cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); +// node_modules/.pnpm/typed-function@4.2.2/node_modules/typed-function/lib/umd/typed-function.js +var require_typed_function = __commonJS({ + "node_modules/.pnpm/typed-function@4.2.2/node_modules/typed-function/lib/umd/typed-function.js"(exports, module) { + (function(global, factory2) { + typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory2() : typeof define === "function" && define.amd ? define(factory2) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, global.typed = factory2()); + })(exports, (function() { + "use strict"; + function ok() { + return true; } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js -var require_pattern = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code2(); - var util_1 = require_util(); - var codegen_1 = require_codegen(); - var error2 = { - message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` - }; - var def = { - keyword: "pattern", - type: "string", - schemaType: "string", - $data: true, - error: error2, - code(cxt) { - const { gen, data, $data, schema: schema2, schemaCode, it } = cxt; - const u = it.opts.unicodeRegExp ? "u" : ""; - if ($data) { - const { regExp } = it.opts.code; - const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); - const valid = gen.let("valid"); - gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); - cxt.fail$data((0, codegen_1._)`!${valid}`); - } else { - const regExp = (0, code_1.usePattern)(cxt, schema2); - cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); - } + function notOk() { + return false; } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js -var require_limitProperties = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var error2 = { - message({ keyword, schemaCode }) { - const comp = keyword === "maxProperties" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }; - var def = { - keyword: ["maxProperties", "minProperties"], - type: "object", - schemaType: "number", - $data: true, - error: error2, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); + function undef() { + return void 0; } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js -var require_required = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code2(); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error2 = { - message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, - params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` - }; - var def = { - keyword: "required", - type: "object", - schemaType: "array", - $data: true, - error: error2, - code(cxt) { - const { gen, schema: schema2, schemaCode, data, $data, it } = cxt; - const { opts } = it; - if (!$data && schema2.length === 0) - return; - const useLoop = schema2.length >= opts.loopRequired; - if (it.allErrors) - allErrorsMode(); - else - exitOnErrorMode(); - if (opts.strictRequired) { - const props = cxt.parentSchema.properties; - const { definedProperties } = cxt.it; - for (const requiredKey of schema2) { - if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { - const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; - const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + const NOT_TYPED_FUNCTION = "Argument is not a typed-function."; + function create() { + function isPlainObject4(x) { + return typeof x === "object" && x !== null && x.constructor === Object; + } + const _types = [{ + name: "number", + test: function(x) { + return typeof x === "number"; + } + }, { + name: "string", + test: function(x) { + return typeof x === "string"; + } + }, { + name: "boolean", + test: function(x) { + return typeof x === "boolean"; + } + }, { + name: "Function", + test: function(x) { + return typeof x === "function"; + } + }, { + name: "Array", + test: Array.isArray + }, { + name: "Date", + test: function(x) { + return x instanceof Date; + } + }, { + name: "RegExp", + test: function(x) { + return x instanceof RegExp; + } + }, { + name: "Object", + test: isPlainObject4 + }, { + name: "null", + test: function(x) { + return x === null; + } + }, { + name: "undefined", + test: function(x) { + return x === void 0; + } + }]; + const anyType2 = { + name: "any", + test: ok, + isAny: true + }; + let typeMap; + let typeList; + let nConversions = 0; + let typed3 = { + createCount: 0 + }; + function findType(typeName) { + const type2 = typeMap.get(typeName); + if (type2) { + return type2; + } + let message = 'Unknown type "' + typeName + '"'; + const name315 = typeName.toLowerCase(); + let otherName; + for (otherName of typeList) { + if (otherName.toLowerCase() === name315) { + message += '. Did you mean "' + otherName + '" ?'; + break; } } + throw new TypeError(message); } - function allErrorsMode() { - if (useLoop || $data) { - cxt.block$data(codegen_1.nil, loopAllRequired); - } else { - for (const prop of schema2) { - (0, code_1.checkReportMissingProp)(cxt, prop); + function addTypes(types) { + let beforeSpec = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "any"; + const beforeIndex = beforeSpec ? findType(beforeSpec).index : typeList.length; + const newTypes = []; + for (let i2 = 0; i2 < types.length; ++i2) { + if (!types[i2] || typeof types[i2].name !== "string" || typeof types[i2].test !== "function") { + throw new TypeError("Object with properties {name: string, test: function} expected"); + } + const typeName = types[i2].name; + if (typeMap.has(typeName)) { + throw new TypeError('Duplicate type name "' + typeName + '"'); } + newTypes.push(typeName); + typeMap.set(typeName, { + name: typeName, + test: types[i2].test, + isAny: types[i2].isAny, + index: beforeIndex + i2, + conversionsTo: [] + // Newly added type can't have any conversions to it + }); + } + const affectedTypes = typeList.slice(beforeIndex); + typeList = typeList.slice(0, beforeIndex).concat(newTypes).concat(affectedTypes); + for (let i2 = beforeIndex + newTypes.length; i2 < typeList.length; ++i2) { + typeMap.get(typeList[i2]).index = i2; } } - function exitOnErrorMode() { - const missing = gen.let("missing"); - if (useLoop || $data) { - const valid = gen.let("valid", true); - cxt.block$data(valid, () => loopUntilMissing(missing, valid)); - cxt.ok(valid); - } else { - gen.if((0, code_1.checkMissingProp)(cxt, schema2, missing)); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); + function clear() { + typeMap = /* @__PURE__ */ new Map(); + typeList = []; + nConversions = 0; + addTypes([anyType2], false); + } + clear(); + addTypes(_types); + function clearConversions() { + let typeName; + for (typeName of typeList) { + typeMap.get(typeName).conversionsTo = []; } + nConversions = 0; } - function loopAllRequired() { - gen.forOf("prop", schemaCode, (prop) => { - cxt.setParams({ missingProperty: prop }); - gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + function findTypeNames(value) { + const matches = typeList.filter((name315) => { + const type2 = typeMap.get(name315); + return !type2.isAny && type2.test(value); }); + if (matches.length) { + return matches; + } + return ["any"]; } - function loopUntilMissing(missing, valid) { - cxt.setParams({ missingProperty: missing }); - gen.forOf(missing, schemaCode, () => { - gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(); - gen.break(); - }); - }, codegen_1.nil); + function isTypedFunction(entity) { + return entity && typeof entity === "function" && "_typedFunctionData" in entity; } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js -var require_limitItems = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var error2 = { - message({ keyword, schemaCode }) { - const comp = keyword === "maxItems" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }; - var def = { - keyword: ["maxItems", "minItems"], - type: "array", - schemaType: "number", - $data: true, - error: error2, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js -var require_equal = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var equal2 = require_fast_deep_equal(); - equal2.code = 'require("ajv/dist/runtime/equal").default'; - exports.default = equal2; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js -var require_uniqueItems = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var dataType_1 = require_dataType(); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var equal_1 = require_equal(); - var error2 = { - message: ({ params: { i: i2, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i2} are identical)`, - params: ({ params: { i: i2, j } }) => (0, codegen_1._)`{i: ${i2}, j: ${j}}` - }; - var def = { - keyword: "uniqueItems", - type: "array", - schemaType: "boolean", - $data: true, - error: error2, - code(cxt) { - const { gen, data, $data, schema: schema2, parentSchema, schemaCode, it } = cxt; - if (!$data && !schema2) - return; - const valid = gen.let("valid"); - const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; - cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); - cxt.ok(valid); - function validateUniqueItems() { - const i2 = gen.let("i", (0, codegen_1._)`${data}.length`); - const j = gen.let("j"); - cxt.setParams({ i: i2, j }); - gen.assign(valid, true); - gen.if((0, codegen_1._)`${i2} > 1`, () => (canOptimize() ? loopN : loopN2)(i2, j)); + function findSignature(fn, signature, options) { + if (!isTypedFunction(fn)) { + throw new TypeError(NOT_TYPED_FUNCTION); + } + const exact = options && options.exact; + const stringSignature = Array.isArray(signature) ? signature.join(",") : signature; + const params = parseSignature(stringSignature); + const canonicalSignature = stringifyParams(params); + if (!exact || canonicalSignature in fn.signatures) { + const match = fn._typedFunctionData.signatureMap.get(canonicalSignature); + if (match) { + return match; + } + } + const nParams = params.length; + let remainingSignatures; + if (exact) { + remainingSignatures = []; + let name315; + for (name315 in fn.signatures) { + remainingSignatures.push(fn._typedFunctionData.signatureMap.get(name315)); + } + } else { + remainingSignatures = fn._typedFunctionData.signatures; + } + for (let i2 = 0; i2 < nParams; ++i2) { + const want = params[i2]; + const filteredSignatures = []; + let possibility; + for (possibility of remainingSignatures) { + const have = getParamAtIndex(possibility.params, i2); + if (!have || want.restParam && !have.restParam) { + continue; + } + if (!have.hasAny) { + const haveTypes = paramTypeSet(have); + if (want.types.some((wtype) => !haveTypes.has(wtype.name))) { + continue; + } + } + filteredSignatures.push(possibility); + } + remainingSignatures = filteredSignatures; + if (remainingSignatures.length === 0) break; + } + let candidate; + for (candidate of remainingSignatures) { + if (candidate.params.length <= nParams) { + return candidate; + } + } + throw new TypeError("Signature not found (signature: " + (fn.name || "unnamed") + "(" + stringifyParams(params, ", ") + "))"); } - function canOptimize() { - return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); + function find(fn, signature, options) { + return findSignature(fn, signature, options).implementation; } - function loopN(i2, j) { - const item = gen.name("item"); - const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); - const indices = gen.const("indices", (0, codegen_1._)`{}`); - gen.for((0, codegen_1._)`;${i2}--;`, () => { - gen.let(item, (0, codegen_1._)`${data}[${i2}]`); - gen.if(wrongType, (0, codegen_1._)`continue`); - if (itemTypes.length > 1) - gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); - gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { - gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); - cxt.error(); - gen.assign(valid, false).break(); - }).code((0, codegen_1._)`${indices}[${item}] = ${i2}`); - }); + function convert(value, typeName) { + const type2 = findType(typeName); + if (type2.test(value)) { + return value; + } + const conversions = type2.conversionsTo; + if (conversions.length === 0) { + throw new Error("There are no conversions to " + typeName + " defined."); + } + for (let i2 = 0; i2 < conversions.length; i2++) { + const fromType = findType(conversions[i2].from); + if (fromType.test(value)) { + return conversions[i2].convert(value); + } + } + throw new Error("Cannot convert " + value + " to " + typeName); } - function loopN2(i2, j) { - const eql = (0, util_1.useFunc)(gen, equal_1.default); - const outer = gen.name("outer"); - gen.label(outer).for((0, codegen_1._)`;${i2}--;`, () => gen.for((0, codegen_1._)`${j} = ${i2}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i2}], ${data}[${j}])`, () => { - cxt.error(); - gen.assign(valid, false).break(outer); - }))); + function stringifyParams(params) { + let separator = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : ","; + return params.map((p) => p.name).join(separator); } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js -var require_const = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var equal_1 = require_equal(); - var error2 = { - message: "must be equal to constant", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` - }; - var def = { - keyword: "const", - $data: true, - error: error2, - code(cxt) { - const { gen, data, $data, schemaCode, schema: schema2 } = cxt; - if ($data || schema2 && typeof schema2 == "object") { - cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); - } else { - cxt.fail((0, codegen_1._)`${schema2} !== ${data}`); + function parseParam(param) { + const restParam = param.indexOf("...") === 0; + const types = !restParam ? param : param.length > 3 ? param.slice(3) : "any"; + const typeDefs = types.split("|").map((s) => findType(s.trim())); + let hasAny = false; + let paramName = restParam ? "..." : ""; + const exactTypes = typeDefs.map(function(type2) { + hasAny = type2.isAny || hasAny; + paramName += type2.name + "|"; + return { + name: type2.name, + typeIndex: type2.index, + test: type2.test, + isAny: type2.isAny, + conversion: null, + conversionIndex: -1 + }; + }); + return { + types: exactTypes, + name: paramName.slice(0, -1), + // remove trailing '|' from above + hasAny, + hasConversion: false, + restParam + }; } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js -var require_enum = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var equal_1 = require_equal(); - var error2 = { - message: "must be equal to one of the allowed values", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` - }; - var def = { - keyword: "enum", - schemaType: "array", - $data: true, - error: error2, - code(cxt) { - const { gen, data, $data, schema: schema2, schemaCode, it } = cxt; - if (!$data && schema2.length === 0) - throw new Error("enum must have non-empty array"); - const useLoop = schema2.length >= it.opts.loopEnum; - let eql; - const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); - let valid; - if (useLoop || $data) { - valid = gen.let("valid"); - cxt.block$data(valid, loopEnum); - } else { - if (!Array.isArray(schema2)) - throw new Error("ajv implementation error"); - const vSchema = gen.const("vSchema", schemaCode); - valid = (0, codegen_1.or)(...schema2.map((_x, i2) => equalCode(vSchema, i2))); + function expandParam(param) { + const typeNames = param.types.map((t) => t.name); + const matchingConversions = availableConversions(typeNames); + let hasAny = param.hasAny; + let newName = param.name; + const convertibleTypes = matchingConversions.map(function(conversion) { + const type2 = findType(conversion.from); + hasAny = type2.isAny || hasAny; + newName += "|" + conversion.from; + return { + name: conversion.from, + typeIndex: type2.index, + test: type2.test, + isAny: type2.isAny, + conversion, + conversionIndex: conversion.index + }; + }); + return { + types: param.types.concat(convertibleTypes), + name: newName, + hasAny, + hasConversion: convertibleTypes.length > 0, + restParam: param.restParam + }; } - cxt.pass(valid); - function loopEnum() { - gen.assign(valid, false); - gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); + function paramTypeSet(param) { + if (!param.typeSet) { + param.typeSet = /* @__PURE__ */ new Set(); + param.types.forEach((type2) => param.typeSet.add(type2.name)); + } + return param.typeSet; } - function equalCode(vSchema, i2) { - const sch = schema2[i2]; - return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i2}])` : (0, codegen_1._)`${data} === ${sch}`; + function parseSignature(rawSignature) { + const params = []; + if (typeof rawSignature !== "string") { + throw new TypeError("Signatures must be strings"); + } + const signature = rawSignature.trim(); + if (signature === "") { + return params; + } + const rawParams = signature.split(","); + for (let i2 = 0; i2 < rawParams.length; ++i2) { + const parsedParam = parseParam(rawParams[i2].trim()); + if (parsedParam.restParam && i2 !== rawParams.length - 1) { + throw new SyntaxError('Unexpected rest parameter "' + rawParams[i2] + '": only allowed for the last parameter'); + } + if (parsedParam.types.length === 0) { + return null; + } + params.push(parsedParam); + } + return params; } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js -var require_validation = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var limitNumber_1 = require_limitNumber(); - var multipleOf_1 = require_multipleOf(); - var limitLength_1 = require_limitLength(); - var pattern_1 = require_pattern(); - var limitProperties_1 = require_limitProperties(); - var required_1 = require_required(); - var limitItems_1 = require_limitItems(); - var uniqueItems_1 = require_uniqueItems(); - var const_1 = require_const(); - var enum_1 = require_enum(); - var validation = [ - // number - limitNumber_1.default, - multipleOf_1.default, - // string - limitLength_1.default, - pattern_1.default, - // object - limitProperties_1.default, - required_1.default, - // array - limitItems_1.default, - uniqueItems_1.default, - // any - { keyword: "type", schemaType: ["string", "array"] }, - { keyword: "nullable", schemaType: "boolean" }, - const_1.default, - enum_1.default - ]; - exports.default = validation; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js -var require_additionalItems = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateAdditionalItems = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error2 = { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }; - var def = { - keyword: "additionalItems", - type: "array", - schemaType: ["boolean", "object"], - before: "uniqueItems", - error: error2, - code(cxt) { - const { parentSchema, it } = cxt; - const { items } = parentSchema; - if (!Array.isArray(items)) { - (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); - return; - } - validateAdditionalItems(cxt, items); - } - }; - function validateAdditionalItems(cxt, items) { - const { gen, schema: schema2, data, keyword, it } = cxt; - it.items = true; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - if (schema2 === false) { - cxt.setParams({ len: items.length }); - cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); - } else if (typeof schema2 == "object" && !(0, util_1.alwaysValidSchema)(it, schema2)) { - const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); - gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); - cxt.ok(valid); - } - function validateItems(valid) { - gen.forRange("i", items.length, len, (i2) => { - cxt.subschema({ keyword, dataProp: i2, dataPropType: util_1.Type.Num }, valid); - if (!it.allErrors) - gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - } - } - exports.validateAdditionalItems = validateAdditionalItems; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js -var require_items = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateTuple = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var code_1 = require_code2(); - var def = { - keyword: "items", - type: "array", - schemaType: ["object", "array", "boolean"], - before: "uniqueItems", - code(cxt) { - const { schema: schema2, it } = cxt; - if (Array.isArray(schema2)) - return validateTuple(cxt, "additionalItems", schema2); - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema2)) - return; - cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - function validateTuple(cxt, extraItems, schArr = cxt.schema) { - const { gen, parentSchema, data, keyword, it } = cxt; - checkStrictTuple(parentSchema); - if (it.opts.unevaluated && schArr.length && it.items !== true) { - it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); - } - const valid = gen.name("valid"); - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - schArr.forEach((sch, i2) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) - return; - gen.if((0, codegen_1._)`${len} > ${i2}`, () => cxt.subschema({ - keyword, - schemaProp: i2, - dataProp: i2 - }, valid)); - cxt.ok(valid); - }); - function checkStrictTuple(sch) { - const { opts, errSchemaPath } = it; - const l = schArr.length; - const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); - if (opts.strictTuples && !fullTuple) { - const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; - (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); - } - } - } - exports.validateTuple = validateTuple; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js -var require_prefixItems = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var items_1 = require_items(); - var def = { - keyword: "prefixItems", - type: "array", - schemaType: ["array"], - before: "uniqueItems", - code: (cxt) => (0, items_1.validateTuple)(cxt, "items") - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js -var require_items2020 = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var code_1 = require_code2(); - var additionalItems_1 = require_additionalItems(); - var error2 = { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }; - var def = { - keyword: "items", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - error: error2, - code(cxt) { - const { schema: schema2, parentSchema, it } = cxt; - const { prefixItems } = parentSchema; - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema2)) - return; - if (prefixItems) - (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); - else - cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js -var require_contains = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error2 = { - message: ({ params: { min: min3, max: max3 } }) => max3 === void 0 ? (0, codegen_1.str)`must contain at least ${min3} valid item(s)` : (0, codegen_1.str)`must contain at least ${min3} and no more than ${max3} valid item(s)`, - params: ({ params: { min: min3, max: max3 } }) => max3 === void 0 ? (0, codegen_1._)`{minContains: ${min3}}` : (0, codegen_1._)`{minContains: ${min3}, maxContains: ${max3}}` - }; - var def = { - keyword: "contains", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - trackErrors: true, - error: error2, - code(cxt) { - const { gen, schema: schema2, parentSchema, data, it } = cxt; - let min3; - let max3; - const { minContains, maxContains } = parentSchema; - if (it.opts.next) { - min3 = minContains === void 0 ? 1 : minContains; - max3 = maxContains; - } else { - min3 = 1; + function hasRestParam(params) { + const param = last(params); + return param ? param.restParam : false; } - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - cxt.setParams({ min: min3, max: max3 }); - if (max3 === void 0 && min3 === 0) { - (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); - return; + function compileTest(param) { + if (!param || param.types.length === 0) { + return ok; + } else if (param.types.length === 1) { + return findType(param.types[0].name).test; + } else if (param.types.length === 2) { + const test0 = findType(param.types[0].name).test; + const test1 = findType(param.types[1].name).test; + return function or2(x) { + return test0(x) || test1(x); + }; + } else { + const tests = param.types.map(function(type2) { + return findType(type2.name).test; + }); + return function or2(x) { + for (let i2 = 0; i2 < tests.length; i2++) { + if (tests[i2](x)) { + return true; + } + } + return false; + }; + } } - if (max3 !== void 0 && min3 > max3) { - (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); - cxt.fail(); - return; + function compileTests(params) { + let tests, test0, test1; + if (hasRestParam(params)) { + tests = initial(params).map(compileTest); + const varIndex = tests.length; + const lastTest = compileTest(last(params)); + const testRestParam = function(args) { + for (let i2 = varIndex; i2 < args.length; i2++) { + if (!lastTest(args[i2])) { + return false; + } + } + return true; + }; + return function testArgs(args) { + for (let i2 = 0; i2 < tests.length; i2++) { + if (!tests[i2](args[i2])) { + return false; + } + } + return testRestParam(args) && args.length >= varIndex + 1; + }; + } else { + if (params.length === 0) { + return function testArgs(args) { + return args.length === 0; + }; + } else if (params.length === 1) { + test0 = compileTest(params[0]); + return function testArgs(args) { + return test0(args[0]) && args.length === 1; + }; + } else if (params.length === 2) { + test0 = compileTest(params[0]); + test1 = compileTest(params[1]); + return function testArgs(args) { + return test0(args[0]) && test1(args[1]) && args.length === 2; + }; + } else { + tests = params.map(compileTest); + return function testArgs(args) { + for (let i2 = 0; i2 < tests.length; i2++) { + if (!tests[i2](args[i2])) { + return false; + } + } + return args.length === tests.length; + }; + } + } } - if ((0, util_1.alwaysValidSchema)(it, schema2)) { - let cond = (0, codegen_1._)`${len} >= ${min3}`; - if (max3 !== void 0) - cond = (0, codegen_1._)`${cond} && ${len} <= ${max3}`; - cxt.pass(cond); - return; + function getParamAtIndex(params, index2) { + return index2 < params.length ? params[index2] : hasRestParam(params) ? last(params) : null; } - it.items = true; - const valid = gen.name("valid"); - if (max3 === void 0 && min3 === 1) { - validateItems(valid, () => gen.if(valid, () => gen.break())); - } else if (min3 === 0) { - gen.let(valid, true); - if (max3 !== void 0) - gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); - } else { - gen.let(valid, false); - validateItemsWithCount(); + function getTypeSetAtIndex(params, index2) { + const param = getParamAtIndex(params, index2); + if (!param) { + return /* @__PURE__ */ new Set(); + } + return paramTypeSet(param); } - cxt.result(valid, () => cxt.reset()); - function validateItemsWithCount() { - const schValid = gen.name("_valid"); - const count2 = gen.let("count", 0); - validateItems(schValid, () => gen.if(schValid, () => checkLimits(count2))); + function isExactType(type2) { + return type2.conversion === null || type2.conversion === void 0; } - function validateItems(_valid, block) { - gen.forRange("i", 0, len, (i2) => { - cxt.subschema({ - keyword: "contains", - dataProp: i2, - dataPropType: util_1.Type.Num, - compositeRule: true - }, _valid); - block(); + function mergeExpectedParams(signatures, index2) { + const typeSet = /* @__PURE__ */ new Set(); + signatures.forEach((signature) => { + const paramSet = getTypeSetAtIndex(signature.params, index2); + let name315; + for (name315 of paramSet) { + typeSet.add(name315); + } }); + return typeSet.has("any") ? ["any"] : Array.from(typeSet); } - function checkLimits(count2) { - gen.code((0, codegen_1._)`${count2}++`); - if (max3 === void 0) { - gen.if((0, codegen_1._)`${count2} >= ${min3}`, () => gen.assign(valid, true).break()); - } else { - gen.if((0, codegen_1._)`${count2} > ${max3}`, () => gen.assign(valid, false).break()); - if (min3 === 1) - gen.assign(valid, true); - else - gen.if((0, codegen_1._)`${count2} >= ${min3}`, () => gen.assign(valid, true)); - } - } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js -var require_dependencies = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var code_1 = require_code2(); - exports.error = { - message: ({ params: { property, depsCount, deps } }) => { - const property_ies = depsCount === 1 ? "property" : "properties"; - return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; - }, - params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, - missingProperty: ${missingProperty}, - depsCount: ${depsCount}, - deps: ${deps}}` - // TODO change to reference - }; - var def = { - keyword: "dependencies", - type: "object", - schemaType: "object", - error: exports.error, - code(cxt) { - const [propDeps, schDeps] = splitDependencies(cxt); - validatePropertyDeps(cxt, propDeps); - validateSchemaDeps(cxt, schDeps); - } - }; - function splitDependencies({ schema: schema2 }) { - const propertyDeps = {}; - const schemaDeps = {}; - for (const key in schema2) { - if (key === "__proto__") - continue; - const deps = Array.isArray(schema2[key]) ? propertyDeps : schemaDeps; - deps[key] = schema2[key]; - } - return [propertyDeps, schemaDeps]; - } - function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { - const { gen, data, it } = cxt; - if (Object.keys(propertyDeps).length === 0) - return; - const missing = gen.let("missing"); - for (const prop in propertyDeps) { - const deps = propertyDeps[prop]; - if (deps.length === 0) - continue; - const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); - cxt.setParams({ - property: prop, - depsCount: deps.length, - deps: deps.join(", ") - }); - if (it.allErrors) { - gen.if(hasProperty, () => { - for (const depProp of deps) { - (0, code_1.checkReportMissingProp)(cxt, depProp); + function createError(name315, args, signatures) { + let err, expected; + const _name = name315 || "unnamed"; + let matchingSignatures = signatures; + let index2; + for (index2 = 0; index2 < args.length; index2++) { + const nextMatchingDefs = []; + matchingSignatures.forEach((signature) => { + const param = getParamAtIndex(signature.params, index2); + const test = compileTest(param); + if ((index2 < signature.params.length || hasRestParam(signature.params)) && test(args[index2])) { + nextMatchingDefs.push(signature); + } + }); + if (nextMatchingDefs.length === 0) { + expected = mergeExpectedParams(matchingSignatures, index2); + if (expected.length > 0) { + const actualTypes = findTypeNames(args[index2]); + err = new TypeError("Unexpected type of argument in function " + _name + " (expected: " + expected.join(" or ") + ", actual: " + actualTypes.join(" | ") + ", index: " + index2 + ")"); + err.data = { + category: "wrongType", + fn: _name, + index: index2, + actual: actualTypes, + expected + }; + return err; + } + } else { + matchingSignatures = nextMatchingDefs; } + } + const lengths = matchingSignatures.map(function(signature) { + return hasRestParam(signature.params) ? Infinity : signature.params.length; }); - } else { - gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); + if (args.length < Math.min.apply(null, lengths)) { + expected = mergeExpectedParams(matchingSignatures, index2); + err = new TypeError("Too few arguments in function " + _name + " (expected: " + expected.join(" or ") + ", index: " + args.length + ")"); + err.data = { + category: "tooFewArgs", + fn: _name, + index: args.length, + expected + }; + return err; + } + const maxLength = Math.max.apply(null, lengths); + if (args.length > maxLength) { + err = new TypeError("Too many arguments in function " + _name + " (expected: " + maxLength + ", actual: " + args.length + ")"); + err.data = { + category: "tooManyArgs", + fn: _name, + index: args.length, + expectedLength: maxLength + }; + return err; + } + const argTypes = []; + for (let i2 = 0; i2 < args.length; ++i2) { + argTypes.push(findTypeNames(args[i2]).join("|")); + } + err = new TypeError('Arguments of type "' + argTypes.join(", ") + '" do not match any of the defined signatures of function ' + _name + "."); + err.data = { + category: "mismatch", + actual: argTypes + }; + return err; } - } - } - exports.validatePropertyDeps = validatePropertyDeps; - function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - for (const prop in schemaDeps) { - if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) - continue; - gen.if( - (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), - () => { - const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); - cxt.mergeValidEvaluated(schCxt, valid); - }, - () => gen.var(valid, true) - // TODO var - ); - cxt.ok(valid); - } - } - exports.validateSchemaDeps = validateSchemaDeps; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js -var require_propertyNames = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error2 = { - message: "property name must be valid", - params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` - }; - var def = { - keyword: "propertyNames", - type: "object", - schemaType: ["object", "boolean"], - error: error2, - code(cxt) { - const { gen, schema: schema2, data, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema2)) - return; - const valid = gen.name("valid"); - gen.forIn("key", data, (key) => { - cxt.setParams({ propertyName: key }); - cxt.subschema({ - keyword: "propertyNames", - data: key, - dataTypes: ["string"], - propertyName: key, - compositeRule: true - }, valid); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(true); - if (!it.allErrors) - gen.break(); - }); - }); - cxt.ok(valid); - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js -var require_additionalProperties = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code2(); - var codegen_1 = require_codegen(); - var names_1 = require_names(); - var util_1 = require_util(); - var error2 = { - message: "must NOT have additional properties", - params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` - }; - var def = { - keyword: "additionalProperties", - type: ["object"], - schemaType: ["boolean", "object"], - allowUndefined: true, - trackErrors: true, - error: error2, - code(cxt) { - const { gen, schema: schema2, parentSchema, data, errsCount, it } = cxt; - if (!errsCount) - throw new Error("ajv implementation error"); - const { allErrors, opts } = it; - it.props = true; - if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema2)) - return; - const props = (0, code_1.allSchemaProperties)(parentSchema.properties); - const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); - checkAdditionalProperties(); - cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - function checkAdditionalProperties() { - gen.forIn("key", data, (key) => { - if (!props.length && !patProps.length) - additionalPropertyCode(key); - else - gen.if(isAdditional(key), () => additionalPropertyCode(key)); - }); - } - function isAdditional(key) { - let definedProp; - if (props.length > 8) { - const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); - definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); - } else if (props.length) { - definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); - } else { - definedProp = codegen_1.nil; - } - if (patProps.length) { - definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); + function getLowestTypeIndex(param) { + let min3 = typeList.length + 1; + for (let i2 = 0; i2 < param.types.length; i2++) { + min3 = Math.min(min3, param.types[i2].typeIndex); } - return (0, codegen_1.not)(definedProp); + return min3; } - function deleteAdditional(key) { - gen.code((0, codegen_1._)`delete ${data}[${key}]`); + function getLowestConversionIndex(param) { + let min3 = nConversions + 1; + for (let i2 = 0; i2 < param.types.length; i2++) { + if (!isExactType(param.types[i2])) { + min3 = Math.min(min3, param.types[i2].conversionIndex); + } + } + return min3; } - function additionalPropertyCode(key) { - if (opts.removeAdditional === "all" || opts.removeAdditional && schema2 === false) { - deleteAdditional(key); - return; + function compareParams(param1, param2) { + if (param1.hasAny) { + if (!param2.hasAny) { + return 0.1; + } + } else if (param2.hasAny) { + return -0.1; } - if (schema2 === false) { - cxt.setParams({ additionalProperty: key }); - cxt.error(); - if (!allErrors) - gen.break(); - return; + if (param1.restParam) { + if (!param2.restParam) { + return 0.01; + } + } else if (param2.restParam) { + return -0.01; } - if (typeof schema2 == "object" && !(0, util_1.alwaysValidSchema)(it, schema2)) { - const valid = gen.name("valid"); - if (opts.removeAdditional === "failing") { - applyAdditionalSchema(key, valid, false); - gen.if((0, codegen_1.not)(valid), () => { - cxt.reset(); - deleteAdditional(key); - }); - } else { - applyAdditionalSchema(key, valid); - if (!allErrors) - gen.if((0, codegen_1.not)(valid), () => gen.break()); + const typeDiff = getLowestTypeIndex(param1) - getLowestTypeIndex(param2); + if (typeDiff < 0) { + return -1e-3; + } + if (typeDiff > 0) { + return 1e-3; + } + const conv1 = getLowestConversionIndex(param1); + const conv2 = getLowestConversionIndex(param2); + if (param1.hasConversion) { + if (!param2.hasConversion) { + return (1 + conv1) * 1e-6; } + } else if (param2.hasConversion) { + return -(1 + conv2) * 1e-6; } - } - function applyAdditionalSchema(key, valid, errors) { - const subschema = { - keyword: "additionalProperties", - dataProp: key, - dataPropType: util_1.Type.Str - }; - if (errors === false) { - Object.assign(subschema, { - compositeRule: true, - createErrors: false, - allErrors: false - }); + const convDiff = conv1 - conv2; + if (convDiff < 0) { + return -1e-7; } - cxt.subschema(subschema, valid); - } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js -var require_properties = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var validate_1 = require_validate(); - var code_1 = require_code2(); - var util_1 = require_util(); - var additionalProperties_1 = require_additionalProperties(); - var def = { - keyword: "properties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema: schema2, parentSchema, data, it } = cxt; - if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { - additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); - } - const allProps = (0, code_1.allSchemaProperties)(schema2); - for (const prop of allProps) { - it.definedProperties.add(prop); - } - if (it.opts.unevaluated && allProps.length && it.props !== true) { - it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); - } - const properties2 = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema2[p])); - if (properties2.length === 0) - return; - const valid = gen.name("valid"); - for (const prop of properties2) { - if (hasDefault(prop)) { - applyPropertySchema(prop); - } else { - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); - applyPropertySchema(prop); - if (!it.allErrors) - gen.else().var(valid, true); - gen.endIf(); + if (convDiff > 0) { + return 1e-7; } - cxt.it.definedProperties.add(prop); - cxt.ok(valid); - } - function hasDefault(prop) { - return it.opts.useDefaults && !it.compositeRule && schema2[prop].default !== void 0; - } - function applyPropertySchema(prop) { - cxt.subschema({ - keyword: "properties", - schemaProp: prop, - dataProp: prop - }, valid); - } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js -var require_patternProperties = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code2(); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var util_2 = require_util(); - var def = { - keyword: "patternProperties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema: schema2, data, parentSchema, it } = cxt; - const { opts } = it; - const patterns = (0, code_1.allSchemaProperties)(schema2); - const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema2[p])); - if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { - return; - } - const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; - const valid = gen.name("valid"); - if (it.props !== true && !(it.props instanceof codegen_1.Name)) { - it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + return 0; } - const { props } = it; - validatePatternProperties(); - function validatePatternProperties() { - for (const pat of patterns) { - if (checkProperties) - checkMatchingProperties(pat); - if (it.allErrors) { - validateProperties(pat); - } else { - gen.var(valid, true); - validateProperties(pat); - gen.if(valid); + function compareSignatures(signature1, signature2) { + const pars1 = signature1.params; + const pars2 = signature2.params; + const last1 = last(pars1); + const last2 = last(pars2); + const hasRest1 = hasRestParam(pars1); + const hasRest2 = hasRestParam(pars2); + if (hasRest1 && last1.hasAny) { + if (!hasRest2 || !last2.hasAny) { + return 1e7; + } + } else if (hasRest2 && last2.hasAny) { + return -1e7; + } + let any1 = 0; + let conv1 = 0; + let par; + for (par of pars1) { + if (par.hasAny) ++any1; + if (par.hasConversion) ++conv1; + } + let any2 = 0; + let conv2 = 0; + for (par of pars2) { + if (par.hasAny) ++any2; + if (par.hasConversion) ++conv2; + } + if (any1 !== any2) { + return (any1 - any2) * 1e6; + } + if (hasRest1 && last1.hasConversion) { + if (!hasRest2 || !last2.hasConversion) { + return 1e5; + } + } else if (hasRest2 && last2.hasConversion) { + return -1e5; + } + if (conv1 !== conv2) { + return (conv1 - conv2) * 1e4; + } + if (hasRest1) { + if (!hasRest2) { + return 1e3; + } + } else if (hasRest2) { + return -1e3; + } + const lengthCriterion = (pars1.length - pars2.length) * (hasRest1 ? -100 : 100); + if (lengthCriterion !== 0) { + return lengthCriterion; + } + const comparisons = []; + let tc = 0; + for (let i2 = 0; i2 < pars1.length; ++i2) { + const thisComparison = compareParams(pars1[i2], pars2[i2]); + comparisons.push(thisComparison); + tc += thisComparison; + } + if (tc !== 0) { + return (tc < 0 ? -10 : 10) + tc; + } + let c; + let bonus = 9; + const decrement = bonus / (comparisons.length + 1); + for (c of comparisons) { + if (c !== 0) { + return (c < 0 ? -bonus : bonus) + c; } + bonus -= decrement; } + return 0; } - function checkMatchingProperties(pat) { - for (const prop in checkProperties) { - if (new RegExp(pat).test(prop)) { - (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + function availableConversions(typeNames) { + if (typeNames.length === 0) { + return []; + } + const types = typeNames.map(findType); + if (typeNames.length === 1) return types[0].conversionsTo; + const knownTypes = new Set(typeNames); + const convertibleTypes = /* @__PURE__ */ new Set(); + for (let i2 = 0; i2 < types.length; ++i2) { + for (const match of types[i2].conversionsTo) { + if (!knownTypes.has(match.from)) convertibleTypes.add(match.from); + } + } + const matches = []; + for (const typeName of convertibleTypes) { + let bestIndex = nConversions + 1; + let bestConversion = null; + for (let i2 = 0; i2 < types.length; ++i2) { + for (const match of types[i2].conversionsTo) { + if (match.from === typeName && match.index < bestIndex) { + bestIndex = match.index; + bestConversion = match; + } + } } + matches.push(bestConversion); } + return matches; } - function validateProperties(pat) { - gen.forIn("key", data, (key) => { - gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { - const alwaysValid = alwaysValidPatterns.includes(pat); - if (!alwaysValid) { - cxt.subschema({ - keyword: "patternProperties", - schemaProp: pat, - dataProp: key, - dataPropType: util_2.Type.Str - }, valid); + function compileArgsPreprocessing(params, fn) { + let fnConvert = fn; + let name315 = ""; + if (params.some((p) => p.hasConversion)) { + const restParam = hasRestParam(params); + const compiledConversions = params.map(compileArgConversion); + name315 = compiledConversions.map((conv) => conv.name).join(";"); + fnConvert = function convertArgs() { + const args = []; + const last2 = restParam ? arguments.length - 1 : arguments.length; + for (let i2 = 0; i2 < last2; i2++) { + args[i2] = compiledConversions[i2](arguments[i2]); } - if (it.opts.unevaluated && props !== true) { - gen.assign((0, codegen_1._)`${props}[${key}]`, true); - } else if (!alwaysValid && !it.allErrors) { - gen.if((0, codegen_1.not)(valid), () => gen.break()); + if (restParam) { + args[last2] = arguments[last2].map(compiledConversions[last2]); } - }); + return fn.apply(this, args); + }; + } + let fnPreprocess = fnConvert; + if (hasRestParam(params)) { + const offset = params.length - 1; + fnPreprocess = function preprocessRestParams() { + return fnConvert.apply(this, slice(arguments, 0, offset).concat([slice(arguments, offset)])); + }; + } + if (name315) Object.defineProperty(fnPreprocess, "name", { + value: name315 }); + return fnPreprocess; } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js -var require_not = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var util_1 = require_util(); - var def = { - keyword: "not", - schemaType: ["object", "boolean"], - trackErrors: true, - code(cxt) { - const { gen, schema: schema2, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema2)) { - cxt.fail(); - return; - } - const valid = gen.name("valid"); - cxt.subschema({ - keyword: "not", - compositeRule: true, - createErrors: false, - allErrors: false - }, valid); - cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); - }, - error: { message: "must NOT be valid" } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js -var require_anyOf = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var code_1 = require_code2(); - var def = { - keyword: "anyOf", - schemaType: "array", - trackErrors: true, - code: code_1.validateUnion, - error: { message: "must match a schema in anyOf" } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js -var require_oneOf = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error2 = { - message: "must match exactly one schema in oneOf", - params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` - }; - var def = { - keyword: "oneOf", - schemaType: "array", - trackErrors: true, - error: error2, - code(cxt) { - const { gen, schema: schema2, parentSchema, it } = cxt; - if (!Array.isArray(schema2)) - throw new Error("ajv implementation error"); - if (it.opts.discriminator && parentSchema.discriminator) - return; - const schArr = schema2; - const valid = gen.let("valid", false); - const passing = gen.let("passing", null); - const schValid = gen.name("_valid"); - cxt.setParams({ passing }); - gen.block(validateOneOf); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - function validateOneOf() { - schArr.forEach((sch, i2) => { - let schCxt; - if ((0, util_1.alwaysValidSchema)(it, sch)) { - gen.var(schValid, true); - } else { - schCxt = cxt.subschema({ - keyword: "oneOf", - schemaProp: i2, - compositeRule: true - }, schValid); - } - if (i2 > 0) { - gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i2}]`).else(); + function compileArgConversion(param) { + let test0, test1, conversion0, conversion1; + const tests = []; + const conversions = []; + let name315 = ""; + param.types.forEach(function(type2) { + if (type2.conversion) { + name315 += type2.conversion.from + "~>" + type2.conversion.to + ","; + tests.push(findType(type2.conversion.from).test); + conversions.push(type2.conversion.convert); } - gen.if(schValid, () => { - gen.assign(valid, true); - gen.assign(passing, i2); - if (schCxt) - cxt.mergeEvaluated(schCxt, codegen_1.Name); - }); }); + if (name315) name315 = name315.slice(0, -1); + else name315 = "pass"; + let convertor = (arg2) => arg2; + switch (conversions.length) { + case 0: + break; + case 1: + test0 = tests[0]; + conversion0 = conversions[0]; + convertor = function convertArg(arg2) { + if (test0(arg2)) { + return conversion0(arg2); + } + return arg2; + }; + break; + case 2: + test0 = tests[0]; + test1 = tests[1]; + conversion0 = conversions[0]; + conversion1 = conversions[1]; + convertor = function convertArg(arg2) { + if (test0(arg2)) { + return conversion0(arg2); + } + if (test1(arg2)) { + return conversion1(arg2); + } + return arg2; + }; + break; + default: + convertor = function convertArg(arg2) { + for (let i2 = 0; i2 < conversions.length; i2++) { + if (tests[i2](arg2)) { + return conversions[i2](arg2); + } + } + return arg2; + }; + } + Object.defineProperty(convertor, "name", { + value: name315 + }); + return convertor; } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js -var require_allOf = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var util_1 = require_util(); - var def = { - keyword: "allOf", - schemaType: "array", - code(cxt) { - const { gen, schema: schema2, it } = cxt; - if (!Array.isArray(schema2)) - throw new Error("ajv implementation error"); - const valid = gen.name("valid"); - schema2.forEach((sch, i2) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) - return; - const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i2 }, valid); - cxt.ok(valid); - cxt.mergeEvaluated(schCxt); - }); - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js -var require_if = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var util_1 = require_util(); - var error2 = { - message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, - params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` - }; - var def = { - keyword: "if", - schemaType: ["object", "boolean"], - trackErrors: true, - error: error2, - code(cxt) { - const { gen, parentSchema, it } = cxt; - if (parentSchema.then === void 0 && parentSchema.else === void 0) { - (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); - } - const hasThen = hasSchema(it, "then"); - const hasElse = hasSchema(it, "else"); - if (!hasThen && !hasElse) - return; - const valid = gen.let("valid", true); - const schValid = gen.name("_valid"); - validateIf(); - cxt.reset(); - if (hasThen && hasElse) { - const ifClause = gen.let("ifClause"); - cxt.setParams({ ifClause }); - gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); - } else if (hasThen) { - gen.if(schValid, validateClause("then")); - } else { - gen.if((0, codegen_1.not)(schValid), validateClause("else")); - } - cxt.pass(valid, () => cxt.error(true)); - function validateIf() { - const schCxt = cxt.subschema({ - keyword: "if", - compositeRule: true, - createErrors: false, - allErrors: false - }, schValid); - cxt.mergeEvaluated(schCxt); + function splitParams(params) { + function _splitParams(params2, index2, paramsSoFar) { + if (index2 < params2.length) { + const param = params2[index2]; + let resultingParams = []; + if (param.restParam) { + const exactTypes = param.types.filter(isExactType); + if (exactTypes.length < param.types.length) { + resultingParams.push({ + types: exactTypes, + name: "..." + exactTypes.map((t) => t.name).join("|"), + hasAny: exactTypes.some((t) => t.isAny), + hasConversion: false, + restParam: true + }); + } + resultingParams.push(param); + } else { + resultingParams = param.types.map(function(type2) { + return { + types: [type2], + name: type2.name, + hasAny: type2.isAny, + hasConversion: type2.conversion, + restParam: false + }; + }); + } + return flatMap(resultingParams, function(nextParam) { + return _splitParams(params2, index2 + 1, paramsSoFar.concat([nextParam])); + }); + } else { + return [paramsSoFar]; + } + } + return _splitParams(params, 0, []); } - function validateClause(keyword, ifClause) { - return () => { - const schCxt = cxt.subschema({ keyword }, schValid); - gen.assign(valid, schValid); - cxt.mergeValidEvaluated(schCxt, valid); - if (ifClause) - gen.assign(ifClause, (0, codegen_1._)`${keyword}`); - else - cxt.setParams({ ifClause: keyword }); - }; + function conflicting(params1, params2) { + const ii = Math.max(params1.length, params2.length); + for (let i2 = 0; i2 < ii; i2++) { + const typeSet1 = getTypeSetAtIndex(params1, i2); + const typeSet2 = getTypeSetAtIndex(params2, i2); + let overlap = false; + let name315; + for (name315 of typeSet2) { + if (typeSet1.has(name315)) { + overlap = true; + break; + } + } + if (!overlap) { + return false; + } + } + const len1 = params1.length; + const len2 = params2.length; + const restParam1 = hasRestParam(params1); + const restParam2 = hasRestParam(params2); + return restParam1 ? restParam2 ? len1 === len2 : len2 >= len1 : restParam2 ? len1 >= len2 : len1 === len2; } - } - }; - function hasSchema(it, keyword) { - const schema2 = it.schema[keyword]; - return schema2 !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema2); - } - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js -var require_thenElse = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var util_1 = require_util(); - var def = { - keyword: ["then", "else"], - schemaType: ["object", "boolean"], - code({ keyword, parentSchema, it }) { - if (parentSchema.if === void 0) - (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js -var require_applicator = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var additionalItems_1 = require_additionalItems(); - var prefixItems_1 = require_prefixItems(); - var items_1 = require_items(); - var items2020_1 = require_items2020(); - var contains_1 = require_contains(); - var dependencies_1 = require_dependencies(); - var propertyNames_1 = require_propertyNames(); - var additionalProperties_1 = require_additionalProperties(); - var properties_1 = require_properties(); - var patternProperties_1 = require_patternProperties(); - var not_1 = require_not(); - var anyOf_1 = require_anyOf(); - var oneOf_1 = require_oneOf(); - var allOf_1 = require_allOf(); - var if_1 = require_if(); - var thenElse_1 = require_thenElse(); - function getApplicator(draft2020 = false) { - const applicator = [ - // any - not_1.default, - anyOf_1.default, - oneOf_1.default, - allOf_1.default, - if_1.default, - thenElse_1.default, - // object - propertyNames_1.default, - additionalProperties_1.default, - dependencies_1.default, - properties_1.default, - patternProperties_1.default - ]; - if (draft2020) - applicator.push(prefixItems_1.default, items2020_1.default); - else - applicator.push(additionalItems_1.default, items_1.default); - applicator.push(contains_1.default); - return applicator; - } - exports.default = getApplicator; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js -var require_format = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var error2 = { - message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` - }; - var def = { - keyword: "format", - type: ["number", "string"], - schemaType: "string", - $data: true, - error: error2, - code(cxt, ruleType) { - const { gen, data, $data, schema: schema2, schemaCode, it } = cxt; - const { opts, errSchemaPath, schemaEnv, self: self2 } = it; - if (!opts.validateFormats) - return; - if ($data) - validate$DataFormat(); - else - validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self2.formats, - code: opts.code.formats + function clearResolutions(functionList) { + return functionList.map((fn) => { + if (isReferToSelf(fn)) { + return referToSelf(fn.referToSelf.callback); + } + if (isReferTo(fn)) { + return makeReferTo(fn.referTo.references, fn.referTo.callback); + } + return fn; }); - const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); - const fType = gen.let("fType"); - const format5 = gen.let("format"); - gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format5, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format5, fDef)); - cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); - function unknownFmt() { - if (opts.strictSchema === false) - return codegen_1.nil; - return (0, codegen_1._)`${schemaCode} && !${format5}`; + } + function collectResolutions(references, functionList, signatureMap) { + const resolvedReferences = []; + let reference; + for (reference of references) { + let resolution = signatureMap[reference]; + if (typeof resolution !== "number") { + throw new TypeError('No definition for referenced signature "' + reference + '"'); + } + resolution = functionList[resolution]; + if (typeof resolution !== "function") { + return false; + } + resolvedReferences.push(resolution); } - function invalidFmt() { - const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format5}(${data}) : ${format5}(${data}))` : (0, codegen_1._)`${format5}(${data})`; - const validData = (0, codegen_1._)`(typeof ${format5} == "function" ? ${callFormat} : ${format5}.test(${data}))`; - return (0, codegen_1._)`${format5} && ${format5} !== true && ${fType} === ${ruleType} && !${validData}`; + return resolvedReferences; + } + function resolveReferences(functionList, signatureMap, self2) { + const resolvedFunctions = clearResolutions(functionList); + const isResolved = new Array(resolvedFunctions.length).fill(false); + let leftUnresolved = true; + while (leftUnresolved) { + leftUnresolved = false; + let nothingResolved = true; + for (let i2 = 0; i2 < resolvedFunctions.length; ++i2) { + if (isResolved[i2]) continue; + const fn = resolvedFunctions[i2]; + if (isReferToSelf(fn)) { + resolvedFunctions[i2] = fn.referToSelf.callback(self2); + resolvedFunctions[i2].referToSelf = fn.referToSelf; + isResolved[i2] = true; + nothingResolved = false; + } else if (isReferTo(fn)) { + const resolvedReferences = collectResolutions(fn.referTo.references, resolvedFunctions, signatureMap); + if (resolvedReferences) { + resolvedFunctions[i2] = fn.referTo.callback.apply(this, resolvedReferences); + resolvedFunctions[i2].referTo = fn.referTo; + isResolved[i2] = true; + nothingResolved = false; + } else { + leftUnresolved = true; + } + } + } + if (nothingResolved && leftUnresolved) { + throw new SyntaxError("Circular reference detected in resolving typed.referTo"); + } } + return resolvedFunctions; } - function validateFormat() { - const formatDef = self2.formats[schema2]; - if (!formatDef) { - unknownFormat(); - return; + function validateDeprecatedThis(signaturesMap) { + const deprecatedThisRegex = /\bthis(\(|\.signatures\b)/; + Object.keys(signaturesMap).forEach((signature) => { + const fn = signaturesMap[signature]; + if (deprecatedThisRegex.test(fn.toString())) { + throw new SyntaxError("Using `this` to self-reference a function is deprecated since typed-function@3. Use typed.referTo and typed.referToSelf instead."); + } + }); + } + function createTypedFunction(name315, rawSignaturesMap) { + typed3.createCount++; + if (Object.keys(rawSignaturesMap).length === 0) { + throw new SyntaxError("No signatures provided"); } - if (formatDef === true) - return; - const [fmtType, format5, fmtRef] = getFormat(formatDef); - if (fmtType === ruleType) - cxt.pass(validCondition()); - function unknownFormat() { - if (opts.strictSchema === false) { - self2.logger.warn(unknownMsg()); - return; + if (typed3.warnAgainstDeprecatedThis) { + validateDeprecatedThis(rawSignaturesMap); + } + const parsedParams = []; + const originalFunctions = []; + const signaturesMap = {}; + const preliminarySignatures = []; + let signature; + for (signature in rawSignaturesMap) { + if (!Object.prototype.hasOwnProperty.call(rawSignaturesMap, signature)) { + continue; } - throw new Error(unknownMsg()); - function unknownMsg() { - return `unknown format "${schema2}" ignored in schema at path "${errSchemaPath}"`; + const params = parseSignature(signature); + if (!params) continue; + parsedParams.forEach(function(pp) { + if (conflicting(pp, params)) { + throw new TypeError('Conflicting signatures "' + stringifyParams(pp) + '" and "' + stringifyParams(params) + '".'); + } + }); + parsedParams.push(params); + const functionIndex = originalFunctions.length; + originalFunctions.push(rawSignaturesMap[signature]); + const conversionParams = params.map(expandParam); + let sp; + for (sp of splitParams(conversionParams)) { + const spName = stringifyParams(sp); + preliminarySignatures.push({ + params: sp, + name: spName, + fn: functionIndex + }); + if (sp.every((p) => !p.hasConversion)) { + signaturesMap[spName] = functionIndex; + } } } - function getFormat(fmtDef) { - const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema2)}` : void 0; - const fmt = gen.scopeValue("formats", { key: schema2, ref: fmtDef, code }); - if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { - return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; + preliminarySignatures.sort(compareSignatures); + const resolvedFunctions = resolveReferences(originalFunctions, signaturesMap, theTypedFn); + let s; + for (s in signaturesMap) { + if (Object.prototype.hasOwnProperty.call(signaturesMap, s)) { + signaturesMap[s] = resolvedFunctions[signaturesMap[s]]; } - return ["string", fmtDef, fmt]; } - function validCondition() { - if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { - if (!schemaEnv.$async) - throw new Error("async format in sync schema"); - return (0, codegen_1._)`await ${fmtRef}(${data})`; + const signatures = []; + const internalSignatureMap = /* @__PURE__ */ new Map(); + for (s of preliminarySignatures) { + if (!internalSignatureMap.has(s.name)) { + s.fn = resolvedFunctions[s.fn]; + signatures.push(s); + internalSignatureMap.set(s.name, s); } - return typeof format5 == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; } + const ok0 = signatures[0] && signatures[0].params.length <= 2 && !hasRestParam(signatures[0].params); + const ok1 = signatures[1] && signatures[1].params.length <= 2 && !hasRestParam(signatures[1].params); + const ok2 = signatures[2] && signatures[2].params.length <= 2 && !hasRestParam(signatures[2].params); + const ok3 = signatures[3] && signatures[3].params.length <= 2 && !hasRestParam(signatures[3].params); + const ok4 = signatures[4] && signatures[4].params.length <= 2 && !hasRestParam(signatures[4].params); + const ok5 = signatures[5] && signatures[5].params.length <= 2 && !hasRestParam(signatures[5].params); + const allOk = ok0 && ok1 && ok2 && ok3 && ok4 && ok5; + for (let i2 = 0; i2 < signatures.length; ++i2) { + signatures[i2].test = compileTests(signatures[i2].params); + } + const test00 = ok0 ? compileTest(signatures[0].params[0]) : notOk; + const test10 = ok1 ? compileTest(signatures[1].params[0]) : notOk; + const test20 = ok2 ? compileTest(signatures[2].params[0]) : notOk; + const test30 = ok3 ? compileTest(signatures[3].params[0]) : notOk; + const test40 = ok4 ? compileTest(signatures[4].params[0]) : notOk; + const test50 = ok5 ? compileTest(signatures[5].params[0]) : notOk; + const test01 = ok0 ? compileTest(signatures[0].params[1]) : notOk; + const test11 = ok1 ? compileTest(signatures[1].params[1]) : notOk; + const test21 = ok2 ? compileTest(signatures[2].params[1]) : notOk; + const test31 = ok3 ? compileTest(signatures[3].params[1]) : notOk; + const test41 = ok4 ? compileTest(signatures[4].params[1]) : notOk; + const test51 = ok5 ? compileTest(signatures[5].params[1]) : notOk; + for (let i2 = 0; i2 < signatures.length; ++i2) { + signatures[i2].implementation = compileArgsPreprocessing(signatures[i2].params, signatures[i2].fn); + } + const fn0 = ok0 ? signatures[0].implementation : undef; + const fn1 = ok1 ? signatures[1].implementation : undef; + const fn2 = ok2 ? signatures[2].implementation : undef; + const fn3 = ok3 ? signatures[3].implementation : undef; + const fn4 = ok4 ? signatures[4].implementation : undef; + const fn5 = ok5 ? signatures[5].implementation : undef; + const len0 = ok0 ? signatures[0].params.length : -1; + const len1 = ok1 ? signatures[1].params.length : -1; + const len2 = ok2 ? signatures[2].params.length : -1; + const len3 = ok3 ? signatures[3].params.length : -1; + const len4 = ok4 ? signatures[4].params.length : -1; + const len5 = ok5 ? signatures[5].params.length : -1; + const iStart = allOk ? 6 : 0; + const iEnd = signatures.length; + const tests = signatures.map((s2) => s2.test); + const fns = signatures.map((s2) => s2.implementation); + const generic = function generic2() { + for (let i2 = iStart; i2 < iEnd; i2++) { + if (tests[i2](arguments)) { + return fns[i2].apply(this, arguments); + } + } + return typed3.onMismatch(name315, arguments, signatures); + }; + function theTypedFn(arg0, arg1) { + if (arguments.length === len0 && test00(arg0) && test01(arg1)) { + return fn0.apply(this, arguments); + } + if (arguments.length === len1 && test10(arg0) && test11(arg1)) { + return fn1.apply(this, arguments); + } + if (arguments.length === len2 && test20(arg0) && test21(arg1)) { + return fn2.apply(this, arguments); + } + if (arguments.length === len3 && test30(arg0) && test31(arg1)) { + return fn3.apply(this, arguments); + } + if (arguments.length === len4 && test40(arg0) && test41(arg1)) { + return fn4.apply(this, arguments); + } + if (arguments.length === len5 && test50(arg0) && test51(arg1)) { + return fn5.apply(this, arguments); + } + return generic.apply(this, arguments); + } + try { + Object.defineProperty(theTypedFn, "name", { + value: name315 + }); + } catch (err) { + } + theTypedFn.signatures = signaturesMap; + theTypedFn._typedFunctionData = { + signatures, + signatureMap: internalSignatureMap + }; + return theTypedFn; } - } - }; - exports.default = def; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js -var require_format2 = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var format_1 = require_format(); - var format5 = [format_1.default]; - exports.default = format5; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js -var require_metadata = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.contentVocabulary = exports.metadataVocabulary = void 0; - exports.metadataVocabulary = [ - "title", - "description", - "default", - "deprecated", - "readOnly", - "writeOnly", - "examples" - ]; - exports.contentVocabulary = [ - "contentMediaType", - "contentEncoding", - "contentSchema" - ]; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js -var require_draft7 = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var core_1 = require_core2(); - var validation_1 = require_validation(); - var applicator_1 = require_applicator(); - var format_1 = require_format2(); - var metadata_1 = require_metadata(); - var draft7Vocabularies = [ - core_1.default, - validation_1.default, - (0, applicator_1.default)(), - format_1.default, - metadata_1.metadataVocabulary, - metadata_1.contentVocabulary - ]; - exports.default = draft7Vocabularies; - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js -var require_types = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DiscrError = void 0; - var DiscrError; - (function(DiscrError2) { - DiscrError2["Tag"] = "tag"; - DiscrError2["Mapping"] = "mapping"; - })(DiscrError || (exports.DiscrError = DiscrError = {})); - } -}); - -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js -var require_discriminator = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var codegen_1 = require_codegen(); - var types_1 = require_types(); - var compile_1 = require_compile(); - var ref_error_1 = require_ref_error(); - var util_1 = require_util(); - var error2 = { - message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, - params: ({ params: { discrError, tag: tag2, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag2}}` - }; - var def = { - keyword: "discriminator", - type: "object", - schemaType: "object", - error: error2, - code(cxt) { - const { gen, data, schema: schema2, parentSchema, it } = cxt; - const { oneOf } = parentSchema; - if (!it.opts.discriminator) { - throw new Error("discriminator: requires discriminator option"); - } - const tagName = schema2.propertyName; - if (typeof tagName != "string") - throw new Error("discriminator: requires propertyName"); - if (schema2.mapping) - throw new Error("discriminator: mapping is not supported"); - if (!oneOf) - throw new Error("discriminator: requires oneOf keyword"); - const valid = gen.let("valid", false); - const tag2 = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); - gen.if((0, codegen_1._)`typeof ${tag2} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag: tag2, tagName })); - cxt.ok(valid); - function validateMapping() { - const mapping = getMapping(); - gen.if(false); - for (const tagValue in mapping) { - gen.elseIf((0, codegen_1._)`${tag2} === ${tagValue}`); - gen.assign(valid, applyTagSchema(mapping[tagValue])); + function _onMismatch(name315, args, signatures) { + throw createError(name315, args, signatures); + } + function initial(arr) { + return slice(arr, 0, arr.length - 1); + } + function last(arr) { + return arr[arr.length - 1]; + } + function slice(arr, start, end) { + return Array.prototype.slice.call(arr, start, end); + } + function findInArray(arr, test) { + for (let i2 = 0; i2 < arr.length; i2++) { + if (test(arr[i2])) { + return arr[i2]; + } } - gen.else(); - cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag: tag2, tagName }); - gen.endIf(); + return void 0; } - function applyTagSchema(schemaProp) { - const _valid = gen.name("valid"); - const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); - cxt.mergeEvaluated(schCxt, codegen_1.Name); - return _valid; + function flatMap(arr, callback) { + return Array.prototype.concat.apply([], arr.map(callback)); } - function getMapping() { - var _a; - const oneOfMapping = {}; - const topRequired = hasRequired(parentSchema); - let tagRequired = true; - for (let i2 = 0; i2 < oneOf.length; i2++) { - let sch = oneOf[i2]; - if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { - const ref = sch.$ref; - sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); - if (sch instanceof compile_1.SchemaEnv) - sch = sch.schema; - if (sch === void 0) - throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + function referTo() { + const references = initial(arguments).map((s) => stringifyParams(parseSignature(s))); + const callback = last(arguments); + if (typeof callback !== "function") { + throw new TypeError("Callback function expected as last argument"); + } + return makeReferTo(references, callback); + } + function makeReferTo(references, callback) { + return { + referTo: { + references, + callback } - const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; - if (typeof propSch != "object") { - throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + }; + } + function referToSelf(callback) { + if (typeof callback !== "function") { + throw new TypeError("Callback function expected as first argument"); + } + return { + referToSelf: { + callback } - tagRequired = tagRequired && (topRequired || hasRequired(sch)); - addMappings(propSch, i2); + }; + } + function isReferTo(objectOrFn) { + return objectOrFn && typeof objectOrFn.referTo === "object" && Array.isArray(objectOrFn.referTo.references) && typeof objectOrFn.referTo.callback === "function"; + } + function isReferToSelf(objectOrFn) { + return objectOrFn && typeof objectOrFn.referToSelf === "object" && typeof objectOrFn.referToSelf.callback === "function"; + } + function checkName(nameSoFar, newName) { + if (!nameSoFar) { + return newName; } - if (!tagRequired) - throw new Error(`discriminator: "${tagName}" must be required`); - return oneOfMapping; - function hasRequired({ required: required2 }) { - return Array.isArray(required2) && required2.includes(tagName); + if (newName && newName !== nameSoFar) { + const err = new Error("Function names do not match (expected: " + nameSoFar + ", actual: " + newName + ")"); + err.data = { + actual: newName, + expected: nameSoFar + }; + throw err; } - function addMappings(sch, i2) { - if (sch.const) { - addMapping(sch.const, i2); - } else if (sch.enum) { - for (const tagValue of sch.enum) { - addMapping(tagValue, i2); + return nameSoFar; + } + function getObjectName(obj) { + let name315; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key) && (isTypedFunction(obj[key]) || typeof obj[key].signature === "string")) { + name315 = checkName(name315, obj[key].name); + } + } + return name315; + } + function mergeSignatures(dest, source) { + let key; + for (key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + if (key in dest) { + if (source[key] !== dest[key]) { + const err = new Error('Signature "' + key + '" is defined twice'); + err.data = { + signature: key, + sourceFunction: source[key], + destFunction: dest[key] + }; + throw err; + } } - } else { - throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + dest[key] = source[key]; } } - function addMapping(tagValue, i2) { - if (typeof tagValue != "string" || tagValue in oneOfMapping) { - throw new Error(`discriminator: "${tagName}" values must be unique strings`); + } + const saveTyped = typed3; + typed3 = function(maybeName) { + const named = typeof maybeName === "string"; + const start = named ? 1 : 0; + let name315 = named ? maybeName : ""; + const allSignatures = {}; + for (let i2 = start; i2 < arguments.length; ++i2) { + const item = arguments[i2]; + let theseSignatures = {}; + let thisName; + if (typeof item === "function") { + thisName = item.name; + if (typeof item.signature === "string") { + theseSignatures[item.signature] = item; + } else if (isTypedFunction(item)) { + theseSignatures = item.signatures; + } + } else if (isPlainObject4(item)) { + theseSignatures = item; + if (!named) { + thisName = getObjectName(item); + } } - oneOfMapping[tagValue] = i2; + if (Object.keys(theseSignatures).length === 0) { + const err = new TypeError("Argument to 'typed' at index " + i2 + " is not a (typed) function, nor an object with signatures as keys and functions as values."); + err.data = { + index: i2, + argument: item + }; + throw err; + } + if (!named) { + name315 = checkName(name315, thisName); + } + mergeSignatures(allSignatures, theseSignatures); + } + return createTypedFunction(name315 || "", allSignatures); + }; + typed3.create = create; + typed3.createCount = saveTyped.createCount; + typed3.onMismatch = _onMismatch; + typed3.throwMismatchError = _onMismatch; + typed3.createError = createError; + typed3.clear = clear; + typed3.clearConversions = clearConversions; + typed3.addTypes = addTypes; + typed3._findType = findType; + typed3.referTo = referTo; + typed3.referToSelf = referToSelf; + typed3.convert = convert; + typed3.findSignature = findSignature; + typed3.find = find; + typed3.isTypedFunction = isTypedFunction; + typed3.warnAgainstDeprecatedThis = true; + typed3.addType = function(type2, beforeObjectTest) { + let before = "any"; + if (beforeObjectTest !== false && typeMap.has("Object")) { + before = "Object"; + } + typed3.addTypes([type2], before); + }; + function _validateConversion(conversion) { + if (!conversion || typeof conversion.from !== "string" || typeof conversion.to !== "string" || typeof conversion.convert !== "function") { + throw new TypeError("Object with properties {from: string, to: string, convert: function} expected"); + } + if (conversion.to === conversion.from) { + throw new SyntaxError('Illegal to define conversion from "' + conversion.from + '" to itself.'); } } + typed3.addConversion = function(conversion) { + let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : { + override: false + }; + _validateConversion(conversion); + const to2 = findType(conversion.to); + const existing = to2.conversionsTo.find((other) => other.from === conversion.from); + if (existing) { + if (options && options.override) { + typed3.removeConversion({ + from: existing.from, + to: conversion.to, + convert: existing.convert + }); + } else { + throw new Error('There is already a conversion from "' + conversion.from + '" to "' + to2.name + '"'); + } + } + to2.conversionsTo.push({ + from: conversion.from, + to: to2.name, + convert: conversion.convert, + index: nConversions++ + }); + }; + typed3.addConversions = function(conversions, options) { + conversions.forEach((conversion) => typed3.addConversion(conversion, options)); + }; + typed3.removeConversion = function(conversion) { + _validateConversion(conversion); + const to2 = findType(conversion.to); + const existingConversion = findInArray(to2.conversionsTo, (c) => c.from === conversion.from); + if (!existingConversion) { + throw new Error("Attempt to remove nonexistent conversion from " + conversion.from + " to " + conversion.to); + } + if (existingConversion.convert !== conversion.convert) { + throw new Error("Conversion to remove does not match existing conversion"); + } + const index2 = to2.conversionsTo.indexOf(existingConversion); + to2.conversionsTo.splice(index2, 1); + }; + typed3.resolve = function(tf, argList) { + if (!isTypedFunction(tf)) { + throw new TypeError(NOT_TYPED_FUNCTION); + } + const sigs = tf._typedFunctionData.signatures; + for (let i2 = 0; i2 < sigs.length; ++i2) { + if (sigs[i2].test(argList)) { + return sigs[i2]; + } + } + return null; + }; + return typed3; } - }; - exports.default = def; + var typedFunction2 = create(); + return typedFunction2; + })); } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json -var require_json_schema_draft_07 = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module) { - module.exports = { - $schema: "http://json-schema.org/draft-07/schema#", - $id: "http://json-schema.org/draft-07/schema#", - title: "Core schema meta-schema", - definitions: { - schemaArray: { - type: "array", - minItems: 1, - items: { $ref: "#" } - }, - nonNegativeInteger: { - type: "integer", - minimum: 0 - }, - nonNegativeIntegerDefault0: { - allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] - }, - simpleTypes: { - enum: ["array", "boolean", "integer", "null", "number", "object", "string"] - }, - stringArray: { - type: "array", - items: { type: "string" }, - uniqueItems: true, - default: [] - } - }, - type: ["object", "boolean"], - properties: { - $id: { - type: "string", - format: "uri-reference" - }, - $schema: { - type: "string", - format: "uri" - }, - $ref: { - type: "string", - format: "uri-reference" - }, - $comment: { - type: "string" - }, - title: { - type: "string" - }, - description: { - type: "string" - }, - default: true, - readOnly: { - type: "boolean", - default: false - }, - examples: { - type: "array", - items: true - }, - multipleOf: { - type: "number", - exclusiveMinimum: 0 - }, - maximum: { - type: "number" - }, - exclusiveMaximum: { - type: "number" - }, - minimum: { - type: "number" - }, - exclusiveMinimum: { - type: "number" - }, - maxLength: { $ref: "#/definitions/nonNegativeInteger" }, - minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, - pattern: { - type: "string", - format: "regex" - }, - additionalItems: { $ref: "#" }, - items: { - anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], - default: true - }, - maxItems: { $ref: "#/definitions/nonNegativeInteger" }, - minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, - uniqueItems: { - type: "boolean", - default: false - }, - contains: { $ref: "#" }, - maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, - minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, - required: { $ref: "#/definitions/stringArray" }, - additionalProperties: { $ref: "#" }, - definitions: { - type: "object", - additionalProperties: { $ref: "#" }, - default: {} - }, - properties: { - type: "object", - additionalProperties: { $ref: "#" }, - default: {} - }, - patternProperties: { - type: "object", - additionalProperties: { $ref: "#" }, - propertyNames: { format: "regex" }, - default: {} - }, - dependencies: { - type: "object", - additionalProperties: { - anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] - } - }, - propertyNames: { $ref: "#" }, - const: true, - enum: { - type: "array", - items: true, - minItems: 1, - uniqueItems: true - }, - type: { - anyOf: [ - { $ref: "#/definitions/simpleTypes" }, - { - type: "array", - items: { $ref: "#/definitions/simpleTypes" }, - minItems: 1, - uniqueItems: true - } - ] - }, - format: { type: "string" }, - contentMediaType: { type: "string" }, - contentEncoding: { type: "string" }, - if: { $ref: "#" }, - then: { $ref: "#" }, - else: { $ref: "#" }, - allOf: { $ref: "#/definitions/schemaArray" }, - anyOf: { $ref: "#/definitions/schemaArray" }, - oneOf: { $ref: "#/definitions/schemaArray" }, - not: { $ref: "#" } - }, - default: true - }; +// node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/typeof.js +var require_typeof = __commonJS({ + "node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/typeof.js"(exports, module) { + function _typeof(o) { + "@babel/helpers - typeof"; + return module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) { + return typeof o2; + } : function(o2) { + return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2; + }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof(o); + } + module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); -// node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js -var require_ajv = __commonJS({ - "node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js"(exports, module) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; - var core_1 = require_core(); - var draft7_1 = require_draft7(); - var discriminator_1 = require_discriminator(); - var draft7MetaSchema = require_json_schema_draft_07(); - var META_SUPPORT_DATA = ["/properties"]; - var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; - var Ajv2 = class extends core_1.default { - _addVocabularies() { - super._addVocabularies(); - draft7_1.default.forEach((v) => this.addVocabulary(v)); - if (this.opts.discriminator) - this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - if (!this.opts.meta) - return; - const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; - this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); +// node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/toPrimitive.js +var require_toPrimitive = __commonJS({ + "node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/toPrimitive.js"(exports, module) { + var _typeof = require_typeof()["default"]; + function toPrimitive(t, r) { + if ("object" != _typeof(t) || !t) return t; + var e3 = t[Symbol.toPrimitive]; + if (void 0 !== e3) { + var i2 = e3.call(t, r || "default"); + if ("object" != _typeof(i2)) return i2; + throw new TypeError("@@toPrimitive must return a primitive value."); } - }; - exports.Ajv = Ajv2; - module.exports = exports = Ajv2; - module.exports.Ajv = Ajv2; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv2; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { - return validate_1.KeywordCxt; - } }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { enumerable: true, get: function() { - return codegen_1._; - } }); - Object.defineProperty(exports, "str", { enumerable: true, get: function() { - return codegen_1.str; - } }); - Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { - return codegen_1.stringify; - } }); - Object.defineProperty(exports, "nil", { enumerable: true, get: function() { - return codegen_1.nil; - } }); - Object.defineProperty(exports, "Name", { enumerable: true, get: function() { - return codegen_1.Name; - } }); - Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { - return codegen_1.CodeGen; - } }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { - return validation_error_1.default; - } }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { - return ref_error_1.default; - } }); + return ("string" === r ? String : Number)(t); + } + module.exports = toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); -// node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js -var require_formats = __commonJS({ - "node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate2, compare2) { - return { validate: validate2, compare: compare2 }; - } - exports.fullFormats = { - // date: http://tools.ietf.org/html/rfc3339#section-5.6 - date: fmtDef(date3, compareDate), - // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 - time: fmtDef(getTime(true), compareTime), - "date-time": fmtDef(getDateTime(true), compareDateTime), - "iso-time": fmtDef(getTime(), compareIsoTime), - "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), - // duration: https://tools.ietf.org/html/rfc3339#appendix-A - duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, - uri, - "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, - // uri-template: https://tools.ietf.org/html/rfc6570 - "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, - // For the source: https://gist.github.com/dperini/729294 - // For test cases: https://mathiasbynens.be/demo/url-regex - url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, - email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, - hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, - // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, - ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, - regex, - // uuid: http://tools.ietf.org/html/rfc4122 - uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, - // JSON-pointer: https://tools.ietf.org/html/rfc6901 - // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A - "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, - "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, - // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 - "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, - // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types - // byte: https://github.com/miguelmota/is-base64 - byte, - // signed 32 bit integer - int32: { type: "number", validate: validateInt32 }, - // signed 64 bit integer - int64: { type: "number", validate: validateInt64 }, - // C-type float - float: { type: "number", validate: validateNumber }, - // C-type double - double: { type: "number", validate: validateNumber }, - // hint to the UI to hide input strings - password: true, - // unchecked string payload - binary: true - }; - exports.fastFormats = { - ...exports.fullFormats, - date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), - time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), - "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), - "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), - "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), - // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js - uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, - "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, - // email (sources from jsen validator): - // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 - // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') - email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i - }; - exports.formatNames = Object.keys(exports.fullFormats); - function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); - } - var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; - var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - function date3(str2) { - const matches = DATE.exec(str2); - if (!matches) - return false; - const year = +matches[1]; - const month = +matches[2]; - const day = +matches[3]; - return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); - } - function compareDate(d1, d2) { - if (!(d1 && d2)) - return void 0; - if (d1 > d2) - return 1; - if (d1 < d2) - return -1; - return 0; - } - var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; - function getTime(strictTimeZone) { - return function time3(str2) { - const matches = TIME.exec(str2); - if (!matches) - return false; - const hr = +matches[1]; - const min3 = +matches[2]; - const sec2 = +matches[3]; - const tz = matches[4]; - const tzSign = matches[5] === "-" ? -1 : 1; - const tzH = +(matches[6] || 0); - const tzM = +(matches[7] || 0); - if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) - return false; - if (hr <= 23 && min3 <= 59 && sec2 < 60) - return true; - const utcMin = min3 - tzM * tzSign; - const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); - return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec2 < 61; - }; - } - function compareTime(s1, s2) { - if (!(s1 && s2)) - return void 0; - const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); - const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); - if (!(t1 && t2)) - return void 0; - return t1 - t2; - } - function compareIsoTime(t1, t2) { - if (!(t1 && t2)) - return void 0; - const a1 = TIME.exec(t1); - const a2 = TIME.exec(t2); - if (!(a1 && a2)) - return void 0; - t1 = a1[1] + a1[2] + a1[3]; - t2 = a2[1] + a2[2] + a2[3]; - if (t1 > t2) - return 1; - if (t1 < t2) - return -1; - return 0; - } - var DATE_TIME_SEPARATOR = /t|\s/i; - function getDateTime(strictTimeZone) { - const time3 = getTime(strictTimeZone); - return function date_time(str2) { - const dateTime = str2.split(DATE_TIME_SEPARATOR); - return dateTime.length === 2 && date3(dateTime[0]) && time3(dateTime[1]); - }; - } - function compareDateTime(dt1, dt2) { - if (!(dt1 && dt2)) - return void 0; - const d1 = new Date(dt1).valueOf(); - const d2 = new Date(dt2).valueOf(); - if (!(d1 && d2)) - return void 0; - return d1 - d2; - } - function compareIsoDateTime(dt1, dt2) { - if (!(dt1 && dt2)) - return void 0; - const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); - const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); - const res = compareDate(d1, d2); - if (res === void 0) - return void 0; - return res || compareTime(t1, t2); - } - var NOT_URI_FRAGMENT = /\/|:/; - var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; - function uri(str2) { - return NOT_URI_FRAGMENT.test(str2) && URI.test(str2); - } - var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; - function byte(str2) { - BYTE.lastIndex = 0; - return BYTE.test(str2); - } - var MIN_INT32 = -(2 ** 31); - var MAX_INT32 = 2 ** 31 - 1; - function validateInt32(value) { - return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; - } - function validateInt64(value) { - return Number.isInteger(value); - } - function validateNumber() { - return true; +// node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/toPropertyKey.js +var require_toPropertyKey = __commonJS({ + "node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/toPropertyKey.js"(exports, module) { + var _typeof = require_typeof()["default"]; + var toPrimitive = require_toPrimitive(); + function toPropertyKey(t) { + var i2 = toPrimitive(t, "string"); + return "symbol" == _typeof(i2) ? i2 : i2 + ""; } - var Z_ANCHOR = /[^\\]\\Z/; - function regex(str2) { - if (Z_ANCHOR.test(str2)) - return false; - try { - new RegExp(str2); - return true; - } catch (e3) { - return false; - } + module.exports = toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports; + } +}); + +// node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/defineProperty.js +var require_defineProperty = __commonJS({ + "node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/defineProperty.js"(exports, module) { + var toPropertyKey = require_toPropertyKey(); + function _defineProperty18(e3, r, t) { + return (r = toPropertyKey(r)) in e3 ? Object.defineProperty(e3, r, { + value: t, + enumerable: true, + configurable: true, + writable: true + }) : e3[r] = t, e3; } + module.exports = _defineProperty18, module.exports.__esModule = true, module.exports["default"] = module.exports; } }); -// node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js -var require_limit = __commonJS({ - "node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatLimitDefinition = void 0; - var ajv_1 = require_ajv(); - var codegen_1 = require_codegen(); - var ops = codegen_1.operators; - var KWDs = { - formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, - formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, - formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, - formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } - }; - var error2 = { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }; - exports.formatLimitDefinition = { - keyword: Object.keys(KWDs), - type: "string", - schemaType: "string", - $data: true, - error: error2, - code(cxt) { - const { gen, data, schemaCode, keyword, it } = cxt; - const { opts, self: self2 } = it; - if (!opts.validateFormats) - return; - const fCxt = new ajv_1.KeywordCxt(it, self2.RULES.all.format.definition, "format"); - if (fCxt.$data) - validate$DataFormat(); - else - validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self2.formats, - code: opts.code.formats - }); - const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); - cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); +// node_modules/.pnpm/javascript-natural-sort@0.7.1/node_modules/javascript-natural-sort/naturalSort.js +var require_naturalSort = __commonJS({ + "node_modules/.pnpm/javascript-natural-sort@0.7.1/node_modules/javascript-natural-sort/naturalSort.js"(exports, module) { + module.exports = function naturalSort2(a, b) { + "use strict"; + var re2 = /(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi, sre = /(^[ ]*|[ ]*$)/g, dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/, hre = /^0x[0-9a-f]+$/i, ore = /^0/, i2 = function(s) { + return naturalSort2.insensitive && ("" + s).toLowerCase() || "" + s; + }, x = i2(a).replace(sre, "") || "", y = i2(b).replace(sre, "") || "", xN = x.replace(re2, "\0$1\0").replace(/\0$/, "").replace(/^\0/, "").split("\0"), yN = y.replace(re2, "\0$1\0").replace(/\0$/, "").replace(/^\0/, "").split("\0"), xD = parseInt(x.match(hre), 16) || xN.length !== 1 && x.match(dre) && Date.parse(x), yD = parseInt(y.match(hre), 16) || xD && y.match(dre) && Date.parse(y) || null, oFxNcL, oFyNcL; + if (yD) { + if (xD < yD) { + return -1; + } else if (xD > yD) { + return 1; } - function validateFormat() { - const format5 = fCxt.schema; - const fmtDef = self2.formats[format5]; - if (!fmtDef || fmtDef === true) - return; - if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") { - throw new Error(`"${keyword}": format "${format5}" does not define "compare" function`); - } - const fmt = gen.scopeValue("formats", { - key: format5, - ref: fmtDef, - code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format5)}` : void 0 - }); - cxt.fail$data(compareCode(fmt)); + } + for (var cLoc = 0, numS = Math.max(xN.length, yN.length); cLoc < numS; cLoc++) { + oFxNcL = !(xN[cLoc] || "").match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0; + oFyNcL = !(yN[cLoc] || "").match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0; + if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { + return isNaN(oFxNcL) ? 1 : -1; + } else if (typeof oFxNcL !== typeof oFyNcL) { + oFxNcL += ""; + oFyNcL += ""; } - function compareCode(fmt) { - return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; + if (oFxNcL < oFyNcL) { + return -1; } - }, - dependencies: ["format"] - }; - var formatLimitPlugin = (ajv2) => { - ajv2.addKeyword(exports.formatLimitDefinition); - return ajv2; + if (oFxNcL > oFyNcL) { + return 1; + } + } + return 0; }; - exports.default = formatLimitPlugin; } }); -// node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js -var require_dist = __commonJS({ - "node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js"(exports, module) { +// node_modules/.pnpm/escape-latex@1.2.0/node_modules/escape-latex/dist/index.js +var require_dist2 = __commonJS({ + "node_modules/.pnpm/escape-latex@1.2.0/node_modules/escape-latex/dist/index.js"(exports, module) { "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - var formats_1 = require_formats(); - var limit_1 = require_limit(); - var codegen_1 = require_codegen(); - var fullName = new codegen_1.Name("fullFormats"); - var fastName = new codegen_1.Name("fastFormats"); - var formatsPlugin = (ajv2, opts = { keywords: true }) => { - if (Array.isArray(opts)) { - addFormats(ajv2, opts, formats_1.fullFormats, fullName); - return ajv2; + var _extends8 = Object.assign || function(target) { + for (var i2 = 1; i2 < arguments.length; i2++) { + var source = arguments[i2]; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } } - const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; - const list = opts.formats || formats_1.formatNames; - addFormats(ajv2, list, formats, exportName); - if (opts.keywords) - (0, limit_1.default)(ajv2); - return ajv2; - }; - formatsPlugin.get = (name315, mode2 = "full") => { - const formats = mode2 === "fast" ? formats_1.fastFormats : formats_1.fullFormats; - const f = formats[name315]; - if (!f) - throw new Error(`Unknown format "${name315}"`); - return f; + return target; }; - function addFormats(ajv2, list, fs, exportName) { - var _a; - var _b; - (_a = (_b = ajv2.opts.code).formats) !== null && _a !== void 0 ? _a : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`; - for (const f of list) - ajv2.addFormat(f, fs[f]); - } - module.exports = exports = formatsPlugin; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = formatsPlugin; - } -}); - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/index.js -var init_zod = __esm({ - "node_modules/.pnpm/zod@3.25.76/node_modules/zod/index.js"() { - init_external(); - init_external(); - } -}); - -// packages/core/dist/domain/prd-context.js -var PRDContextSchema, PRD_CONTEXT_CONFIGS; -var init_prd_context = __esm({ - "packages/core/dist/domain/prd-context.js"() { - "use strict"; - init_zod(); - PRDContextSchema = external_exports.enum([ - "proposal", - "feature", - "bug", - "incident", - "poc", - "mvp", - "release", - "cicd" - ]); - PRD_CONTEXT_CONFIGS = { - proposal: { - displayName: "Proposal", - description: "High-level, stakeholder-facing PRD focused on business value and ROI", - clarificationRange: [5, 6], - ragMaxHops: 1, - expectedSectionCount: 7, - preferredStrategyTier: 2 - }, - feature: { - displayName: "Feature", - description: "Implementation-ready PRD with deep technical specifications", - clarificationRange: [8, 10], - ragMaxHops: 3, - expectedSectionCount: 11, - preferredStrategyTier: 1 - }, - bug: { - displayName: "Bug Fix", - description: "Root cause analysis PRD focused on targeted fix and regression prevention", - clarificationRange: [6, 8], - ragMaxHops: 3, - expectedSectionCount: 6, - preferredStrategyTier: 1 - }, - incident: { - displayName: "Incident", - description: "Forensic investigation PRD for urgent response and mitigation", - clarificationRange: [10, 12], - ragMaxHops: 4, - expectedSectionCount: 8, - preferredStrategyTier: 1 - }, - poc: { - displayName: "Proof of Concept", - description: "Technical feasibility validation PRD with minimal scope", - clarificationRange: [4, 5], - ragMaxHops: 2, - expectedSectionCount: 5, - preferredStrategyTier: 3 - }, - mvp: { - displayName: "MVP", - description: "Minimum viable product PRD focused on core value and fast delivery", - clarificationRange: [6, 7], - ragMaxHops: 2, - expectedSectionCount: 8, - preferredStrategyTier: 2 - }, - release: { - displayName: "Release", - description: "Production release PRD with full documentation and migration guides", - clarificationRange: [9, 11], - ragMaxHops: 3, - expectedSectionCount: 10, - preferredStrategyTier: 1 - }, - cicd: { - displayName: "CI/CD Pipeline", - description: "CI/CD pipeline PRD with automation stages, testing, and deployment flows", - clarificationRange: [7, 9], - ragMaxHops: 3, - expectedSectionCount: 9, - preferredStrategyTier: 1 - } + var defaultEscapes = { + "{": "\\{", + "}": "\\}", + "\\": "\\textbackslash{}", + "#": "\\#", + $: "\\$", + "%": "\\%", + "&": "\\&", + "^": "\\textasciicircum{}", + _: "\\_", + "~": "\\textasciitilde{}" }; - } -}); - -// packages/core/dist/domain/section-type.js -var SectionTypeSchema, SECTION_DISPLAY_NAMES, SECTION_ORDER; -var init_section_type = __esm({ - "packages/core/dist/domain/section-type.js"() { - "use strict"; - init_zod(); - SectionTypeSchema = external_exports.enum([ - "overview", - "goals", - "requirements", - "user_stories", - "technical_specification", - "acceptance_criteria", - "data_model", - "api_specification", - "security_considerations", - "performance_requirements", - "testing", - "deployment", - "risks", - "timeline", - "source_code", - "test_code", - "jira_tickets" - ]); - SECTION_DISPLAY_NAMES = { - overview: "Overview", - goals: "Goals & Objectives", - requirements: "Requirements", - user_stories: "User Stories", - technical_specification: "Technical Specification", - acceptance_criteria: "Acceptance Criteria", - data_model: "Data Model", - api_specification: "API Specification", - security_considerations: "Security Considerations", - performance_requirements: "Performance Requirements", - testing: "Testing Strategy", - deployment: "Deployment Plan", - risks: "Risks & Mitigation", - timeline: "Timeline & Milestones", - source_code: "Source Code", - test_code: "Test Code", - jira_tickets: "JIRA Tickets" + var formatEscapes = { + "\u2013": "\\--", + "\u2014": "\\---", + " ": "~", + " ": "\\qquad{}", + "\r\n": "\\newline{}", + "\n": "\\newline{}" }; - SECTION_ORDER = { - overview: 0, - goals: 1, - requirements: 2, - user_stories: 3, - technical_specification: 4, - acceptance_criteria: 5, - data_model: 6, - api_specification: 7, - security_considerations: 8, - performance_requirements: 9, - testing: 10, - deployment: 11, - risks: 12, - timeline: 13, - source_code: 14, - test_code: 15, - jira_tickets: 16 + var defaultEscapeMapFn = function defaultEscapeMapFn2(defaultEscapes2, formatEscapes2) { + return _extends8({}, defaultEscapes2, formatEscapes2); }; - } -}); - -// packages/core/dist/domain/hard-output-rule.js -function isCriticalRule(rule) { - return !NON_CRITICAL_RULES.has(rule); -} -function scorePenalty(rule) { - return isCriticalRule(rule) ? 0.15 : 0.05; -} -var HardOutputRuleSchema, NON_CRITICAL_RULES; -var init_hard_output_rule = __esm({ - "packages/core/dist/domain/hard-output-rule.js"() { - "use strict"; - init_zod(); - HardOutputRuleSchema = external_exports.enum([ - // Core PRD Rules (1-17+) - "sp_arithmetic", - "no_self_referencing_deps", - "ac_numbering", - "no_orphan_ddl", - "no_now_in_partial_indexes", - "no_any_codable", - "no_placeholder_tests", - "sp_not_in_fr_table", - "uneven_sp_distribution", - "metrics_disclaimer", - "fr_traceability", - "clean_architecture", - "post_generation_self_check", - "mandatory_codebase_analysis", - "honest_verification_verdicts", - "code_example_port_compliance", - "test_traceability_integrity", - "duplicate_requirement_ids", - "fr_to_ac_coverage", - "ac_to_test_coverage", - "fk_references_exist", - "fr_numbering_gaps", - "risk_mitigation_completeness", - "deployment_rollback_plan", - // Architecture & Code Quality (18-24) - "generic_over_specific", - "no_nested_types", - "single_responsibility", - "explicit_access_control", - "factory_based_injection", - "solid_compliance", - "code_reusability", - // Security (25-32) - "no_hardcoded_secrets", - "input_validation_required", - "output_encoding_injection_prevention", - "auth_on_every_endpoint", - "security_safe_error_handling", - "cryptographic_standards", - "rate_limiting_required", - "secure_communication", - // Data Protection & Compliance (33-38) - "data_classification_required", - "sensitive_data_protection", - "no_sensitive_data_in_logs", - "data_minimization", - "audit_trail_required", - "consent_and_erasure_support", - // Error Handling & Resilience (39-43) - "structured_error_handling", - "resilience_patterns", - "graceful_degradation", - "transaction_boundaries", - "consistent_error_format", - // Concurrency & State Management (44-46) - "concurrency_safety", - "immutability_by_default", - "atomic_operations", - // Senior Code Quality Standards (47-52) - "no_magic_numbers", - "defensive_coding", - "method_size_limits", - "consistent_naming", - "api_contract_documentation", - "deprecation_strategy", - // Comprehensive Testing (53-58) - "mandatory_test_coverage", - "security_testing_required", - "performance_testing_required", - "no_production_data_in_tests", - "edge_case_negative_tests", - "test_isolation", - // Observability & Monitoring (59-62) - "structured_logging", - "distributed_tracing", - "no_pii_in_observability", - "alerting_thresholds", - // Dependency & Supply Chain (63-64) - "dependency_vulnerability_scanning", - "minimal_dependency_principle" - ]); - NON_CRITICAL_RULES = /* @__PURE__ */ new Set([ - "uneven_sp_distribution", - "metrics_disclaimer", - "post_generation_self_check", - "mandatory_codebase_analysis", - "fr_numbering_gaps", - "risk_mitigation_completeness", - "deployment_rollback_plan", - "explicit_access_control", - "code_reusability", - "immutability_by_default", - "consistent_naming", - "deprecation_strategy", - "distributed_tracing", - "alerting_thresholds", - "minimal_dependency_principle" - ]); - } -}); - -// packages/core/dist/domain/thinking-strategy.js -var ThinkingStrategySchema, STRATEGY_TIERS; -var init_thinking_strategy = __esm({ - "packages/core/dist/domain/thinking-strategy.js"() { - "use strict"; - init_zod(); - ThinkingStrategySchema = external_exports.enum([ - // Core reasoning strategies - "chain_of_thought", - "tree_of_thoughts", - "graph_of_thoughts", - "react", - "reflexion", - "plan_and_solve", - "verified_reasoning", - "recursive_refinement", - "problem_analysis", - // Prompting strategies - "zero_shot", - "few_shot", - "self_consistency", - "generate_knowledge", - "prompt_chaining", - "multimodal_cot", - "meta_prompting" - ]); - STRATEGY_TIERS = { - 1: { - selectionWeight: 3, - strategies: [ - "recursive_refinement", - "verified_reasoning", - "self_consistency", - "graph_of_thoughts" - ] - }, - 2: { - selectionWeight: 2, - strategies: [ - "tree_of_thoughts", - "react", - "reflexion", - "problem_analysis" - ] - }, - 3: { - selectionWeight: 1, - strategies: [ - "few_shot", - "meta_prompting", - "plan_and_solve", - "generate_knowledge" - ] - }, - 4: { - selectionWeight: 0.3, - strategies: [ - "zero_shot", - "chain_of_thought", - "prompt_chaining", - "multimodal_cot" - ] + module.exports = function(str2) { + var _ref = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, _ref$preserveFormatti = _ref.preserveFormatting, preserveFormatting = _ref$preserveFormatti === void 0 ? false : _ref$preserveFormatti, _ref$escapeMapFn = _ref.escapeMapFn, escapeMapFn = _ref$escapeMapFn === void 0 ? defaultEscapeMapFn : _ref$escapeMapFn; + var runningStr = String(str2); + var result = ""; + var escapes = escapeMapFn(_extends8({}, defaultEscapes), preserveFormatting ? _extends8({}, formatEscapes) : {}); + var escapeKeys = Object.keys(escapes); + var _loop = function _loop2() { + var specialCharFound = false; + escapeKeys.forEach(function(key, index2) { + if (specialCharFound) { + return; + } + if (runningStr.length >= key.length && runningStr.slice(0, key.length) === key) { + result += escapes[escapeKeys[index2]]; + runningStr = runningStr.slice(key.length, runningStr.length); + specialCharFound = true; + } + }); + if (!specialCharFound) { + result += runningStr.slice(0, 1); + runningStr = runningStr.slice(1, runningStr.length); + } + }; + while (runningStr) { + _loop(); } + return result; }; } }); -// packages/core/dist/domain/clarification.js -var ClarificationAnswerSchema, ClarificationStateSchema; -var init_clarification = __esm({ - "packages/core/dist/domain/clarification.js"() { - "use strict"; - init_zod(); - ClarificationAnswerSchema = external_exports.object({ - questionId: external_exports.string(), - round: external_exports.number().int().min(1), - question: external_exports.string(), - answer: external_exports.string(), - category: external_exports.string(), - priority: external_exports.number().min(0).max(1), - source: external_exports.enum(["user_freeform", "user_selection", "codebase_inferred", "default"]) - }); - ClarificationStateSchema = external_exports.object({ - answers: external_exports.array(ClarificationAnswerSchema), - currentRound: external_exports.number().int().min(0), - confidenceScore: external_exports.number().min(0).max(1), - isComplete: external_exports.boolean() - }); - } -}); - -// packages/core/dist/domain/verdict.js -var VerdictSchema; -var init_verdict = __esm({ - "packages/core/dist/domain/verdict.js"() { - "use strict"; - init_zod(); - VerdictSchema = external_exports.enum([ - "PASS", - "SPEC-COMPLETE", - "NEEDS-RUNTIME", - "INCONCLUSIVE", - "FAIL" - ]); - } -}); - -// packages/core/dist/domain/capabilities.js -var CAPABILITIES; -var init_capabilities = __esm({ - "packages/core/dist/domain/capabilities.js"() { - "use strict"; - CAPABILITIES = { - // source: matches allowedStrategies.length below. - maxStrategies: 16, - allowedStrategies: [ - "chain_of_thought", - "tree_of_thoughts", - "graph_of_thoughts", - "react", - "reflexion", - "plan_and_solve", - "verified_reasoning", - "recursive_refinement", - "problem_analysis", - "zero_shot", - "few_shot", - "self_consistency", - "generate_knowledge", - "prompt_chaining", - "multimodal_cot", - "meta_prompting" - ], - maxClarificationRounds: Infinity, - allowedContextTypes: [ - "proposal", - "feature", - "bug", - "incident", - "poc", - "mvp", - "release", - "cicd" - ], - maxSections: 11, - verificationLevel: "full" - }; - } -}); - -// packages/core/dist/domain/prd-document.js -var PRDSectionSchema, PRDDocumentSchema; -var init_prd_document = __esm({ - "packages/core/dist/domain/prd-document.js"() { - "use strict"; - init_zod(); - init_prd_context(); - init_section_type(); - init_clarification(); - PRDSectionSchema = external_exports.object({ - type: SectionTypeSchema, - title: external_exports.string(), - content: external_exports.string(), - order: external_exports.number().int().min(0), - metadata: external_exports.object({ - generatedAt: external_exports.string().datetime(), - wordCount: external_exports.number().int().min(0), - strategy: external_exports.string().optional(), - validationStatus: external_exports.enum(["pending", "passed", "failed"]), - violationCount: external_exports.number().int().min(0).default(0) - }) - }); - PRDDocumentSchema = external_exports.object({ - id: external_exports.string().uuid(), - name: external_exports.string().min(1), - context: PRDContextSchema, - sections: external_exports.array(PRDSectionSchema), - clarificationAnswers: external_exports.array(ClarificationAnswerSchema), - createdAt: external_exports.string().datetime(), - updatedAt: external_exports.string().datetime() - }); - } -}); - -// packages/core/dist/domain/validation-result.js -var HardOutputRuleViolationSchema, ValidationReportSchema, CrossRefValidationResultSchema; -var init_validation_result = __esm({ - "packages/core/dist/domain/validation-result.js"() { - "use strict"; - init_zod(); - init_hard_output_rule(); - init_section_type(); - HardOutputRuleViolationSchema = external_exports.object({ - rule: HardOutputRuleSchema, - sectionType: SectionTypeSchema.nullable(), - message: external_exports.string(), - offendingContent: external_exports.string().nullable(), - location: external_exports.string().nullable(), - isCritical: external_exports.boolean(), - scorePenalty: external_exports.number().min(0).max(1) - }); - ValidationReportSchema = external_exports.object({ - violations: external_exports.array(HardOutputRuleViolationSchema), - rulesChecked: external_exports.array(HardOutputRuleSchema), - rulesPassed: external_exports.array(HardOutputRuleSchema), - sectionType: SectionTypeSchema.nullable(), - hasCriticalViolations: external_exports.boolean(), - totalScore: external_exports.number().min(0).max(1), - checkedAt: external_exports.string().datetime() - }); - CrossRefValidationResultSchema = external_exports.object({ - danglingReferences: external_exports.array(external_exports.object({ - id: external_exports.string(), - referencedIn: external_exports.string(), - type: external_exports.string() - })), - orphanNodes: external_exports.array(external_exports.object({ - id: external_exports.string(), - type: external_exports.string(), - reason: external_exports.string() - })), - cycles: external_exports.array(external_exports.array(external_exports.string())), - numberingGaps: external_exports.array(external_exports.object({ - prefix: external_exports.string(), - expected: external_exports.number(), - actual: external_exports.number() - })), - duplicateIds: external_exports.array(external_exports.string()), - isValid: external_exports.boolean() - }); - } -}); - -// packages/core/dist/domain/agent.js -function agentSubagentType(identity2) { - return identity2.kind === "genius" ? `zetetic-team-subagents:genius:${identity2.name}` : `zetetic-team-subagents:${identity2.name}`; -} -var GeniusAgentSchema, TeamAgentSchema, AgentIdentitySchema, ExternalGroundingTypeSchema, ClaimSchema, JudgeVerdictSchema, JudgeRequestSchema, SubagentInvocationSchema, SubagentResponseSchema; -var init_agent = __esm({ - "packages/core/dist/domain/agent.js"() { - "use strict"; - init_zod(); - init_verdict(); - GeniusAgentSchema = external_exports.enum([ - "alexander", - "alkhwarizmi", - "altshuller", - "archimedes", - "arendt", - "aristotle", - "bateson", - "beer", - "borges", - "boyd", - "braudel", - "bruner", - "carnot", - "champollion", - "coase", - "cochrane", - "curie", - "darwin", - "deming", - "dijkstra", - "eco", - "einstein", - "ekman", - "engelbart", - "erdos", - "erlang", - "euler", - "feinstein", - "fermi", - "feynman", - "fisher", - "fleming", - "foucault", - "gadamer", - "galileo", - "geertz", - "ginzburg", - "godel", - "hamilton", - "hart", - "hopper", - "ibnalhaytham", - "ibnkhaldun", - "jobs", - "kahneman", - "kauffman", - "kay", - "kekule", - "knuth", - "lamport", - "laplace", - "lavoisier", - "leguin", - "lem", - "liskov", - "mandelbrot", - "margulis", - "maxwell", - "mcclintock", - "meadows", - "mendeleev", - "midgley", - "mill", - "nagarjuna", - "noether", - "ostrom", - "panini", - "pearl", - "peirce", - "poincare", - "polya", - "popper", - "propp", - "ramanujan", - "ranganathan", - "rawls", - "rejewski", - "rogerfisher", - "rogers", - "schelling", - "schon", - "semmelweis", - "shannon", - "simon", - "snow", - "strauss", - "taleb", - "thompson", - "toulmin", - "turing", - "varela", - "ventris", - "vonneumann", - "vygotsky", - "wittgenstein", - "wu", - "zhuangzi" - ]); - TeamAgentSchema = external_exports.enum([ - "architect", - "code-reviewer", - "data-scientist", - "dba", - "devops-engineer", - "engineer", - "experiment-runner", - "frontend-engineer", - "latex-engineer", - "mlops", - "orchestrator", - "paper-writer", - "professor", - "refactorer", - "research-scientist", - "reviewer-academic", - "security-auditor", - "test-engineer", - "ux-designer" - ]); - AgentIdentitySchema = external_exports.discriminatedUnion("kind", [ - external_exports.object({ kind: external_exports.literal("genius"), name: GeniusAgentSchema }), - external_exports.object({ kind: external_exports.literal("team"), name: TeamAgentSchema }) - ]); - ExternalGroundingTypeSchema = external_exports.enum([ - "schema", - "math", - "code", - "spec" - ]); - ClaimSchema = external_exports.object({ - claim_id: external_exports.string().describe("Stable ID, e.g., FR-001, AC-005, NFR-LATENCY"), - claim_type: external_exports.enum([ - "architecture", - "performance", - "correctness", - "security", - "data_model", - "test_coverage", - "story_point_arithmetic", - "fr_traceability", - "risk", - "acceptance_criteria_completeness", - "cross_file_consistency" - ]), - text: external_exports.string().describe("The claim being verified, in plain language"), - evidence: external_exports.string().describe("Section content / surrounding context"), - source_section: external_exports.string().optional(), - /** - * Optional oracle grounding. When present, the downstream oracle pipeline - * resolves the claim's ground truth deterministically instead of relying on - * judge consensus alone. - * - * Leaving this field undefined preserves the existing consensus-majority - * behaviour for that claim. - */ - external_grounding: external_exports.object({ - type: ExternalGroundingTypeSchema, - payload: external_exports.unknown().describe("Oracle-specific payload; shape validated by the oracle implementation") - }).optional() - }); - JudgeVerdictSchema = external_exports.object({ - judge: AgentIdentitySchema, - claim_id: external_exports.string(), - verdict: VerdictSchema, - rationale: external_exports.string(), - caveats: external_exports.array(external_exports.string()).default([]), - confidence: external_exports.number().min(0).max(1) - }); - JudgeRequestSchema = external_exports.object({ - judge: AgentIdentitySchema, - claim: ClaimSchema, - context: external_exports.object({ - prd_excerpt: external_exports.string().optional(), - codebase_excerpts: external_exports.array(external_exports.string()).default([]), - memory_excerpts: external_exports.array(external_exports.string()).default([]) - }).default({ prd_excerpt: void 0, codebase_excerpts: [], memory_excerpts: [] }) - }); - SubagentInvocationSchema = external_exports.object({ - agent: AgentIdentitySchema, - task_description: external_exports.string().describe("Short title for the task"), - prompt: external_exports.string().describe("Full self-contained prompt \u2014 agent has no prior context"), - expected_format: external_exports.enum(["freeform", "json", "markdown"]).default("freeform"), - isolation: external_exports.enum(["worktree", "none"]).default("none") - }); - SubagentResponseSchema = external_exports.object({ - agent: AgentIdentitySchema, - text: external_exports.string(), - duration_ms: external_exports.number().int().nonnegative().optional() - }); - } -}); - -// packages/core/dist/utils/json-extract.js -function extractJsonObject(text) { - const stripped = text.replace(/```(?:json)?\s*/gi, "").replace(/```/g, ""); - const start = stripped.indexOf("{"); - if (start === -1) - throw new Error("no JSON object found in response"); - let depth = 0; - let inString = false; - let escape3 = false; - for (let i2 = start; i2 < stripped.length; i2++) { - const ch = stripped[i2]; - if (escape3) { - escape3 = false; - continue; - } - if (ch === "\\") { - escape3 = true; - continue; - } - if (ch === '"') { - inString = !inString; - continue; - } - if (inString) - continue; - if (ch === "{") - depth++; - else if (ch === "}") { - depth--; - if (depth === 0) { - const candidate = stripped.slice(start, i2 + 1); - return JSON.parse(candidate); - } - } - } - throw new Error("unbalanced JSON object in response"); -} -var init_json_extract = __esm({ - "packages/core/dist/utils/json-extract.js"() { - "use strict"; - } -}); - -// packages/core/dist/persistence/evidence-repository.js -import { join } from "node:path"; -import { homedir } from "node:os"; -import { mkdirSync, existsSync } from "node:fs"; -function tryCreateEvidenceRepository(dbPath) { - if (!Database) - return null; - try { - return new EvidenceRepository(dbPath); - } catch { - return null; - } -} -var Database, EvidenceRepository; -var init_evidence_repository = __esm({ - async "packages/core/dist/persistence/evidence-repository.js"() { - "use strict"; - Database = null; - try { - Database = (await import("better-sqlite3")).default; - } catch { - } - EvidenceRepository = class { - db; - constructor(dbPath) { - if (!Database) { - throw new Error("better-sqlite3 not available \u2014 install it with: pnpm add better-sqlite3"); +// node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js +var require_alea = __commonJS({ + "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js"(exports, module) { + (function(global, module2, define2) { + function Alea(seed) { + var me = this, mash = Mash(); + me.next = function() { + var t = 2091639 * me.s0 + me.c * 23283064365386963e-26; + me.s0 = me.s1; + me.s1 = me.s2; + return me.s2 = t - (me.c = t | 0); + }; + me.c = 1; + me.s0 = mash(" "); + me.s1 = mash(" "); + me.s2 = mash(" "); + me.s0 -= mash(seed); + if (me.s0 < 0) { + me.s0 += 1; } - const resolvedPath = dbPath ?? this.defaultDbPath(); - const dir = resolvedPath.substring(0, resolvedPath.lastIndexOf("/")); - if (!existsSync(dir)) { - mkdirSync(dir, { recursive: true }); + me.s1 -= mash(seed); + if (me.s1 < 0) { + me.s1 += 1; } - this.db = new Database(resolvedPath); - this.db.pragma("journal_mode = WAL"); - this.db.pragma("foreign_keys = ON"); - this.migrate(); - } - defaultDbPath() { - return join(homedir(), ".prd-gen", "evidence.db"); - } - migrate() { - this.db.exec(` - CREATE TABLE IF NOT EXISTS strategy_executions ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - session_id TEXT NOT NULL DEFAULT '', - strategy TEXT NOT NULL, - claim_characteristics TEXT NOT NULL, - complexity_tier TEXT NOT NULL, - expected_improvement REAL NOT NULL, - actual_confidence_gain REAL NOT NULL, - was_compliant INTEGER NOT NULL DEFAULT 1, - retry_count INTEGER NOT NULL DEFAULT 0, - prd_context TEXT NOT NULL, - created_at TEXT NOT NULL DEFAULT (datetime('now')) - ); - - CREATE TABLE IF NOT EXISTS prd_quality_scores ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - prd_id TEXT NOT NULL, - prd_context TEXT NOT NULL, - rules_checked INTEGER NOT NULL, - rules_passed INTEGER NOT NULL, - critical_violations INTEGER NOT NULL, - total_score REAL NOT NULL, - audit_flags_raised INTEGER NOT NULL DEFAULT 0, - created_at TEXT NOT NULL DEFAULT (datetime('now')) - ); - - CREATE TABLE IF NOT EXISTS adaptive_thresholds ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - metric_name TEXT NOT NULL UNIQUE, - current_value REAL NOT NULL, - sample_count INTEGER NOT NULL DEFAULT 0, - last_updated TEXT NOT NULL DEFAULT (datetime('now')) - ); - - CREATE INDEX IF NOT EXISTS idx_strategy_executions_strategy - ON strategy_executions(strategy); - CREATE INDEX IF NOT EXISTS idx_strategy_executions_context - ON strategy_executions(prd_context); - CREATE INDEX IF NOT EXISTS idx_prd_quality_scores_context - ON prd_quality_scores(prd_context); - CREATE INDEX IF NOT EXISTS idx_prd_quality_scores_prd_id - ON prd_quality_scores(prd_id); - `); - } - // ─── Strategy Executions ───────────────────────────────────────────────── - recordStrategyExecution(execution, sessionId) { - const stmt = this.db.prepare(` - INSERT INTO strategy_executions - (session_id, strategy, claim_characteristics, complexity_tier, - expected_improvement, actual_confidence_gain, was_compliant, - retry_count, prd_context) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) - `); - stmt.run(sessionId ?? "", execution.strategy, JSON.stringify(execution.claimCharacteristics), execution.complexityTier, execution.expectedImprovement, execution.actualConfidenceGain, execution.wasCompliant ? 1 : 0, execution.retryCount, execution.prdContext); - } - /** - * Get performance summary per strategy — used to close the feedback loop. - * Returns historical adjustment factor for the selector. - */ - getStrategyPerformance(minExecutions = 10) { - const rows = this.db.prepare(` - SELECT - strategy, - COUNT(*) as execution_count, - AVG(expected_improvement) as avg_expected, - AVG(actual_confidence_gain) as avg_actual, - AVG(CAST(was_compliant AS REAL)) as compliance_rate - FROM strategy_executions - GROUP BY strategy - HAVING COUNT(*) >= ? - ORDER BY COUNT(*) DESC - `).all(minExecutions); - return rows.map((row2) => ({ - strategy: row2.strategy, - executionCount: row2.execution_count, - avgExpectedImprovement: row2.avg_expected, - avgActualGain: row2.avg_actual, - performanceDelta: row2.avg_actual - row2.avg_expected, - complianceRate: row2.compliance_rate - })); - } - /** - * Compute historical adjustments for strategy selection. - * Bounded [-0.3, +0.3] — prevents runaway feedback. - */ - getHistoricalAdjustments(minExecutions = 10) { - const summaries = this.getStrategyPerformance(minExecutions); - const adjustments = /* @__PURE__ */ new Map(); - for (const summary of summaries) { - if (summary.avgExpectedImprovement === 0) - continue; - const rawAdjustment = summary.performanceDelta / summary.avgExpectedImprovement; - const clamped = Math.max(-0.3, Math.min(0.3, rawAdjustment)); - adjustments.set(summary.strategy, clamped); + me.s2 -= mash(seed); + if (me.s2 < 0) { + me.s2 += 1; } - return adjustments; + mash = null; } - // ─── PRD Quality Scores ────────────────────────────────────────────────── - recordQualityScore(score) { - const stmt = this.db.prepare(` - INSERT INTO prd_quality_scores - (prd_id, prd_context, rules_checked, rules_passed, - critical_violations, total_score, audit_flags_raised) - VALUES (?, ?, ?, ?, ?, ?, ?) - `); - stmt.run(score.prdId, score.prdContext, score.rulesChecked, score.rulesPassed, score.criticalViolations, score.totalScore, score.auditFlagsRaised); + function copy(f, t) { + t.c = f.c; + t.s0 = f.s0; + t.s1 = f.s1; + t.s2 = f.s2; + return t; } - getQualityHistory(limit = 50) { - const rows = this.db.prepare(` - SELECT prd_id, prd_context, rules_checked, rules_passed, - critical_violations, total_score, audit_flags_raised - FROM prd_quality_scores - ORDER BY created_at DESC - LIMIT ? - `).all(limit); - return rows.map((row2) => ({ - prdId: row2.prd_id, - prdContext: row2.prd_context, - rulesChecked: row2.rules_checked, - rulesPassed: row2.rules_passed, - criticalViolations: row2.critical_violations, - totalScore: row2.total_score, - auditFlagsRaised: row2.audit_flags_raised - })); + function impl(seed, opts) { + var xg = new Alea(seed), state = opts && opts.state, prng = xg.next; + prng.int32 = function() { + return xg.next() * 4294967296 | 0; + }; + prng.double = function() { + return prng() + (prng() * 2097152 | 0) * 11102230246251565e-32; + }; + prng.quick = prng; + if (state) { + if (typeof state == "object") copy(state, xg); + prng.state = function() { + return copy(xg, {}); + }; + } + return prng; } - // ─── Adaptive Thresholds ───────────────────────────────────────────────── - getThreshold(metricName) { - const row2 = this.db.prepare(`SELECT metric_name, current_value, sample_count, last_updated - FROM adaptive_thresholds WHERE metric_name = ?`).get(metricName); - if (!row2) - return void 0; - return { - metricName: row2.metric_name, - currentValue: row2.current_value, - sampleCount: row2.sample_count, - lastUpdated: row2.last_updated + function Mash() { + var n = 4022871197; + var mash = function(data) { + data = String(data); + for (var i2 = 0; i2 < data.length; i2++) { + n += data.charCodeAt(i2); + var h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 4294967296; + } + return (n >>> 0) * 23283064365386963e-26; }; + return mash; } - /** - * Recalculate adaptive thresholds from historical quality data. - * Uses percentiles: p25 = fail, p50 = needs-improvement, p75 = good. - * Only updates if sufficient data exists (minSamples). - */ - recalculateThresholds(minSamples = 20) { - const scores = this.db.prepare(`SELECT total_score FROM prd_quality_scores ORDER BY total_score ASC`).all(); - if (scores.length < minSamples) - return; - const values = scores.map((s) => s.total_score); - const p25 = values[Math.floor(values.length * 0.25)]; - const p50 = values[Math.floor(values.length * 0.5)]; - const p75 = values[Math.floor(values.length * 0.75)]; - const upsert = this.db.prepare(` - INSERT INTO adaptive_thresholds (metric_name, current_value, sample_count, last_updated) - VALUES (?, ?, ?, datetime('now')) - ON CONFLICT(metric_name) DO UPDATE SET - current_value = excluded.current_value, - sample_count = excluded.sample_count, - last_updated = datetime('now') - `); - const updateAll = this.db.transaction(() => { - upsert.run("quality_fail_threshold", p25, values.length); - upsert.run("quality_improvement_threshold", p50, values.length); - upsert.run("quality_good_threshold", p75, values.length); + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; }); - updateAll(); - } - // ─── Lifecycle ─────────────────────────────────────────────────────────── - close() { - this.db.close(); + } else { + this.alea = impl; } - }; + })( + exports, + typeof module == "object" && module, + // present in node.js + typeof define == "function" && define + // present with an AMD loader + ); } }); -// packages/core/dist/persistence/reliability-repository.js -var RELIABILITY_SCHEMA_VERSION, DEFAULT_RELIABILITY_PRIOR, RELIABILITY_PRIOR_ESS; -var init_reliability_repository = __esm({ - "packages/core/dist/persistence/reliability-repository.js"() { - "use strict"; - RELIABILITY_SCHEMA_VERSION = 2; - DEFAULT_RELIABILITY_PRIOR = Object.freeze({ - alpha: 7, - beta: 3 - }); - RELIABILITY_PRIOR_ESS = DEFAULT_RELIABILITY_PRIOR.alpha + DEFAULT_RELIABILITY_PRIOR.beta; +// node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js +var require_xor128 = __commonJS({ + "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js"(exports, module) { + (function(global, module2, define2) { + function XorGen(seed) { + var me = this, strseed = ""; + me.x = 0; + me.y = 0; + me.z = 0; + me.w = 0; + me.next = function() { + var t = me.x ^ me.x << 11; + me.x = me.y; + me.y = me.z; + me.z = me.w; + return me.w ^= me.w >>> 19 ^ t ^ t >>> 8; + }; + if (seed === (seed | 0)) { + me.x = seed; + } else { + strseed += seed; + } + for (var k = 0; k < strseed.length + 64; k++) { + me.x ^= strseed.charCodeAt(k) | 0; + me.next(); + } + } + function copy(f, t) { + t.x = f.x; + t.y = f.y; + t.z = f.z; + t.w = f.w; + return t; + } + function impl(seed, opts) { + var xg = new XorGen(seed), state = opts && opts.state, prng = function() { + return (xg.next() >>> 0) / 4294967296; + }; + prng.double = function() { + do { + var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (typeof state == "object") copy(state, xg); + prng.state = function() { + return copy(xg, {}); + }; + } + return prng; + } + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; + }); + } else { + this.xor128 = impl; + } + })( + exports, + typeof module == "object" && module, + // present in node.js + typeof define == "function" && define + // present with an AMD loader + ); } }); -// packages/core/dist/persistence/sqlite-reliability-repository.js -import { join as join2 } from "node:path"; -import { homedir as homedir2 } from "node:os"; -import { mkdirSync as mkdirSync2, existsSync as existsSync2 } from "node:fs"; -function defaultDbPath() { - return join2(homedir2(), ".prd-gen", "reliability.db"); -} -function rowToRecord(row2) { - return { - agentKind: row2.agent_kind, - agentName: row2.agent_name, - claimType: row2.claim_type, - verdictDirection: row2.verdict_direction, - alpha: row2.alpha, - beta: row2.beta, - nObservations: row2.n_observations, - lastUpdated: row2.last_updated, - schemaVersion: RELIABILITY_SCHEMA_VERSION - }; -} -function tryCreateReliabilityRepository(dbPath) { - if (!Database2) - return null; - try { - return new SqliteReliabilityRepository(dbPath); - } catch { - return null; - } -} -var Database2, SqliteReliabilityRepository; -var init_sqlite_reliability_repository = __esm({ - async "packages/core/dist/persistence/sqlite-reliability-repository.js"() { - "use strict"; - init_reliability_repository(); - Database2 = null; - try { - Database2 = (await import("better-sqlite3")).default; - } catch { - } - SqliteReliabilityRepository = class { - db; - closed = false; - constructor(dbPath) { - if (!Database2) { - throw new Error("better-sqlite3 not available \u2014 install it with: pnpm add better-sqlite3"); - } - const resolvedPath = dbPath ?? defaultDbPath(); - const dir = resolvedPath.substring(0, resolvedPath.lastIndexOf("/")); - if (!existsSync2(dir)) { - mkdirSync2(dir, { recursive: true }); - } - this.db = new Database2(resolvedPath); - this.db.pragma("journal_mode = WAL"); - this.db.pragma("foreign_keys = ON"); - this.db.pragma("busy_timeout = 5000"); - this.migrate(); - this.verifySchemaVersion(); - } - // ─── Schema lifecycle ─────────────────────────────────────────────────── - migrate() { - this.db.exec(` - CREATE TABLE IF NOT EXISTS schema_meta ( - schema_version INTEGER NOT NULL - ); - - CREATE TABLE IF NOT EXISTS agent_reliability ( - agent_kind TEXT NOT NULL, - agent_name TEXT NOT NULL, - claim_type TEXT NOT NULL, - verdict_direction TEXT NOT NULL CHECK (verdict_direction IN ('sensitivity_arm', 'specificity_arm')), - alpha REAL NOT NULL, - beta REAL NOT NULL, - n_observations INTEGER NOT NULL DEFAULT 0, - last_updated TEXT NOT NULL DEFAULT (datetime('now')), - PRIMARY KEY (agent_kind, agent_name, claim_type, verdict_direction) - ); - - CREATE INDEX IF NOT EXISTS idx_ar_agent - ON agent_reliability (agent_kind, agent_name); - - CREATE INDEX IF NOT EXISTS idx_ar_claim_type - ON agent_reliability (claim_type); - `); - const existing = this.db.prepare("SELECT schema_version FROM schema_meta LIMIT 1").get(); - if (!existing) { - this.db.prepare("INSERT INTO schema_meta (schema_version) VALUES (?)").run(RELIABILITY_SCHEMA_VERSION); - } - } - /** - * Read the persisted schema_version and refuse to continue if it does not - * match RELIABILITY_SCHEMA_VERSION. - * - * Auto-migration is out of scope for Wave B. A version mismatch means the DB - * was written by a different schema and must be migrated manually or deleted - * before this implementation can use it. - * - * source: Laplace L6 / docs/PHASE_4_PLAN.md §4.1 Persistence. - */ - verifySchemaVersion() { - const row2 = this.db.prepare("SELECT schema_version FROM schema_meta LIMIT 1").get(); - if (!row2) { - throw new Error("SqliteReliabilityRepository: schema_meta table is empty after migration \u2014 this should not happen; the DB may be corrupt."); - } - if (row2.schema_version !== RELIABILITY_SCHEMA_VERSION) { - throw new Error(`SqliteReliabilityRepository: schema version mismatch \u2014 DB has version ${row2.schema_version}, implementation expects version ${RELIABILITY_SCHEMA_VERSION}. Delete the DB or run a manual migration before proceeding.`); - } - } - // ─── ReliabilityRepository port ───────────────────────────────────────── - getSchemaVersion() { - this.assertOpen(); - const row2 = this.db.prepare("SELECT schema_version FROM schema_meta LIMIT 1").get(); - return row2?.schema_version ?? RELIABILITY_SCHEMA_VERSION; - } - getReliability(judge, claimType, verdictDirection) { - this.assertOpen(); - const row2 = this.db.prepare(`SELECT agent_kind, agent_name, claim_type, verdict_direction, - alpha, beta, n_observations, last_updated - FROM agent_reliability - WHERE agent_kind = ? AND agent_name = ? AND claim_type = ? AND verdict_direction = ?`).get(judge.kind, judge.name, claimType, verdictDirection); - if (!row2) - return null; - return rowToRecord(row2); - } - /** - * Record one ground-truth-matched observation. - * - * Uses an UPSERT (INSERT ... ON CONFLICT DO UPDATE) so the first call for - * a new cell initialises from the Beta(7,3) prior, and subsequent calls - * accumulate. - * - * Concurrency: SQLite WAL + file lock serialises concurrent writes. - * Two callers racing on the same cell will execute their UPSERTs sequentially - * (last writer wins at the OS file lock level). Because each UPSERT is an - * atomic read-modify-write on the server side (no separate SELECT), the - * result matches sequential application — there is no lost-update anomaly. - * - * source: SQLite documentation — "WAL mode allows concurrent readers; - * writers serialise at the WAL lock" (https://www.sqlite.org/wal.html). - * source: docs/PHASE_4_PLAN.md §Persistence concurrency — "writes serialize - * at the SQLite file lock." - */ - recordObservation(judge, claimType, observation) { - this.assertOpen(); - const verdictDirection = observation.groundTruthIsFail ? "sensitivity_arm" : "specificity_arm"; - const alphaDelta = observation.judgeWasCorrect ? 1 : 0; - const betaDelta = observation.judgeWasCorrect ? 0 : 1; - this.db.prepare(`INSERT INTO agent_reliability - (agent_kind, agent_name, claim_type, verdict_direction, - alpha, beta, n_observations, last_updated) - VALUES (?, ?, ?, ?, ?, ?, 1, datetime('now')) - ON CONFLICT(agent_kind, agent_name, claim_type, verdict_direction) DO UPDATE SET - alpha = alpha + ?, - beta = beta + ?, - n_observations = n_observations + 1, - last_updated = datetime('now')`).run( - judge.kind, - judge.name, - claimType, - verdictDirection, - // INSERT values (first-run cell): prior + this observation - // source: DEFAULT_RELIABILITY_PRIOR = Beta(7,3); docs/PHASE_4_PLAN.md §4.1 - DEFAULT_RELIABILITY_PRIOR.alpha + alphaDelta, - DEFAULT_RELIABILITY_PRIOR.beta + betaDelta, - // UPDATE deltas - alphaDelta, - betaDelta - ); +// node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js +var require_xorwow = __commonJS({ + "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js"(exports, module) { + (function(global, module2, define2) { + function XorGen(seed) { + var me = this, strseed = ""; + me.next = function() { + var t = me.x ^ me.x >>> 2; + me.x = me.y; + me.y = me.z; + me.z = me.w; + me.w = me.v; + return (me.d = me.d + 362437 | 0) + (me.v = me.v ^ me.v << 4 ^ (t ^ t << 1)) | 0; + }; + me.x = 0; + me.y = 0; + me.z = 0; + me.w = 0; + me.v = 0; + if (seed === (seed | 0)) { + me.x = seed; + } else { + strseed += seed; + } + for (var k = 0; k < strseed.length + 64; k++) { + me.x ^= strseed.charCodeAt(k) | 0; + if (k == strseed.length) { + me.d = me.x << 10 ^ me.x >>> 4; + } + me.next(); + } } - getAllRecords() { - this.assertOpen(); - const rows = this.db.prepare(`SELECT agent_kind, agent_name, claim_type, verdict_direction, - alpha, beta, n_observations, last_updated - FROM agent_reliability - ORDER BY agent_kind, agent_name, claim_type, verdict_direction`).all(); - return rows.map(rowToRecord); + function copy(f, t) { + t.x = f.x; + t.y = f.y; + t.z = f.z; + t.w = f.w; + t.v = f.v; + t.d = f.d; + return t; } - close() { - if (!this.closed) { - this.db.close(); - this.closed = true; + function impl(seed, opts) { + var xg = new XorGen(seed), state = opts && opts.state, prng = function() { + return (xg.next() >>> 0) / 4294967296; + }; + prng.double = function() { + do { + var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (typeof state == "object") copy(state, xg); + prng.state = function() { + return copy(xg, {}); + }; } + return prng; } - assertOpen() { - if (this.closed) { - throw new Error("SqliteReliabilityRepository: cannot call methods after close()"); - } + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; + }); + } else { + this.xorwow = impl; } - }; + })( + exports, + typeof module == "object" && module, + // present in node.js + typeof define == "function" && define + // present with an AMD loader + ); } }); -// packages/core/dist/index.js -var init_dist = __esm({ - async "packages/core/dist/index.js"() { - "use strict"; - init_prd_context(); - init_section_type(); - init_hard_output_rule(); - init_thinking_strategy(); - init_clarification(); - init_verdict(); - init_capabilities(); - init_prd_document(); - init_validation_result(); - init_agent(); - init_json_extract(); - await init_evidence_repository(); - init_reliability_repository(); - await init_sqlite_reliability_repository(); +// node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js +var require_xorshift7 = __commonJS({ + "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js"(exports, module) { + (function(global, module2, define2) { + function XorGen(seed) { + var me = this; + me.next = function() { + var X = me.x, i2 = me.i, t, v, w; + t = X[i2]; + t ^= t >>> 7; + v = t ^ t << 24; + t = X[i2 + 1 & 7]; + v ^= t ^ t >>> 10; + t = X[i2 + 3 & 7]; + v ^= t ^ t >>> 3; + t = X[i2 + 4 & 7]; + v ^= t ^ t << 7; + t = X[i2 + 7 & 7]; + t = t ^ t << 13; + v ^= t ^ t << 9; + X[i2] = v; + me.i = i2 + 1 & 7; + return v; + }; + function init(me2, seed2) { + var j, w, X = []; + if (seed2 === (seed2 | 0)) { + w = X[0] = seed2; + } else { + seed2 = "" + seed2; + for (j = 0; j < seed2.length; ++j) { + X[j & 7] = X[j & 7] << 15 ^ seed2.charCodeAt(j) + X[j + 1 & 7] << 13; + } + } + while (X.length < 8) X.push(0); + for (j = 0; j < 8 && X[j] === 0; ++j) ; + if (j == 8) w = X[7] = -1; + else w = X[j]; + me2.x = X; + me2.i = 0; + for (j = 256; j > 0; --j) { + me2.next(); + } + } + init(me, seed); + } + function copy(f, t) { + t.x = f.x.slice(); + t.i = f.i; + return t; + } + function impl(seed, opts) { + if (seed == null) seed = +/* @__PURE__ */ new Date(); + var xg = new XorGen(seed), state = opts && opts.state, prng = function() { + return (xg.next() >>> 0) / 4294967296; + }; + prng.double = function() { + do { + var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (state.x) copy(state, xg); + prng.state = function() { + return copy(xg, {}); + }; + } + return prng; + } + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; + }); + } else { + this.xorshift7 = impl; + } + })( + exports, + typeof module == "object" && module, + // present in node.js + typeof define == "function" && define + // present with an AMD loader + ); } }); -// packages/validation/dist/hard-output-rules/rule-mapping.js -function rulesForSection(sectionType) { - return [...SECTION_RULES[sectionType]]; -} -var SECTION_RULES; -var init_rule_mapping = __esm({ - "packages/validation/dist/hard-output-rules/rule-mapping.js"() { - "use strict"; - SECTION_RULES = { - requirements: [ - "sp_not_in_fr_table", - "fr_traceability", - "no_self_referencing_deps", - "duplicate_requirement_ids", - "fr_numbering_gaps" - ], - user_stories: ["no_self_referencing_deps"], - technical_specification: [ - // Architecture & Code Quality (18-24) - "clean_architecture", - "no_any_codable", - "code_example_port_compliance", - "generic_over_specific", - "no_nested_types", - "single_responsibility", - "explicit_access_control", - "factory_based_injection", - "solid_compliance", - "code_reusability", - // Security (25-32) - "no_hardcoded_secrets", - "input_validation_required", - "output_encoding_injection_prevention", - "auth_on_every_endpoint", - "security_safe_error_handling", - "cryptographic_standards", - "rate_limiting_required", - "secure_communication", - // Data Protection (33-38) - "data_classification_required", - "sensitive_data_protection", - "no_sensitive_data_in_logs", - "data_minimization", - "audit_trail_required", - "consent_and_erasure_support", - // Error Handling & Resilience (39-43) - "structured_error_handling", - "resilience_patterns", - "graceful_degradation", - "transaction_boundaries", - "consistent_error_format", - // Concurrency (44-46) - "concurrency_safety", - "immutability_by_default", - "atomic_operations", - // Senior Code Quality (47-52) - "no_magic_numbers", - "defensive_coding", - "method_size_limits", - "consistent_naming", - "api_contract_documentation", - "deprecation_strategy", - // Observability (59-62) - "structured_logging", - "distributed_tracing", - "no_pii_in_observability", - "alerting_thresholds", - // Dependencies (63-64) - "dependency_vulnerability_scanning", - "minimal_dependency_principle" - ], - data_model: [ - "no_orphan_ddl", - "no_now_in_partial_indexes", - "no_any_codable", - "fk_references_exist", - "data_classification_required", - "sensitive_data_protection", - "consent_and_erasure_support" - ], - api_specification: [ - "no_any_codable", - "auth_on_every_endpoint", - "rate_limiting_required", - "consistent_error_format", - "api_contract_documentation", - "deprecation_strategy" - ], - security_considerations: [ - "no_hardcoded_secrets", - "input_validation_required", - "output_encoding_injection_prevention", - "auth_on_every_endpoint", - "security_safe_error_handling", - "cryptographic_standards", - "rate_limiting_required", - "secure_communication", - "data_classification_required", - "sensitive_data_protection", - "no_sensitive_data_in_logs", - "data_minimization", - "audit_trail_required", - "consent_and_erasure_support" - ], - testing: [ - "no_placeholder_tests", - "test_traceability_integrity", - "mandatory_test_coverage", - "security_testing_required", - "performance_testing_required", - "no_production_data_in_tests", - "edge_case_negative_tests", - "test_isolation" - ], - timeline: [ - "sp_arithmetic", - "uneven_sp_distribution", - "no_self_referencing_deps" - ], - deployment: [ - "sp_arithmetic", - "ac_numbering", - "deployment_rollback_plan", - "structured_logging", - "distributed_tracing", - "no_pii_in_observability", - "alerting_thresholds" - ], - acceptance_criteria: ["ac_numbering"], - performance_requirements: ["honest_verification_verdicts"], - risks: ["risk_mitigation_completeness"], - overview: [], - goals: [], - source_code: [], - test_code: [], - // jira_tickets is a synthetic bucket emitted by jira-generation; its - // rules apply to the source sections (requirements / acceptance_criteria), - // not to the JIRA markdown itself. - jira_tickets: [] - }; +// node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js +var require_xor4096 = __commonJS({ + "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js"(exports, module) { + (function(global, module2, define2) { + function XorGen(seed) { + var me = this; + me.next = function() { + var w = me.w, X = me.X, i2 = me.i, t, v; + me.w = w = w + 1640531527 | 0; + v = X[i2 + 34 & 127]; + t = X[i2 = i2 + 1 & 127]; + v ^= v << 13; + t ^= t << 17; + v ^= v >>> 15; + t ^= t >>> 12; + v = X[i2] = v ^ t; + me.i = i2; + return v + (w ^ w >>> 16) | 0; + }; + function init(me2, seed2) { + var t, v, i2, j, w, X = [], limit = 128; + if (seed2 === (seed2 | 0)) { + v = seed2; + seed2 = null; + } else { + seed2 = seed2 + "\0"; + v = 0; + limit = Math.max(limit, seed2.length); + } + for (i2 = 0, j = -32; j < limit; ++j) { + if (seed2) v ^= seed2.charCodeAt((j + 32) % seed2.length); + if (j === 0) w = v; + v ^= v << 10; + v ^= v >>> 15; + v ^= v << 4; + v ^= v >>> 13; + if (j >= 0) { + w = w + 1640531527 | 0; + t = X[j & 127] ^= v + w; + i2 = 0 == t ? i2 + 1 : 0; + } + } + if (i2 >= 128) { + X[(seed2 && seed2.length || 0) & 127] = -1; + } + i2 = 127; + for (j = 4 * 128; j > 0; --j) { + v = X[i2 + 34 & 127]; + t = X[i2 = i2 + 1 & 127]; + v ^= v << 13; + t ^= t << 17; + v ^= v >>> 15; + t ^= t >>> 12; + X[i2] = v ^ t; + } + me2.w = w; + me2.X = X; + me2.i = i2; + } + init(me, seed); + } + function copy(f, t) { + t.i = f.i; + t.w = f.w; + t.X = f.X.slice(); + return t; + } + ; + function impl(seed, opts) { + if (seed == null) seed = +/* @__PURE__ */ new Date(); + var xg = new XorGen(seed), state = opts && opts.state, prng = function() { + return (xg.next() >>> 0) / 4294967296; + }; + prng.double = function() { + do { + var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (state.X) copy(state, xg); + prng.state = function() { + return copy(xg, {}); + }; + } + return prng; + } + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; + }); + } else { + this.xor4096 = impl; + } + })( + exports, + // window object or global + typeof module == "object" && module, + // present in node.js + typeof define == "function" && define + // present with an AMD loader + ); } }); -// packages/validation/dist/hard-output-rules/rules/helpers.js -function findPatternViolations(pattern, content, rule, sectionType, message) { - const matches = content.match(pattern); - if (!matches) - return []; - return matches.map((match) => ({ - rule, - sectionType, - message, - offendingContent: match.length > 0 ? match.substring(0, 120) : null, - location: null, - isCritical: isCriticalRule(rule), - scorePenalty: scorePenalty(rule) - })); -} -function findAbsenceViolation(content, signals, threshold, rule, sectionType, message) { - const lowered = content.toLowerCase(); - const signalCount = signals.filter((s) => lowered.includes(s)).length; - if (signalCount < threshold) { - return [ - { - rule, - sectionType, - message, - offendingContent: null, - location: null, - isCritical: isCriticalRule(rule), - scorePenalty: scorePenalty(rule) +// node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js +var require_tychei = __commonJS({ + "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js"(exports, module) { + (function(global, module2, define2) { + function XorGen(seed) { + var me = this, strseed = ""; + me.next = function() { + var b = me.b, c = me.c, d = me.d, a = me.a; + b = b << 25 ^ b >>> 7 ^ c; + c = c - d | 0; + d = d << 24 ^ d >>> 8 ^ a; + a = a - b | 0; + me.b = b = b << 20 ^ b >>> 12 ^ c; + me.c = c = c - d | 0; + me.d = d << 16 ^ c >>> 16 ^ a; + return me.a = a - b | 0; + }; + me.a = 0; + me.b = 0; + me.c = 2654435769 | 0; + me.d = 1367130551; + if (seed === Math.floor(seed)) { + me.a = seed / 4294967296 | 0; + me.b = seed | 0; + } else { + strseed += seed; + } + for (var k = 0; k < strseed.length + 20; k++) { + me.b ^= strseed.charCodeAt(k) | 0; + me.next(); + } } - ]; - } - return []; -} -function makeViolation(rule, sectionType, message, offendingContent = null) { - return { - rule, - sectionType, - message, - offendingContent, - location: null, - isCritical: isCriticalRule(rule), - scorePenalty: scorePenalty(rule) - }; -} -function extractCodeBlocks(content) { - const pattern = /```(?:\w+)?\s*\n([\s\S]*?)```/g; - const blocks = []; - let match; - while ((match = pattern.exec(content)) !== null) { - blocks.push(match[1]); - } - return blocks; -} -function hasExplicitOptOut(content, topicSignals) { - if (topicSignals.length === 0) - return false; - const lowered = content.toLowerCase(); - for (const topic of topicSignals) { - const t = topic.toLowerCase(); - let idx = lowered.indexOf(t); - while (idx !== -1) { - const start = Math.max(0, idx - OPT_OUT_WINDOW); - const end = Math.min(lowered.length, idx + t.length + OPT_OUT_WINDOW); - const window = lowered.substring(start, end); - for (const marker of OPT_OUT_MARKERS) { - if (window.includes(marker)) - return true; + function copy(f, t) { + t.a = f.a; + t.b = f.b; + t.c = f.c; + t.d = f.d; + return t; } - idx = lowered.indexOf(t, idx + t.length); - } - } - return false; -} -function extractTypeName(line) { - const typeKeywords = [ - "struct", - "class", - "enum", - "interface", - "object", - "record" - ]; - const words = line.split(/\s+/).filter((w) => w.length > 0); - for (let i2 = 0; i2 < words.length; i2++) { - const clean = words[i2].toLowerCase().replace(/[^\w]/g, ""); - if (typeKeywords.includes(clean) && i2 + 1 < words.length) { - return words[i2 + 1].replace(/[^\w]/g, ""); - } - } - return "Unknown"; -} -var OPT_OUT_WINDOW, OPT_OUT_MARKERS; -var init_helpers = __esm({ - async "packages/validation/dist/hard-output-rules/rules/helpers.js"() { - "use strict"; - await init_dist(); - OPT_OUT_WINDOW = 240; - OPT_OUT_MARKERS = [ - "n/a", - "not applicable", - "by construction", - "no network", - "no database", - "no endpoint", - "no public surface", - "no public interface", - "no http", - "no rest", - "no graphql", - "no grpc", - "no users", - "no caller", - "no remote", - "no service", - "no api", - "absent surface", - "no attack surface", - "out of scope" - ]; + ; + function impl(seed, opts) { + var xg = new XorGen(seed), state = opts && opts.state, prng = function() { + return (xg.next() >>> 0) / 4294967296; + }; + prng.double = function() { + do { + var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); + } while (result === 0); + return result; + }; + prng.int32 = xg.next; + prng.quick = prng; + if (state) { + if (typeof state == "object") copy(state, xg); + prng.state = function() { + return copy(xg, {}); + }; + } + return prng; + } + if (module2 && module2.exports) { + module2.exports = impl; + } else if (define2 && define2.amd) { + define2(function() { + return impl; + }); + } else { + this.tychei = impl; + } + })( + exports, + typeof module == "object" && module, + // present in node.js + typeof define == "function" && define + // present with an AMD loader + ); } }); -// packages/validation/dist/hard-output-rules/rules/sp-rules.js -function checkSPNotInFRTable(content, sectionType) { - return findPatternViolations(/^\s*\|(?:[^|]*\|)*[^|]*(?:Story\s*Points?)[^|]*\|/gim, content, "sp_not_in_fr_table", sectionType, "FR table contains Story Points column \u2014 SP belongs only in Implementation Roadmap"); -} -function checkUnevenSPDistribution(content, sectionType) { - const sprintPattern = /(?:sprint|iteration)\s*\d+[^|]*?\|\s*(\d+)\s*(?:SP|story\s*points?)/gim; - const spValues = []; - let match; - while ((match = sprintPattern.exec(content)) !== null) { - const val = parseInt(match[1], 10); - if (!isNaN(val)) - spValues.push(val); +// node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js +var require_seedrandom = __commonJS({ + "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js"(exports, module) { + (function(global, pool, math2) { + var width = 256, chunks = 6, digits2 = 52, rngname = "random", startdenom = math2.pow(width, chunks), significance = math2.pow(2, digits2), overflow = significance * 2, mask = width - 1, nodecrypto; + function seedrandom2(seed, options, callback) { + var key = []; + options = options == true ? { entropy: true } : options || {}; + var shortseed = mixkey(flatten3( + options.entropy ? [seed, tostring(pool)] : seed == null ? autoseed() : seed, + 3 + ), key); + var arc4 = new ARC4(key); + var prng = function() { + var n = arc4.g(chunks), d = startdenom, x = 0; + while (n < significance) { + n = (n + x) * width; + d *= width; + x = arc4.g(1); + } + while (n >= overflow) { + n /= 2; + d /= 2; + x >>>= 1; + } + return (n + x) / d; + }; + prng.int32 = function() { + return arc4.g(4) | 0; + }; + prng.quick = function() { + return arc4.g(4) / 4294967296; + }; + prng.double = prng; + mixkey(tostring(arc4.S), pool); + return (options.pass || callback || function(prng2, seed2, is_math_call, state) { + if (state) { + if (state.S) { + copy(state, arc4); + } + prng2.state = function() { + return copy(arc4, {}); + }; + } + if (is_math_call) { + math2[rngname] = prng2; + return seed2; + } else return prng2; + })( + prng, + shortseed, + "global" in options ? options.global : this == math2, + options.state + ); + } + function ARC4(key) { + var t, keylen = key.length, me = this, i2 = 0, j = me.i = me.j = 0, s = me.S = []; + if (!keylen) { + key = [keylen++]; + } + while (i2 < width) { + s[i2] = i2++; + } + for (i2 = 0; i2 < width; i2++) { + s[i2] = s[j = mask & j + key[i2 % keylen] + (t = s[i2])]; + s[j] = t; + } + (me.g = function(count2) { + var t2, r = 0, i3 = me.i, j2 = me.j, s2 = me.S; + while (count2--) { + t2 = s2[i3 = mask & i3 + 1]; + r = r * width + s2[mask & (s2[i3] = s2[j2 = mask & j2 + t2]) + (s2[j2] = t2)]; + } + me.i = i3; + me.j = j2; + return r; + })(width); + } + function copy(f, t) { + t.i = f.i; + t.j = f.j; + t.S = f.S.slice(); + return t; + } + ; + function flatten3(obj, depth) { + var result = [], typ = typeof obj, prop; + if (depth && typ == "object") { + for (prop in obj) { + try { + result.push(flatten3(obj[prop], depth - 1)); + } catch (e3) { + } + } + } + return result.length ? result : typ == "string" ? obj : obj + "\0"; + } + function mixkey(seed, key) { + var stringseed = seed + "", smear, j = 0; + while (j < stringseed.length) { + key[mask & j] = mask & (smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++); + } + return tostring(key); + } + function autoseed() { + try { + var out; + if (nodecrypto && (out = nodecrypto.randomBytes)) { + out = out(width); + } else { + out = new Uint8Array(width); + (global.crypto || global.msCrypto).getRandomValues(out); + } + return tostring(out); + } catch (e3) { + var browser = global.navigator, plugins = browser && browser.plugins; + return [+/* @__PURE__ */ new Date(), global, plugins, global.screen, tostring(pool)]; + } + } + function tostring(a) { + return String.fromCharCode.apply(0, a); + } + mixkey(math2.random(), pool); + if (typeof module == "object" && module.exports) { + module.exports = seedrandom2; + try { + nodecrypto = __require("crypto"); + } catch (ex) { + } + } else if (typeof define == "function" && define.amd) { + define(function() { + return seedrandom2; + }); + } else { + math2["seed" + rngname] = seedrandom2; + } + })( + // global: `self` in browsers (including strict mode and web workers), + // otherwise `this` in Node and other environments + typeof self !== "undefined" ? self : exports, + [], + // pool: entropy pool starts empty + Math + // math: package containing random, pow, and seedrandom + ); } - if (spValues.length < 3) - return []; - const allSame = new Set(spValues).size === 1; - if (allSame) { - return [ - makeViolation("uneven_sp_distribution", sectionType, `All ${spValues.length} sprints have identical SP (${spValues[0]}) \u2014 real projects have uneven complexity`, `Sprint SP values: ${spValues.join(", ")}`) - ]; +}); + +// node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/index.js +var require_seedrandom2 = __commonJS({ + "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/index.js"(exports, module) { + var alea = require_alea(); + var xor128 = require_xor128(); + var xorwow = require_xorwow(); + var xorshift7 = require_xorshift7(); + var xor4096 = require_xor4096(); + var tychei = require_tychei(); + var sr = require_seedrandom(); + sr.alea = alea; + sr.xor128 = xor128; + sr.xorwow = xorwow; + sr.xorshift7 = xorshift7; + sr.xor4096 = xor4096; + sr.tychei = tychei; + module.exports = sr; } - return []; -} -function checkSPArithmetic(content, sectionType) { - const totalRowPattern = /^\s*\|\s*(?:\*{0,2})(?:Total|Sum|Grand\s+Total)(?:\*{0,2})\s*\|(.+)\|/gim; - const numberPattern = /(\d+)/g; - const dataRowPattern = /^\s*\|\s*(?!\s*(?:-|(?:\*{0,2})(?:Total|Sum|Grand\s+Total)))([^|]+)\|(.+)\|/gim; - const individualSPs = []; - let dataMatch; - while ((dataMatch = dataRowPattern.exec(content)) !== null) { - const cellsText = dataMatch[2]; - const numbers = []; - let numMatch; - const numRegex = /(\d+)/g; - while ((numMatch = numRegex.exec(cellsText)) !== null) { - numbers.push(parseInt(numMatch[1], 10)); +}); + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js +var external_exports = {}; +__export(external_exports, { + BRAND: () => BRAND, + DIRTY: () => DIRTY, + EMPTY_PATH: () => EMPTY_PATH, + INVALID: () => INVALID, + NEVER: () => NEVER, + OK: () => OK, + ParseStatus: () => ParseStatus, + Schema: () => ZodType, + ZodAny: () => ZodAny, + ZodArray: () => ZodArray, + ZodBigInt: () => ZodBigInt, + ZodBoolean: () => ZodBoolean, + ZodBranded: () => ZodBranded, + ZodCatch: () => ZodCatch, + ZodDate: () => ZodDate, + ZodDefault: () => ZodDefault, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodEffects: () => ZodEffects, + ZodEnum: () => ZodEnum, + ZodError: () => ZodError, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, + ZodFunction: () => ZodFunction, + ZodIntersection: () => ZodIntersection, + ZodIssueCode: () => ZodIssueCode, + ZodLazy: () => ZodLazy, + ZodLiteral: () => ZodLiteral, + ZodMap: () => ZodMap, + ZodNaN: () => ZodNaN, + ZodNativeEnum: () => ZodNativeEnum, + ZodNever: () => ZodNever, + ZodNull: () => ZodNull, + ZodNullable: () => ZodNullable, + ZodNumber: () => ZodNumber, + ZodObject: () => ZodObject, + ZodOptional: () => ZodOptional, + ZodParsedType: () => ZodParsedType, + ZodPipeline: () => ZodPipeline, + ZodPromise: () => ZodPromise, + ZodReadonly: () => ZodReadonly, + ZodRecord: () => ZodRecord, + ZodSchema: () => ZodType, + ZodSet: () => ZodSet, + ZodString: () => ZodString, + ZodSymbol: () => ZodSymbol, + ZodTransformer: () => ZodEffects, + ZodTuple: () => ZodTuple, + ZodType: () => ZodType, + ZodUndefined: () => ZodUndefined, + ZodUnion: () => ZodUnion, + ZodUnknown: () => ZodUnknown, + ZodVoid: () => ZodVoid, + addIssueToContext: () => addIssueToContext, + any: () => anyType, + array: () => arrayType, + bigint: () => bigIntType, + boolean: () => booleanType, + coerce: () => coerce, + custom: () => custom, + date: () => dateType, + datetimeRegex: () => datetimeRegex, + defaultErrorMap: () => en_default, + discriminatedUnion: () => discriminatedUnionType, + effect: () => effectsType, + enum: () => enumType, + function: () => functionType, + getErrorMap: () => getErrorMap, + getParsedType: () => getParsedType, + instanceof: () => instanceOfType, + intersection: () => intersectionType, + isAborted: () => isAborted, + isAsync: () => isAsync, + isDirty: () => isDirty, + isValid: () => isValid, + late: () => late, + lazy: () => lazyType, + literal: () => literalType, + makeIssue: () => makeIssue, + map: () => mapType, + nan: () => nanType, + nativeEnum: () => nativeEnumType, + never: () => neverType, + null: () => nullType, + nullable: () => nullableType, + number: () => numberType, + object: () => objectType, + objectUtil: () => objectUtil, + oboolean: () => oboolean, + onumber: () => onumber, + optional: () => optionalType, + ostring: () => ostring, + pipeline: () => pipelineType, + preprocess: () => preprocessType, + promise: () => promiseType, + quotelessJson: () => quotelessJson, + record: () => recordType, + set: () => setType, + setErrorMap: () => setErrorMap, + strictObject: () => strictObjectType, + string: () => stringType, + symbol: () => symbolType, + transformer: () => effectsType, + tuple: () => tupleType, + undefined: () => undefinedType, + union: () => unionType, + unknown: () => unknownType, + util: () => util, + void: () => voidType +}); + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js +var util; +(function(util2) { + util2.assertEqual = (_) => { + }; + function assertIs2(_arg) { + } + util2.assertIs = assertIs2; + function assertNever2(_x) { + throw new Error(); + } + util2.assertNever = assertNever2; + util2.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; } - if (numbers.length > 0) { - individualSPs.push(numbers[numbers.length - 1]); + return obj; + }; + util2.getValidEnumValues = (obj) => { + const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; } - } - const violations = []; - let totalMatch; - while ((totalMatch = totalRowPattern.exec(content)) !== null) { - const cellsText = totalMatch[1]; - const numbers = []; - let numMatch; - const numRegex = /(\d+)/g; - while ((numMatch = numRegex.exec(cellsText)) !== null) { - numbers.push(parseInt(numMatch[1], 10)); + return util2.objectValues(filtered); + }; + util2.objectValues = (obj) => { + return util2.objectKeys(obj).map(function(e3) { + return obj[e3]; + }); + }; + util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object3) => { + const keys = []; + for (const key in object3) { + if (Object.prototype.hasOwnProperty.call(object3, key)) { + keys.push(key); + } } - if (numbers.length === 0) - continue; - const totalValue = numbers[numbers.length - 1]; - const computedSum = individualSPs.reduce((sum3, v) => sum3 + v, 0); - if (computedSum > 0 && computedSum !== totalValue) { - violations.push(makeViolation("sp_arithmetic", sectionType, `SP total row shows ${totalValue} but individual rows sum to ${computedSum}`, `Total: ${totalValue}, Computed: ${computedSum}`)); + return keys; + }; + util2.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; } + return void 0; + }; + util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; + function joinValues2(array2, separator = " | ") { + return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); } - return violations; -} -function checkDocumentSPArithmetic(sections) { - const spSections = sections.filter((s) => s.type === "timeline" || s.type === "deployment" || s.type === "requirements"); - if (spSections.length === 0) - return []; - const combinedContent = spSections.map((s) => s.content).join("\n\n"); - return checkSPArithmetic(combinedContent, "timeline"); -} -var init_sp_rules = __esm({ - async "packages/validation/dist/hard-output-rules/rules/sp-rules.js"() { - "use strict"; - await init_helpers(); + util2.joinValues = joinValues2; + util2.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; +})(util || (util = {})); +var objectUtil; +(function(objectUtil2) { + objectUtil2.mergeShapes = (first, second) => { + return { + ...first, + ...second + // second overwrites first + }; + }; +})(objectUtil || (objectUtil = {})); +var ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" +]); +var getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; } -}); +}; -// packages/validation/dist/hard-output-rules/rules/quality-rules.js -function checkNoSelfReferencingDeps(content, sectionType) { - const violations = []; - const pattern = /((?:STORY|US|EPIC|FR)-\d+)[^|\n]{0,200}?(?:depends\s+on|blocked\s+by|requires)[^|\n]{0,200}?\1/gi; - let match; - while ((match = pattern.exec(content)) !== null) { - const storyId = match[1]; - const matchText = match[0].substring(0, 120); - violations.push(makeViolation("no_self_referencing_deps", sectionType, `${storyId} references itself in dependencies`, matchText)); +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js +var ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" +]); +var quotelessJson = (obj) => { + const json2 = JSON.stringify(obj, null, 2); + return json2.replace(/"([^"]+)":/g, "$1:"); +}; +var ZodError = class _ZodError extends Error { + get errors() { + return this.issues; + } + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub2) => { + this.issues = [...this.issues, sub2]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; } - const tablePattern = /^\s*\|\s*((?:STORY|US|EPIC|FR)-\d+)\s*\|(?:[^|\n]*\|)*[^|\n]*\1[^|\n]*\|/gm; - while ((match = tablePattern.exec(content)) !== null) { - const storyId = match[1]; - const alreadyReported = violations.some((v) => v.offendingContent?.includes(storyId) === true); - if (!alreadyReported) { - violations.push(makeViolation("no_self_referencing_deps", sectionType, `${storyId} appears to reference itself in table row`, storyId)); + format(_mapper) { + const mapper = _mapper || function(issue2) { + return issue2.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error2) => { + for (const issue2 of error2.issues) { + if (issue2.code === "invalid_union") { + issue2.unionErrors.map(processError); + } else if (issue2.code === "invalid_return_type") { + processError(issue2.returnTypeError); + } else if (issue2.code === "invalid_arguments") { + processError(issue2.argumentsError); + } else if (issue2.path.length === 0) { + fieldErrors._errors.push(mapper(issue2)); + } else { + let curr = fieldErrors; + let i2 = 0; + while (i2 < issue2.path.length) { + const el = issue2.path[i2]; + const terminal = i2 === issue2.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue2)); + } + curr = curr[el]; + i2++; + } + } + } + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof _ZodError)) { + throw new Error(`Not a ZodError: ${value}`); } } - return violations; -} -function checkMetricsDisclaimer(content, sectionType) { - const lowered = content.toLowerCase(); - const hasMetrics = lowered.includes("reasoning") && lowered.includes("metric"); - if (!hasMetrics) - return []; - const hasDisclaimer = lowered.includes("model-projected") || lowered.includes("projected") || lowered.includes("not independent") || lowered.includes("disclaimer"); - if (!hasDisclaimer) { - return [ - makeViolation("metrics_disclaimer", sectionType, "Verification metrics found without 'model-projected' disclaimer") - ]; + toString() { + return this.message; } - return []; -} -function checkHonestVerificationVerdicts(content, sectionType) { - const nfrPattern = /NFR-\d+|(?:p95|p99|latency|throughput|response\s+time)\s*[:<≤<=]\s*\d+/gi; - if (!nfrPattern.test(content)) - return []; - const verdictPattern = /\b(?:PASS|SPEC-COMPLETE|NEEDS-RUNTIME|INCONCLUSIVE|FAIL)\b/gi; - const verdicts = []; - let match; - while ((match = verdictPattern.exec(content)) !== null) { - verdicts.push(match[0].toUpperCase()); + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); } - if (verdicts.length === 0) - return []; - const hasOnlyPass = verdicts.every((v) => v === "PASS"); - if (hasOnlyPass && verdicts.length >= 2) { - return [ - makeViolation("honest_verification_verdicts", sectionType, `All ${verdicts.length} verdicts are PASS despite NFR performance claims that require runtime measurement \u2014 use SPEC-COMPLETE or NEEDS-RUNTIME for unverified metrics`, `Verdicts: ${verdicts.length}x PASS, 0x SPEC-COMPLETE/NEEDS-RUNTIME`) - ]; + get isEmpty() { + return this.issues.length === 0; } - return []; -} -function checkDocumentVerificationVerdicts(sections) { - const perfSections = sections.filter((s) => s.type === "performance_requirements"); - const testSections = sections.filter((s) => s.type === "testing"); - if (perfSections.length === 0) - return []; - const perfContent = perfSections.map((s) => s.content).join("\n\n"); - const testContent = testSections.map((s) => s.content).join("\n\n"); - const combinedContent = perfContent + "\n\n" + testContent; - return checkHonestVerificationVerdicts(combinedContent, "performance_requirements"); -} -function checkRiskMitigationCompleteness(content, sectionType) { - const headerPattern = /^\s*\|[^\n]*(?:Risk|Threat)[^\n]*(?:Mitigation|Response|Action)[^\n]*\|/gim; - if (!headerPattern.test(content)) - return []; - const rowPattern = /^\s*\|(?!\s*[-:]+\s*\|)(.+)\|/gm; - const violations = []; - const emptyMitigationPattern = /^\s*(?:-|N\/?A|TBD|TODO|None)?\s*$/i; - let index2 = 0; - let match; - while ((match = rowPattern.exec(content)) !== null) { - index2++; - if (index2 === 1) - continue; - const rowText = match[1]; - const cells = rowText.split("|").map((c) => c.trim()); - const isSeparator = cells.every((cell) => [...cell].every((ch) => ch === "-" || ch === ":" || ch === " ")); - if (isSeparator) - continue; - const lastCell = cells[cells.length - 1]; - if (lastCell === void 0) - continue; - if (emptyMitigationPattern.test(lastCell)) { - const riskDescription = cells[0] ?? "Unknown"; - violations.push(makeViolation("risk_mitigation_completeness", sectionType, `Risk '${riskDescription.substring(0, 60)}' has empty or placeholder mitigation`, `Mitigation: ${lastCell.length === 0 ? "(empty)" : lastCell}`)); + flatten(mapper = (issue2) => issue2.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub2 of this.issues) { + if (sub2.path.length > 0) { + const firstEl = sub2.path[0]; + fieldErrors[firstEl] = fieldErrors[firstEl] || []; + fieldErrors[firstEl].push(mapper(sub2)); + } else { + formErrors.push(mapper(sub2)); + } } + return { formErrors, fieldErrors }; } - return violations; -} -function checkDeploymentRollbackPlan(content, sectionType) { - const lowered = content.toLowerCase(); - const rollbackKeywords = [ - "rollback", - "roll back", - "undo", - "revert", - "restore", - "fallback" - ]; - const hasRollbackPlan = rollbackKeywords.some((k) => lowered.includes(k)); - if (!hasRollbackPlan) { - return [ - makeViolation("deployment_rollback_plan", sectionType, "Deployment section lacks a rollback/restore strategy \u2014 every deployment must have a recovery plan") - ]; - } - return []; -} -var init_quality_rules = __esm({ - async "packages/validation/dist/hard-output-rules/rules/quality-rules.js"() { - "use strict"; - await init_helpers(); + get formErrors() { + return this.flatten(); } -}); +}; +ZodError.create = (issues) => { + const error2 = new ZodError(issues); + return error2; +}; -// packages/validation/dist/hard-output-rules/rules/numbering-rules.js -function checkACNumbering(content, sectionType) { - const acPattern = /AC-(\d+)/g; - const acNumbers = []; - let match; - while ((match = acPattern.exec(content)) !== null) { - acNumbers.push(parseInt(match[1], 10)); - } - if (acNumbers.length === 0) - return []; - const sorted = [...new Set(acNumbers)].sort((a, b) => a - b); - const first = sorted[0]; - const last = sorted[sorted.length - 1]; - const gaps = []; - for (let n = first; n <= last; n++) { - if (!sorted.includes(n)) - gaps.push(n); - } - if (gaps.length > 0) { - return [ - makeViolation("ac_numbering", sectionType, `AC numbering has gaps: missing AC-${gaps.join(", AC-")}`, `Found: AC-${sorted.join(", AC-")}`) - ]; - } - return []; -} -function checkFRTraceability(content, sectionType) { - const tableHeaderPattern = /^\s*\|[^\n]*\bID\b[^\n]*(?:Requirement|Description)[^\n]*\|/gim; - if (!tableHeaderPattern.test(content)) - return []; - const sourcePattern = /^\s*\|[^\n]*\bID\b[^\n]*\bSource\b[^\n]*\|/gim; - if (!sourcePattern.test(content)) { - return [ - makeViolation("fr_traceability", sectionType, "FR table exists but lacks a Source/Traceability column \u2014 every FR must trace to its origin") - ]; - } - return []; -} -function checkDuplicateRequirementIds(content, sectionType) { - const idPattern = /^\s*\|\s*((FR|NFR)-\d+)\s*\|/gm; - const seenIds = /* @__PURE__ */ new Map(); - let match; - while ((match = idPattern.exec(content)) !== null) { - const id = match[1]; - seenIds.set(id, (seenIds.get(id) ?? 0) + 1); - } - const violations = []; - for (const [id, count2] of seenIds) { - if (count2 > 1) { - violations.push(makeViolation("duplicate_requirement_ids", sectionType, `Requirement ID '${id}' appears ${count2} times \u2014 each ID must be unique`, id)); - } +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js +var errorMap = (issue2, _ctx) => { + let message; + switch (issue2.code) { + case ZodIssueCode.invalid_type: + if (issue2.received === ZodParsedType.undefined) { + message = "Required"; + } else { + message = `Expected ${issue2.expected}, received ${issue2.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue2.validation === "object") { + if ("includes" in issue2.validation) { + message = `Invalid input: must include "${issue2.validation.includes}"`; + if (typeof issue2.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`; + } + } else if ("startsWith" in issue2.validation) { + message = `Invalid input: must start with "${issue2.validation.startsWith}"`; + } else if ("endsWith" in issue2.validation) { + message = `Invalid input: must end with "${issue2.validation.endsWith}"`; + } else { + util.assertNever(issue2.validation); + } + } else if (issue2.validation !== "regex") { + message = `Invalid ${issue2.validation}`; + } else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue2.type === "array") + message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`; + else if (issue2.type === "string") + message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`; + else if (issue2.type === "number") + message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; + else if (issue2.type === "bigint") + message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; + else if (issue2.type === "date") + message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue2.type === "array") + message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`; + else if (issue2.type === "string") + message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`; + else if (issue2.type === "number") + message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; + else if (issue2.type === "bigint") + message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; + else if (issue2.type === "date") + message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue2.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util.assertNever(issue2); } - return violations; + return { message }; +}; +var en_default = errorMap; + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js +var overrideErrorMap = en_default; +function setErrorMap(map4) { + overrideErrorMap = map4; } -function checkFRNumberingGaps(content, sectionType) { - return [ - ...checkIdNumberingGaps(content, "FR", "fr_numbering_gaps", sectionType), - ...checkIdNumberingGaps(content, "NFR", "fr_numbering_gaps", sectionType) - ]; +function getErrorMap() { + return overrideErrorMap; } -function checkIdNumberingGaps(content, prefix, rule, sectionType) { - const pattern = new RegExp(`${prefix}-(\\d+)`, "g"); - const numbers = []; - let match; - while ((match = pattern.exec(content)) !== null) { - numbers.push(parseInt(match[1], 10)); - } - if (numbers.length === 0) - return []; - const sorted = [...new Set(numbers)].sort((a, b) => a - b); - const first = sorted[0]; - const last = sorted[sorted.length - 1]; - const gaps = []; - for (let n = first; n <= last; n++) { - if (!sorted.includes(n)) - gaps.push(n); + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js +var makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...issueData.path || []]; + const fullIssue = { + ...issueData, + path: fullPath + }; + if (issueData.message !== void 0) { + return { + ...issueData, + path: fullPath, + message: issueData.message + }; } - if (gaps.length > 0) { - return [ - makeViolation(rule, sectionType, `${prefix} numbering has gaps: missing ${prefix}-${gaps.join(`, ${prefix}-`)}`, `Found: ${prefix}-${sorted.join(`, ${prefix}-`)}`) - ]; + let errorMessage = ""; + const maps = errorMaps.filter((m) => !!m).slice().reverse(); + for (const map4 of maps) { + errorMessage = map4(fullIssue, { data, defaultError: errorMessage }).message; } - return []; + return { + ...issueData, + path: fullPath, + message: errorMessage + }; +}; +var EMPTY_PATH = []; +function addIssueToContext(ctx, issueData) { + const overrideMap = getErrorMap(); + const issue2 = makeIssue({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + // contextual error map is first priority + ctx.schemaErrorMap, + // then schema-bound map if available + overrideMap, + // then global override map + overrideMap === en_default ? void 0 : en_default + // then global default map + ].filter((x) => !!x) + }); + ctx.common.issues.push(issue2); } -function checkDocumentACConsistency(content) { - const acPattern = /AC-(\d+)/g; - const acNumbers = []; - let match; - while ((match = acPattern.exec(content)) !== null) { - acNumbers.push(parseInt(match[1], 10)); - } - if (acNumbers.length <= 1) - return []; - const sorted = [...new Set(acNumbers)].sort((a, b) => a - b); - const first = sorted[0]; - const last = sorted[sorted.length - 1]; - const gaps = []; - for (let n = first; n <= last; n++) { - if (!sorted.includes(n)) - gaps.push(n); +var ParseStatus = class _ParseStatus { + constructor() { + this.value = "valid"; } - if (gaps.length > 0) { - return [ - makeViolation("ac_numbering", null, `Document-level AC numbering has gaps: missing AC-${gaps.join(", AC-")}`, `Found across document: AC-${sorted.join(", AC-")}`) - ]; + dirty() { + if (this.value === "valid") + this.value = "dirty"; } - return []; -} -var init_numbering_rules = __esm({ - async "packages/validation/dist/hard-output-rules/rules/numbering-rules.js"() { - "use strict"; - await init_helpers(); + abort() { + if (this.value !== "aborted") + this.value = "aborted"; } -}); - -// packages/validation/dist/hard-output-rules/rules/database-rules.js -function checkNoAnyCodable(content, sectionType) { - return findPatternViolations(/\bAny(?:Codable|Encodable|Decodable|JSON)\b/g, content, "no_any_codable", sectionType, "Found prohibited AnyCodable/AnyEncodable/AnyDecodable/AnyJSON type"); -} -function checkNoNowInPartialIndexes(content, sectionType) { - return findPatternViolations(/CREATE\s+INDEX\b[^;]*WHERE\b[^;]*\b(?:NOW\s*\(\)|CURRENT_TIMESTAMP)/gi, content, "no_now_in_partial_indexes", sectionType, "NOW()/CURRENT_TIMESTAMP in partial index WHERE clause \u2014 evaluated once at creation, not at query time"); -} -function checkNoOrphanDDL(content, sectionType) { - const typePattern = /CREATE\s+(?:TYPE|ENUM)\s+(\w+)/gi; - const violations = []; - let match; - while ((match = typePattern.exec(content)) !== null) { - const typeName = match[1]; - const escapedName = typeName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - const refPattern = new RegExp(`\\b${escapedName}\\b`, "gi"); - const refMatches = content.match(refPattern); - const refCount = refMatches ? refMatches.length : 0; - if (refCount <= 1) { - violations.push(makeViolation("no_orphan_ddl", sectionType, `Type '${typeName}' is defined but never referenced by any table or column`, `CREATE TYPE/ENUM ${typeName}`)); + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs2) { + const syncPairs = []; + for (const pair of pairs2) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value + }); } + return _ParseStatus.mergeObjectSync(status, syncPairs); } - return violations; -} -function checkFKReferencesExist(content, sectionType) { - const createPattern = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(\w+)/gi; - const tableNames = /* @__PURE__ */ new Set(); - let match; - while ((match = createPattern.exec(content)) !== null) { - tableNames.add(match[1].toLowerCase()); - } - if (tableNames.size === 0) - return []; - const refPattern = /REFERENCES\s+(\w+)/gi; - const violations = []; - while ((match = refPattern.exec(content)) !== null) { - const refTarget = match[1]; - if (!tableNames.has(refTarget.toLowerCase())) { - violations.push(makeViolation("fk_references_exist", sectionType, `Foreign key references table '${refTarget}' which has no CREATE TABLE in the data model`, `REFERENCES ${refTarget}`)); + static mergeObjectSync(status, pairs2) { + const finalObject = {}; + for (const pair of pairs2) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } } + return { status: status.value, value: finalObject }; } - return violations; -} -var init_database_rules = __esm({ - async "packages/validation/dist/hard-output-rules/rules/database-rules.js"() { - "use strict"; - await init_helpers(); - } +}; +var INVALID = Object.freeze({ + status: "aborted" }); +var DIRTY = (value) => ({ status: "dirty", value }); +var OK = (value) => ({ status: "valid", value }); +var isAborted = (x) => x.status === "aborted"; +var isDirty = (x) => x.status === "dirty"; +var isValid = (x) => x.status === "valid"; +var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; -// packages/validation/dist/hard-output-rules/rules/test-rules.js -function checkNoPlaceholderTests(content, sectionType) { - const patterns = [ - /func\s+test\w+\s*\([^)]*\)\s*(?:throws\s+)?(?:async\s+)?(?:throws\s+)?\{[^}]*\/\/\s*(?:TODO|FIXME|PLACEHOLDER)[^}]*\}/g, - /func\s+test\w+\s*\([^)]*\)\s*(?:throws\s+)?(?:async\s+)?(?:throws\s+)?\{\s*\}/g, - /^\s*\|\s*test\w+\s*\|[^|]*\|\s*`?\s*\/\/\s*(?:TODO|Setup)/gm - ]; - const violations = []; - for (const pattern of patterns) { - violations.push(...findPatternViolations(pattern, content, "no_placeholder_tests", sectionType, "Found placeholder test with empty or TODO-only body")); +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js +var errorUtil; +(function(errorUtil2) { + errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; +})(errorUtil || (errorUtil = {})); + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js +var ParseInputLazyPath = class { + constructor(parent, value, path, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; } - return violations; -} -function checkTestTraceabilityIntegrity(content, sectionType) { - const matrixRowPattern = /^\s*\|\s*(test\w+)\s*\|/gm; - const matrixTestNames = []; - let match; - while ((match = matrixRowPattern.exec(content)) !== null) { - matrixTestNames.push(match[1]); +}; +var handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error2 = new ZodError(ctx.common.issues); + this._error = error2; + return this._error; + } + }; } - if (matrixTestNames.length === 0) - return []; - const testFuncPattern = /func\s+(test\w+)\s*\(/g; - const definedTestNames = /* @__PURE__ */ new Set(); - while ((match = testFuncPattern.exec(content)) !== null) { - definedTestNames.add(match[1]); +}; +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; + if (errorMap2 && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } - const violations = []; - for (const matrixName of matrixTestNames) { - if (!definedTestNames.has(matrixName)) { - violations.push(makeViolation("test_traceability_integrity", sectionType, `Test '${matrixName}' listed in traceability matrix but no matching func ${matrixName}() found in test code`, matrixName)); + if (errorMap2) + return { errorMap: errorMap2, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; } - } - return violations; -} -function checkDocumentTestTraceability(sections) { - const testSections = sections.filter((s) => s.type === "testing"); - if (testSections.length === 0) - return []; - const combinedTestContent = testSections.map((s) => s.content).join("\n\n"); - return checkTestTraceabilityIntegrity(combinedTestContent, "testing"); + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; } -var init_test_rules = __esm({ - async "packages/validation/dist/hard-output-rules/rules/test-rules.js"() { - "use strict"; - await init_helpers(); - } -}); - -// packages/validation/dist/hard-output-rules/rules/architecture-rules.js -function checkCleanArchitecture(content, sectionType) { - const lowered = content.toLowerCase(); - const hasPortAdapter = lowered.includes("port") && lowered.includes("adapter"); - const hasHexagonal = lowered.includes("hexagonal"); - const hasCleanArch = lowered.includes("clean architecture"); - const hasDomainLayer = lowered.includes("domain layer") || lowered.includes("domain model"); - const hasCompositionRoot = lowered.includes("composition root") || lowered.includes("composition layer"); - const hasArchPattern = hasPortAdapter || hasHexagonal || hasCleanArch; - const hasLayerSeparation = hasDomainLayer || hasCompositionRoot; - if (!hasArchPattern && !hasLayerSeparation) { - return [ - makeViolation("clean_architecture", sectionType, "Technical spec lacks ports/adapters architecture \u2014 must show domain layer with ports, adapter layer, and composition root") - ]; +var ZodType = class { + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + }; } - return []; -} -function checkCodeExamplePortCompliance(content, sectionType) { - const codeBlocks = extractCodeBlocks(content); - if (codeBlocks.length === 0) - return []; - const portViolations = [ - { pattern: /\bDate\(\)/, message: "Date() \u2014 inject a Clock port instead" }, - { - pattern: /\bUUID\(\)/, - message: "UUID() \u2014 inject a UUIDGenerator port instead" - }, - { - pattern: /\bFileManager\b/, - message: "FileManager \u2014 inject a FileSystem port instead" - }, - { - pattern: /\bURLSession\b/, - message: "URLSession \u2014 inject an HTTPClient port instead" - }, - { - pattern: /\bUserDefaults\b/, - message: "UserDefaults \u2014 inject a KeyValueStore port instead" - } - ]; - const foundViolations = []; - for (const codeBlock of codeBlocks) { - if (!isDomainLayerCode(codeBlock)) - continue; - for (const { pattern, message } of portViolations) { - const globalPattern = new RegExp(pattern.source, "g"); - let match; - while ((match = globalPattern.exec(codeBlock)) !== null) { - foundViolations.push(makeViolation("code_example_port_compliance", sectionType, `Domain-layer code example uses framework type: ${message}`, match[0])); + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent } + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); } + return result; } - return foundViolations; -} -function checkGenericOverSpecific(content, sectionType) { - const lowered = content.toLowerCase(); - const paramSignals = [ - "parameter", - "configurable", - "configuration", - "default value", - "sensible default", - "optional", - "override", - "customizable" - ]; - const extensibilitySignals = [ - "extensible", - "reusable", - "composable", - "generic", - "abstraction", - "centralized", - "single source of truth", - "shared component", - "common module" - ]; - const patternSignals = [ - "strategy pattern", - "builder pattern", - "factory", - "protocol", - "interface", - "contract", - "dependency injection", - "inversion of control", - "plugin", - "middleware", - "decorator" - ]; - let categoriesPresent = 0; - if (paramSignals.some((s) => lowered.includes(s))) - categoriesPresent++; - if (extensibilitySignals.some((s) => lowered.includes(s))) - categoriesPresent++; - if (patternSignals.some((s) => lowered.includes(s))) - categoriesPresent++; - if (categoriesPresent < 2) { - return [ - makeViolation("generic_over_specific", sectionType, "Technical spec lacks scalable design \u2014 must demonstrate parameterization (configurable values, defaults) AND extensibility (reusable abstractions, centralized components, design patterns). A solution that requires repeating the same fix across many files is not scalable.") - ]; + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); } - return []; -} -function isDomainLayerCode(code) { - const lowered = code.toLowerCase(); - const hasDomainSignals = lowered.includes("protocol ") || lowered.includes("entity") || lowered.includes("use case") || lowered.includes("usecase") || lowered.includes("domain") || lowered.includes("port") || lowered.includes("repository"); - const hasAdapterSignals = lowered.includes("import uikit") || lowered.includes("import swiftui") || lowered.includes("import foundation") || lowered.includes("adapter") || lowered.includes("controller") || lowered.includes("viewmodel") || lowered.includes("@main") || lowered.includes("@objc"); - return hasDomainSignals && !hasAdapterSignals; -} -var init_architecture_rules = __esm({ - async "packages/validation/dist/hard-output-rules/rules/architecture-rules.js"() { - "use strict"; - await init_helpers(); + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; } -}); - -// packages/validation/dist/hard-output-rules/rules/code-quality-rules.js -function checkNoNestedTypes(content, sectionType) { - const codeBlocks = extractCodeBlocks(content); - if (codeBlocks.length === 0) - return []; - const typeKeywordPattern = /(?:^|\n)\s*(?:public\s+|private\s+|internal\s+|protected\s+|open\s+|fileprivate\s+|final\s+|abstract\s+|sealed\s+|data\s+)*(?:struct|class|enum|interface|object|record)\s+\w+/; - const violations = []; - for (const codeBlock of codeBlocks) { - const lines = codeBlock.split("\n"); - let braceDepth = 0; - for (const line of lines) { - if (typeKeywordPattern.test(line)) { - if (braceDepth > 0) { - const typeName = extractTypeName(line.trim()); - violations.push(makeViolation("no_nested_types", sectionType, `Nested type declaration detected \u2014 extract '${typeName}' to its own top-level definition. Nested types reduce readability and reusability.`, line.trim())); + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }; + } catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; } + ctx.common = { + issues: [], + async: true + }; } - braceDepth += (line.match(/\{/g) || []).length; - braceDepth -= (line.match(/\}/g) || []).length; - braceDepth = Math.max(0, braceDepth); } + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }); } - return violations; -} -function checkSingleResponsibility(content, sectionType) { - const violations = []; - const lowered = content.toLowerCase(); - const srpSignals = [ - "single responsibility", - "separation of concern", - "one reason to change", - "focused class", - "small class", - "cohesion", - "cohesive", - "do one thing", - "bounded context" - ]; - if (!srpSignals.some((s) => lowered.includes(s))) { - violations.push(makeViolation("single_responsibility", sectionType, "Technical spec must establish single responsibility constraints \u2014 classes should have one reason to change, with clear separation of concerns.")); + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; } - const codeBlocks = extractCodeBlocks(content); - const typeStartPattern = /(?:public\s+|private\s+|internal\s+|protected\s+|open\s+|final\s+|abstract\s+|sealed\s+|data\s+)*(?:struct|class|enum|interface|object)\s+(\w+)/; - for (const codeBlock of codeBlocks) { - const lines = codeBlock.split("\n"); - let currentTypeName = null; - let typeStartLine = 0; - let braceDepth = 0; - for (let index2 = 0; index2 < lines.length; index2++) { - const line = lines[index2]; - if (braceDepth === 0) { - const match = line.match(typeStartPattern); - if (match) { - currentTypeName = match[1] ?? extractTypeName(line.trim()); - typeStartLine = index2; - } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check2, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } else if (typeof message === "function") { + return message(val); + } else { + return message; } - braceDepth += (line.match(/\{/g) || []).length; - braceDepth -= (line.match(/\}/g) || []).length; - if (braceDepth <= 0 && currentTypeName !== null) { - const typeLineCount = index2 - typeStartLine + 1; - if (typeLineCount > 50) { - violations.push(makeViolation("single_responsibility", sectionType, `Code example shows '${currentTypeName}' spanning ${typeLineCount} lines \u2014 split into smaller, focused types. A single class/struct should not exceed ~50 lines in a PRD example.`, currentTypeName)); - } - currentTypeName = null; - braceDepth = 0; + }; + return this._refinement((val, ctx) => { + const result = check2(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val) + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } else { + return true; + } + }); } - } + if (!result) { + setError(); + return false; + } else { + return true; + } + }); } - return violations; -} -function checkExplicitAccessControl(content, sectionType) { - return findAbsenceViolation(content, [ - "access control", - "visibility", - "scope", - "public", - "private", - "internal", - "protected", - "encapsulation", - "information hiding", - "expose only", - "minimal api surface", - "least privilege", - "api boundary" - ], 2, "explicit_access_control", sectionType, "Technical spec should establish access control guidelines \u2014 define what is public vs private, enforce encapsulation, and minimize exposed API surface."); -} -function checkFactoryBasedInjection(content, sectionType) { - return findAbsenceViolation(content, [ - "dependency injection", - "inject", - "factory", - "container", - "composition root", - "wire", - "provider", - "resolver", - "assembler", - "inversion of control", - "ioc" - ], 2, "factory_based_injection", sectionType, "Technical spec must mandate dependency injection through factories or DI containers \u2014 concrete types should not be instantiated directly in business logic. Specify how dependencies are wired."); -} -function checkSolidCompliance(content, sectionType) { - const lowered = content.toLowerCase(); - const solidCategories = [ - { - principle: "Single Responsibility", - signals: [ - "single responsibility", - "one reason to change", - "separation of concern", - "focused", - "cohesive" - ] - }, - { - principle: "Open/Closed", - signals: [ - "open/closed", - "open for extension", - "closed for modification", - "extensible", - "plugin", - "strategy", - "decorator" - ] - }, - { - principle: "Dependency Inversion", - signals: [ - "dependency inversion", - "depend on abstraction", - "protocol", - "interface", - "port", - "contract", - "injection", - "inversion of control" - ] - } - ]; - let categoriesMet = 0; - for (const { signals } of solidCategories) { - if (signals.some((s) => lowered.includes(s))) { - categoriesMet++; - } + refinement(check2, refinementData) { + return this._refinement((val, ctx) => { + if (!check2(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } else { + return true; + } + }); } - if (categoriesMet < 2) { - return [ - makeViolation("solid_compliance", sectionType, "Technical spec must demonstrate SOLID principles \u2014 at minimum: single responsibility (focused classes), open/closed (extensible without modification), and dependency inversion (depend on abstractions, not concretions).") - ]; + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement } + }); } - return []; -} -function checkCodeReusability(content, sectionType) { - const lowered = content.toLowerCase(); - const reusabilitySignals = [ - "reusable", - "reuse", - "shared", - "common", - "utility", - "helper", - "library", - "module", - "component", - "centralized" - ]; - const readabilitySignals = [ - "readable", - "readability", - "naming convention", - "self-documenting", - "clean code", - "maintainable", - "clear", - "descriptive", - "consistent" - ]; - const hasReusability = reusabilitySignals.some((s) => lowered.includes(s)); - const hasReadability = readabilitySignals.some((s) => lowered.includes(s)); - if (!hasReusability && !hasReadability) { - return [ - makeViolation("code_reusability", sectionType, "Technical spec should establish code quality standards \u2014 specify that code must be reusable (shared components, centralized utilities) and readable (clear naming, self-documenting, consistent patterns).") - ]; + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def) { + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data) + }; } - return []; -} -var init_code_quality_rules = __esm({ - async "packages/validation/dist/hard-output-rules/rules/code-quality-rules.js"() { - "use strict"; - await init_helpers(); + optional() { + return ZodOptional.create(this, this._def); } -}); - -// packages/validation/dist/hard-output-rules/rules/coverage-rules.js -function checkDocumentFRToACCoverage(sections) { - const reqSections = sections.filter((s) => s.type === "requirements"); - const acSections = sections.filter((s) => s.type === "acceptance_criteria"); - if (reqSections.length === 0) - return []; - const reqContent = reqSections.map((s) => s.content).join("\n\n"); - const frPattern = /^\s*\|\s*(FR-\d+)\s*\|/gm; - const definedFRs = /* @__PURE__ */ new Set(); - let match; - while ((match = frPattern.exec(reqContent)) !== null) { - definedFRs.add(match[1]); + nullable() { + return ZodNullable.create(this, this._def); } - if (definedFRs.size === 0) - return []; - const acContent = acSections.map((s) => s.content).join("\n\n"); - const frRefPattern = /(FR-\d+)/g; - const referencedFRs = /* @__PURE__ */ new Set(); - while ((match = frRefPattern.exec(acContent)) !== null) { - referencedFRs.add(match[1]); + nullish() { + return this.nullable().optional(); } - const uncoveredFRs = [...definedFRs].filter((fr) => !referencedFRs.has(fr)).sort(); - if (uncoveredFRs.length > 0) { - return [ - makeViolation("fr_to_ac_coverage", null, `${uncoveredFRs.length} FR(s) have no acceptance criteria: ${uncoveredFRs.join(", ")}`, `Uncovered: ${uncoveredFRs.join(", ")}`) - ]; + array() { + return ZodArray.create(this); } - return []; -} -function checkDocumentACToTestCoverage(sections) { - const acSections = sections.filter((s) => s.type === "acceptance_criteria"); - const testSections = sections.filter((s) => s.type === "testing"); - if (acSections.length === 0) - return []; - const acContent = acSections.map((s) => s.content).join("\n\n"); - const acPattern = /(AC-\d+)/g; - const definedACs = /* @__PURE__ */ new Set(); - let match; - while ((match = acPattern.exec(acContent)) !== null) { - definedACs.add(match[1]); + promise() { + return ZodPromise.create(this, this._def); } - if (definedACs.size === 0) - return []; - const testContent = testSections.map((s) => s.content).join("\n\n"); - const acRefPattern = /(AC-\d+)/g; - const referencedACs = /* @__PURE__ */ new Set(); - while ((match = acRefPattern.exec(testContent)) !== null) { - referencedACs.add(match[1]); + or(option) { + return ZodUnion.create([this, option], this._def); } - const uncoveredACs = [...definedACs].filter((ac) => !referencedACs.has(ac)).sort(); - if (uncoveredACs.length > 0) { - return [ - makeViolation("ac_to_test_coverage", null, `${uncoveredACs.length} AC(s) have no test coverage: ${uncoveredACs.join(", ")}`, `Uncovered: ${uncoveredACs.join(", ")}`) - ]; + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); } - return []; -} -var init_coverage_rules = __esm({ - async "packages/validation/dist/hard-output-rules/rules/coverage-rules.js"() { - "use strict"; - await init_helpers(); + transform(transform2) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform: transform2 } + }); } -}); - -// packages/validation/dist/hard-output-rules/rules/security-rules.js -function checkNoHardcodedSecrets(content, sectionType) { - const violations = []; - const codeBlocks = extractCodeBlocks(content); - const secretPatterns = [ - { - pattern: /(?:password|passwd|pwd)\s*[:=]\s*["'][^"']{3,}/i, - description: "hardcoded password" - }, - { - pattern: /(?:api[_-]?key|apikey)\s*[:=]\s*["'][^"']{8,}/i, - description: "hardcoded API key" - }, - { - pattern: /(?:secret|token|auth)\s*[:=]\s*["'][A-Za-z0-9+/=]{16,}/i, - description: "hardcoded secret/token" - }, - { - pattern: /(?:Bearer|Basic)\s+[A-Za-z0-9+/=]{20,}/i, - description: "hardcoded auth token" - }, - { - pattern: /(?:jdbc|mongodb|postgres|mysql|redis):\/\/[^\s"']+:[^\s"']+@/i, - description: "hardcoded connection string with credentials" - }, - { - pattern: /-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/, - description: "embedded private key" - } - ]; - for (const codeBlock of codeBlocks) { - for (const { pattern, description } of secretPatterns) { - if (pattern.test(codeBlock)) { - violations.push(makeViolation("no_hardcoded_secrets", sectionType, `Code example contains ${description} \u2014 use environment variables, secret managers, or configuration injection instead.`, description)); - } - } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault + }); } - const lowered = content.toLowerCase(); - const dangerousPhrases = [ - "hardcode the password", - "hardcode the key", - "embed the secret", - "paste your api key", - "put your token directly" - ]; - for (const phrase of dangerousPhrases) { - if (lowered.includes(phrase)) { - violations.push(makeViolation("no_hardcoded_secrets", sectionType, "Spec instructs hardcoding secrets \u2014 must use secure configuration (env vars, vault, secret manager).", phrase)); - } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def) + }); } - return violations; -} -function checkInputValidationRequired(content, sectionType) { - return findAbsenceViolation(content, [ - "input validation", - "validate input", - "sanitize", - "sanitization", - "whitelist", - "allowlist", - "blocklist", - "reject invalid", - "schema validation", - "request validation", - "payload validation", - "type check", - "bounds check", - "length check", - "format validation", - "validate request", - "input filter", - "data validation" - ], 2, "input_validation_required", sectionType, "Technical spec must specify input validation strategy \u2014 every external input (API, user, file, webhook) needs validation and sanitization rules at system boundaries."); -} -function checkOutputEncodingInjectionPrevention(content, sectionType) { - const lowered = content.toLowerCase(); - const injectionSignals = [ - "injection prevention", - "sql injection", - "xss", - "cross-site scripting", - "command injection", - "output encoding", - "escape", - "parameterized quer", - "prepared statement", - "orm", - "html encoding", - "content security policy", - "csp", - "sanitize output", - "template escaping", - "injection attack" - ]; - const signalCount = injectionSignals.filter((s) => lowered.includes(s)).length; - if (signalCount < 2) { - return [ - makeViolation("output_encoding_injection_prevention", sectionType, "Technical spec must address injection prevention \u2014 specify parameterized queries (SQL injection), output encoding (XSS), and input sanitization strategies.") - ]; + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch + }); } - const violations = []; - const codeBlocks = extractCodeBlocks(content); - const unsafeQueryPatterns = [ - { - pattern: /(?:SELECT|INSERT|UPDATE|DELETE).*\+\s*(?:user|input|param|req)/i, - description: "string concatenation in SQL query" - }, - { - pattern: /(?:SELECT|INSERT|UPDATE|DELETE).*\$\{.*\}/i, - description: "string interpolation in SQL query" - }, - { - pattern: /exec\s*\(.*\+.*\)/i, - description: "string concatenation in exec/eval" - } - ]; - for (const codeBlock of codeBlocks) { - for (const { pattern, description } of unsafeQueryPatterns) { - if (pattern.test(codeBlock)) { - violations.push(makeViolation("output_encoding_injection_prevention", sectionType, `Code example shows ${description} \u2014 use parameterized queries or prepared statements instead.`, description)); - } - } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description + }); } - return violations; -} -function checkAuthOnEveryEndpoint(content, sectionType) { - if (hasExplicitOptOut(content, [ - "authentication", - "authorization", - "endpoint", - "auth strategy", - "caller identity" - ])) { - return []; + pipe(target) { + return ZodPipeline.create(this, target); } - const lowered = content.toLowerCase(); - const authNSignals = [ - "authentication", - "authenticate", - "login", - "sign in", - "jwt", - "oauth", - "api key", - "bearer token", - "session", - "identity", - "credential", - "mfa", - "multi-factor", - "sso" - ]; - const authZSignals = [ - "authorization", - "authorize", - "permission", - "role", - "rbac", - "abac", - "access control", - "privilege", - "scope", - "claim", - "policy", - "grant" - ]; - const hasAuthN = authNSignals.some((s) => lowered.includes(s)); - const hasAuthZ = authZSignals.some((s) => lowered.includes(s)); - if (!hasAuthN || !hasAuthZ) { - const missing = []; - if (!hasAuthN) - missing.push("authentication"); - if (!hasAuthZ) - missing.push("authorization"); - return [ - makeViolation("auth_on_every_endpoint", sectionType, `Technical spec must specify ${missing.join(" and ")} strategy \u2014 every endpoint/operation needs auth method, roles, and permission checks.`) - ]; + readonly() { + return ZodReadonly.create(this); } - return []; -} -function checkSecuritySafeErrorHandling(content, sectionType) { - const lowered = content.toLowerCase(); - const safeErrorSignals = [ - "no stack trace", - "hide internal", - "generic error", - "error message sanitiz", - "no implementation detail", - "user-facing error", - "error boundary", - "safe error", - "don't leak", - "do not expose", - "error abstraction", - "error mapping", - "client-safe", - "production error" - ]; - const signalCount = safeErrorSignals.filter((s) => lowered.includes(s)).length; - if (signalCount < 1) { - const hasErrorSecurity = lowered.includes("error") && (lowered.includes("secur") || lowered.includes("sensitive")); - if (!hasErrorSecurity) { - return [ - makeViolation("security_safe_error_handling", sectionType, "Technical spec must ensure errors don't leak implementation details \u2014 no stack traces, internal paths, DB schemas, or server versions in error responses to clients.") - ]; - } + isOptional() { + return this.safeParse(void 0).success; } - return []; -} -function checkCryptographicStandards(content, sectionType) { - const lowered = content.toLowerCase(); - const violations = []; - const cryptoSignals = [ - "encrypt", - "encryption", - "aes", - "rsa", - "tls", - "hash", - "bcrypt", - "argon2", - "scrypt", - "pbkdf2", - "hmac", - "sha-256", - "sha-384", - "sha-512", - "key management", - "key rotation", - "certificate" - ]; - const signalCount = cryptoSignals.filter((s) => lowered.includes(s)).length; - if (signalCount < 2) { - violations.push(makeViolation("cryptographic_standards", sectionType, "Technical spec must specify cryptographic standards \u2014 define encryption algorithms, hashing for passwords (bcrypt/argon2), minimum key sizes, and key management strategy.")); + isNullable() { + return this.safeParse(null).success; } - const codeBlocks = extractCodeBlocks(content); - const weakPatterns = [ - { pattern: /\bMD5\b/, description: "MD5 (cryptographically broken)" }, - { pattern: /\bSHA-?1\b/, description: "SHA-1 (deprecated for security)" }, - { pattern: /\bDES\b/, description: "DES (obsolete, use AES)" }, - { pattern: /\bRC4\b/, description: "RC4 (broken)" } - ]; - for (const codeBlock of codeBlocks) { - for (const { pattern, description } of weakPatterns) { - if (pattern.test(codeBlock)) { - violations.push(makeViolation("cryptographic_standards", sectionType, `Code example uses weak cryptographic algorithm: ${description}. Use AES-256, SHA-256+, bcrypt/argon2 for passwords.`, description)); - } - } +}; +var cuidRegex = /^c[^\s-]{8,}$/i; +var cuid2Regex = /^[0-9a-z]+$/; +var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; +var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +var nanoidRegex = /^[a-z0-9_-]{21}$/i; +var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; +var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var emojiRegex; +var ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +var ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; +var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; +var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; +var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; +var dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; +var dateRegex = new RegExp(`^${dateRegexSource}$`); +function timeRegexSource(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; } - return violations; + const secondsQuantifier = args.precision ? "+" : "?"; + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; } -function checkRateLimitingRequired(content, sectionType) { - if (hasExplicitOptOut(content, [ - "rate limit", - "rate limiting", - "throttl", - "endpoint", - "abuse prevention" - ])) { - return []; - } - return findAbsenceViolation(content, [ - "rate limit", - "rate-limit", - "throttl", - "request limit", - "quota", - "burst limit", - "sliding window", - "token bucket", - "leaky bucket", - "ddos", - "abuse prevention", - "requests per", - "calls per" - ], 1, "rate_limiting_required", sectionType, "Technical spec must specify rate limiting strategy \u2014 define request limits per user/IP, throttling behavior, and abuse prevention for public-facing endpoints."); +function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); } -function checkSecureCommunication(content, sectionType) { - if (hasExplicitOptOut(content, [ - "tls", - "https", - "network i/o", - "network", - "secure communication", - "transport", - "encrypted channel" - ])) { - return []; - } - return findAbsenceViolation(content, [ - "tls", - "https", - "ssl", - "transport layer security", - "encrypt in transit", - "encryption in transit", - "certificate", - "cert pinning", - "certificate pinning", - "mutual tls", - "mtls", - "secure channel", - "encrypted connection" - ], 1, "secure_communication", sectionType, "Technical spec must specify secure communication \u2014 TLS requirements, certificate validation, no mixed content, encrypted channels for all data in transit."); +function datetimeRegex(args) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); } -var init_security_rules = __esm({ - async "packages/validation/dist/hard-output-rules/rules/security-rules.js"() { - "use strict"; - await init_helpers(); +function isValidIP(ip, version4) { + if ((version4 === "v4" || !version4) && ipv4Regex.test(ip)) { + return true; } -}); - -// packages/validation/dist/hard-output-rules/rules/data-protection-rules.js -function checkDataClassificationRequired(content, sectionType) { - if (hasExplicitOptOut(content, [ - "data classification", - "sensitivity", - "pii", - "personal data", - "sensitive data" - ])) { - return []; + if ((version4 === "v6" || !version4) && ipv6Regex.test(ip)) { + return true; } - return findAbsenceViolation(content, [ - "data classification", - "classify", - "classification level", - "public data", - "internal data", - "confidential", - "restricted", - "sensitivity level", - "sensitivity class", - "data tier", - "data category", - "personal data", - "non-personal", - "pii", - "phi", - "pci", - "sensitive data" - ], 2, "data_classification_required", sectionType, "Technical spec must classify all data entities \u2014 define sensitivity levels (public/internal/confidential/restricted) with handling rules per classification."); + return false; } -function checkSensitiveDataProtection(content, sectionType) { - if (hasExplicitOptOut(content, [ - "sensitive data", - "sensitive data protection", - "pii", - "personal data", - "credentials", - "secrets" - ])) { - return []; - } - const lowered = content.toLowerCase(); - const encryptionSignals = [ - "encrypt at rest", - "encryption at rest", - "field-level encryption", - "column encryption", - "database encryption", - "aes" - ]; - const maskingSignals = [ - "mask", - "anonymiz", - "pseudonymiz", - "redact", - "obfuscat", - "tokeniz", - "de-identif", - "data scrub" - ]; - const accessSignals = [ - "row-level security", - "rls", - "column-level", - "field-level access", - "data access control", - "need-to-know", - "least privilege" - ]; - let categoriesMet = 0; - if (encryptionSignals.some((s) => lowered.includes(s))) - categoriesMet++; - if (maskingSignals.some((s) => lowered.includes(s))) - categoriesMet++; - if (accessSignals.some((s) => lowered.includes(s))) - categoriesMet++; - if (categoriesMet < 2) { - return [ - makeViolation("sensitive_data_protection", sectionType, "Technical spec must specify sensitive data protection strategy \u2014 address at least 2 of: encryption at rest, masking/anonymization, and access restrictions for PII and sensitive fields.") - ]; +function isValidJWT(jwt, alg) { + if (!jwtRegex.test(jwt)) + return false; + try { + const [header] = jwt.split("."); + if (!header) + return false; + const base642 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); + const decoded = JSON.parse(atob(base642)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; + } catch { + return false; } - return []; } -function checkNoSensitiveDataInLogs(content, sectionType) { - if (hasExplicitOptOut(content, [ - "sensitive data", - "pii", - "personal data", - "log", - "credentials", - "tokens" - ])) { - return []; +function isValidCidr(ip, version4) { + if ((version4 === "v4" || !version4) && ipv4CidrRegex.test(ip)) { + return true; } - const lowered = content.toLowerCase(); - const noLogPIISignals = [ - "no pii in log", - "mask in log", - "redact in log", - "filter sensitive", - "log sanitiz", - "scrub log", - "no sensitive data in log", - "log masking", - "exclude pii", - "strip pii", - "no personal data in log", - "structured log", - "safe logging" - ]; - const hasLogProtection = noLogPIISignals.some((s) => lowered.includes(s)); - const broaderSignals = lowered.includes("sensitive") && lowered.includes("log") && (lowered.includes("never") || lowered.includes("must not") || lowered.includes("exclude") || lowered.includes("prevent")); - if (!hasLogProtection && !broaderSignals) { - return [ - makeViolation("no_sensitive_data_in_logs", sectionType, "Technical spec must explicitly prevent sensitive data (PII, credentials, tokens) from appearing in logs, error messages, URLs, or query parameters.") - ]; + if ((version4 === "v6" || !version4) && ipv6CidrRegex.test(ip)) { + return true; } - return []; + return false; } -function checkDataMinimization(content, sectionType) { - if (hasExplicitOptOut(content, [ - "data minimization", - "personal data", - "pii", - "user data", - "data collected" - ])) { - return []; +var ZodString = class _ZodString2 extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.string) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx2.parsedType + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check2 of this._def.checks) { + if (check2.kind === "min") { + if (input.data.length < check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check2.value, + type: "string", + inclusive: true, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "max") { + if (input.data.length > check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check2.value, + type: "string", + inclusive: true, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "length") { + const tooBig = input.data.length > check2.value; + const tooSmall = input.data.length < check2.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check2.value, + type: "string", + inclusive: true, + exact: true, + message: check2.message + }); + } else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check2.value, + type: "string", + inclusive: true, + exact: true, + message: check2.message + }); + } + status.dirty(); + } + } else if (check2.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "url") { + try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "regex") { + check2.regex.lastIndex = 0; + const testResult = check2.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "trim") { + input.data = input.data.trim(); + } else if (check2.kind === "includes") { + if (!input.data.includes(check2.value, check2.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check2.value, position: check2.position }, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } else if (check2.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } else if (check2.kind === "startsWith") { + if (!input.data.startsWith(check2.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check2.value }, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "endsWith") { + if (!input.data.endsWith(check2.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check2.value }, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "datetime") { + const regex = datetimeRegex(check2); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "date") { + const regex = dateRegex; + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "date", + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "time") { + const regex = timeRegex(check2); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "time", + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "ip") { + if (!isValidIP(input.data, check2.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "jwt") { + if (!isValidJWT(input.data, check2.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "jwt", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "cidr") { + if (!isValidCidr(input.data, check2.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cidr", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "base64url") { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64url", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else { + util.assertNever(check2); + } + } + return { status: status.value, value: input.data }; } - return findAbsenceViolation(content, [ - "data minimization", - "minimal data", - "minimise", - "collect only", - "store only", - "need-to-know", - "purpose limitation", - "data purpose", - "justified", - "necessary data", - "required fields only", - "no unnecessary", - "reduce data footprint" - ], 1, "data_minimization", sectionType, "Technical spec must address data minimization \u2014 collect and store only what's necessary, justify every sensitive field, define purpose limitation."); -} -function checkAuditTrailRequired(content, sectionType) { - if (hasExplicitOptOut(content, [ - "audit", - "audit trail", - "compliance", - "authentication events", - "data access" - ])) { - return []; + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message) + }); } - return findAbsenceViolation(content, [ - "audit trail", - "audit log", - "audit event", - "who did what", - "who/what/when", - "accountability", - "compliance log", - "activity log", - "change log", - "access log", - "security log", - "event sourcing", - "tamper-proof log", - "immutable log" - ], 1, "audit_trail_required", sectionType, "Technical spec must require audit trails for sensitive operations \u2014 log who/what/when for authentication events, data access, configuration changes, and admin actions."); -} -function checkConsentAndErasureSupport(content, sectionType) { - if (hasExplicitOptOut(content, [ - "consent", - "erasure", - "personal data", - "gdpr", - "privacy compliance", - "user data" - ])) { - return []; + _addCheck(check2) { + return new _ZodString2({ + ...this._def, + checks: [...this._def.checks, check2] + }); } - const lowered = content.toLowerCase(); - const consentSignals = [ - "consent", - "opt-in", - "opt-out", - "user agreement", - "privacy preference", - "data subject", - "lawful basis" - ]; - const erasureSignals = [ - "right to erasure", - "right to deletion", - "right to be forgotten", - "gdpr erasure", - "data deletion", - "cascade delete", - "soft delete", - "hard delete", - "purge", - "anonymize on delete", - "account deletion", - "data removal" - ]; - const hasConsent = consentSignals.some((s) => lowered.includes(s)); - const hasErasure = erasureSignals.some((s) => lowered.includes(s)); - if (!hasConsent && !hasErasure) { - return [ - makeViolation("consent_and_erasure_support", sectionType, "Technical spec must support consent management and data erasure \u2014 specify how user consent is tracked, how deletion cascades through the data model, and GDPR/privacy compliance.") - ]; + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); } - return []; -} -var init_data_protection_rules = __esm({ - async "packages/validation/dist/hard-output-rules/rules/data-protection-rules.js"() { - "use strict"; - await init_helpers(); + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); } -}); - -// packages/validation/dist/hard-output-rules/rules/resilience-rules.js -function checkStructuredErrorHandling(content, sectionType) { - if (hasExplicitOptOut(content, [ - "error", - "exception", - "error handling", - "error propagation", - "swallowed exception" - ])) { - return []; + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); } - const lowered = content.toLowerCase(); - const domainErrorSignals = [ - "domain error", - "error type", - "error enum", - "error class", - "custom exception", - "business exception", - "typed error", - "error hierarchy", - "error code", - "error catalog" - ]; - const propagationSignals = [ - "error propagation", - "error boundary", - "error handling strategy", - "catch and rethrow", - "error translation", - "error mapping", - "exception filter", - "global error handler", - "error middleware", - "no swallow", - "never swallow", - "always propagate" - ]; - const hasDomainErrors = domainErrorSignals.some((s) => lowered.includes(s)); - const hasPropagation = propagationSignals.some((s) => lowered.includes(s)); - if (!hasDomainErrors && !hasPropagation) { - return [ - makeViolation("structured_error_handling", sectionType, "Technical spec must define structured error handling \u2014 domain-specific error types, no swallowed exceptions, no generic catch-all, and explicit error propagation strategy.") - ]; + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); } - return []; -} -function checkResiliencePatterns(content, sectionType) { - if (hasExplicitOptOut(content, [ - "resilience", - "circuit breaker", - "retry", - "external dependency", - "remote call", - "transient" - ])) { - return []; + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); } - return findAbsenceViolation(content, [ - "circuit breaker", - "retry", - "exponential backoff", - "timeout", - "bulkhead", - "rate limit", - "failure isolation", - "fault tolerance", - "resilience", - "health check", - "dead letter", - "fallback", - "backpressure", - "load shedding" - ], 2, "resilience_patterns", sectionType, "Technical spec must specify resilience patterns \u2014 circuit breaker for external dependencies, retry with exponential backoff, and timeout on every external call."); -} -function checkGracefulDegradation(content, sectionType) { - if (hasExplicitOptOut(content, [ - "graceful degradation", - "degradation", - "fallback", - "dependency failure", - "cascading failure" - ])) { - return []; + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); } - return findAbsenceViolation(content, [ - "graceful degradation", - "degrade gracefully", - "fallback", - "fail gracefully", - "partial failure", - "degraded mode", - "offline mode", - "cache fallback", - "default response", - "service unavailable", - "cascading failure", - "blast radius" - ], 1, "graceful_degradation", sectionType, "Technical spec must define graceful degradation \u2014 specify fallback behavior when dependencies fail, prevent cascading failures, and define degraded operation modes."); -} -function checkTransactionBoundaries(content, sectionType) { - if (hasExplicitOptOut(content, [ - "transaction", - "rollback", - "atomic", - "multi-step", - "read-only", - "no writes", - "database" - ])) { - return []; + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); } - return findAbsenceViolation(content, [ - "transaction", - "transactional", - "atomicity", - "atomic operation", - "isolation level", - "rollback", - "commit", - "saga", - "compensating transaction", - "eventual consistency", - "two-phase commit", - "optimistic lock", - "pessimistic lock", - "idempoten", - "exactly-once", - "at-least-once" - ], 2, "transaction_boundaries", sectionType, "Technical spec must define transaction boundaries \u2014 specify transaction scope, isolation level, rollback strategy, and idempotency for multi-step operations."); -} -function checkConsistentErrorFormat(content, sectionType) { - if (hasExplicitOptOut(content, [ - "error format", - "error response", - "error envelope", - "error code", - "error catalog" - ])) { - return []; + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); } - return findAbsenceViolation(content, [ - "error format", - "error response format", - "error schema", - "error contract", - "rfc 7807", - "problem detail", - "error code", - "error_code", - "error response structure", - "standardized error", - "consistent error", - "error envelope", - "error body", - "machine-readable error" - ], 1, "consistent_error_format", sectionType, "Technical spec must define a consistent error response format \u2014 standardized structure with error codes, human-readable messages, and machine-readable details (e.g., RFC 7807)."); -} -var init_resilience_rules = __esm({ - async "packages/validation/dist/hard-output-rules/rules/resilience-rules.js"() { - "use strict"; - await init_helpers(); + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); } -}); - -// packages/validation/dist/hard-output-rules/rules/concurrency-rules.js -function checkConcurrencySafety(content, sectionType) { - return findAbsenceViolation(content, [ - "thread safe", - "thread-safe", - "concurren", - "race condition", - "mutex", - "semaphore", - "lock", - "synchronized", - "atomic", - "volatile", - "actor", - "serial queue", - "dispatch queue", - "async/await", - "coroutine", - "channel", - "deadlock", - "livelock", - "starvation", - "shared state", - "mutable state", - "concurrent access" - ], 2, "concurrency_safety", sectionType, "Technical spec must address concurrency safety \u2014 specify how shared mutable state is protected, thread safety guarantees, race condition prevention, and deadlock avoidance strategies."); -} -function checkImmutabilityByDefault(content, sectionType) { - return findAbsenceViolation(content, [ - "immutable", - "immutability", - "value type", - "value object", - "val ", - "let ", - "const ", - "readonly", - "read-only", - "frozen", - "unmodifiable", - "persistent data structure", - "copy-on-write", - "defensive copy", - "final field" - ], 1, "immutability_by_default", sectionType, "Technical spec should prefer immutable data structures \u2014 use value types, const/let/val by default, and justify any mutable state explicitly."); -} -function checkAtomicOperations(content, sectionType) { - return findAbsenceViolation(content, [ - "atomic", - "atomicity", - "compare-and-swap", - "cas ", - "transaction isolation", - "serializable", - "read committed", - "repeatable read", - "snapshot isolation", - "optimistic concurrency", - "version check", - "etag", - "if-match", - "conditional update" - ], 1, "atomic_operations", sectionType, "Technical spec must specify atomicity for multi-step state changes \u2014 define transaction isolation levels, optimistic concurrency control, and atomic operation boundaries."); -} -var init_concurrency_rules = __esm({ - async "packages/validation/dist/hard-output-rules/rules/concurrency-rules.js"() { - "use strict"; - await init_helpers(); + base64url(message) { + return this._addCheck({ + kind: "base64url", + ...errorUtil.errToObj(message) + }); } -}); - -// packages/validation/dist/hard-output-rules/rules/senior-quality-rules.js -function checkNoMagicNumbers(content, sectionType) { - const violations = []; - const codeBlocks = extractCodeBlocks(content); - const magicNumberPattern = /(?:(?:timeout|delay|limit|max|min|size|count|threshold|retry|interval|duration|width|height|margin|padding)\s*[:=]\s*)\d{2,}/gi; - for (const codeBlock of codeBlocks) { - const matches = codeBlock.match(magicNumberPattern); - if (matches && matches.length >= 3) { - violations.push(makeViolation("no_magic_numbers", sectionType, "Code examples contain multiple raw numeric literals \u2014 extract to named constants (e.g., MAX_RETRY_COUNT, DEFAULT_TIMEOUT_MS) for maintainability.", `Found ${matches.length} magic numbers in code block`)); + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); + } + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options + }); } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil.errToObj(options?.message) + }); } - const lowered = content.toLowerCase(); - const constantSignals = [ - "named constant", - "named variable", - "const ", - "static let", - "static final", - "companion object", - "no magic number", - "extract constant", - "configuration value" - ]; - const hasConstantGuidance = constantSignals.some((s) => lowered.includes(s)); - if (!hasConstantGuidance && codeBlocks.length > 0) { - violations.push(makeViolation("no_magic_numbers", sectionType, "Technical spec should mandate named constants \u2014 all configuration values, thresholds, and limits must be extracted to named constants, not raw literals.")); + date(message) { + return this._addCheck({ kind: "date", message }); } - return violations; -} -function checkDefensiveCoding(content, sectionType) { - return findAbsenceViolation(content, [ - "guard", - "precondition", - "require", - "assert", - "null safe", - "null check", - "nil check", - "optional", - "non-null", - "nonnull", - "notnull", - "bounds check", - "range check", - "defensive", - "fail fast", - "early return", - "validation", - "contract", - "invariant" - ], 2, "defensive_coding", sectionType, "Technical spec must enforce defensive coding \u2014 guard clauses, preconditions, null safety, bounds checking at all entry points. Fail fast on invalid state."); + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options + }); + } + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil.errToObj(options?.message) + }); + } + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex, + ...errorUtil.errToObj(message) + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value, + position: options?.position, + ...errorUtil.errToObj(options?.message) + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil.errToObj(message) + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil.errToObj(message) + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message) + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message) + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message) + }); + } + /** + * Equivalent to `.min(1)` + */ + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); + } + trim() { + return new _ZodString2({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] + }); + } + toLowerCase() { + return new _ZodString2({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }] + }); + } + toUpperCase() { + return new _ZodString2({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }] + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min3 = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min3 === null || ch.value > min3) + min3 = ch.value; + } + } + return min3; + } + get maxLength() { + let max3 = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max3 === null || ch.value < max3) + max3 = ch.value; + } + } + return max3; + } +}; +ZodString.create = (params) => { + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); +}; +function floatSafeRemainder(val, step2) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step2.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step2.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; } -function checkMethodSizeLimits(content, sectionType) { - const violations = []; - const codeBlocks = extractCodeBlocks(content); - const funcPattern = /(?:func |function |def |fn |fun |public |private |protected |internal |static )*(?:func|function|def|fn|fun|method)\s+(\w+)/; - for (const codeBlock of codeBlocks) { - const lines = codeBlock.split("\n"); - let currentFuncName = null; - let funcStartLine = 0; - let braceDepth = 0; - let inFunction = false; - for (let index2 = 0; index2 < lines.length; index2++) { - const line = lines[index2]; - if (!inFunction) { - const match = line.match(funcPattern); - if (match) { - currentFuncName = match[1] ?? "anonymous"; - funcStartLine = index2; - inFunction = true; - braceDepth = 0; +var ZodNumber = class _ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.number) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx2.parsedType + }); + return INVALID; + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check2 of this._def.checks) { + if (check2.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check2.message + }); + status.dirty(); } - } - if (inFunction) { - braceDepth += (line.match(/\{/g) || []).length; - braceDepth -= (line.match(/\}/g) || []).length; - if (braceDepth <= 0 && line.includes("}")) { - const funcLineCount = index2 - funcStartLine + 1; - if (funcLineCount > 30) { - violations.push(makeViolation("method_size_limits", sectionType, `Code example shows function '${currentFuncName}' spanning ${funcLineCount} lines \u2014 extract logic into smaller functions. Methods should be ~30 lines max in PRD examples.`, currentFuncName)); - } - inFunction = false; - currentFuncName = null; + } else if (check2.kind === "min") { + const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check2.value, + type: "number", + inclusive: check2.inclusive, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "max") { + const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check2.value, + type: "number", + inclusive: check2.inclusive, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check2.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check2.value, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check2.message + }); + status.dirty(); } + } else { + util.assertNever(check2); } } + return { status: status.value, value: input.data }; } - return violations; -} -function checkConsistentNaming(content, sectionType) { - return findAbsenceViolation(content, [ - "naming convention", - "naming standard", - "naming rule", - "camelcase", - "camel case", - "snake_case", - "snake case", - "pascalcase", - "pascal case", - "kebab-case", - "descriptive name", - "self-documenting", - "meaningful name", - "no abbreviation", - "full word", - "consistent naming" - ], 1, "consistent_naming", sectionType, "Technical spec should establish naming conventions \u2014 specify casing style, use descriptive names, avoid abbreviations in public APIs, and enforce consistent patterns."); -} -function checkAPIContractDocumentation(content, sectionType) { - return findAbsenceViolation(content, [ - "request schema", - "response schema", - "api contract", - "openapi", - "swagger", - "api spec", - "endpoint spec", - "request body", - "response body", - "status code", - "content-type", - "accept header", - "api documentation", - "typed request", - "typed response" - ], 2, "api_contract_documentation", sectionType, "Technical spec must document API contracts \u2014 every endpoint needs typed request/response schemas, status codes, error responses, and content-type specifications."); -} -function checkDeprecationStrategy(content, sectionType) { - return findAbsenceViolation(content, [ - "deprecat", - "sunset", - "breaking change", - "migration path", - "backward compat", - "backwards compat", - "version", - "api version", - "v1", - "v2", - "changelog", - "upgrade guide", - "migration guide" - ], 1, "deprecation_strategy", sectionType, "Technical spec should define deprecation strategy \u2014 specify migration paths for breaking changes, sunset timelines, and versioning approach."); -} -var init_senior_quality_rules = __esm({ - async "packages/validation/dist/hard-output-rules/rules/senior-quality-rules.js"() { - "use strict"; - await init_helpers(); + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); } -}); - -// packages/validation/dist/hard-output-rules/rules/testing-rules.js -function checkMandatoryTestCoverage(content, sectionType) { - const lowered = content.toLowerCase(); - const unitSignals = [ - "unit test", - "ut-", - "unit coverage", - "function test", - "method test", - "class test", - "module test" - ]; - const integrationSignals = [ - "integration test", - "it-", - "api test", - "contract test", - "component test", - "service test", - "end-to-end", - "e2e" - ]; - const coverageSignals = [ - "test coverage", - "code coverage", - "coverage target", - "coverage threshold", - "coverage report", - "line coverage", - "branch coverage", - "100% coverage", - "minimum coverage" - ]; - const hasUnit = unitSignals.some((s) => lowered.includes(s)); - const hasIntegration = integrationSignals.some((s) => lowered.includes(s)); - const hasCoverage = coverageSignals.some((s) => lowered.includes(s)); - const violations = []; - if (!hasUnit || !hasIntegration) { - violations.push(makeViolation("mandatory_test_coverage", sectionType, "Test spec must include both unit tests and integration tests \u2014 every public method/endpoint needs corresponding test specifications.")); + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); } - if (!hasCoverage) { - violations.push(makeViolation("mandatory_test_coverage", sectionType, "Test spec must define coverage targets \u2014 specify minimum code coverage thresholds for unit, integration, and overall coverage.")); + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); } - return violations; -} -function checkSecurityTestingRequired(content, sectionType) { - return findAbsenceViolation(content, [ - "security test", - "penetration test", - "pen test", - "sast", - "dast", - "static analysis", - "dynamic analysis", - "vulnerability scan", - "dependency scan", - "snyk", - "owasp", - "security audit", - "threat model", - "fuzz", - "injection test", - "auth test", - "access control test", - "privilege escalation" - ], 2, "security_testing_required", sectionType, "Test spec must include security testing \u2014 SAST/DAST, dependency vulnerability scanning, penetration test plan, and OWASP-based test cases."); -} -function checkPerformanceTestingRequired(content, sectionType) { - return findAbsenceViolation(content, [ - "performance test", - "load test", - "stress test", - "benchmark", - "throughput test", - "latency test", - "spike test", - "soak test", - "capacity test", - "response time", - "p95", - "p99", - "percentile", - "concurrent user", - "requests per second", - "rps" - ], 2, "performance_testing_required", sectionType, "Test spec must include performance testing \u2014 load test scenarios, stress thresholds, baseline comparisons, and latency percentile targets."); -} -function checkNoProductionDataInTests(content, sectionType) { - return findAbsenceViolation(content, [ - "synthetic data", - "anonymized", - "anonymised", - "test fixture", - "mock data", - "fake data", - "factory", - "faker", - "seed data", - "generated data", - "no production data", - "no real data", - "test data", - "sample data", - "fixture" - ], 1, "no_production_data_in_tests", sectionType, "Test spec must mandate synthetic test data \u2014 no real PII, no production data dumps, use factories/fakers/fixtures for all test data."); -} -function checkEdgeCaseNegativeTests(content, sectionType) { - const lowered = content.toLowerCase(); - const negativeSignals = [ - "negative test", - "failure case", - "error case", - "unhappy path", - "sad path", - "invalid input", - "reject", - "unauthorized", - "forbidden", - "not found", - "timeout", - "failure scenario" - ]; - const edgeCaseSignals = [ - "edge case", - "boundary", - "corner case", - "empty", - "null", - "zero", - "overflow", - "maximum", - "minimum", - "limit", - "concurrent", - "race condition", - "duplicate", - "idempoten" - ]; - const hasNegative = negativeSignals.some((s) => lowered.includes(s)); - const hasEdgeCases = edgeCaseSignals.some((s) => lowered.includes(s)); - if (!hasNegative || !hasEdgeCases) { - return [ - makeViolation("edge_case_negative_tests", sectionType, "Test spec must include both negative tests (failure scenarios, invalid inputs, unauthorized access) and edge cases (boundary values, empty states, concurrent operations).") - ]; + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); } - return []; -} -function checkTestIsolation(content, sectionType) { - return findAbsenceViolation(content, [ - "test isolation", - "isolated test", - "independent test", - "no shared state", - "setup and teardown", - "setup/teardown", - "before each", - "after each", - "beforeeach", - "aftereach", - "fresh instance", - "clean state", - "reset", - "test container", - "in-memory database", - "mock" - ], 2, "test_isolation", sectionType, "Test spec must ensure test isolation \u2014 no shared mutable state between tests, proper setup/teardown, each test independent and repeatable in any order."); -} -var init_testing_rules = __esm({ - async "packages/validation/dist/hard-output-rules/rules/testing-rules.js"() { - "use strict"; - await init_helpers(); + setLimit(kind, value, inclusive, message) { + return new _ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); } -}); - -// packages/validation/dist/hard-output-rules/rules/observability-rules.js -function checkStructuredLogging(content, sectionType) { - const lowered = content.toLowerCase(); - const formatSignals = [ - "structured log", - "json log", - "log format", - "log schema", - "log standard", - "log framework" - ]; - const levelSignals = [ - "log level", - "debug", - "info", - "warn", - "error", - "trace", - "fatal", - "severity", - "verbosity" - ]; - const hasFormat = formatSignals.some((s) => lowered.includes(s)); - const hasLevels = levelSignals.filter((s) => lowered.includes(s)).length >= 2; - if (!hasFormat && !hasLevels) { - return [ - makeViolation("structured_logging", sectionType, "Technical spec must define structured logging \u2014 specify log format (JSON/structured), log levels (DEBUG/INFO/WARN/ERROR), and what to log at each level.") - ]; + _addCheck(check2) { + return new _ZodNumber({ + ...this._def, + checks: [...this._def.checks, check2] + }); } - return []; -} -function checkDistributedTracing(content, sectionType) { - if (hasExplicitOptOut(content, [ - "distributed tracing", - "tracing", - "correlation id", - "single-process", - "single process", - "cross-service", - "second hop" - ])) { - return []; + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message) + }); } - return findAbsenceViolation(content, [ - "correlation id", - "trace id", - "request id", - "distributed trac", - "opentelemetry", - "jaeger", - "zipkin", - "trace context", - "span", - "trace propagat", - "x-request-id", - "x-correlation-id", - "end-to-end trac", - "cross-service trac" - ], 1, "distributed_tracing", sectionType, "Technical spec should specify distributed tracing \u2014 correlation IDs for cross-service request tracking, trace context propagation, and observability integration."); -} -function checkNoPIIInObservability(content, sectionType) { - if (hasExplicitOptOut(content, [ - "pii", - "observability", - "personal data", - "logs", - "metrics", - "traces", - "dashboards" - ])) { - return []; - } - const lowered = content.toLowerCase(); - const piiProtectionSignals = [ - "no pii in log", - "no pii in metric", - "no pii in trace", - "mask sensitive", - "redact", - "scrub", - "sanitize log", - "filter pii", - "exclude sensitive", - "log safe", - "safe to log", - "no personal data in" - ]; - const hasProtection = piiProtectionSignals.some((s) => lowered.includes(s)); - const hasBroader = (lowered.includes("pii") || lowered.includes("sensitive") || lowered.includes("personal data")) && (lowered.includes("log") || lowered.includes("metric") || lowered.includes("trace") || lowered.includes("monitor")) && (lowered.includes("never") || lowered.includes("must not") || lowered.includes("exclude") || lowered.includes("prevent") || lowered.includes("mask") || lowered.includes("redact")); - if (!hasProtection && !hasBroader) { - return [ - makeViolation("no_pii_in_observability", sectionType, "Technical spec must ensure no PII in observability \u2014 logs, metrics, traces, and dashboards must not contain sensitive personal data. Specify masking/redaction strategy.") - ]; - } - return []; -} -function checkAlertingThresholds(content, sectionType) { - return findAbsenceViolation(content, [ - "alert", - "alerting", - "threshold", - "alarm", - "escalat", - "on-call", - "pagerduty", - "opsgenie", - "notification", - "sla breach", - "slo", - "warning threshold", - "critical threshold", - "runbook", - "incident response" - ], 2, "alerting_thresholds", sectionType, "Technical spec should define alerting thresholds \u2014 specify what triggers alerts, severity levels, escalation paths, and on-call routing."); -} -var init_observability_rules = __esm({ - async "packages/validation/dist/hard-output-rules/rules/observability-rules.js"() { - "use strict"; - await init_helpers(); + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); } -}); - -// packages/validation/dist/hard-output-rules/rules/dependency-rules.js -function checkDependencyVulnerabilityScanning(content, sectionType) { - return findAbsenceViolation(content, [ - "dependency scan", - "vulnerability scan", - "cve", - "snyk", - "dependabot", - "renovate", - "trivy", - "software composition analysis", - "sca", - "supply chain", - "sbom", - "software bill of materials", - "known vulnerabilit", - "security advisory", - "dependency audit", - "npm audit", - "pip audit" - ], 1, "dependency_vulnerability_scanning", sectionType, "Technical spec must require dependency vulnerability scanning \u2014 specify SCA tooling, CVE monitoring, and automated scanning in CI/CD pipeline."); -} -function checkMinimalDependencyPrinciple(content, sectionType) { - return findAbsenceViolation(content, [ - "minimal dependenc", - "minimize dependenc", - "reduce dependenc", - "standard library", - "built-in", - "native", - "justify dependenc", - "dependency rationale", - "license compliance", - "license audit", - "license check", - "dependency review", - "approved dependenc" - ], 1, "minimal_dependency_principle", sectionType, "Technical spec should apply minimal dependency principle \u2014 justify new dependencies, prefer standard library, and verify license compliance."); -} -var init_dependency_rules = __esm({ - async "packages/validation/dist/hard-output-rules/rules/dependency-rules.js"() { - "use strict"; - await init_helpers(); + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); } -}); - -// packages/validation/dist/hard-output-rules/index.js -function checkRule(rule, content, sectionType) { - switch (rule) { - // Core PRD Rules - case "sp_arithmetic": - return checkSPArithmetic(content, sectionType); - case "no_self_referencing_deps": - return checkNoSelfReferencingDeps(content, sectionType); - case "ac_numbering": - return checkACNumbering(content, sectionType); - case "no_orphan_ddl": - return checkNoOrphanDDL(content, sectionType); - case "no_now_in_partial_indexes": - return checkNoNowInPartialIndexes(content, sectionType); - case "no_any_codable": - return checkNoAnyCodable(content, sectionType); - case "no_placeholder_tests": - return checkNoPlaceholderTests(content, sectionType); - case "sp_not_in_fr_table": - return checkSPNotInFRTable(content, sectionType); - case "uneven_sp_distribution": - return checkUnevenSPDistribution(content, sectionType); - case "metrics_disclaimer": - return checkMetricsDisclaimer(content, sectionType); - case "fr_traceability": - return checkFRTraceability(content, sectionType); - case "clean_architecture": - return checkCleanArchitecture(content, sectionType); - case "honest_verification_verdicts": - return checkHonestVerificationVerdicts(content, sectionType); - case "code_example_port_compliance": - return checkCodeExamplePortCompliance(content, sectionType); - case "test_traceability_integrity": - return checkTestTraceabilityIntegrity(content, sectionType); - case "duplicate_requirement_ids": - return checkDuplicateRequirementIds(content, sectionType); - case "fk_references_exist": - return checkFKReferencesExist(content, sectionType); - case "fr_numbering_gaps": - return checkFRNumberingGaps(content, sectionType); - case "risk_mitigation_completeness": - return checkRiskMitigationCompleteness(content, sectionType); - case "deployment_rollback_plan": - return checkDeploymentRollbackPlan(content, sectionType); - // Architecture & Code Quality (18-24) - case "generic_over_specific": - return checkGenericOverSpecific(content, sectionType); - case "no_nested_types": - return checkNoNestedTypes(content, sectionType); - case "single_responsibility": - return checkSingleResponsibility(content, sectionType); - case "explicit_access_control": - return checkExplicitAccessControl(content, sectionType); - case "factory_based_injection": - return checkFactoryBasedInjection(content, sectionType); - case "solid_compliance": - return checkSolidCompliance(content, sectionType); - case "code_reusability": - return checkCodeReusability(content, sectionType); - // Security (25-32) - case "no_hardcoded_secrets": - return checkNoHardcodedSecrets(content, sectionType); - case "input_validation_required": - return checkInputValidationRequired(content, sectionType); - case "output_encoding_injection_prevention": - return checkOutputEncodingInjectionPrevention(content, sectionType); - case "auth_on_every_endpoint": - return checkAuthOnEveryEndpoint(content, sectionType); - case "security_safe_error_handling": - return checkSecuritySafeErrorHandling(content, sectionType); - case "cryptographic_standards": - return checkCryptographicStandards(content, sectionType); - case "rate_limiting_required": - return checkRateLimitingRequired(content, sectionType); - case "secure_communication": - return checkSecureCommunication(content, sectionType); - // Data Protection (33-38) - case "data_classification_required": - return checkDataClassificationRequired(content, sectionType); - case "sensitive_data_protection": - return checkSensitiveDataProtection(content, sectionType); - case "no_sensitive_data_in_logs": - return checkNoSensitiveDataInLogs(content, sectionType); - case "data_minimization": - return checkDataMinimization(content, sectionType); - case "audit_trail_required": - return checkAuditTrailRequired(content, sectionType); - case "consent_and_erasure_support": - return checkConsentAndErasureSupport(content, sectionType); - // Error Handling & Resilience (39-43) - case "structured_error_handling": - return checkStructuredErrorHandling(content, sectionType); - case "resilience_patterns": - return checkResiliencePatterns(content, sectionType); - case "graceful_degradation": - return checkGracefulDegradation(content, sectionType); - case "transaction_boundaries": - return checkTransactionBoundaries(content, sectionType); - case "consistent_error_format": - return checkConsistentErrorFormat(content, sectionType); - // Concurrency (44-46) - case "concurrency_safety": - return checkConcurrencySafety(content, sectionType); - case "immutability_by_default": - return checkImmutabilityByDefault(content, sectionType); - case "atomic_operations": - return checkAtomicOperations(content, sectionType); - // Senior Quality (47-52) - case "no_magic_numbers": - return checkNoMagicNumbers(content, sectionType); - case "defensive_coding": - return checkDefensiveCoding(content, sectionType); - case "method_size_limits": - return checkMethodSizeLimits(content, sectionType); - case "consistent_naming": - return checkConsistentNaming(content, sectionType); - case "api_contract_documentation": - return checkAPIContractDocumentation(content, sectionType); - case "deprecation_strategy": - return checkDeprecationStrategy(content, sectionType); - // Testing (53-58) - case "mandatory_test_coverage": - return checkMandatoryTestCoverage(content, sectionType); - case "security_testing_required": - return checkSecurityTestingRequired(content, sectionType); - case "performance_testing_required": - return checkPerformanceTestingRequired(content, sectionType); - case "no_production_data_in_tests": - return checkNoProductionDataInTests(content, sectionType); - case "edge_case_negative_tests": - return checkEdgeCaseNegativeTests(content, sectionType); - case "test_isolation": - return checkTestIsolation(content, sectionType); - // Observability (59-62) - case "structured_logging": - return checkStructuredLogging(content, sectionType); - case "distributed_tracing": - return checkDistributedTracing(content, sectionType); - case "no_pii_in_observability": - return checkNoPIIInObservability(content, sectionType); - case "alerting_thresholds": - return checkAlertingThresholds(content, sectionType); - // Dependencies (63-64) - case "dependency_vulnerability_scanning": - return checkDependencyVulnerabilityScanning(content, sectionType); - case "minimal_dependency_principle": - return checkMinimalDependencyPrinciple(content, sectionType); - // Document-level / process-level rules — checked in validateDocument() - case "fr_to_ac_coverage": - case "ac_to_test_coverage": - case "post_generation_self_check": - case "mandatory_codebase_analysis": - return []; + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); } -} -function validateSection(content, sectionType) { - const applicableRules = rulesForSection(sectionType); - const violations = []; - const rulesPassed = []; - for (const rule of applicableRules) { - const ruleViolations = checkRule(rule, content, sectionType); - if (ruleViolations.length === 0) { - rulesPassed.push(rule); - } else { - violations.push(...ruleViolations); - } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); } - const hasCriticalViolations = violations.some((v) => v.isCritical); - const totalPenalty = violations.reduce((sum3, v) => sum3 + v.scorePenalty, 0); - const totalScore = Math.max(0, 1 - totalPenalty); - return { - violations, - rulesChecked: applicableRules, - rulesPassed, - sectionType, - hasCriticalViolations, - totalScore, - checkedAt: (/* @__PURE__ */ new Date()).toISOString() - }; -} -function validateDocument(sections) { - const allViolations = []; - const allRulesChecked = /* @__PURE__ */ new Set(); - const allRulesPassed = /* @__PURE__ */ new Set(); - for (const section of sections) { - const report = validateSection(section.content, section.type); - allViolations.push(...report.violations); - for (const r of report.rulesChecked) - allRulesChecked.add(r); - for (const r of report.rulesPassed) - allRulesPassed.add(r); + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); } - const combinedContent = sections.map((s) => s.content).join("\n\n"); - const addDocCheck = (rule, violations) => { - allRulesChecked.add(rule); - if (violations.length === 0) { - allRulesPassed.add(rule); - } else { - allRulesPassed.delete(rule); - allViolations.push(...violations); - } - }; - addDocCheck("sp_arithmetic", checkDocumentSPArithmetic(sections)); - addDocCheck("ac_numbering", checkDocumentACConsistency(combinedContent)); - addDocCheck("honest_verification_verdicts", checkDocumentVerificationVerdicts(sections)); - addDocCheck("test_traceability_integrity", checkDocumentTestTraceability(sections)); - addDocCheck("fr_to_ac_coverage", checkDocumentFRToACCoverage(sections)); - addDocCheck("ac_to_test_coverage", checkDocumentACToTestCoverage(sections)); - const violatedRules = new Set(allViolations.map((v) => v.rule)); - for (const rule of violatedRules) { - allRulesPassed.delete(rule); + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message) + }); } - const hasCriticalViolations = allViolations.some((v) => v.isCritical); - const totalPenalty = allViolations.reduce((sum3, v) => sum3 + v.scorePenalty, 0); - const totalScore = Math.max(0, 1 - totalPenalty); - return { - violations: allViolations, - rulesChecked: [...allRulesChecked].sort(), - rulesPassed: [...allRulesPassed].sort(), - sectionType: null, - hasCriticalViolations, - totalScore, - checkedAt: (/* @__PURE__ */ new Date()).toISOString() - }; -} -var init_hard_output_rules = __esm({ - async "packages/validation/dist/hard-output-rules/index.js"() { - "use strict"; - init_rule_mapping(); - await init_sp_rules(); - await init_quality_rules(); - await init_numbering_rules(); - await init_database_rules(); - await init_test_rules(); - await init_architecture_rules(); - await init_code_quality_rules(); - await init_coverage_rules(); - await init_security_rules(); - await init_data_protection_rules(); - await init_resilience_rules(); - await init_concurrency_rules(); - await init_senior_quality_rules(); - await init_testing_rules(); - await init_observability_rules(); - await init_dependency_rules(); - init_rule_mapping(); + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message) + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message) + }); } -}); - -// packages/validation/dist/cross-ref-validator.js -function extractIds(content, sectionName) { - const occurrences = []; - for (const [type2, pattern] of Object.entries(ID_PATTERNS)) { - const regex = new RegExp(pattern.source, pattern.flags); - let match; - while ((match = regex.exec(content)) !== null) { - const id = match[0]; - const lineStart = content.lastIndexOf("\n", match.index) + 1; - const linePrefix = content.slice(lineStart, match.index).trim(); - const isDefinition = linePrefix === "" || linePrefix === "|" || linePrefix.startsWith("#"); - occurrences.push({ id, type: type2, section: sectionName, isDefinition }); + get minValue() { + let min3 = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min3 === null || ch.value > min3) + min3 = ch.value; + } } + return min3; } - return occurrences; -} -function detectCycles(adjacency) { - const cycles = []; - const visited = /* @__PURE__ */ new Set(); - const inStack = /* @__PURE__ */ new Set(); - function dfs(node, path) { - if (inStack.has(node)) { - const cycleStart2 = path.indexOf(node); - if (cycleStart2 >= 0) { - cycles.push(path.slice(cycleStart2)); + get maxValue() { + let max3 = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max3 === null || ch.value < max3) + max3 = ch.value; } - return; - } - if (visited.has(node)) - return; - visited.add(node); - inStack.add(node); - path.push(node); - for (const neighbor of adjacency.get(node) ?? []) { - dfs(neighbor, [...path]); } - inStack.delete(node); + return max3; } - for (const node of adjacency.keys()) { - if (!visited.has(node)) { - dfs(node, []); - } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); } - return cycles; -} -function checkNumberingContinuity(ids, prefix) { - const gaps = []; - const numbers = ids.filter((id) => id.startsWith(`${prefix}-`)).map((id) => parseInt(id.split("-")[1], 10)).filter((n) => !isNaN(n)).sort((a, b) => a - b); - for (let i2 = 1; i2 < numbers.length; i2++) { - if (numbers[i2] !== numbers[i2 - 1] + 1) { - gaps.push({ - prefix, - expected: numbers[i2 - 1] + 1, - actual: numbers[i2] - }); + get isFinite() { + let max3 = null; + let min3 = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } else if (ch.kind === "min") { + if (min3 === null || ch.value > min3) + min3 = ch.value; + } else if (ch.kind === "max") { + if (max3 === null || ch.value < max3) + max3 = ch.value; + } } + return Number.isFinite(min3) && Number.isFinite(max3); } - return gaps; -} -function validateCrossReferences(sections) { - const allOccurrences = []; - for (const section of sections) { - allOccurrences.push(...extractIds(section.content, section.name)); +}; +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); +}; +var ZodBigInt = class _ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; } - const definitions = /* @__PURE__ */ new Set(); - const references = /* @__PURE__ */ new Map(); - for (const occ of allOccurrences) { - if (occ.isDefinition) { - definitions.add(occ.id); + _parse(input) { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } catch { + return this._getInvalidInput(input); + } } - const refs = references.get(occ.id) ?? []; - refs.push(occ.section); - references.set(occ.id, refs); - } - const danglingReferences = [...references.entries()].filter(([id]) => !definitions.has(id)).map(([id, sections2]) => ({ - id, - referencedIn: sections2.join(", "), - type: id.split("-")[0] - })); - const orphanNodes = [...definitions].filter((id) => { - const refs = references.get(id) ?? []; - return new Set(refs).size <= 1; - }).map((id) => ({ - id, - type: id.split("-")[0], - reason: "Defined but not referenced in other sections" - })); - const dependsOnPattern = /Depends\s*(?:On|on)[:\s]*([^\n|]+)/g; - const adjacency = /* @__PURE__ */ new Map(); - for (const section of sections) { - let match; - const regex = new RegExp(dependsOnPattern.source, dependsOnPattern.flags); - while ((match = regex.exec(section.content)) !== null) { - const depList = match[1]; - const ids = depList.match(/(?:FR|US|STORY|AC)-\d+/g) ?? []; - const lineStart = section.content.lastIndexOf("\n", match.index); - const lineBefore = section.content.slice(Math.max(0, lineStart - 200), match.index); - const ownerMatch = lineBefore.match(/(?:FR|US|STORY|AC)-\d+/g); - const owner = ownerMatch?.[ownerMatch.length - 1]; - if (owner) { - if (!adjacency.has(owner)) - adjacency.set(owner, /* @__PURE__ */ new Set()); - for (const dep of ids) { - adjacency.get(owner).add(dep); + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.bigint) { + return this._getInvalidInput(input); + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check2 of this._def.checks) { + if (check2.kind === "min") { + const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check2.value, + inclusive: check2.inclusive, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "max") { + const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check2.value, + inclusive: check2.inclusive, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "multipleOf") { + if (input.data % check2.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check2.value, + message: check2.message + }); + status.dirty(); } + } else { + util.assertNever(check2); } } + return { status: status.value, value: input.data }; } - const cycles = detectCycles(adjacency); - const allDefinedIds = [...definitions]; - const numberingGaps = [ - ...checkNumberingContinuity(allDefinedIds, "FR"), - ...checkNumberingContinuity(allDefinedIds, "AC"), - ...checkNumberingContinuity(allDefinedIds, "US"), - ...checkNumberingContinuity(allDefinedIds, "NFR") - ]; - const idCounts = /* @__PURE__ */ new Map(); - for (const occ of allOccurrences.filter((o) => o.isDefinition)) { - idCounts.set(occ.id, (idCounts.get(occ.id) ?? 0) + 1); + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType + }); + return INVALID; } - const duplicateIds = [...idCounts.entries()].filter(([, count2]) => count2 > 1).map(([id]) => id); - const isValid2 = danglingReferences.length === 0 && cycles.length === 0 && duplicateIds.length === 0; - return { - danglingReferences, - orphanNodes, - cycles, - numberingGaps, - duplicateIds, - isValid: isValid2 - }; -} -var ID_PATTERNS; -var init_cross_ref_validator = __esm({ - "packages/validation/dist/cross-ref-validator.js"() { - "use strict"; - ID_PATTERNS = { - FR: /\bFR-(\d+)\b/g, - AC: /\bAC-(\d+)\b/g, - US: /\bUS-(\d+)\b/g, - STORY: /\bSTORY-(\d+)\b/g, - TEST: /\bTEST-(\d+)\b/g, - OQ: /\bOQ-(\d+)\b/g, - RISK: /\bRISK-(\d+)\b/g, - NFR: /\bNFR-(\d+)\b/g - }; + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); } -}); - -// node_modules/.pnpm/js-yaml@4.1.1/node_modules/js-yaml/dist/js-yaml.mjs -function isNothing(subject) { - return typeof subject === "undefined" || subject === null; -} -function isObject2(subject) { - return typeof subject === "object" && subject !== null; -} -function toArray(sequence) { - if (Array.isArray(sequence)) return sequence; - else if (isNothing(sequence)) return []; - return [sequence]; -} -function extend2(target, source) { - var index2, length, key, sourceKeys; - if (source) { - sourceKeys = Object.keys(source); - for (index2 = 0, length = sourceKeys.length; index2 < length; index2 += 1) { - key = sourceKeys[index2]; - target[key] = source[key]; - } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); } - return target; -} -function repeat(string4, count2) { - var result = "", cycle; - for (cycle = 0; cycle < count2; cycle += 1) { - result += string4; + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); } - return result; -} -function isNegativeZero(number4) { - return number4 === 0 && Number.NEGATIVE_INFINITY === 1 / number4; -} -function formatError2(exception2, compact) { - var where = "", message = exception2.reason || "(unknown reason)"; - if (!exception2.mark) return message; - if (exception2.mark.name) { - where += 'in "' + exception2.mark.name + '" '; - } - where += "(" + (exception2.mark.line + 1) + ":" + (exception2.mark.column + 1) + ")"; - if (!compact && exception2.mark.snippet) { - where += "\n\n" + exception2.mark.snippet; + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); } - return message + " " + where; -} -function YAMLException$1(reason, mark) { - Error.call(this); - this.name = "YAMLException"; - this.reason = reason; - this.mark = mark; - this.message = formatError2(this, false); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - this.stack = new Error().stack || ""; + setLimit(kind, value, inclusive, message) { + return new _ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); } -} -function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { - var head = ""; - var tail = ""; - var maxHalfLength = Math.floor(maxLineLength / 2) - 1; - if (position - lineStart > maxHalfLength) { - head = " ... "; - lineStart = position - maxHalfLength + head.length; + _addCheck(check2) { + return new _ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check2] + }); } - if (lineEnd - position > maxHalfLength) { - tail = " ..."; - lineEnd = position + maxHalfLength - tail.length; + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); } - return { - str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail, - pos: position - lineStart + head.length - // relative position - }; -} -function padStart(string4, max3) { - return common.repeat(" ", max3 - string4.length) + string4; -} -function makeSnippet(mark, options) { - options = Object.create(options || null); - if (!mark.buffer) return null; - if (!options.maxLength) options.maxLength = 79; - if (typeof options.indent !== "number") options.indent = 1; - if (typeof options.linesBefore !== "number") options.linesBefore = 3; - if (typeof options.linesAfter !== "number") options.linesAfter = 2; - var re2 = /\r?\n|\r|\0/g; - var lineStarts = [0]; - var lineEnds = []; - var match; - var foundLineNo = -1; - while (match = re2.exec(mark.buffer)) { - lineEnds.push(match.index); - lineStarts.push(match.index + match[0].length); - if (mark.position <= match.index && foundLineNo < 0) { - foundLineNo = lineStarts.length - 2; - } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); } - if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; - var result = "", i2, line; - var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; - var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); - for (i2 = 1; i2 <= options.linesBefore; i2++) { - if (foundLineNo - i2 < 0) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo - i2], - lineEnds[foundLineNo - i2], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i2]), - maxLineLength - ); - result = common.repeat(" ", options.indent) + padStart((mark.line - i2 + 1).toString(), lineNoLength) + " | " + line.str + "\n" + result; + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); } - line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); - result += common.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\n"; - result += common.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\n"; - for (i2 = 1; i2 <= options.linesAfter; i2++) { - if (foundLineNo + i2 >= lineEnds.length) break; - line = getLine( - mark.buffer, - lineStarts[foundLineNo + i2], - lineEnds[foundLineNo + i2], - mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i2]), - maxLineLength - ); - result += common.repeat(" ", options.indent) + padStart((mark.line + i2 + 1).toString(), lineNoLength) + " | " + line.str + "\n"; + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); } - return result.replace(/\n$/, ""); -} -function compileStyleAliases(map4) { - var result = {}; - if (map4 !== null) { - Object.keys(map4).forEach(function(style) { - map4[style].forEach(function(alias) { - result[String(alias)] = style; - }); + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) }); } - return result; -} -function Type$1(tag2, options) { - options = options || {}; - Object.keys(options).forEach(function(name315) { - if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name315) === -1) { - throw new exception('Unknown option "' + name315 + '" is met in definition of "' + tag2 + '" YAML type.'); + get minValue() { + let min3 = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min3 === null || ch.value > min3) + min3 = ch.value; + } } - }); - this.options = options; - this.tag = tag2; - this.kind = options["kind"] || null; - this.resolve = options["resolve"] || function() { - return true; - }; - this.construct = options["construct"] || function(data) { - return data; - }; - this.instanceOf = options["instanceOf"] || null; - this.predicate = options["predicate"] || null; - this.represent = options["represent"] || null; - this.representName = options["representName"] || null; - this.defaultStyle = options["defaultStyle"] || null; - this.multi = options["multi"] || false; - this.styleAliases = compileStyleAliases(options["styleAliases"] || null); - if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { - throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag2 + '" YAML type.'); + return min3; } -} -function compileList(schema2, name315) { - var result = []; - schema2[name315].forEach(function(currentType) { - var newIndex = result.length; - result.forEach(function(previousType, previousIndex) { - if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) { - newIndex = previousIndex; + get maxValue() { + let max3 = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max3 === null || ch.value < max3) + max3 = ch.value; } - }); - result[newIndex] = currentType; + } + return max3; + } +}; +ZodBigInt.create = (params) => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params) }); - return result; -} -function compileMap() { - var result = { - scalar: {}, - sequence: {}, - mapping: {}, - fallback: {}, - multi: { - scalar: [], - sequence: [], - mapping: [], - fallback: [] +}; +var ZodBoolean = class extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType + }); + return INVALID; } - }, index2, length; - function collectType(type2) { - if (type2.multi) { - result.multi[type2.kind].push(type2); - result.multi["fallback"].push(type2); - } else { - result[type2.kind][type2.tag] = result["fallback"][type2.tag] = type2; + return OK(input.data); + } +}; +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); +}; +var ZodDate = class _ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.date) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx2.parsedType + }); + return INVALID; + } + if (Number.isNaN(input.data.getTime())) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_date + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check2 of this._def.checks) { + if (check2.kind === "min") { + if (input.data.getTime() < check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check2.message, + inclusive: true, + exact: false, + minimum: check2.value, + type: "date" + }); + status.dirty(); + } + } else if (check2.kind === "max") { + if (input.data.getTime() > check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check2.message, + inclusive: true, + exact: false, + maximum: check2.value, + type: "date" + }); + status.dirty(); + } + } else { + util.assertNever(check2); + } } + return { + status: status.value, + value: new Date(input.data.getTime()) + }; } - for (index2 = 0, length = arguments.length; index2 < length; index2 += 1) { - arguments[index2].forEach(collectType); + _addCheck(check2) { + return new _ZodDate({ + ...this._def, + checks: [...this._def.checks, check2] + }); } - return result; -} -function Schema$1(definition) { - return this.extend(definition); -} -function resolveYamlNull(data) { - if (data === null) return true; - var max3 = data.length; - return max3 === 1 && data === "~" || max3 === 4 && (data === "null" || data === "Null" || data === "NULL"); -} -function constructYamlNull() { - return null; -} -function isNull(object3) { - return object3 === null; -} -function resolveYamlBoolean(data) { - if (data === null) return false; - var max3 = data.length; - return max3 === 4 && (data === "true" || data === "True" || data === "TRUE") || max3 === 5 && (data === "false" || data === "False" || data === "FALSE"); -} -function constructYamlBoolean(data) { - return data === "true" || data === "True" || data === "TRUE"; -} -function isBoolean(object3) { - return Object.prototype.toString.call(object3) === "[object Boolean]"; -} -function isHexCode(c) { - return 48 <= c && c <= 57 || 65 <= c && c <= 70 || 97 <= c && c <= 102; -} -function isOctCode(c) { - return 48 <= c && c <= 55; -} -function isDecCode(c) { - return 48 <= c && c <= 57; -} -function resolveYamlInteger(data) { - if (data === null) return false; - var max3 = data.length, index2 = 0, hasDigits = false, ch; - if (!max3) return false; - ch = data[index2]; - if (ch === "-" || ch === "+") { - ch = data[++index2]; + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message) + }); } - if (ch === "0") { - if (index2 + 1 === max3) return true; - ch = data[++index2]; - if (ch === "b") { - index2++; - for (; index2 < max3; index2++) { - ch = data[index2]; - if (ch === "_") continue; - if (ch !== "0" && ch !== "1") return false; - hasDigits = true; + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message) + }); + } + get minDate() { + let min3 = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min3 === null || ch.value > min3) + min3 = ch.value; } - return hasDigits && ch !== "_"; } - if (ch === "x") { - index2++; - for (; index2 < max3; index2++) { - ch = data[index2]; - if (ch === "_") continue; - if (!isHexCode(data.charCodeAt(index2))) return false; - hasDigits = true; + return min3 != null ? new Date(min3) : null; + } + get maxDate() { + let max3 = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max3 === null || ch.value < max3) + max3 = ch.value; } - return hasDigits && ch !== "_"; } - if (ch === "o") { - index2++; - for (; index2 < max3; index2++) { - ch = data[index2]; - if (ch === "_") continue; - if (!isOctCode(data.charCodeAt(index2))) return false; - hasDigits = true; - } - return hasDigits && ch !== "_"; + return max3 != null ? new Date(max3) : null; + } +}; +ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params) + }); +}; +var ZodSymbol = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType + }); + return INVALID; } + return OK(input.data); } - if (ch === "_") return false; - for (; index2 < max3; index2++) { - ch = data[index2]; - if (ch === "_") continue; - if (!isDecCode(data.charCodeAt(index2))) { - return false; +}; +ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params) + }); +}; +var ZodUndefined = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType + }); + return INVALID; } - hasDigits = true; + return OK(input.data); } - if (!hasDigits || ch === "_") return false; - return true; -} -function constructYamlInteger(data) { - var value = data, sign4 = 1, ch; - if (value.indexOf("_") !== -1) { - value = value.replace(/_/g, ""); +}; +ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params) + }); +}; +var ZodNull = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); } - ch = value[0]; - if (ch === "-" || ch === "+") { - if (ch === "-") sign4 = -1; - value = value.slice(1); - ch = value[0]; +}; +ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params) + }); +}; +var ZodAny = class extends ZodType { + constructor() { + super(...arguments); + this._any = true; } - if (value === "0") return 0; - if (ch === "0") { - if (value[1] === "b") return sign4 * parseInt(value.slice(2), 2); - if (value[1] === "x") return sign4 * parseInt(value.slice(2), 16); - if (value[1] === "o") return sign4 * parseInt(value.slice(2), 8); + _parse(input) { + return OK(input.data); } - return sign4 * parseInt(value, 10); -} -function isInteger(object3) { - return Object.prototype.toString.call(object3) === "[object Number]" && (object3 % 1 === 0 && !common.isNegativeZero(object3)); -} -function resolveYamlFloat(data) { - if (data === null) return false; - if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_` - // Probably should update regexp & check speed - data[data.length - 1] === "_") { - return false; +}; +ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params) + }); +}; +var ZodUnknown = class extends ZodType { + constructor() { + super(...arguments); + this._unknown = true; } - return true; -} -function constructYamlFloat(data) { - var value, sign4; - value = data.replace(/_/g, "").toLowerCase(); - sign4 = value[0] === "-" ? -1 : 1; - if ("+-".indexOf(value[0]) >= 0) { - value = value.slice(1); + _parse(input) { + return OK(input.data); } - if (value === ".inf") { - return sign4 === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - } else if (value === ".nan") { - return NaN; +}; +ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params) + }); +}; +var ZodNever = class extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType + }); + return INVALID; } - return sign4 * parseFloat(value, 10); -} -function representYamlFloat(object3, style) { - var res; - if (isNaN(object3)) { - switch (style) { - case "lowercase": - return ".nan"; - case "uppercase": - return ".NAN"; - case "camelcase": - return ".NaN"; +}; +ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params) + }); +}; +var ZodVoid = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType + }); + return INVALID; } - } else if (Number.POSITIVE_INFINITY === object3) { - switch (style) { - case "lowercase": - return ".inf"; - case "uppercase": - return ".INF"; - case "camelcase": - return ".Inf"; + return OK(input.data); + } +}; +ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params) + }); +}; +var ZodArray = class _ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; } - } else if (Number.NEGATIVE_INFINITY === object3) { - switch (style) { - case "lowercase": - return "-.inf"; - case "uppercase": - return "-.INF"; - case "camelcase": - return "-.Inf"; + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: tooSmall ? def.exactLength.value : void 0, + maximum: tooBig ? def.exactLength.value : void 0, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message + }); + status.dirty(); + } } - } else if (common.isNegativeZero(object3)) { - return "-0.0"; - } - res = object3.toString(10); - return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res; -} -function isFloat(object3) { - return Object.prototype.toString.call(object3) === "[object Number]" && (object3 % 1 !== 0 || common.isNegativeZero(object3)); -} -function resolveYamlTimestamp(data) { - if (data === null) return false; - if (YAML_DATE_REGEXP.exec(data) !== null) return true; - if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; - return false; -} -function constructYamlTimestamp(data) { - var match, year, month, day, hour, minute, second, fraction2 = 0, delta = null, tz_hour, tz_minute, date3; - match = YAML_DATE_REGEXP.exec(data); - if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); - if (match === null) throw new Error("Date resolve error"); - year = +match[1]; - month = +match[2] - 1; - day = +match[3]; - if (!match[4]) { - return new Date(Date.UTC(year, month, day)); - } - hour = +match[4]; - minute = +match[5]; - second = +match[6]; - if (match[7]) { - fraction2 = match[7].slice(0, 3); - while (fraction2.length < 3) { - fraction2 += "0"; + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message + }); + status.dirty(); + } } - fraction2 = +fraction2; + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i2) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i2)); + })).then((result2) => { + return ParseStatus.mergeArray(status, result2); + }); + } + const result = [...ctx.data].map((item, i2) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i2)); + }); + return ParseStatus.mergeArray(status, result); } - if (match[9]) { - tz_hour = +match[10]; - tz_minute = +(match[11] || 0); - delta = (tz_hour * 60 + tz_minute) * 6e4; - if (match[9] === "-") delta = -delta; + get element() { + return this._def.type; } - date3 = new Date(Date.UTC(year, month, day, hour, minute, second, fraction2)); - if (delta) date3.setTime(date3.getTime() - delta); - return date3; -} -function representYamlTimestamp(object3) { - return object3.toISOString(); -} -function resolveYamlMerge(data) { - return data === "<<" || data === null; -} -function resolveYamlBinary(data) { - if (data === null) return false; - var code, idx, bitlen = 0, max3 = data.length, map4 = BASE64_MAP; - for (idx = 0; idx < max3; idx++) { - code = map4.indexOf(data.charAt(idx)); - if (code > 64) continue; - if (code < 0) return false; - bitlen += 6; + min(minLength, message) { + return new _ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) } + }); } - return bitlen % 8 === 0; -} -function constructYamlBinary(data) { - var idx, tailbits, input = data.replace(/[\r\n=]/g, ""), max3 = input.length, map4 = BASE64_MAP, bits = 0, result = []; - for (idx = 0; idx < max3; idx++) { - if (idx % 4 === 0 && idx) { - result.push(bits >> 16 & 255); - result.push(bits >> 8 & 255); - result.push(bits & 255); - } - bits = bits << 6 | map4.indexOf(input.charAt(idx)); + max(maxLength, message) { + return new _ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) } + }); } - tailbits = max3 % 4 * 6; - if (tailbits === 0) { - result.push(bits >> 16 & 255); - result.push(bits >> 8 & 255); - result.push(bits & 255); - } else if (tailbits === 18) { - result.push(bits >> 10 & 255); - result.push(bits >> 2 & 255); - } else if (tailbits === 12) { - result.push(bits >> 4 & 255); + length(len, message) { + return new _ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) } + }); } - return new Uint8Array(result); -} -function representYamlBinary(object3) { - var result = "", bits = 0, idx, tail, max3 = object3.length, map4 = BASE64_MAP; - for (idx = 0; idx < max3; idx++) { - if (idx % 3 === 0 && idx) { - result += map4[bits >> 18 & 63]; - result += map4[bits >> 12 & 63]; - result += map4[bits >> 6 & 63]; - result += map4[bits & 63]; - } - bits = (bits << 8) + object3[idx]; + nonempty(message) { + return this.min(1, message); } - tail = max3 % 3; - if (tail === 0) { - result += map4[bits >> 18 & 63]; - result += map4[bits >> 12 & 63]; - result += map4[bits >> 6 & 63]; - result += map4[bits & 63]; - } else if (tail === 2) { - result += map4[bits >> 10 & 63]; - result += map4[bits >> 4 & 63]; - result += map4[bits << 2 & 63]; - result += map4[64]; - } else if (tail === 1) { - result += map4[bits >> 2 & 63]; - result += map4[bits << 4 & 63]; - result += map4[64]; - result += map4[64]; +}; +ZodArray.create = (schema2, params) => { + return new ZodArray({ + type: schema2, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params) + }); +}; +function deepPartialify(schema2) { + if (schema2 instanceof ZodObject) { + const newShape = {}; + for (const key in schema2.shape) { + const fieldSchema = schema2.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema2._def, + shape: () => newShape + }); + } else if (schema2 instanceof ZodArray) { + return new ZodArray({ + ...schema2._def, + type: deepPartialify(schema2.element) + }); + } else if (schema2 instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema2.unwrap())); + } else if (schema2 instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema2.unwrap())); + } else if (schema2 instanceof ZodTuple) { + return ZodTuple.create(schema2.items.map((item) => deepPartialify(item))); + } else { + return schema2; } - return result; -} -function isBinary(obj) { - return Object.prototype.toString.call(obj) === "[object Uint8Array]"; } -function resolveYamlOmap(data) { - if (data === null) return true; - var objectKeys = [], index2, length, pair, pairKey, pairHasKey, object3 = data; - for (index2 = 0, length = object3.length; index2 < length; index2 += 1) { - pair = object3[index2]; - pairHasKey = false; - if (_toString$2.call(pair) !== "[object Object]") return false; - for (pairKey in pair) { - if (_hasOwnProperty$3.call(pair, pairKey)) { - if (!pairHasKey) pairHasKey = true; - else return false; +var ZodObject = class _ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + this.nonstrict = this.passthrough; + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; + } + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.object) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx2.parsedType + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs2 = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs2.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs2.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] } + }); + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys + }); + status.dirty(); + } + } else if (unknownKeys === "strip") { + } else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } else { + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs2.push({ + key: { status: "valid", value: key }, + value: catchall._parse( + new ParseInputLazyPath(ctx, value, ctx.path, key) + //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data + }); } } - if (!pairHasKey) return false; - if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); - else return false; + if (ctx.common.async) { + return Promise.resolve().then(async () => { + const syncPairs = []; + for (const pair of pairs2) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet + }); + } + return syncPairs; + }).then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } else { + return ParseStatus.mergeObjectSync(status, pairs2); + } } - return true; -} -function constructYamlOmap(data) { - return data !== null ? data : []; -} -function resolveYamlPairs(data) { - if (data === null) return true; - var index2, length, pair, keys, result, object3 = data; - result = new Array(object3.length); - for (index2 = 0, length = object3.length; index2 < length; index2 += 1) { - pair = object3[index2]; - if (_toString$1.call(pair) !== "[object Object]") return false; - keys = Object.keys(pair); - if (keys.length !== 1) return false; - result[index2] = [keys[0], pair[keys[0]]]; + get shape() { + return this._def.shape(); } - return true; -} -function constructYamlPairs(data) { - if (data === null) return []; - var index2, length, pair, keys, result, object3 = data; - result = new Array(object3.length); - for (index2 = 0, length = object3.length; index2 < length; index2 += 1) { - pair = object3[index2]; - keys = Object.keys(pair); - result[index2] = [keys[0], pair[keys[0]]]; + strict(message) { + errorUtil.errToObj; + return new _ZodObject({ + ...this._def, + unknownKeys: "strict", + ...message !== void 0 ? { + errorMap: (issue2, ctx) => { + const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError; + if (issue2.code === "unrecognized_keys") + return { + message: errorUtil.errToObj(message).message ?? defaultError + }; + return { + message: defaultError + }; + } + } : {} + }); } - return result; -} -function resolveYamlSet(data) { - if (data === null) return true; - var key, object3 = data; - for (key in object3) { - if (_hasOwnProperty$2.call(object3, key)) { - if (object3[key] !== null) return false; - } + strip() { + return new _ZodObject({ + ...this._def, + unknownKeys: "strip" + }); } - return true; -} -function constructYamlSet(data) { - return data !== null ? data : {}; -} -function _class(obj) { - return Object.prototype.toString.call(obj); -} -function is_EOL(c) { - return c === 10 || c === 13; -} -function is_WHITE_SPACE(c) { - return c === 9 || c === 32; -} -function is_WS_OR_EOL(c) { - return c === 9 || c === 32 || c === 10 || c === 13; -} -function is_FLOW_INDICATOR(c) { - return c === 44 || c === 91 || c === 93 || c === 123 || c === 125; -} -function fromHexCode(c) { - var lc; - if (48 <= c && c <= 57) { - return c - 48; + passthrough() { + return new _ZodObject({ + ...this._def, + unknownKeys: "passthrough" + }); } - lc = c | 32; - if (97 <= lc && lc <= 102) { - return lc - 97 + 10; + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new _ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) + }); } - return -1; -} -function escapedHexLen(c) { - if (c === 120) { - return 2; + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new _ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: ZodFirstPartyTypeKind.ZodObject + }); + return merged; } - if (c === 117) { - return 4; + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema2) { + return this.augment({ [key]: schema2 }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index2) { + return new _ZodObject({ + ...this._def, + catchall: index2 + }); } - if (c === 85) { - return 8; + pick(mask) { + const shape = {}; + for (const key of util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); } - return 0; -} -function fromDecimalCode(c) { - if (48 <= c && c <= 57) { - return c - 48; + omit(mask) { + const shape = {}; + for (const key of util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); } - return -1; -} -function simpleEscapeSequence(c) { - return c === 48 ? "\0" : c === 97 ? "\x07" : c === 98 ? "\b" : c === 116 ? " " : c === 9 ? " " : c === 110 ? "\n" : c === 118 ? "\v" : c === 102 ? "\f" : c === 114 ? "\r" : c === 101 ? "\x1B" : c === 32 ? " " : c === 34 ? '"' : c === 47 ? "/" : c === 92 ? "\\" : c === 78 ? "\x85" : c === 95 ? "\xA0" : c === 76 ? "\u2028" : c === 80 ? "\u2029" : ""; -} -function charFromCodepoint(c) { - if (c <= 65535) { - return String.fromCharCode(c); + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); } - return String.fromCharCode( - (c - 65536 >> 10) + 55296, - (c - 65536 & 1023) + 56320 - ); -} -function setProperty(object3, key, value) { - if (key === "__proto__") { - Object.defineProperty(object3, key, { - configurable: true, - enumerable: true, - writable: true, - value + partial(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } else { + newShape[key] = fieldSchema.optional(); + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape }); - } else { - object3[key] = value; - } -} -function State$1(input, options) { - this.input = input; - this.filename = options["filename"] || null; - this.schema = options["schema"] || _default2; - this.onWarning = options["onWarning"] || null; - this.legacy = options["legacy"] || false; - this.json = options["json"] || false; - this.listener = options["listener"] || null; - this.implicitTypes = this.schema.compiledImplicit; - this.typeMap = this.schema.compiledTypeMap; - this.length = input.length; - this.position = 0; - this.line = 0; - this.lineStart = 0; - this.lineIndent = 0; - this.firstTabInLine = -1; - this.documents = []; -} -function generateError(state, message) { - var mark = { - name: state.filename, - buffer: state.input.slice(0, -1), - // omit trailing \0 - position: state.position, - line: state.line, - column: state.position - state.lineStart - }; - mark.snippet = snippet(mark); - return new exception(message, mark); -} -function throwError(state, message) { - throw generateError(state, message); -} -function throwWarning(state, message) { - if (state.onWarning) { - state.onWarning.call(null, generateError(state, message)); } -} -function captureSegment(state, start, end, checkJson) { - var _position, _length2, _character, _result; - if (start < end) { - _result = state.input.slice(start, end); - if (checkJson) { - for (_position = 0, _length2 = _result.length; _position < _length2; _position += 1) { - _character = _result.charCodeAt(_position); - if (!(_character === 9 || 32 <= _character && _character <= 1114111)) { - throwError(state, "expected valid JSON character"); + required(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; } + newShape[key] = newField; } - } else if (PATTERN_NON_PRINTABLE.test(_result)) { - throwError(state, "the stream contains non-printable characters"); } - state.result += _result; + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); } -} -function mergeMappings(state, destination, source, overridableKeys) { - var sourceKeys, key, index2, quantity; - if (!common.isObject(source)) { - throwError(state, "cannot merge mappings; the provided source object is unacceptable"); + keyof() { + return createZodEnum(util.objectKeys(this.shape)); } - sourceKeys = Object.keys(source); - for (index2 = 0, quantity = sourceKeys.length; index2 < quantity; index2 += 1) { - key = sourceKeys[index2]; - if (!_hasOwnProperty$1.call(destination, key)) { - setProperty(destination, key, source[key]); - overridableKeys[key] = true; +}; +ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +var ZodUnion = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; } - } -} -function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) { - var index2, quantity; - if (Array.isArray(keyNode)) { - keyNode = Array.prototype.slice.call(keyNode); - for (index2 = 0, quantity = keyNode.length; index2 < quantity; index2 += 1) { - if (Array.isArray(keyNode[index2])) { - throwError(state, "nested arrays are not supported inside keys"); + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + } else { + let dirty = void 0; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } } - if (typeof keyNode === "object" && _class(keyNode[index2]) === "[object Object]") { - keyNode[index2] = "[object Object]"; + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; } + const unionErrors = issues.map((issues2) => new ZodError(issues2)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; } } - if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") { - keyNode = "[object Object]"; + get options() { + return this._def.options; } - keyNode = String(keyNode); - if (_result === null) { - _result = {}; +}; +ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params) + }); +}; +var getDiscriminator = (type2) => { + if (type2 instanceof ZodLazy) { + return getDiscriminator(type2.schema); + } else if (type2 instanceof ZodEffects) { + return getDiscriminator(type2.innerType()); + } else if (type2 instanceof ZodLiteral) { + return [type2.value]; + } else if (type2 instanceof ZodEnum) { + return type2.options; + } else if (type2 instanceof ZodNativeEnum) { + return util.objectValues(type2.enum); + } else if (type2 instanceof ZodDefault) { + return getDiscriminator(type2._def.innerType); + } else if (type2 instanceof ZodUndefined) { + return [void 0]; + } else if (type2 instanceof ZodNull) { + return [null]; + } else if (type2 instanceof ZodOptional) { + return [void 0, ...getDiscriminator(type2.unwrap())]; + } else if (type2 instanceof ZodNullable) { + return [null, ...getDiscriminator(type2.unwrap())]; + } else if (type2 instanceof ZodBranded) { + return getDiscriminator(type2.unwrap()); + } else if (type2 instanceof ZodReadonly) { + return getDiscriminator(type2.unwrap()); + } else if (type2 instanceof ZodCatch) { + return getDiscriminator(type2._def.innerType); + } else { + return []; } - if (keyTag === "tag:yaml.org,2002:merge") { - if (Array.isArray(valueNode)) { - for (index2 = 0, quantity = valueNode.length; index2 < quantity; index2 += 1) { - mergeMappings(state, _result, valueNode[index2], overridableKeys); - } - } else { - mergeMappings(state, _result, valueNode, overridableKeys); +}; +var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }); + return INVALID; } - } else { - if (!state.json && !_hasOwnProperty$1.call(overridableKeys, keyNode) && _hasOwnProperty$1.call(_result, keyNode)) { - state.line = startLine || state.line; - state.lineStart = startLineStart || state.lineStart; - state.position = startPos || state.position; - throwError(state, "duplicated mapping key"); + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); } - setProperty(_result, keyNode, valueNode); - delete overridableKeys[keyNode]; } - return _result; -} -function readLineBreak(state) { - var ch; - ch = state.input.charCodeAt(state.position); - if (ch === 10) { - state.position++; - } else if (ch === 13) { - state.position++; - if (state.input.charCodeAt(state.position) === 10) { - state.position++; + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + const optionsMap = /* @__PURE__ */ new Map(); + for (const type2 of options) { + const discriminatorValues = getDiscriminator(type2.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type2); + } + } + return new _ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params) + }); + } +}; +function mergeValues(a, b) { + const aType = getParsedType(a); + const bType = getParsedType(b); + if (a === b) { + return { valid: true, data: a }; + } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index2 = 0; index2 < a.length; index2++) { + const itemA = a[index2]; + const itemB = b[index2]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); } + return { valid: true, data: newArray }; + } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; } else { - throwError(state, "a line break is expected"); + return { valid: false }; } - state.line += 1; - state.lineStart = state.position; - state.firstTabInLine = -1; } -function skipSeparationSpace(state, allowComments, checkIndent) { - var lineBreaks = 0, ch = state.input.charCodeAt(state.position); - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - if (ch === 9 && state.firstTabInLine === -1) { - state.firstTabInLine = state.position; +var ZodIntersection = class extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; } - ch = state.input.charCodeAt(++state.position); + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right]) => handleParsed(left, right)); + } else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); } - if (allowComments && ch === 35) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 10 && ch !== 13 && ch !== 0); + } +}; +ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left, + right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params) + }); +}; +var ZodTuple = class _ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; } - if (is_EOL(ch)) { - readLineBreak(state); - ch = state.input.charCodeAt(state.position); - lineBreaks++; - state.lineIndent = 0; - while (ch === 32) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + status.dirty(); + } + const items = [...ctx.data].map((item, itemIndex) => { + const schema2 = this._def.items[itemIndex] || this._def.rest; + if (!schema2) + return null; + return schema2._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }).filter((x) => !!x); + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); } else { - break; + return ParseStatus.mergeArray(status, items); } } - if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { - throwWarning(state, "deficient indentation"); + get items() { + return this._def.items; } - return lineBreaks; -} -function testDocumentSeparator(state) { - var _position = state.position, ch; - ch = state.input.charCodeAt(_position); - if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) { - _position += 3; - ch = state.input.charCodeAt(_position); - if (ch === 0 || is_WS_OR_EOL(ch)) { - return true; - } + rest(rest) { + return new _ZodTuple({ + ...this._def, + rest + }); } - return false; -} -function writeFoldedLines(state, count2) { - if (count2 === 1) { - state.result += " "; - } else if (count2 > 1) { - state.result += common.repeat("\n", count2 - 1); +}; +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params) + }); +}; +var ZodRecord = class _ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const pairs2 = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs2.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs2); + } else { + return ParseStatus.mergeObjectSync(status, pairs2); + } } -} -function readPlainScalar(state, nodeIndent, withinFlowCollection) { - var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch; - ch = state.input.charCodeAt(state.position); - if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) { - return false; + get element() { + return this._def.valueType; } - if (ch === 63 || ch === 45) { - following = state.input.charCodeAt(state.position + 1); - if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { - return false; + static create(first, second, third) { + if (second instanceof ZodType) { + return new _ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third) + }); } + return new _ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second) + }); } - state.kind = "scalar"; - state.result = ""; - captureStart = captureEnd = state.position; - hasPendingContent = false; - while (ch !== 0) { - if (ch === 58) { - following = state.input.charCodeAt(state.position + 1); - if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { - break; +}; +var ZodMap = class extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs2 = [...ctx.data.entries()].map(([key, value], index2) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"])) + }; + }); + if (ctx.common.async) { + const finalMap = /* @__PURE__ */ new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs2) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + const finalMap = /* @__PURE__ */ new Map(); + for (const pair of pairs2) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); } - } else if (ch === 35) { - preceding = state.input.charCodeAt(state.position - 1); - if (is_WS_OR_EOL(preceding)) { - break; + return { status: status.value, value: finalMap }; + } + } +}; +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params) + }); +}; +var ZodSet = class _ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message + }); + status.dirty(); } - } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && is_FLOW_INDICATOR(ch)) { - break; - } else if (is_EOL(ch)) { - _line = state.line; - _lineStart = state.lineStart; - _lineIndent = state.lineIndent; - skipSeparationSpace(state, false, -1); - if (state.lineIndent >= nodeIndent) { - hasPendingContent = true; - ch = state.input.charCodeAt(state.position); - continue; - } else { - state.position = captureEnd; - state.line = _line; - state.lineStart = _lineStart; - state.lineIndent = _lineIndent; - break; + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message + }); + status.dirty(); } } - if (hasPendingContent) { - captureSegment(state, captureStart, captureEnd, false); - writeFoldedLines(state, state.line - _line); - captureStart = captureEnd = state.position; - hasPendingContent = false; + const valueType = this._def.valueType; + function finalizeSet(elements2) { + const parsedSet = /* @__PURE__ */ new Set(); + for (const element of elements2) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; } - if (!is_WHITE_SPACE(ch)) { - captureEnd = state.position + 1; + const elements = [...ctx.data.values()].map((item, i2) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i2))); + if (ctx.common.async) { + return Promise.all(elements).then((elements2) => finalizeSet(elements2)); + } else { + return finalizeSet(elements); } - ch = state.input.charCodeAt(++state.position); } - captureSegment(state, captureStart, captureEnd, false); - if (state.result) { - return true; + min(minSize, message) { + return new _ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) } + }); } - state.kind = _kind; - state.result = _result; - return false; -} -function readSingleQuotedScalar(state, nodeIndent) { - var ch, captureStart, captureEnd; - ch = state.input.charCodeAt(state.position); - if (ch !== 39) { - return false; + max(maxSize, message) { + return new _ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) } + }); } - state.kind = "scalar"; - state.result = ""; - state.position++; - captureStart = captureEnd = state.position; - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 39) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - if (ch === 39) { - captureStart = state.position; - state.position++; - captureEnd = state.position; - } else { - return true; - } - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, "unexpected end of the document within a single quoted scalar"); - } else { - state.position++; - captureEnd = state.position; - } + size(size2, message) { + return this.min(size2, message).max(size2, message); } - throwError(state, "unexpected end of the stream within a single quoted scalar"); -} -function readDoubleQuotedScalar(state, nodeIndent) { - var captureStart, captureEnd, hexLength, hexResult, tmp, ch; - ch = state.input.charCodeAt(state.position); - if (ch !== 34) { - return false; + nonempty(message) { + return this.min(1, message); } - state.kind = "scalar"; - state.result = ""; - state.position++; - captureStart = captureEnd = state.position; - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 34) { - captureSegment(state, captureStart, state.position, true); - state.position++; - return true; - } else if (ch === 92) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - if (is_EOL(ch)) { - skipSeparationSpace(state, false, nodeIndent); - } else if (ch < 256 && simpleEscapeCheck[ch]) { - state.result += simpleEscapeMap[ch]; - state.position++; - } else if ((tmp = escapedHexLen(ch)) > 0) { - hexLength = tmp; - hexResult = 0; - for (; hexLength > 0; hexLength--) { - ch = state.input.charCodeAt(++state.position); - if ((tmp = fromHexCode(ch)) >= 0) { - hexResult = (hexResult << 4) + tmp; - } else { - throwError(state, "expected hexadecimal character"); - } +}; +ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params) + }); +}; +var ZodFunction = class _ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType + }); + return INVALID; + } + function makeArgsIssue(args, error2) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error2 } - state.result += charFromCodepoint(hexResult); - state.position++; - } else { - throwError(state, "unknown escape sequence"); - } - captureStart = captureEnd = state.position; - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, "unexpected end of the document within a double quoted scalar"); + }); + } + function makeReturnsIssue(returns, error2) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error2 + } + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + const me = this; + return OK(async function(...args) { + const error2 = new ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e3) => { + error2.addIssue(makeArgsIssue(args, e3)); + throw error2; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e3) => { + error2.addIssue(makeReturnsIssue(result, e3)); + throw error2; + }); + return parsedReturns; + }); } else { - state.position++; - captureEnd = state.position; + const me = this; + return OK(function(...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); } } - throwError(state, "unexpected end of the stream within a double quoted scalar"); -} -function readFlowCollection(state, nodeIndent) { - var readNext = true, _line, _lineStart, _pos, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = /* @__PURE__ */ Object.create(null), keyNode, keyTag, valueNode, ch; - ch = state.input.charCodeAt(state.position); - if (ch === 91) { - terminator = 93; - isMapping = false; - _result = []; - } else if (ch === 123) { - terminator = 125; - isMapping = true; - _result = {}; - } else { - return false; + parameters() { + return this._def.args; } - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; + returnType() { + return this._def.returns; } - ch = state.input.charCodeAt(++state.position); - while (ch !== 0) { - skipSeparationSpace(state, true, nodeIndent); - ch = state.input.charCodeAt(state.position); - if (ch === terminator) { - state.position++; - state.tag = _tag; - state.anchor = _anchor; - state.kind = isMapping ? "mapping" : "sequence"; - state.result = _result; - return true; - } else if (!readNext) { - throwError(state, "missed comma between flow collection entries"); - } else if (ch === 44) { - throwError(state, "expected the node content, but found ','"); + args(...items) { + return new _ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()) + }); + } + returns(returnType) { + return new _ZodFunction({ + ...this._def, + returns: returnType + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new _ZodFunction({ + args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params) + }); + } +}; +var ZodLazy = class extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } +}; +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params) + }); +}; +var ZodLiteral = class extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value + }); + return INVALID; } - keyTag = keyNode = valueNode = null; - isPair = isExplicitPair = false; - if (ch === 63) { - following = state.input.charCodeAt(state.position + 1); - if (is_WS_OR_EOL(following)) { - isPair = isExplicitPair = true; - state.position++; - skipSeparationSpace(state, true, nodeIndent); - } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } +}; +ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params) + }); +}; +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params) + }); +} +var ZodEnum = class _ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(this._def.values); + } + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; } - _line = state.line; - _lineStart = state.lineStart; - _pos = state.position; - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - keyTag = state.tag; - keyNode = state.result; - skipSeparationSpace(state, true, nodeIndent); - ch = state.input.charCodeAt(state.position); - if ((isExplicitPair || state.line === _line) && ch === 58) { - isPair = true; - ch = state.input.charCodeAt(++state.position); - skipSeparationSpace(state, true, nodeIndent); - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - valueNode = state.result; + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; } - if (isMapping) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); - } else if (isPair) { - _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); - } else { - _result.push(keyNode); + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; } - skipSeparationSpace(state, true, nodeIndent); - ch = state.input.charCodeAt(state.position); - if (ch === 44) { - readNext = true; - ch = state.input.charCodeAt(++state.position); - } else { - readNext = false; + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; } + return enumValues; } - throwError(state, "unexpected end of the stream within a flow collection"); -} -function readBlockScalar(state, nodeIndent) { - var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch; - ch = state.input.charCodeAt(state.position); - if (ch === 124) { - folding = false; - } else if (ch === 62) { - folding = true; - } else { - return false; + extract(values, newDef = this._def) { + return _ZodEnum.create(values, { + ...this._def, + ...newDef + }); } - state.kind = "scalar"; - state.result = ""; - while (ch !== 0) { - ch = state.input.charCodeAt(++state.position); - if (ch === 43 || ch === 45) { - if (CHOMPING_CLIP === chomping) { - chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP; - } else { - throwError(state, "repeat of a chomping mode identifier"); - } - } else if ((tmp = fromDecimalCode(ch)) >= 0) { - if (tmp === 0) { - throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one"); - } else if (!detectedIndent) { - textIndent = nodeIndent + tmp - 1; - detectedIndent = true; - } else { - throwError(state, "repeat of an indentation width identifier"); - } - } else { - break; - } + exclude(values, newDef = this._def) { + return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef + }); } - if (is_WHITE_SPACE(ch)) { - do { - ch = state.input.charCodeAt(++state.position); - } while (is_WHITE_SPACE(ch)); - if (ch === 35) { - do { - ch = state.input.charCodeAt(++state.position); - } while (!is_EOL(ch) && ch !== 0); +}; +ZodEnum.create = createZodEnum; +var ZodNativeEnum = class extends ZodType { + _parse(input) { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; } - } - while (ch !== 0) { - readLineBreak(state); - state.lineIndent = 0; - ch = state.input.charCodeAt(state.position); - while ((!detectedIndent || state.lineIndent < textIndent) && ch === 32) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); + if (!this._cache) { + this._cache = new Set(util.getValidEnumValues(this._def.values)); } - if (!detectedIndent && state.lineIndent > textIndent) { - textIndent = state.lineIndent; + if (!this._cache.has(input.data)) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; } - if (is_EOL(ch)) { - emptyLines++; - continue; + return OK(input.data); + } + get enum() { + return this._def.values; + } +}; +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params) + }); +}; +var ZodPromise = class extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType + }); + return INVALID; } - if (state.lineIndent < textIndent) { - if (chomping === CHOMPING_KEEP) { - state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); - } else if (chomping === CHOMPING_CLIP) { - if (didReadContent) { - state.result += "\n"; + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }); + })); + } +}; +ZodPromise.create = (schema2, params) => { + return new ZodPromise({ + type: schema2, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params) + }); +}; +var ZodEffects = class extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg2) => { + addIssueToContext(ctx, arg2); + if (arg2.fatal) { + status.abort(); + } else { + status.dirty(); } + }, + get path() { + return ctx.path; + } + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed2) => { + if (status.value === "aborted") + return INVALID; + const result = await this._def.schema._parseAsync({ + data: processed2, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + }); + } else { + if (status.value === "aborted") + return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; } - break; } - if (folding) { - if (is_WHITE_SPACE(ch)) { - atMoreIndented = true; - state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); - } else if (atMoreIndented) { - atMoreIndented = false; - state.result += common.repeat("\n", emptyLines + 1); - } else if (emptyLines === 0) { - if (didReadContent) { - state.result += " "; + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; } else { - state.result += common.repeat("\n", emptyLines); + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); } - } else { - state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); } - didReadContent = true; - detectedIndent = true; - emptyLines = 0; - captureStart = state.position; - while (!is_EOL(ch) && ch !== 0) { - ch = state.input.charCodeAt(++state.position); + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!isValid(base)) + return INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) + return INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result + })); + }); + } } - captureSegment(state, captureStart, state.position, false); - } - return true; -} -function readBlockSequence(state, nodeIndent) { - var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch; - if (state.firstTabInLine !== -1) return false; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; + util.assertNever(effect); } - ch = state.input.charCodeAt(state.position); - while (ch !== 0) { - if (state.firstTabInLine !== -1) { - state.position = state.firstTabInLine; - throwError(state, "tab characters must not be used in indentation"); - } - if (ch !== 45) { - break; - } - following = state.input.charCodeAt(state.position + 1); - if (!is_WS_OR_EOL(following)) { - break; - } - detected = true; - state.position++; - if (skipSeparationSpace(state, true, -1)) { - if (state.lineIndent <= nodeIndent) { - _result.push(null); - ch = state.input.charCodeAt(state.position); - continue; - } +}; +ZodEffects.create = (schema2, effect, params) => { + return new ZodEffects({ + schema: schema2, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params) + }); +}; +ZodEffects.createWithPreprocess = (preprocess2, schema2, params) => { + return new ZodEffects({ + schema: schema2, + effect: { type: "preprocess", transform: preprocess2 }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params) + }); +}; +var ZodOptional = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 === ZodParsedType.undefined) { + return OK(void 0); } - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); - _result.push(state.result); - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); - if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) { - throwError(state, "bad indentation of a sequence entry"); - } else if (state.lineIndent < nodeIndent) { - break; + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +}; +ZodOptional.create = (type2, params) => { + return new ZodOptional({ + innerType: type2, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params) + }); +}; +var ZodNullable = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 === ZodParsedType.null) { + return OK(null); } + return this._def.innerType._parse(input); } - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = "sequence"; - state.result = _result; - return true; + unwrap() { + return this._def.innerType; } - return false; -} -function readBlockMapping(state, nodeIndent, flowIndent) { - var following, allowCompact, _line, _keyLine, _keyLineStart, _keyPos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = /* @__PURE__ */ Object.create(null), keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch; - if (state.firstTabInLine !== -1) return false; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; +}; +ZodNullable.create = (type2, params) => { + return new ZodNullable({ + innerType: type2, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params) + }); +}; +var ZodDefault = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx + }); } - ch = state.input.charCodeAt(state.position); - while (ch !== 0) { - if (!atExplicitKey && state.firstTabInLine !== -1) { - state.position = state.firstTabInLine; - throwError(state, "tab characters must not be used in indentation"); - } - following = state.input.charCodeAt(state.position + 1); - _line = state.line; - if ((ch === 63 || ch === 58) && is_WS_OR_EOL(following)) { - if (ch === 63) { - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } - detected = true; - atExplicitKey = true; - allowCompact = true; - } else if (atExplicitKey) { - atExplicitKey = false; - allowCompact = true; - } else { - throwError(state, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"); - } - state.position += 1; - ch = following; - } else { - _keyLine = state.line; - _keyLineStart = state.lineStart; - _keyPos = state.position; - if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { - break; - } - if (state.line === _line) { - ch = state.input.charCodeAt(state.position); - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - if (ch === 58) { - ch = state.input.charCodeAt(++state.position); - if (!is_WS_OR_EOL(ch)) { - throwError(state, "a whitespace character is expected after the key-value separator within a block mapping"); - } - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; - } - detected = true; - atExplicitKey = false; - allowCompact = false; - keyTag = state.tag; - keyNode = state.result; - } else if (detected) { - throwError(state, "can not read an implicit mapping pair; a colon is missed"); - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; - } - } else if (detected) { - throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key"); - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; - } - } - if (state.line === _line || state.lineIndent > nodeIndent) { - if (atExplicitKey) { - _keyLine = state.line; - _keyLineStart = state.lineStart; - _keyPos = state.position; - } - if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { - if (atExplicitKey) { - keyNode = state.result; - } else { - valueNode = state.result; - } + removeDefault() { + return this._def.innerType; + } +}; +ZodDefault.create = (type2, params) => { + return new ZodDefault({ + innerType: type2, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params) + }); +}; +var ZodCatch = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] } - if (!atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); - keyTag = keyNode = valueNode = null; + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx } - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); - } - if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) { - throwError(state, "bad indentation of a mapping entry"); - } else if (state.lineIndent < nodeIndent) { - break; + }); + if (isAsync(result)) { + return result.then((result2) => { + return { + status: "valid", + value: result2.status === "valid" ? result2.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + }); + } else { + return { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; } } - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + removeCatch() { + return this._def.innerType; } - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = "mapping"; - state.result = _result; +}; +ZodCatch.create = (type2, params) => { + return new ZodCatch({ + innerType: type2, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params) + }); +}; +var ZodNaN = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType + }); + return INVALID; + } + return { status: "valid", value: input.data }; } - return detected; -} -function readTagProperty(state) { - var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch; - ch = state.input.charCodeAt(state.position); - if (ch !== 33) return false; - if (state.tag !== null) { - throwError(state, "duplication of a tag property"); +}; +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params) + }); +}; +var BRAND = /* @__PURE__ */ Symbol("zod_brand"); +var ZodBranded = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx + }); } - ch = state.input.charCodeAt(++state.position); - if (ch === 60) { - isVerbatim = true; - ch = state.input.charCodeAt(++state.position); - } else if (ch === 33) { - isNamed = true; - tagHandle = "!!"; - ch = state.input.charCodeAt(++state.position); - } else { - tagHandle = "!"; + unwrap() { + return this._def.type; } - _position = state.position; - if (isVerbatim) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 0 && ch !== 62); - if (state.position < state.length) { - tagName = state.input.slice(_position, state.position); - ch = state.input.charCodeAt(++state.position); - } else { - throwError(state, "unexpected end of the stream within a verbatim tag"); - } - } else { - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - if (ch === 33) { - if (!isNamed) { - tagHandle = state.input.slice(_position - 1, state.position + 1); - if (!PATTERN_TAG_HANDLE.test(tagHandle)) { - throwError(state, "named tag handle cannot contain such characters"); - } - isNamed = true; - _position = state.position + 1; +}; +var ZodPipeline = class _ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); } else { - throwError(state, "tag suffix cannot contain exclamation marks"); + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); } + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); } - ch = state.input.charCodeAt(++state.position); } - tagName = state.input.slice(_position, state.position); - if (PATTERN_FLOW_INDICATORS.test(tagName)) { - throwError(state, "tag suffix cannot contain flow indicator characters"); - } - } - if (tagName && !PATTERN_TAG_URI.test(tagName)) { - throwError(state, "tag name cannot contain such characters: " + tagName); - } - try { - tagName = decodeURIComponent(tagName); - } catch (err) { - throwError(state, "tag name is malformed: " + tagName); - } - if (isVerbatim) { - state.tag = tagName; - } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) { - state.tag = state.tagMap[tagHandle] + tagName; - } else if (tagHandle === "!") { - state.tag = "!" + tagName; - } else if (tagHandle === "!!") { - state.tag = "tag:yaml.org,2002:" + tagName; - } else { - throwError(state, 'undeclared tag handle "' + tagHandle + '"'); - } - return true; -} -function readAnchorProperty(state) { - var _position, ch; - ch = state.input.charCodeAt(state.position); - if (ch !== 38) return false; - if (state.anchor !== null) { - throwError(state, "duplication of an anchor property"); } - ch = state.input.charCodeAt(++state.position); - _position = state.position; - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - if (state.position === _position) { - throwError(state, "name of an anchor node must contain at least one character"); - } - state.anchor = state.input.slice(_position, state.position); - return true; -} -function readAlias(state) { - var _position, alias, ch; - ch = state.input.charCodeAt(state.position); - if (ch !== 42) return false; - ch = state.input.charCodeAt(++state.position); - _position = state.position; - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); + static create(a, b) { + return new _ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline + }); } - if (state.position === _position) { - throwError(state, "name of an alias node must contain at least one character"); +}; +var ZodReadonly = class extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze = (data) => { + if (isValid(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); } - alias = state.input.slice(_position, state.position); - if (!_hasOwnProperty$1.call(state.anchorMap, alias)) { - throwError(state, 'unidentified alias "' + alias + '"'); + unwrap() { + return this._def.innerType; } - state.result = state.anchorMap[alias]; - skipSeparationSpace(state, true, -1); - return true; +}; +ZodReadonly.create = (type2, params) => { + return new ZodReadonly({ + innerType: type2, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params) + }); +}; +function cleanParams(params, data) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p2 = typeof p === "string" ? { message: p } : p; + return p2; } -function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { - var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, typeIndex, typeQuantity, typeList, type2, flowIndent, blockIndent; - if (state.listener !== null) { - state.listener("open", state); - } - state.tag = null; - state.anchor = null; - state.kind = null; - state.result = null; - allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext; - if (allowToSeek) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } - } - if (indentStatus === 1) { - while (readTagProperty(state) || readAnchorProperty(state)) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - allowBlockCollections = allowBlockStyles; - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } - } else { - allowBlockCollections = false; - } - } - } - if (allowBlockCollections) { - allowBlockCollections = atNewLine || allowCompact; - } - if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { - if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { - flowIndent = parentIndent; - } else { - flowIndent = parentIndent + 1; - } - blockIndent = state.position - state.lineStart; - if (indentStatus === 1) { - if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) { - hasContent = true; - } else { - if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) { - hasContent = true; - } else if (readAlias(state)) { - hasContent = true; - if (state.tag !== null || state.anchor !== null) { - throwError(state, "alias node should not have any properties"); - } - } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { - hasContent = true; - if (state.tag === null) { - state.tag = "?"; +function custom(check2, _params = {}, fatal) { + if (check2) + return ZodAny.create().superRefine((data, ctx) => { + const r = check2(data); + if (r instanceof Promise) { + return r.then((r2) => { + if (!r2) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); } - } - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } - } else if (indentStatus === 0) { - hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); - } - } - if (state.tag === null) { - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - } else if (state.tag === "?") { - if (state.result !== null && state.kind !== "scalar") { - throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); - } - for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { - type2 = state.implicitTypes[typeIndex]; - if (type2.resolve(state.result)) { - state.result = type2.construct(state.result); - state.tag = type2.tag; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - break; - } - } - } else if (state.tag !== "!") { - if (_hasOwnProperty$1.call(state.typeMap[state.kind || "fallback"], state.tag)) { - type2 = state.typeMap[state.kind || "fallback"][state.tag]; - } else { - type2 = null; - typeList = state.typeMap.multi[state.kind || "fallback"]; - for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { - if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { - type2 = typeList[typeIndex]; - break; - } + }); } - } - if (!type2) { - throwError(state, "unknown tag !<" + state.tag + ">"); - } - if (state.result !== null && type2.kind !== state.kind) { - throwError(state, "unacceptable node kind for !<" + state.tag + '> tag; it should be "' + type2.kind + '", not "' + state.kind + '"'); - } - if (!type2.resolve(state.result, state.tag)) { - throwError(state, "cannot resolve a node with !<" + state.tag + "> explicit tag"); - } else { - state.result = type2.construct(state.result, state.tag); - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); } - } - } - if (state.listener !== null) { - state.listener("close", state); - } - return state.tag !== null || state.anchor !== null || hasContent; + return; + }); + return ZodAny.create(); } -function readDocument(state) { - var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch; - state.version = null; - state.checkLineBreaks = state.legacy; - state.tagMap = /* @__PURE__ */ Object.create(null); - state.anchorMap = /* @__PURE__ */ Object.create(null); - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); - if (state.lineIndent > 0 || ch !== 37) { - break; - } - hasDirectives = true; - ch = state.input.charCodeAt(++state.position); - _position = state.position; - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - directiveName = state.input.slice(_position, state.position); - directiveArgs = []; - if (directiveName.length < 1) { - throwError(state, "directive name must not be less than one character in length"); - } - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - if (ch === 35) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 0 && !is_EOL(ch)); - break; - } - if (is_EOL(ch)) break; - _position = state.position; - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - directiveArgs.push(state.input.slice(_position, state.position)); - } - if (ch !== 0) readLineBreak(state); - if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) { - directiveHandlers[directiveName](state, directiveName, directiveArgs); - } else { - throwWarning(state, 'unknown document directive "' + directiveName + '"'); +var late = { + object: ZodObject.lazycreate +}; +var ZodFirstPartyTypeKind; +(function(ZodFirstPartyTypeKind2) { + ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); +var instanceOfType = (cls, params = { + message: `Input not instance of ${cls.name}` +}) => custom((data) => data instanceof cls, params); +var stringType = ZodString.create; +var numberType = ZodNumber.create; +var nanType = ZodNaN.create; +var bigIntType = ZodBigInt.create; +var booleanType = ZodBoolean.create; +var dateType = ZodDate.create; +var symbolType = ZodSymbol.create; +var undefinedType = ZodUndefined.create; +var nullType = ZodNull.create; +var anyType = ZodAny.create; +var unknownType = ZodUnknown.create; +var neverType = ZodNever.create; +var voidType = ZodVoid.create; +var arrayType = ZodArray.create; +var objectType = ZodObject.create; +var strictObjectType = ZodObject.strictCreate; +var unionType = ZodUnion.create; +var discriminatedUnionType = ZodDiscriminatedUnion.create; +var intersectionType = ZodIntersection.create; +var tupleType = ZodTuple.create; +var recordType = ZodRecord.create; +var mapType = ZodMap.create; +var setType = ZodSet.create; +var functionType = ZodFunction.create; +var lazyType = ZodLazy.create; +var literalType = ZodLiteral.create; +var enumType = ZodEnum.create; +var nativeEnumType = ZodNativeEnum.create; +var promiseType = ZodPromise.create; +var effectsType = ZodEffects.create; +var optionalType = ZodOptional.create; +var nullableType = ZodNullable.create; +var preprocessType = ZodEffects.createWithPreprocess; +var pipelineType = ZodPipeline.create; +var ostring = () => stringType().optional(); +var onumber = () => numberType().optional(); +var oboolean = () => booleanType().optional(); +var coerce = { + string: ((arg2) => ZodString.create({ ...arg2, coerce: true })), + number: ((arg2) => ZodNumber.create({ ...arg2, coerce: true })), + boolean: ((arg2) => ZodBoolean.create({ + ...arg2, + coerce: true + })), + bigint: ((arg2) => ZodBigInt.create({ ...arg2, coerce: true })), + date: ((arg2) => ZodDate.create({ ...arg2, coerce: true })) +}; +var NEVER = INVALID; + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/core.js +var NEVER2 = Object.freeze({ + status: "aborted" +}); +// @__NO_SIDE_EFFECTS__ +function $constructor(name315, initializer3, params) { + function init(inst, def) { + var _a; + Object.defineProperty(inst, "_zod", { + value: inst._zod ?? {}, + enumerable: false + }); + (_a = inst._zod).traits ?? (_a.traits = /* @__PURE__ */ new Set()); + inst._zod.traits.add(name315); + initializer3(inst, def); + for (const k in _.prototype) { + if (!(k in inst)) + Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) }); } + inst._zod.constr = _; + inst._zod.def = def; } - skipSeparationSpace(state, true, -1); - if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) { - state.position += 3; - skipSeparationSpace(state, true, -1); - } else if (hasDirectives) { - throwError(state, "directives end mark is expected"); - } - composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); - skipSeparationSpace(state, true, -1); - if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { - throwWarning(state, "non-ASCII line breaks are interpreted as content"); + const Parent = params?.Parent ?? Object; + class Definition extends Parent { } - state.documents.push(state.result); - if (state.position === state.lineStart && testDocumentSeparator(state)) { - if (state.input.charCodeAt(state.position) === 46) { - state.position += 3; - skipSeparationSpace(state, true, -1); + Object.defineProperty(Definition, "name", { value: name315 }); + function _(def) { + var _a; + const inst = params?.Parent ? new Definition() : this; + init(inst, def); + (_a = inst._zod).deferred ?? (_a.deferred = []); + for (const fn of inst._zod.deferred) { + fn(); } - return; - } - if (state.position < state.length - 1) { - throwError(state, "end of the stream or a document separator is expected"); - } else { - return; + return inst; } -} -function loadDocuments(input, options) { - input = String(input); - options = options || {}; - if (input.length !== 0) { - if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) { - input += "\n"; - } - if (input.charCodeAt(0) === 65279) { - input = input.slice(1); + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name315); } + }); + Object.defineProperty(_, "name", { value: name315 }); + return _; +} +var $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); } - var state = new State$1(input, options); - var nullpos = input.indexOf("\0"); - if (nullpos !== -1) { - state.position = nullpos; - throwError(state, "null byte is not allowed in input"); - } - state.input += "\0"; - while (state.input.charCodeAt(state.position) === 32) { - state.lineIndent += 1; - state.position += 1; - } - while (state.position < state.length - 1) { - readDocument(state); - } - return state.documents; +}; +var globalConfig = {}; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; } -function loadAll$1(input, iterator, options) { - if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") { - options = iterator; - iterator = null; - } - var documents = loadDocuments(input, options); - if (typeof iterator !== "function") { - return documents; - } - for (var index2 = 0, length = documents.length; index2 < length; index2 += 1) { - iterator(documents[index2]); - } + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/util.js +var util_exports = {}; +__export(util_exports, { + BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + Class: () => Class, + NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, + aborted: () => aborted, + allowsEval: () => allowsEval, + assert: () => assert, + assertEqual: () => assertEqual, + assertIs: () => assertIs, + assertNever: () => assertNever, + assertNotEqual: () => assertNotEqual, + assignProp: () => assignProp, + cached: () => cached, + captureStackTrace: () => captureStackTrace, + cleanEnum: () => cleanEnum, + cleanRegex: () => cleanRegex, + clone: () => clone, + createTransparentProxy: () => createTransparentProxy, + defineLazy: () => defineLazy, + esc: () => esc, + escapeRegex: () => escapeRegex, + extend: () => extend, + finalizeIssue: () => finalizeIssue, + floatSafeRemainder: () => floatSafeRemainder2, + getElementAtPath: () => getElementAtPath, + getEnumValues: () => getEnumValues, + getLengthableOrigin: () => getLengthableOrigin, + getParsedType: () => getParsedType2, + getSizableOrigin: () => getSizableOrigin, + isObject: () => isObject, + isPlainObject: () => isPlainObject, + issue: () => issue, + joinValues: () => joinValues, + jsonStringifyReplacer: () => jsonStringifyReplacer, + merge: () => merge, + normalizeParams: () => normalizeParams, + nullish: () => nullish, + numKeys: () => numKeys, + omit: () => omit, + optionalKeys: () => optionalKeys, + partial: () => partial, + pick: () => pick, + prefixIssues: () => prefixIssues, + primitiveTypes: () => primitiveTypes, + promiseAllObject: () => promiseAllObject, + propertyKeyTypes: () => propertyKeyTypes, + randomString: () => randomString, + required: () => required, + stringifyPrimitive: () => stringifyPrimitive, + unwrapMessage: () => unwrapMessage +}); +function assertEqual(val) { + return val; } -function load$1(input, options) { - var documents = loadDocuments(input, options); - if (documents.length === 0) { - return void 0; - } else if (documents.length === 1) { - return documents[0]; - } - throw new exception("expected a single document in the stream, but found more"); +function assertNotEqual(val) { + return val; } -function compileStyleMap(schema2, map4) { - var result, keys, index2, length, tag2, style, type2; - if (map4 === null) return {}; - result = {}; - keys = Object.keys(map4); - for (index2 = 0, length = keys.length; index2 < length; index2 += 1) { - tag2 = keys[index2]; - style = String(map4[tag2]); - if (tag2.slice(0, 2) === "!!") { - tag2 = "tag:yaml.org,2002:" + tag2.slice(2); - } - type2 = schema2.compiledTypeMap["fallback"][tag2]; - if (type2 && _hasOwnProperty.call(type2.styleAliases, style)) { - style = type2.styleAliases[style]; - } - result[tag2] = style; - } - return result; +function assertIs(_arg) { } -function encodeHex(character) { - var string4, handle, length; - string4 = character.toString(16).toUpperCase(); - if (character <= 255) { - handle = "x"; - length = 2; - } else if (character <= 65535) { - handle = "u"; - length = 4; - } else if (character <= 4294967295) { - handle = "U"; - length = 8; - } else { - throw new exception("code point within a string may not be greater than 0xFFFFFFFF"); - } - return "\\" + handle + common.repeat("0", length - string4.length) + string4; +function assertNever(_x) { + throw new Error(); } -function State(options) { - this.schema = options["schema"] || _default2; - this.indent = Math.max(1, options["indent"] || 2); - this.noArrayIndent = options["noArrayIndent"] || false; - this.skipInvalid = options["skipInvalid"] || false; - this.flowLevel = common.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"]; - this.styleMap = compileStyleMap(this.schema, options["styles"] || null); - this.sortKeys = options["sortKeys"] || false; - this.lineWidth = options["lineWidth"] || 80; - this.noRefs = options["noRefs"] || false; - this.noCompatMode = options["noCompatMode"] || false; - this.condenseFlow = options["condenseFlow"] || false; - this.quotingType = options["quotingType"] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; - this.forceQuotes = options["forceQuotes"] || false; - this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null; - this.implicitTypes = this.schema.compiledImplicit; - this.explicitTypes = this.schema.compiledExplicit; - this.tag = null; - this.result = ""; - this.duplicates = []; - this.usedDuplicates = null; +function assert(_) { } -function indentString(string4, spaces) { - var ind = common.repeat(" ", spaces), position = 0, next = -1, result = "", line, length = string4.length; - while (position < length) { - next = string4.indexOf("\n", position); - if (next === -1) { - line = string4.slice(position); - position = length; - } else { - line = string4.slice(position, next + 1); - position = next + 1; - } - if (line.length && line !== "\n") result += ind; - result += line; - } - return result; +function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); + return values; } -function generateNextLine(state, level) { - return "\n" + common.repeat(" ", state.indent * level); +function joinValues(array2, separator = "|") { + return array2.map((val) => stringifyPrimitive(val)).join(separator); } -function testImplicitResolving(state, str2) { - var index2, length, type2; - for (index2 = 0, length = state.implicitTypes.length; index2 < length; index2 += 1) { - type2 = state.implicitTypes[index2]; - if (type2.resolve(str2)) { - return true; +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function cached(getter) { + const set2 = false; + return { + get value() { + if (!set2) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); } - } - return false; + }; } -function isWhitespace(c) { - return c === CHAR_SPACE || c === CHAR_TAB; +function nullish(input) { + return input === null || input === void 0; } -function isPrintable(c) { - return 32 <= c && c <= 126 || 161 <= c && c <= 55295 && c !== 8232 && c !== 8233 || 57344 <= c && c <= 65533 && c !== CHAR_BOM || 65536 <= c && c <= 1114111; +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); } -function isNsCharOrWhitespace(c) { - return isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED; +function floatSafeRemainder2(val, step2) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step2.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step2.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; } -function isPlainSafe(c, prev, inblock) { - var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); - var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); - return ( - // ns-plain-safe - (inblock ? ( - // c = flow-in - cIsNsCharOrWhitespace - ) : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar - ); +function defineLazy(object3, key, getter) { + const set2 = false; + Object.defineProperty(object3, key, { + get() { + if (!set2) { + const value = getter(); + object3[key] = value; + return value; + } + throw new Error("cached value already set"); + }, + set(v) { + Object.defineProperty(object3, key, { + value: v + // configurable: true, + }); + }, + configurable: true + }); } -function isPlainSafeFirst(c) { - return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT; +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true + }); } -function isPlainSafeLast(c) { - return !isWhitespace(c) && c !== CHAR_COLON; +function getElementAtPath(obj, path) { + if (!path) + return obj; + return path.reduce((acc, key) => acc?.[key], obj); } -function codePointAt(string4, pos) { - var first = string4.charCodeAt(pos), second; - if (first >= 55296 && first <= 56319 && pos + 1 < string4.length) { - second = string4.charCodeAt(pos + 1); - if (second >= 56320 && second <= 57343) { - return (first - 55296) * 1024 + second - 56320 + 65536; +function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i2 = 0; i2 < keys.length; i2++) { + resolvedObj[keys[i2]] = results[i2]; } + return resolvedObj; + }); +} +function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str2 = ""; + for (let i2 = 0; i2 < length; i2++) { + str2 += chars[Math.floor(Math.random() * chars.length)]; } - return first; + return str2; } -function needIndentIndicator(string4) { - var leadingSpaceRe = /^\n* /; - return leadingSpaceRe.test(string4); +function esc(str2) { + return JSON.stringify(str2); } -function chooseScalarStyle(string4, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) { - var i2; - var char = 0; - var prevChar = null; - var hasLineBreak = false; - var hasFoldableLine = false; - var shouldTrackWidth = lineWidth !== -1; - var previousLineBreak = -1; - var plain = isPlainSafeFirst(codePointAt(string4, 0)) && isPlainSafeLast(codePointAt(string4, string4.length - 1)); - if (singleLineOnly || forceQuotes) { - for (i2 = 0; i2 < string4.length; char >= 65536 ? i2 += 2 : i2++) { - char = codePointAt(string4, i2); - if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - plain = plain && isPlainSafe(char, prevChar, inblock); - prevChar = char; - } - } else { - for (i2 = 0; i2 < string4.length; char >= 65536 ? i2 += 2 : i2++) { - char = codePointAt(string4, i2); - if (char === CHAR_LINE_FEED) { - hasLineBreak = true; - if (shouldTrackWidth) { - hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented. - i2 - previousLineBreak - 1 > lineWidth && string4[previousLineBreak + 1] !== " "; - previousLineBreak = i2; - } - } else if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - plain = plain && isPlainSafe(char, prevChar, inblock); - prevChar = char; - } - hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i2 - previousLineBreak - 1 > lineWidth && string4[previousLineBreak + 1] !== " "); - } - if (!hasLineBreak && !hasFoldableLine) { - if (plain && !forceQuotes && !testAmbiguousType(string4)) { - return STYLE_PLAIN; - } - return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; +var captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => { +}; +function isObject(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +var allowsEval = cached(() => { + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; } - if (indentPerLevel > 9 && needIndentIndicator(string4)) { - return STYLE_DOUBLE; + try { + const F = Function; + new F(""); + return true; + } catch (_) { + return false; } - if (!forceQuotes) { - return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; +}); +function isPlainObject(o) { + if (isObject(o) === false) + return false; + const ctor = o.constructor; + if (ctor === void 0) + return true; + const prot = ctor.prototype; + if (isObject(prot) === false) + return false; + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; } - return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; + return true; } -function writeScalar(state, string4, level, iskey, inblock) { - state.dump = (function() { - if (string4.length === 0) { - return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; - } - if (!state.noCompatMode) { - if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string4) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string4)) { - return state.quotingType === QUOTING_TYPE_DOUBLE ? '"' + string4 + '"' : "'" + string4 + "'"; - } - } - var indent = state.indent * Math.max(1, level); - var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); - var singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel; - function testAmbiguity(string5) { - return testImplicitResolving(state, string5); - } - switch (chooseScalarStyle( - string4, - singleLineOnly, - state.indent, - lineWidth, - testAmbiguity, - state.quotingType, - state.forceQuotes && !iskey, - inblock - )) { - case STYLE_PLAIN: - return string4; - case STYLE_SINGLE: - return "'" + string4.replace(/'/g, "''") + "'"; - case STYLE_LITERAL: - return "|" + blockHeader(string4, state.indent) + dropEndingNewline(indentString(string4, indent)); - case STYLE_FOLDED: - return ">" + blockHeader(string4, state.indent) + dropEndingNewline(indentString(foldString(string4, lineWidth), indent)); - case STYLE_DOUBLE: - return '"' + escapeString(string4) + '"'; - default: - throw new exception("impossible error: invalid scalar style"); +function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; } - })(); + } + return keyCount; } -function blockHeader(string4, indentPerLevel) { - var indentIndicator = needIndentIndicator(string4) ? String(indentPerLevel) : ""; - var clip = string4[string4.length - 1] === "\n"; - var keep = clip && (string4[string4.length - 2] === "\n" || string4 === "\n"); - var chomp = keep ? "+" : clip ? "" : "-"; - return indentIndicator + chomp + "\n"; +var getParsedType2 = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return "date"; + } + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t}`); + } +}; +var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); +var primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); +function escapeRegex(str2) { + return str2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } -function dropEndingNewline(string4) { - return string4[string4.length - 1] === "\n" ? string4.slice(0, -1) : string4; +function clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) + cl._zod.parent = inst; + return cl; } -function foldString(string4, width) { - var lineRe = /(\n+)([^\n]*)/g; - var result = (function() { - var nextLF = string4.indexOf("\n"); - nextLF = nextLF !== -1 ? nextLF : string4.length; - lineRe.lastIndex = nextLF; - return foldLine(string4.slice(0, nextLF), width); - })(); - var prevMoreIndented = string4[0] === "\n" || string4[0] === " "; - var moreIndented; - var match; - while (match = lineRe.exec(string4)) { - var prefix = match[1], line = match[2]; - moreIndented = line[0] === " "; - result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width); - prevMoreIndented = moreIndented; +function normalizeParams(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== void 0) { + if (params?.error !== void 0) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; } - return result; + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; } -function foldLine(line, width) { - if (line === "" || line[0] === " ") return line; - var breakRe = / [^ ]/g; - var match; - var start = 0, end, curr = 0, next = 0; - var result = ""; - while (match = breakRe.exec(line)) { - next = match.index; - if (next - start > width) { - end = curr > start ? curr : next; - result += "\n" + line.slice(start, end); - start = end + 1; +function createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); } - curr = next; - } - result += "\n"; - if (line.length - start > width && curr > start) { - result += line.slice(start, curr) + "\n" + line.slice(curr + 1); - } else { - result += line.slice(start); - } - return result.slice(1); + }); } -function escapeString(string4) { - var result = ""; - var char = 0; - var escapeSeq; - for (var i2 = 0; i2 < string4.length; char >= 65536 ? i2 += 2 : i2++) { - char = codePointAt(string4, i2); - escapeSeq = ESCAPE_SEQUENCES[char]; - if (!escapeSeq && isPrintable(char)) { - result += string4[i2]; - if (char >= 65536) result += string4[i2 + 1]; - } else { - result += escapeSeq || encodeHex(char); - } - } - return result; +function stringifyPrimitive(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; } -function writeFlowSequence(state, level, object3) { - var _result = "", _tag = state.tag, index2, length, value; - for (index2 = 0, length = object3.length; index2 < length; index2 += 1) { - value = object3[index2]; - if (state.replacer) { - value = state.replacer.call(object3, String(index2), value); - } - if (writeNode(state, level, value, false, false) || typeof value === "undefined" && writeNode(state, level, null, false, false)) { - if (_result !== "") _result += "," + (!state.condenseFlow ? " " : ""); - _result += state.dump; - } - } - state.tag = _tag; - state.dump = "[" + _result + "]"; +function optionalKeys(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + }); } -function writeBlockSequence(state, level, object3, compact) { - var _result = "", _tag = state.tag, index2, length, value; - for (index2 = 0, length = object3.length; index2 < length; index2 += 1) { - value = object3[index2]; - if (state.replacer) { - value = state.replacer.call(object3, String(index2), value); - } - if (writeNode(state, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state, level + 1, null, true, true, false, true)) { - if (!compact || _result !== "") { - _result += generateNextLine(state, level); - } - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - _result += "-"; - } else { - _result += "- "; - } - _result += state.dump; +var NUMBER_FORMAT_RANGES = { + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-34028234663852886e22, 34028234663852886e22], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE] +}; +var BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], + uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] +}; +function pick(schema2, mask) { + const newShape = {}; + const currDef = schema2._zod.def; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); } + if (!mask[key]) + continue; + newShape[key] = currDef.shape[key]; } - state.tag = _tag; - state.dump = _result || "[]"; + return clone(schema2, { + ...schema2._zod.def, + shape: newShape, + checks: [] + }); } -function writeFlowMapping(state, level, object3) { - var _result = "", _tag = state.tag, objectKeyList = Object.keys(object3), index2, length, objectKey, objectValue, pairBuffer; - for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) { - pairBuffer = ""; - if (_result !== "") pairBuffer += ", "; - if (state.condenseFlow) pairBuffer += '"'; - objectKey = objectKeyList[index2]; - objectValue = object3[objectKey]; - if (state.replacer) { - objectValue = state.replacer.call(object3, objectKey, objectValue); - } - if (!writeNode(state, level, objectKey, false, false)) { - continue; +function omit(schema2, mask) { + const newShape = { ...schema2._zod.def.shape }; + const currDef = schema2._zod.def; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); } - if (state.dump.length > 1024) pairBuffer += "? "; - pairBuffer += state.dump + (state.condenseFlow ? '"' : "") + ":" + (state.condenseFlow ? "" : " "); - if (!writeNode(state, level, objectValue, false, false)) { + if (!mask[key]) continue; - } - pairBuffer += state.dump; - _result += pairBuffer; + delete newShape[key]; } - state.tag = _tag; - state.dump = "{" + _result + "}"; + return clone(schema2, { + ...schema2._zod.def, + shape: newShape, + checks: [] + }); } -function writeBlockMapping(state, level, object3, compact) { - var _result = "", _tag = state.tag, objectKeyList = Object.keys(object3), index2, length, objectKey, objectValue, explicitPair, pairBuffer; - if (state.sortKeys === true) { - objectKeyList.sort(); - } else if (typeof state.sortKeys === "function") { - objectKeyList.sort(state.sortKeys); - } else if (state.sortKeys) { - throw new exception("sortKeys must be a boolean or a function"); +function extend(schema2, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to extend: expected a plain object"); } - for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) { - pairBuffer = ""; - if (!compact || _result !== "") { - pairBuffer += generateNextLine(state, level); - } - objectKey = objectKeyList[index2]; - objectValue = object3[objectKey]; - if (state.replacer) { - objectValue = state.replacer.call(object3, objectKey, objectValue); - } - if (!writeNode(state, level + 1, objectKey, true, true, true)) { - continue; - } - explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024; - if (explicitPair) { - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += "?"; - } else { - pairBuffer += "? "; + const def = { + ...schema2._zod.def, + get shape() { + const _shape = { ...schema2._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); + return _shape; + }, + checks: [] + // delete existing checks + }; + return clone(schema2, def); +} +function merge(a, b) { + return clone(a, { + ...a._zod.def, + get shape() { + const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; + assignProp(this, "shape", _shape); + return _shape; + }, + catchall: b._zod.def.catchall, + checks: [] + // delete existing checks + }); +} +function partial(Class2, schema2, mask) { + const oldShape = schema2._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in oldShape)) { + throw new Error(`Unrecognized key: "${key}"`); } + if (!mask[key]) + continue; + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; } - pairBuffer += state.dump; - if (explicitPair) { - pairBuffer += generateNextLine(state, level); + } else { + for (const key in oldShape) { + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; } - if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { - continue; + } + return clone(schema2, { + ...schema2._zod.def, + shape, + checks: [] + }); +} +function required(Class2, schema2, mask) { + const oldShape = schema2._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); } - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += ":"; - } else { - pairBuffer += ": "; + } else { + for (const key in oldShape) { + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); } - pairBuffer += state.dump; - _result += pairBuffer; } - state.tag = _tag; - state.dump = _result || "{}"; + return clone(schema2, { + ...schema2._zod.def, + shape, + // optional: [], + checks: [] + }); } -function detectType(state, object3, explicit) { - var _result, typeList, index2, length, type2, style; - typeList = explicit ? state.explicitTypes : state.implicitTypes; - for (index2 = 0, length = typeList.length; index2 < length; index2 += 1) { - type2 = typeList[index2]; - if ((type2.instanceOf || type2.predicate) && (!type2.instanceOf || typeof object3 === "object" && object3 instanceof type2.instanceOf) && (!type2.predicate || type2.predicate(object3))) { - if (explicit) { - if (type2.multi && type2.representName) { - state.tag = type2.representName(object3); - } else { - state.tag = type2.tag; - } - } else { - state.tag = "?"; - } - if (type2.represent) { - style = state.styleMap[type2.tag] || type2.defaultStyle; - if (_toString.call(type2.represent) === "[object Function]") { - _result = type2.represent(object3, style); - } else if (_hasOwnProperty.call(type2.represent, style)) { - _result = type2.represent[style](object3, style); - } else { - throw new exception("!<" + type2.tag + '> tag resolver accepts not "' + style + '" style'); - } - state.dump = _result; - } +function aborted(x, startIndex = 0) { + for (let i2 = startIndex; i2 < x.issues.length; i2++) { + if (x.issues[i2]?.continue !== true) return true; - } } return false; } -function writeNode(state, level, object3, block, compact, iskey, isblockseq) { - state.tag = null; - state.dump = object3; - if (!detectType(state, object3, false)) { - detectType(state, object3, true); +function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a; + (_a = iss).path ?? (_a.path = []); + iss.path.unshift(path); + return iss; + }); +} +function unwrapMessage(message) { + return typeof message === "string" ? message : message?.message; +} +function finalizeIssue(iss, ctx, config5) { + const full = { ...iss, path: iss.path ?? [] }; + if (!iss.message) { + const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config5.customError?.(iss)) ?? unwrapMessage(config5.localeError?.(iss)) ?? "Invalid input"; + full.message = message; } - var type2 = _toString.call(state.dump); - var inblock = block; - var tagStr; - if (block) { - block = state.flowLevel < 0 || state.flowLevel > level; + delete full.inst; + delete full.continue; + if (!ctx?.reportInput) { + delete full.input; } - var objectOrArray = type2 === "[object Object]" || type2 === "[object Array]", duplicateIndex, duplicate; - if (objectOrArray) { - duplicateIndex = state.duplicates.indexOf(object3); - duplicate = duplicateIndex !== -1; + return full; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + if (input instanceof File) + return "file"; + return "unknown"; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; +} +function issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst + }; } - if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) { - compact = false; + return { ...iss }; +} +function cleanEnum(obj) { + return Object.entries(obj).filter(([k, _]) => { + return Number.isNaN(Number.parseInt(k, 10)); + }).map((el) => el[1]); +} +var Class = class { + constructor(..._args) { } - if (duplicate && state.usedDuplicates[duplicateIndex]) { - state.dump = "*ref_" + duplicateIndex; - } else { - if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { - state.usedDuplicates[duplicateIndex] = true; - } - if (type2 === "[object Object]") { - if (block && Object.keys(state.dump).length !== 0) { - writeBlockMapping(state, level, state.dump, compact); - if (duplicate) { - state.dump = "&ref_" + duplicateIndex + state.dump; - } - } else { - writeFlowMapping(state, level, state.dump); - if (duplicate) { - state.dump = "&ref_" + duplicateIndex + " " + state.dump; - } - } - } else if (type2 === "[object Array]") { - if (block && state.dump.length !== 0) { - if (state.noArrayIndent && !isblockseq && level > 0) { - writeBlockSequence(state, level - 1, state.dump, compact); - } else { - writeBlockSequence(state, level, state.dump, compact); - } - if (duplicate) { - state.dump = "&ref_" + duplicateIndex + state.dump; - } - } else { - writeFlowSequence(state, level, state.dump); - if (duplicate) { - state.dump = "&ref_" + duplicateIndex + " " + state.dump; - } - } - } else if (type2 === "[object String]") { - if (state.tag !== "?") { - writeScalar(state, state.dump, level, iskey, inblock); - } - } else if (type2 === "[object Undefined]") { - return false; +}; + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/errors.js +var initializer = (inst, def) => { + inst.name = "$ZodError"; + Object.defineProperty(inst, "_zod", { + value: inst._zod, + enumerable: false + }); + Object.defineProperty(inst, "issues", { + value: def, + enumerable: false + }); + Object.defineProperty(inst, "message", { + get() { + return JSON.stringify(def, jsonStringifyReplacer, 2); + }, + enumerable: true + // configurable: false, + }); + Object.defineProperty(inst, "toString", { + value: () => inst.message, + enumerable: false + }); +}; +var $ZodError = $constructor("$ZodError", initializer); +var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); +function flattenError(error2, mapper = (issue2) => issue2.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub2 of error2.issues) { + if (sub2.path.length > 0) { + fieldErrors[sub2.path[0]] = fieldErrors[sub2.path[0]] || []; + fieldErrors[sub2.path[0]].push(mapper(sub2)); } else { - if (state.skipInvalid) return false; - throw new exception("unacceptable kind of an object to dump " + type2); + formErrors.push(mapper(sub2)); } - if (state.tag !== null && state.tag !== "?") { - tagStr = encodeURI( - state.tag[0] === "!" ? state.tag.slice(1) : state.tag - ).replace(/!/g, "%21"); - if (state.tag[0] === "!") { - tagStr = "!" + tagStr; - } else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") { - tagStr = "!!" + tagStr.slice(18); + } + return { formErrors, fieldErrors }; +} +function formatError(error2, _mapper) { + const mapper = _mapper || function(issue2) { + return issue2.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error3) => { + for (const issue2 of error3.issues) { + if (issue2.code === "invalid_union" && issue2.errors.length) { + issue2.errors.map((issues) => processError({ issues })); + } else if (issue2.code === "invalid_key") { + processError({ issues: issue2.issues }); + } else if (issue2.code === "invalid_element") { + processError({ issues: issue2.issues }); + } else if (issue2.path.length === 0) { + fieldErrors._errors.push(mapper(issue2)); } else { - tagStr = "!<" + tagStr + ">"; + let curr = fieldErrors; + let i2 = 0; + while (i2 < issue2.path.length) { + const el = issue2.path[i2]; + const terminal = i2 === issue2.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue2)); + } + curr = curr[el]; + i2++; + } } - state.dump = tagStr + " " + state.dump; } - } - return true; + }; + processError(error2); + return fieldErrors; } -function getDuplicateReferences(object3, state) { - var objects = [], duplicatesIndexes = [], index2, length; - inspectNode(object3, objects, duplicatesIndexes); - for (index2 = 0, length = duplicatesIndexes.length; index2 < length; index2 += 1) { - state.duplicates.push(objects[duplicatesIndexes[index2]]); + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/parse.js +var _parse = (_Err) => (schema2, value, _ctx, _params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; + const result = schema2._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); } - state.usedDuplicates = new Array(length); -} -function inspectNode(object3, objects, duplicatesIndexes) { - var objectKeyList, index2, length; - if (object3 !== null && typeof object3 === "object") { - index2 = objects.indexOf(object3); - if (index2 !== -1) { - if (duplicatesIndexes.indexOf(index2) === -1) { - duplicatesIndexes.push(index2); - } - } else { - objects.push(object3); - if (Array.isArray(object3)) { - for (index2 = 0, length = object3.length; index2 < length; index2 += 1) { - inspectNode(object3[index2], objects, duplicatesIndexes); - } - } else { - objectKeyList = Object.keys(object3); - for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) { - inspectNode(object3[objectKeyList[index2]], objects, duplicatesIndexes); - } - } - } + if (result.issues.length) { + const e3 = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e3, _params?.callee); + throw e3; } -} -function dump$1(input, options) { - options = options || {}; - var state = new State(options); - if (!state.noRefs) getDuplicateReferences(input, state); - var value = input; - if (state.replacer) { - value = state.replacer.call({ "": value }, "", value); + return result.value; +}; +var parse = /* @__PURE__ */ _parse($ZodRealError); +var _parseAsync = (_Err) => async (schema2, value, _ctx, params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema2._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e3 = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e3, params?.callee); + throw e3; } - if (writeNode(state, 0, value, true, true)) return state.dump + "\n"; - return ""; + return result.value; +}; +var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); +var _safeParse = (_Err) => (schema2, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema2._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length ? { + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + } : { success: true, data: result.value }; +}; +var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); +var _safeParseAsync = (_Err) => async (schema2, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema2._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + } : { success: true, data: result.value }; +}; +var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/regexes.js +var cuid = /^[cC][^\s-]{8,}$/; +var cuid2 = /^[0-9a-z]+$/; +var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +var xid = /^[0-9a-vA-V]{20}$/; +var ksuid = /^[A-Za-z0-9]{27}$/; +var nanoid = /^[a-zA-Z0-9_-]{21}$/; +var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +var 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})$/; +var uuid = (version4) => { + if (!version4) + return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version4}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}; +var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +function emoji() { + return new RegExp(_emoji, "u"); } -function renamed(from, to2) { - return function() { - throw new Error("Function yaml." + from + " is removed in js-yaml 4. Use yaml." + to2 + " instead, which is now safe by default."); - }; +var 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])$/; +var ipv6 = /^(([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})$/; +var 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])$/; +var 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])$/; +var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +var base64url = /^[A-Za-z0-9_-]*$/; +var hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; +var e164 = /^\+(?:[0-9]){6,14}[0-9]$/; +var 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])))`; +var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); +function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = 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+)?)?`; + return regex; } -var isNothing_1, isObject_1, toArray_1, repeat_1, isNegativeZero_1, extend_1, common, exception, snippet, TYPE_CONSTRUCTOR_OPTIONS, YAML_NODE_KINDS, type, schema, str, seq, map, failsafe, _null4, bool, int2, YAML_FLOAT_PATTERN, SCIENTIFIC_WITHOUT_DOT, float, json, core, YAML_DATE_REGEXP, YAML_TIMESTAMP_REGEXP, timestamp, merge2, BASE64_MAP, binary, _hasOwnProperty$3, _toString$2, omap, _toString$1, pairs, _hasOwnProperty$2, set, _default2, _hasOwnProperty$1, CONTEXT_FLOW_IN, CONTEXT_FLOW_OUT, CONTEXT_BLOCK_IN, CONTEXT_BLOCK_OUT, CHOMPING_CLIP, CHOMPING_STRIP, CHOMPING_KEEP, PATTERN_NON_PRINTABLE, PATTERN_NON_ASCII_LINE_BREAKS, PATTERN_FLOW_INDICATORS, PATTERN_TAG_HANDLE, PATTERN_TAG_URI, simpleEscapeCheck, simpleEscapeMap, i2, directiveHandlers, loadAll_1, load_1, loader, _toString, _hasOwnProperty, CHAR_BOM, CHAR_TAB, CHAR_LINE_FEED, CHAR_CARRIAGE_RETURN, CHAR_SPACE, CHAR_EXCLAMATION, CHAR_DOUBLE_QUOTE, CHAR_SHARP, CHAR_PERCENT, CHAR_AMPERSAND, CHAR_SINGLE_QUOTE, CHAR_ASTERISK, CHAR_COMMA, CHAR_MINUS, CHAR_COLON, CHAR_EQUALS, CHAR_GREATER_THAN, CHAR_QUESTION, CHAR_COMMERCIAL_AT, CHAR_LEFT_SQUARE_BRACKET, CHAR_RIGHT_SQUARE_BRACKET, CHAR_GRAVE_ACCENT, CHAR_LEFT_CURLY_BRACKET, CHAR_VERTICAL_LINE, CHAR_RIGHT_CURLY_BRACKET, ESCAPE_SEQUENCES, DEPRECATED_BOOLEANS_SYNTAX, DEPRECATED_BASE60_SYNTAX, QUOTING_TYPE_SINGLE, QUOTING_TYPE_DOUBLE, STYLE_PLAIN, STYLE_SINGLE, STYLE_LITERAL, STYLE_FOLDED, STYLE_DOUBLE, dump_1, dumper, load, loadAll, dump, safeLoad, safeLoadAll, safeDump; -var init_js_yaml = __esm({ - "node_modules/.pnpm/js-yaml@4.1.1/node_modules/js-yaml/dist/js-yaml.mjs"() { - isNothing_1 = isNothing; - isObject_1 = isObject2; - toArray_1 = toArray; - repeat_1 = repeat; - isNegativeZero_1 = isNegativeZero; - extend_1 = extend2; - common = { - isNothing: isNothing_1, - isObject: isObject_1, - toArray: toArray_1, - repeat: repeat_1, - isNegativeZero: isNegativeZero_1, - extend: extend_1 - }; - YAMLException$1.prototype = Object.create(Error.prototype); - YAMLException$1.prototype.constructor = YAMLException$1; - YAMLException$1.prototype.toString = function toString(compact) { - return this.name + ": " + formatError2(this, compact); - }; - exception = YAMLException$1; - snippet = makeSnippet; - TYPE_CONSTRUCTOR_OPTIONS = [ - "kind", - "multi", - "resolve", - "construct", - "instanceOf", - "predicate", - "represent", - "representName", - "defaultStyle", - "styleAliases" - ]; - YAML_NODE_KINDS = [ - "scalar", - "sequence", - "mapping" - ]; - type = Type$1; - Schema$1.prototype.extend = function extend3(definition) { - var implicit = []; - var explicit = []; - if (definition instanceof type) { - explicit.push(definition); - } else if (Array.isArray(definition)) { - explicit = explicit.concat(definition); - } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { - if (definition.implicit) implicit = implicit.concat(definition.implicit); - if (definition.explicit) explicit = explicit.concat(definition.explicit); - } else { - throw new exception("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })"); - } - implicit.forEach(function(type$1) { - if (!(type$1 instanceof type)) { - throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object."); - } - if (type$1.loadKind && type$1.loadKind !== "scalar") { - throw new exception("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported."); - } - if (type$1.multi) { - throw new exception("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit."); - } - }); - explicit.forEach(function(type$1) { - if (!(type$1 instanceof type)) { - throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object."); - } - }); - var result = Object.create(Schema$1.prototype); - result.implicit = (this.implicit || []).concat(implicit); - result.explicit = (this.explicit || []).concat(explicit); - result.compiledImplicit = compileList(result, "implicit"); - result.compiledExplicit = compileList(result, "explicit"); - result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); - return result; - }; - schema = Schema$1; - str = new type("tag:yaml.org,2002:str", { - kind: "scalar", - construct: function(data) { - return data !== null ? data : ""; - } - }); - seq = new type("tag:yaml.org,2002:seq", { - kind: "sequence", - construct: function(data) { - return data !== null ? data : []; - } - }); - map = new type("tag:yaml.org,2002:map", { - kind: "mapping", - construct: function(data) { - return data !== null ? data : {}; - } - }); - failsafe = new schema({ - explicit: [ - str, - seq, - map - ] +function time(args) { + return new RegExp(`^${timeSource(args)}$`); +} +function datetime(args) { + const time3 = timeSource({ precision: args.precision }); + const opts = ["Z"]; + if (args.local) + opts.push(""); + if (args.offset) + opts.push(`([+-]\\d{2}:\\d{2})`); + const timeRegex2 = `${time3}(?:${opts.join("|")})`; + return new RegExp(`^${dateSource}T(?:${timeRegex2})$`); +} +var string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); +}; +var integer = /^\d+$/; +var number = /^-?\d+(?:\.\d+)?/i; +var boolean = /true|false/i; +var _null = /null/i; +var lowercase = /^[^A-Z]*$/; +var uppercase = /^[^a-z]*$/; + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/checks.js +var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { + var _a; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a = inst._zod).onattach ?? (_a.onattach = []); +}); +var numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date" +}; +var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def.value < curr) { + if (def.inclusive) + bag.maximum = def.value; + else + bag.exclusiveMaximum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { + return; + } + payload.issues.push({ + origin, + code: "too_big", + maximum: def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort }); - _null4 = new type("tag:yaml.org,2002:null", { - kind: "scalar", - resolve: resolveYamlNull, - construct: constructYamlNull, - predicate: isNull, - represent: { - canonical: function() { - return "~"; - }, - lowercase: function() { - return "null"; - }, - uppercase: function() { - return "NULL"; - }, - camelcase: function() { - return "Null"; - }, - empty: function() { - return ""; - } - }, - defaultStyle: "lowercase" + }; +}); +var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def.value > curr) { + if (def.inclusive) + bag.minimum = def.value; + else + bag.exclusiveMinimum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { + return; + } + payload.issues.push({ + origin, + code: "too_small", + minimum: def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort }); - bool = new type("tag:yaml.org,2002:bool", { - kind: "scalar", - resolve: resolveYamlBoolean, - construct: constructYamlBoolean, - predicate: isBoolean, - represent: { - lowercase: function(object3) { - return object3 ? "true" : "false"; - }, - uppercase: function(object3) { - return object3 ? "TRUE" : "FALSE"; - }, - camelcase: function(object3) { - return object3 ? "True" : "False"; - } - }, - defaultStyle: "lowercase" + }; +}); +var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst2) => { + var _a; + (_a = inst2._zod.bag).multipleOf ?? (_a.multipleOf = def.value); + }); + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder2(payload.value, def.value) === 0; + if (isMultiple) + return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def.value, + input: payload.value, + inst, + continue: !def.abort }); - int2 = new type("tag:yaml.org,2002:int", { - kind: "scalar", - resolve: resolveYamlInteger, - construct: constructYamlInteger, - predicate: isInteger, - represent: { - binary: function(obj) { - return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1); - }, - octal: function(obj) { - return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1); - }, - decimal: function(obj) { - return obj.toString(10); - }, - /* eslint-disable max-len */ - hexadecimal: function(obj) { - return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1); + }; +}); +var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) + bag.pattern = integer; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) { + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + input, + inst + }); + return; + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + continue: !def.abort + }); + } else { + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + continue: !def.abort + }); } - }, - defaultStyle: "decimal", - styleAliases: { - binary: [2, "bin"], - octal: [8, "oct"], - decimal: [10, "dec"], - hexadecimal: [16, "hex"] + return; } + } + if (input < minimum) { + payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inst + }); + } + }; +}); +var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; + if (def.maximum < curr) + inst2._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length <= def.maximum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort }); - YAML_FLOAT_PATTERN = new RegExp( - // 2.5e4, 2.5 and integers - "^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$" - ); - SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - float = new type("tag:yaml.org,2002:float", { - kind: "scalar", - resolve: resolveYamlFloat, - construct: constructYamlFloat, - predicate: isFloat, - represent: representYamlFloat, - defaultStyle: "lowercase" - }); - json = failsafe.extend({ - implicit: [ - _null4, - bool, - int2, - float - ] - }); - core = json; - YAML_DATE_REGEXP = new RegExp( - "^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$" - ); - YAML_TIMESTAMP_REGEXP = new RegExp( - "^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$" - ); - timestamp = new type("tag:yaml.org,2002:timestamp", { - kind: "scalar", - resolve: resolveYamlTimestamp, - construct: constructYamlTimestamp, - instanceOf: Date, - represent: representYamlTimestamp - }); - merge2 = new type("tag:yaml.org,2002:merge", { - kind: "scalar", - resolve: resolveYamlMerge - }); - BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r"; - binary = new type("tag:yaml.org,2002:binary", { - kind: "scalar", - resolve: resolveYamlBinary, - construct: constructYamlBinary, - predicate: isBinary, - represent: representYamlBinary - }); - _hasOwnProperty$3 = Object.prototype.hasOwnProperty; - _toString$2 = Object.prototype.toString; - omap = new type("tag:yaml.org,2002:omap", { - kind: "sequence", - resolve: resolveYamlOmap, - construct: constructYamlOmap + }; +}); +var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; + if (def.minimum > curr) + inst2._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length >= def.minimum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort }); - _toString$1 = Object.prototype.toString; - pairs = new type("tag:yaml.org,2002:pairs", { - kind: "sequence", - resolve: resolveYamlPairs, - construct: constructYamlPairs + }; +}); +var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length === def.length) + return; + const origin = getLengthableOrigin(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }, + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort }); - _hasOwnProperty$2 = Object.prototype.hasOwnProperty; - set = new type("tag:yaml.org,2002:set", { - kind: "mapping", - resolve: resolveYamlSet, - construct: constructYamlSet + }; +}); +var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { + var _a, _b; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(def.pattern); + } + }); + if (def.pattern) + (_a = inst._zod).check ?? (_a.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...def.pattern ? { pattern: def.pattern.toString() } : {}, + inst, + continue: !def.abort + }); }); - _default2 = core.extend({ - implicit: [ - timestamp, - merge2 - ], - explicit: [ - binary, - omap, - pairs, - set - ] + else + (_b = inst._zod).check ?? (_b.check = () => { }); - _hasOwnProperty$1 = Object.prototype.hasOwnProperty; - CONTEXT_FLOW_IN = 1; - CONTEXT_FLOW_OUT = 2; - CONTEXT_BLOCK_IN = 3; - CONTEXT_BLOCK_OUT = 4; - CHOMPING_CLIP = 1; - CHOMPING_STRIP = 2; - CHOMPING_KEEP = 3; - PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; - PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; - PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; - PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; - PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; - simpleEscapeCheck = new Array(256); - simpleEscapeMap = new Array(256); - for (i2 = 0; i2 < 256; i2++) { - simpleEscapeCheck[i2] = simpleEscapeSequence(i2) ? 1 : 0; - simpleEscapeMap[i2] = simpleEscapeSequence(i2); - } - directiveHandlers = { - YAML: function handleYamlDirective(state, name315, args) { - var match, major, minor; - if (state.version !== null) { - throwError(state, "duplication of %YAML directive"); - } - if (args.length !== 1) { - throwError(state, "YAML directive accepts exactly one argument"); - } - match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); - if (match === null) { - throwError(state, "ill-formed argument of the YAML directive"); - } - major = parseInt(match[1], 10); - minor = parseInt(match[2], 10); - if (major !== 1) { - throwError(state, "unacceptable YAML version of the document"); - } - state.version = args[0]; - state.checkLineBreaks = minor < 2; - if (minor !== 1 && minor !== 2) { - throwWarning(state, "unsupported YAML version of the document"); - } - }, - TAG: function handleTagDirective(state, name315, args) { - var handle, prefix; - if (args.length !== 2) { - throwError(state, "TAG directive accepts exactly two arguments"); - } - handle = args[0]; - prefix = args[1]; - if (!PATTERN_TAG_HANDLE.test(handle)) { - throwError(state, "ill-formed tag handle (first argument) of the TAG directive"); - } - if (_hasOwnProperty$1.call(state.tagMap, handle)) { - throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); - } - if (!PATTERN_TAG_URI.test(prefix)) { - throwError(state, "ill-formed tag prefix (second argument) of the TAG directive"); - } - try { - prefix = decodeURIComponent(prefix); - } catch (err) { - throwError(state, "tag prefix is malformed: " + prefix); - } - state.tagMap[handle] = prefix; - } - }; - loadAll_1 = loadAll$1; - load_1 = load$1; - loader = { - loadAll: loadAll_1, - load: load_1 - }; - _toString = Object.prototype.toString; - _hasOwnProperty = Object.prototype.hasOwnProperty; - CHAR_BOM = 65279; - CHAR_TAB = 9; - CHAR_LINE_FEED = 10; - CHAR_CARRIAGE_RETURN = 13; - CHAR_SPACE = 32; - CHAR_EXCLAMATION = 33; - CHAR_DOUBLE_QUOTE = 34; - CHAR_SHARP = 35; - CHAR_PERCENT = 37; - CHAR_AMPERSAND = 38; - CHAR_SINGLE_QUOTE = 39; - CHAR_ASTERISK = 42; - CHAR_COMMA = 44; - CHAR_MINUS = 45; - CHAR_COLON = 58; - CHAR_EQUALS = 61; - CHAR_GREATER_THAN = 62; - CHAR_QUESTION = 63; - CHAR_COMMERCIAL_AT = 64; - CHAR_LEFT_SQUARE_BRACKET = 91; - CHAR_RIGHT_SQUARE_BRACKET = 93; - CHAR_GRAVE_ACCENT = 96; - CHAR_LEFT_CURLY_BRACKET = 123; - CHAR_VERTICAL_LINE = 124; - CHAR_RIGHT_CURLY_BRACKET = 125; - ESCAPE_SEQUENCES = {}; - ESCAPE_SEQUENCES[0] = "\\0"; - ESCAPE_SEQUENCES[7] = "\\a"; - ESCAPE_SEQUENCES[8] = "\\b"; - ESCAPE_SEQUENCES[9] = "\\t"; - ESCAPE_SEQUENCES[10] = "\\n"; - ESCAPE_SEQUENCES[11] = "\\v"; - ESCAPE_SEQUENCES[12] = "\\f"; - ESCAPE_SEQUENCES[13] = "\\r"; - ESCAPE_SEQUENCES[27] = "\\e"; - ESCAPE_SEQUENCES[34] = '\\"'; - ESCAPE_SEQUENCES[92] = "\\\\"; - ESCAPE_SEQUENCES[133] = "\\N"; - ESCAPE_SEQUENCES[160] = "\\_"; - ESCAPE_SEQUENCES[8232] = "\\L"; - ESCAPE_SEQUENCES[8233] = "\\P"; - DEPRECATED_BOOLEANS_SYNTAX = [ - "y", - "Y", - "yes", - "Yes", - "YES", - "on", - "On", - "ON", - "n", - "N", - "no", - "No", - "NO", - "off", - "Off", - "OFF" - ]; - DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; - QUOTING_TYPE_SINGLE = 1; - QUOTING_TYPE_DOUBLE = 2; - STYLE_PLAIN = 1; - STYLE_SINGLE = 2; - STYLE_LITERAL = 3; - STYLE_FOLDED = 4; - STYLE_DOUBLE = 5; - dump_1 = dump$1; - dumper = { - dump: dump_1 - }; - load = loader.load; - loadAll = loader.loadAll; - dump = dumper.dump; - safeLoad = renamed("safeLoad", "load"); - safeLoadAll = renamed("safeLoadAll", "loadAll"); - safeDump = renamed("safeDump", "dump"); - } }); - -// packages/validation/dist/audit-flags/helpers.js -var init_helpers2 = __esm({ - "packages/validation/dist/audit-flags/helpers.js"() { - "use strict"; - } +var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort + }); + }; }); - -// packages/validation/dist/audit-flags/pipeline-ops.js -var init_pipeline_ops = __esm({ - "packages/validation/dist/audit-flags/pipeline-ops.js"() { - "use strict"; - init_helpers2(); - } +var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def); }); - -// packages/validation/dist/audit-flags/engine.js -var init_engine = __esm({ - "packages/validation/dist/audit-flags/engine.js"() { - "use strict"; - init_js_yaml(); - init_helpers2(); - init_pipeline_ops(); - } +var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def); }); - -// packages/validation/dist/audit-flags/index.js -var init_audit_flags = __esm({ - "packages/validation/dist/audit-flags/index.js"() { - "use strict"; - init_engine(); - } +var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = escapeRegex(def.includes); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; }); -// packages/validation/dist/index.js -var init_dist2 = __esm({ - async "packages/validation/dist/index.js"() { - "use strict"; - await init_hard_output_rules(); - init_cross_ref_validator(); - init_audit_flags(); +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/doc.js +var Doc = class { + constructor(args = []) { + this.content = []; + this.indent = 0; + if (this) + this.args = args; } -}); + indented(fn) { + this.indent += 1; + fn(this); + this.indent -= 1; + } + write(arg2) { + if (typeof arg2 === "function") { + arg2(this, { execution: "sync" }); + arg2(this, { execution: "async" }); + return; + } + const content = arg2; + const lines = content.split("\n").filter((x) => x); + const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); + const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + for (const line of dedented) { + this.content.push(line); + } + } + compile() { + const F = Function; + const args = this?.args; + const content = this?.content ?? [``]; + const lines = [...content.map((x) => ` ${x}`)]; + return new F(...args, lines.join("\n")); + } +}; -// packages/strategy/dist/research-evidence-database.js -var TIER_1_EVIDENCE, TIER_2_EVIDENCE, TIER_3_EVIDENCE, TIER_4_EVIDENCE, ALL_EVIDENCE, ResearchEvidenceDatabase; -var init_research_evidence_database = __esm({ - async "packages/strategy/dist/research-evidence-database.js"() { - "use strict"; - await init_dist(); - TIER_1_EVIDENCE = [ - { - strategy: "recursive_refinement", - tier: 1, - improvementPercent: 0.32, - claimCharacteristics: [ - "mathematical_reasoning", - "multi_step_logic", - "complex_technical", - "iterative_refinement", - "high_precision" - ], - source: "DeepSeek (2025) \u2014 DeepSeek-R1: Incentivizing Reasoning Capability in LLMs", - citation: "arXiv:2501.12948" - }, - { - strategy: "recursive_refinement", - tier: 1, - improvementPercent: 0.74, - claimCharacteristics: [ - "mathematical_reasoning", - "multi_step_logic", - "self_correction", - "high_precision" - ], - source: "OpenAI (2024) \u2014 Learning to Reason with LLMs", - citation: "OpenAI technical report (non-peer-reviewed)" - }, - { - strategy: "verified_reasoning", - tier: 1, - improvementPercent: 0.18, - claimCharacteristics: [ - "accuracy_critical", - "fact_verification", - "consistency_check", - "high_precision" - ], - source: "Stanford/Anthropic (2024) \u2014 Chain-of-Verification Reduces Hallucination in LLMs", - citation: "Stanford/Anthropic 2024" - }, - { - strategy: "graph_of_thoughts", - tier: 1, - improvementPercent: 0.62, - claimCharacteristics: [ - "dependency_analysis", - "cross_reference", - "structural_reasoning", - "complex_technical" - ], - source: "ETH Zurich (2024) \u2014 Graph of Thoughts: Solving Elaborate Problems with LLMs", - citation: "arXiv:2308.09687" - }, - { - strategy: "self_consistency", - tier: 1, - improvementPercent: 0.179, - claimCharacteristics: [ - "mathematical_reasoning", - "multiple_approaches", - "consistency_check", - "uncertainty_handling" - ], - source: "Google Research (2023) \u2014 Self-Consistency Improves Chain of Thought Reasoning", - citation: "arXiv:2203.11171" - }, - { - strategy: "reflexion", - tier: 1, - improvementPercent: 0.21, - claimCharacteristics: [ - "iterative_refinement", - "self_correction", - "quality_improvement", - "code_generation" - ], - source: "MIT/Northeastern (2023) \u2014 Reflexion: Language Agents with Verbal Reinforcement Learning", - citation: "arXiv:2303.11366" - }, - { - strategy: "problem_analysis", - tier: 1, - improvementPercent: 0.24, - claimCharacteristics: [ - "complex_technical", - "multi_dimensional", - "structural_reasoning", - "risk_analysis" - ], - source: "Harvard/MIT (2024) \u2014 Structured Decomposition Outperforms Linear Reasoning", - citation: "Harvard/MIT 2024" +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/versions.js +var version = { + major: 4, + minor: 0, + patch: 0 +}; + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/schemas.js +var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { + var _a; + inst ?? (inst = {}); + inst._zod.def = def; + inst._zod.bag = inst._zod.bag || {}; + inst._zod.version = version; + const checks = [...inst._zod.def.checks ?? []]; + if (inst._zod.traits.has("$ZodCheck")) { + checks.unshift(inst); + } + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + if (checks.length === 0) { + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } else { + const runChecks = (payload, checks2, ctx) => { + let isAborted2 = aborted(payload); + let asyncResult; + for (const ch of checks2) { + if (ch._zod.def.when) { + const shouldRun = ch._zod.def.when(payload); + if (!shouldRun) + continue; + } else if (isAborted2) { + continue; + } + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) { + throw new $ZodAsyncError(); + } + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload.issues.length; + if (nextLen === currLen) + return; + if (!isAborted2) + isAborted2 = aborted(payload, currLen); + }); + } else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + if (!isAborted2) + isAborted2 = aborted(payload, currLen); + } } - ]; - TIER_2_EVIDENCE = [ - { - strategy: "tree_of_thoughts", - tier: 2, - improvementPercent: 0.74, - claimCharacteristics: [ - "exploratory_reasoning", - "multiple_approaches", - "creative_problems", - "branch_exploration" - ], - source: "Princeton/Google DeepMind (2024) \u2014 Tree of Thoughts: Deliberate Problem Solving with LLMs", - citation: "arXiv:2305.10601" - }, - { - strategy: "react", - tier: 2, - improvementPercent: 0.27, - claimCharacteristics: [ - "codebase_integration", - "tool_use", - "external_knowledge", - "cross_reference" - ], - source: "Princeton/Google (2023) \u2014 ReAct: Synergizing Reasoning and Acting in Language Models", - citation: "arXiv:2210.03629" - }, - { - strategy: "meta_prompting", - tier: 2, - improvementPercent: 0.171, - claimCharacteristics: [ - "complex_technical", - "multi_step_logic", - "role_based_reasoning", - "expert_orchestration" - ], - source: "Stanford (2024) \u2014 Meta-Prompting: Enhancing Language Models with Task-Agnostic Scaffolding", - citation: "Stanford 2024" - }, - { - strategy: "plan_and_solve", - tier: 2, - improvementPercent: 0.058, - claimCharacteristics: [ - "multi_step_logic", - "sequential_planning", - "structural_reasoning" - ], - source: "NUS (2023) \u2014 Plan-and-Solve Prompting: Improving Zero-Shot CoT", - citation: "arXiv:2305.04091" + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); } - ]; - TIER_3_EVIDENCE = [ - { - strategy: "few_shot", - tier: 3, - improvementPercent: 0.25, - claimCharacteristics: [ - "pattern_matching", - "domain_specific", - "example_based" - ], - source: "OpenAI (2020) \u2014 Language Models are Few-Shot Learners", - citation: "arXiv:2005.14165" - }, - { - strategy: "generate_knowledge", - tier: 3, - improvementPercent: 0.15, - claimCharacteristics: [ - "domain_knowledge", - "fact_generation", - "commonsense_reasoning" - ], - source: "AI2 (2022) \u2014 Generated Knowledge Prompting for Commonsense Reasoning", - citation: "arXiv:2110.08387" - }, - { - strategy: "multimodal_cot", - tier: 3, - improvementPercent: 0.16, - claimCharacteristics: [ - "visual_reasoning", - "multimodal", - "diagram_analysis" - ], - source: "Amazon/UCLA (2023) \u2014 Multimodal Chain-of-Thought Reasoning", - citation: "arXiv:2302.00923" + return payload; + }; + inst._zod.run = (payload, ctx) => { + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return result.then((result2) => runChecks(result2, checks, ctx)); } - ]; - TIER_4_EVIDENCE = [ - { - strategy: "chain_of_thought", - tier: 4, - improvementPercent: 0, - claimCharacteristics: ["basic_reasoning"], - source: "Google/DeepMind (2024) \u2014 Chain-of-Thought Reasoning Without Prompting", - citation: "arXiv:2402.10200" - }, - { - strategy: "zero_shot", - tier: 4, - improvementPercent: 0, - claimCharacteristics: [], - source: "Various (2023) \u2014 Baseline comparison meta-analysis", - citation: "Various 2023" + return runChecks(result, checks, ctx); + }; + } + inst["~standard"] = { + validate: (value) => { + try { + const r = safeParse(inst, value); + return r.success ? { value: r.data } : { issues: r.error?.issues }; + } catch (_) { + return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); } - ]; - ALL_EVIDENCE = [ - ...TIER_1_EVIDENCE, - ...TIER_2_EVIDENCE, - ...TIER_3_EVIDENCE, - ...TIER_4_EVIDENCE - ]; - ResearchEvidenceDatabase = class { - evidence = ALL_EVIDENCE; - getEvidence(strategy) { - return this.evidence.filter((e3) => e3.strategy === strategy); - } - getBestEvidence(strategy) { - return this.getEvidence(strategy).sort((a, b) => b.improvementPercent - a.improvementPercent)[0]; - } - getTier(strategy) { - const first = this.evidence.find((e3) => e3.strategy === strategy); - return first?.tier; - } - getStrategiesInTier(tier) { - const seen = /* @__PURE__ */ new Set(); - for (const e3 of this.evidence) { - if (e3.tier === tier) - seen.add(e3.strategy); - } - return [...seen]; - } - getMatchingStrategies(characteristics) { - const charSet = new Set(characteristics); - return this.evidence.filter((e3) => e3.claimCharacteristics.some((c) => charSet.has(c))).sort((a, b) => { - if (a.tier !== b.tier) - return a.tier - b.tier; - return b.improvementPercent - a.improvementPercent; - }); + }, + vendor: "zod", + version: 1 + }; +}); +var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } catch (_2) { } - calculateScore(strategy, characteristics) { - const matching = this.getEvidence(strategy); - if (matching.length === 0) - return 0; - let totalScore = 0; - for (const ev of matching) { - const evChars = new Set(ev.claimCharacteristics); - let overlap = 0; - for (const c of characteristics) { - if (evChars.has(c)) - overlap++; - } - const overlapRatio = overlap / Math.max(1, ev.claimCharacteristics.length); - const tierWeight = STRATEGY_TIERS[ev.tier].selectionWeight; - totalScore += ev.improvementPercent * tierWeight * (0.5 + 0.5 * overlapRatio); + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; +}); +var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); +}); +var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = guid); + $ZodStringFormat.init(inst, def); +}); +var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => { + if (def.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8 + }; + const v = versionMap[def.version]; + if (v === void 0) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid(v)); + } else + def.pattern ?? (def.pattern = uuid()); + $ZodStringFormat.init(inst, def); +}); +var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = email); + $ZodStringFormat.init(inst, def); +}); +var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + const orig = payload.value; + const url = new URL(orig); + const href = url.href; + if (def.hostname) { + def.hostname.lastIndex = 0; + if (!def.hostname.test(url.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: hostname.source, + input: payload.value, + inst, + continue: !def.abort + }); } - return totalScore / matching.length; } - getCitations(strategy) { - return this.getEvidence(strategy).map((e3) => e3.citation); - } - getAllStrategies() { - const seen = /* @__PURE__ */ new Set(); - for (const e3 of this.evidence) { - seen.add(e3.strategy); + if (def.protocol) { + def.protocol.lastIndex = 0; + if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); } - return [...seen]; } - getAllEvidence() { - return this.evidence; + if (!orig.endsWith("/") && href.endsWith("/")) { + payload.value = href.slice(0, -1); + } else { + payload.value = href; } - }; - } + return; + } catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; }); - -// packages/strategy/dist/claim-analyzer.js -function containsAny(text, patterns) { - return patterns.some((p) => text.includes(p)); -} -function detectReasoningComplexity(text) { - const characteristics = /* @__PURE__ */ new Set(); - const notes = []; - if (containsAny(text, ["calculate", "compute", "formula", "equation", "math"])) { - characteristics.add("mathematical_reasoning"); - notes.push("Mathematical reasoning detected"); - } - if (containsAny(text, ["step", "sequence", "then", "after", "before", "process"])) { - characteristics.add("multi_step_logic"); - characteristics.add("sequential_planning"); - } - if (containsAny(text, ["technical", "architecture", "system", "implementation", "api", "database"])) { - characteristics.add("complex_technical"); - notes.push("Technical domain content"); - } - if (containsAny(text, ["precise", "exact", "accurate", "critical", "must", "shall"])) { - characteristics.add("high_precision"); - characteristics.add("accuracy_critical"); - } - return { characteristics, notes }; -} -function detectStructurePatterns(text) { - const characteristics = /* @__PURE__ */ new Set(); - if (containsAny(text, ["depend", "relationship", "connect", "link", "reference"])) { - characteristics.add("dependency_analysis"); - characteristics.add("cross_reference"); - } - if (containsAny(text, ["structure", "hierarchy", "organize", "component", "module"])) { - characteristics.add("structural_reasoning"); +var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = emoji()); + $ZodStringFormat.init(inst, def); +}); +var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { + def.pattern ?? (def.pattern = nanoid); + $ZodStringFormat.init(inst, def); +}); +var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = cuid); + $ZodStringFormat.init(inst, def); +}); +var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = cuid2); + $ZodStringFormat.init(inst, def); +}); +var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = ulid); + $ZodStringFormat.init(inst, def); +}); +var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = xid); + $ZodStringFormat.init(inst, def); +}); +var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = ksuid); + $ZodStringFormat.init(inst, def); +}); +var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = datetime(def)); + $ZodStringFormat.init(inst, def); +}); +var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = date); + $ZodStringFormat.init(inst, def); +}); +var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = time(def)); + $ZodStringFormat.init(inst, def); +}); +var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = duration); + $ZodStringFormat.init(inst, def); +}); +var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = ipv4); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = `ipv4`; + }); +}); +var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = ipv6); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = `ipv6`; + }); + inst._zod.check = (payload) => { + try { + new URL(`http://[${payload.value}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; +}); +var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = cidrv4); + $ZodStringFormat.init(inst, def); +}); +var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = cidrv6); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + const [address, prefix] = payload.value.split("/"); + try { + if (!prefix) + throw new Error(); + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + throw new Error(); + if (prefixNum < 0 || prefixNum > 128) + throw new Error(); + new URL(`http://[${address}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; +}); +function isValidBase64(data) { + if (data === "") + return true; + if (data.length % 4 !== 0) + return false; + try { + atob(data); + return true; + } catch { + return false; } - return characteristics; } -function detectExplorationPatterns(text) { - const characteristics = /* @__PURE__ */ new Set(); - const notes = []; - if (containsAny(text, ["explore", "alternative", "option", "approach", "possibility"])) { - characteristics.add("exploratory_reasoning"); - characteristics.add("multiple_approaches"); - characteristics.add("branch_exploration"); - } - if (containsAny(text, ["creative", "innovative", "novel", "design"])) { - characteristics.add("creative_problems"); - } - if (containsAny(text, ["uncertain", "unclear", "ambiguous", "complex", "difficult"])) { - characteristics.add("uncertainty_handling"); - notes.push("High uncertainty detected"); - } - return { characteristics, notes }; -} -function detectVerificationNeeds(text) { - const characteristics = /* @__PURE__ */ new Set(); - if (containsAny(text, ["verify", "validate", "check", "ensure", "confirm"])) { - characteristics.add("fact_verification"); - characteristics.add("consistency_check"); - } - if (containsAny(text, ["risk", "threat", "vulnerability", "issue", "problem"])) { - characteristics.add("risk_analysis"); - } - return characteristics; -} -function detectDomainPatterns(text) { - const characteristics = /* @__PURE__ */ new Set(); - const notes = []; - if (containsAny(text, ["codebase", "repository", "existing code", "current system"])) { - characteristics.add("codebase_integration"); - characteristics.add("tool_use"); - notes.push("Codebase integration required"); - } - if (containsAny(text, ["example", "sample", "template", "pattern"])) { - characteristics.add("pattern_matching"); - characteristics.add("example_based"); - } - if (containsAny(text, ["code", "function", "class", "method", "implement"])) { - characteristics.add("code_generation"); - } - return { characteristics, notes }; -} -function detectIterativePatterns(text) { - const characteristics = /* @__PURE__ */ new Set(); - if (containsAny(text, ["refine", "improve", "iterate", "enhance", "optimize"])) { - characteristics.add("iterative_refinement"); - characteristics.add("quality_improvement"); - } - if (containsAny(text, ["correct", "fix", "revise", "update"])) { - characteristics.add("self_correction"); - } - return characteristics; -} -function detectExternalDependencies(text) { - const characteristics = /* @__PURE__ */ new Set(); - if (containsAny(text, ["search", "find", "lookup", "retrieve", "fetch"])) { - characteristics.add("external_knowledge"); - characteristics.add("tool_use"); - } - return characteristics; -} -function detectSpecialModes(text) { - const characteristics = /* @__PURE__ */ new Set(); - const notes = []; - if (containsAny(text, ["image", "visual", "diagram", "mockup", "screenshot", "ui"])) { - characteristics.add("visual_reasoning"); - characteristics.add("multimodal"); - characteristics.add("diagram_analysis"); - notes.push("Visual content processing needed"); - } - if (containsAny(text, ["perspective", "role", "stakeholder", "expert"])) { - characteristics.add("role_based_reasoning"); - characteristics.add("expert_orchestration"); - } - return { characteristics, notes }; -} -function calculateComplexityScore(characteristics, text) { - let score = characteristics.size * 0.05; - for (const c of characteristics) { - if (HIGH_COMPLEXITY_CHARS.has(c)) { - score += 0.12; - } else if (MEDIUM_COMPLEXITY_CHARS.has(c)) { - score += 0.08; - } else { - score += 0.04; - } - } - const wordCount = text.split(/\s+/).length; - score += Math.min(0.15, wordCount / 500); - return Math.min(1, score); -} -function complexityTierFromScore(score) { - if (score >= 0.6) - return "complex"; - if (score >= 0.3) - return "moderate"; - return "simple"; -} -function analyzeClaim(claim, context) { - const text = (claim + " " + (context ?? "")).toLowerCase(); - const reasoning = detectReasoningComplexity(text); - const structure = detectStructurePatterns(text); - const exploration = detectExplorationPatterns(text); - const verification = detectVerificationNeeds(text); - const domain = detectDomainPatterns(text); - const iterative = detectIterativePatterns(text); - const external2 = detectExternalDependencies(text); - const special = detectSpecialModes(text); - const characteristics = /* @__PURE__ */ new Set(); - for (const set2 of [ - reasoning.characteristics, - structure, - exploration.characteristics, - verification, - domain.characteristics, - iterative, - external2, - special.characteristics - ]) { - for (const c of set2) - characteristics.add(c); - } - if (characteristics.size === 0) { - characteristics.add("basic_reasoning"); - } - const notes = [ - ...reasoning.notes, - ...exploration.notes, - ...domain.notes, - ...special.notes - ]; - const complexityScore = calculateComplexityScore(characteristics, text); - return { - claim, - // Persisted as a deduplicated array. Set semantics recovered via - // `characteristicSet(...)` or `characteristics.includes(...)` at use sites. - characteristics: [...characteristics], - complexityScore, - complexityTier: complexityTierFromScore(complexityScore), - analysisNotes: notes +var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = base64); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst2) => { + inst2._zod.bag.contentEncoding = "base64"; + }); + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort + }); }; +}); +function isValidBase64URL(data) { + if (!base64url.test(data)) + return false; + const base642 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); + const padded = base642.padEnd(Math.ceil(base642.length / 4) * 4, "="); + return isValidBase64(padded); } -var ClaimAnalysisResultSchema, HIGH_COMPLEXITY_CHARS, MEDIUM_COMPLEXITY_CHARS; -var init_claim_analyzer = __esm({ - "packages/strategy/dist/claim-analyzer.js"() { - "use strict"; - init_zod(); - ClaimAnalysisResultSchema = external_exports.object({ - claim: external_exports.string(), - characteristics: external_exports.array(external_exports.string()), - complexityScore: external_exports.number(), - complexityTier: external_exports.enum(["simple", "moderate", "complex"]), - analysisNotes: external_exports.array(external_exports.string()) +var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = base64url); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst2) => { + inst2._zod.bag.contentEncoding = "base64url"; + }); + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort }); - HIGH_COMPLEXITY_CHARS = /* @__PURE__ */ new Set([ - "mathematical_reasoning", - "complex_technical", - "dependency_analysis", - "multi_dimensional", - "accuracy_critical", - "risk_analysis", - "codebase_integration", - "iterative_refinement" - ]); - MEDIUM_COMPLEXITY_CHARS = /* @__PURE__ */ new Set([ - "multi_step_logic", - "cross_reference", - "structural_reasoning", - "exploratory_reasoning", - "multiple_approaches", - "uncertainty_handling", - "fact_verification", - "self_correction" - ]); + }; +}); +var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = e164); + $ZodStringFormat.init(inst, def); +}); +function isValidJWT2(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + if (!header) + return false; + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") + return false; + if (!parsedHeader.alg) + return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) + return false; + return true; + } catch { + return false; } +} +var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidJWT2(payload.value, def.alg)) + return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort + }); + }; }); - -// packages/strategy/dist/selector.js -function scoreStrategies(characteristics, historicalAdjustments, overlapWeight, minimumThreshold) { - const allStrategies = db.getAllStrategies(); - const scored = []; - for (const strategy of allStrategies) { - const tier = db.getTier(strategy); - if (tier === void 0) - continue; - const evidence = db.getEvidence(strategy); - if (evidence.length === 0) - continue; - let totalOverlap = 0; - let weightedImprovement = 0; - for (const ev of evidence) { - const evChars = new Set(ev.claimCharacteristics); - let overlap = 0; - for (const c of characteristics) { - if (evChars.has(c)) - overlap++; +var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Number(payload.value); + } catch (_) { } - totalOverlap += overlap; - const overlapRatio = overlap / Math.max(1, ev.claimCharacteristics.length); - weightedImprovement += ev.improvementPercent * (overlapWeight * overlapRatio + (1 - overlapWeight)); + const input = payload.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload; } - const avgImprovement = weightedImprovement / evidence.length; - if (avgImprovement < minimumThreshold && tier !== 1) - continue; - const overlapFactor = 1 + totalOverlap / Math.max(1, characteristics.size); - let score = STRATEGY_TIERS[tier].selectionWeight * avgImprovement * overlapFactor; - const adjustment = historicalAdjustments.get(strategy) ?? 0; - const clampedAdjustment = Math.max(-0.3, Math.min(0.3, adjustment)); - score = score * (1 + clampedAdjustment); - scored.push({ strategy, score, tier, improvement: avgImprovement, overlapCount: totalOverlap }); + const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...received ? { received } : {} + }); + return payload; + }; +}); +var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { + $ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); +}); +var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = boolean; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Boolean(payload.value); + } catch (_) { + } + const input = payload.value; + if (typeof input === "boolean") + return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _null; + inst._zod.values = /* @__PURE__ */ new Set([null]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input === null) + return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; +}); +function handleArrayResult(result, final, index2) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index2, result.issues)); } - return scored.sort((a, b) => { - if (a.tier !== b.tier) - return a.tier - b.tier; - return b.score - a.score; - }); -} -function applyComplexityConstraints(strategies, complexityTier) { - const maxAllowedTier = complexityTier === "complex" ? 2 : complexityTier === "moderate" ? 3 : 4; - return strategies.filter((s) => s.tier <= maxAllowedTier); + final.value[index2] = result.value; } -function selectRequired(strategies, analysis, maxRequired) { - const required2 = []; - if (analysis.complexityTier === "complex") { - const tier1 = strategies.find((s) => s.tier === 1); - if (tier1) - required2.push(tier1.strategy); - } - const best = strategies[0]; - if (best && !required2.includes(best.strategy)) { - required2.push(best.strategy); - } - if (analysis.characteristics.includes("accuracy_critical") || analysis.characteristics.includes("high_precision")) { - if (!required2.includes("verified_reasoning")) { - required2.push("verified_reasoning"); +var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst + }); + return payload; } - } - if (analysis.characteristics.includes("codebase_integration")) { - if (!required2.includes("react") && !required2.includes("verified_reasoning")) { - required2.push("react"); + payload.value = Array(input.length); + const proms = []; + for (let i2 = 0; i2 < input.length; i2++) { + const item = input[i2]; + const result = def.element._zod.run({ + value: item, + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleArrayResult(result2, payload, i2))); + } else { + handleArrayResult(result, payload, i2); + } } - } - return required2.slice(0, maxRequired); -} -function selectOptional(strategies, required2) { - const reqSet = new Set(required2); - return strategies.filter((s) => !reqSet.has(s.strategy) && s.tier <= 3).slice(0, 3).map((s) => s.strategy); -} -function selectForbidden(complexityTier) { - switch (complexityTier) { - case "complex": - return ["zero_shot", "chain_of_thought"]; - case "moderate": - return ["zero_shot"]; - case "simple": - return []; - } -} -function buildCitations(strategies) { - const citations = []; - for (const strategy of strategies) { - const evidence = db.getEvidence(strategy); - for (const ev of evidence.slice(0, 2)) { - citations.push(ev.citation); + if (proms.length) { + return Promise.all(proms).then(() => payload); } + return payload; + }; +}); +function handleObjectResult(result, final, key) { + if (result.issues.length) { + final.issues.push(...prefixIssues(key, result.issues)); } - return citations; -} -function calculateExpectedImprovement(strategies, characteristics) { - if (strategies.length === 0) - return 0; - const improvements = strategies.map((s) => db.calculateScore(s, characteristics)); - return Math.max(...improvements); + final.value[key] = result.value; } -function calculateAssignmentConfidence(strategies, characteristics, complexityTier) { - let confidence = 0.5; - if (complexityTier === "complex") { - const hasTier1 = strategies.some((s) => db.getTier(s) === 1); - if (hasTier1) - confidence += 0.3; - } - let totalOverlap = 0; - for (const strategy of strategies) { - for (const ev of db.getEvidence(strategy)) { - const evChars = new Set(ev.claimCharacteristics); - for (const c of characteristics) { - if (evChars.has(c)) - totalOverlap++; +function handleOptionalObjectResult(result, final, key, input) { + if (result.issues.length) { + if (input[key] === void 0) { + if (key in input) { + final.value[key] = void 0; + } else { + final.value[key] = result.value; } + } else { + final.issues.push(...prefixIssues(key, result.issues)); } + } else if (result.value === void 0) { + if (key in input) + final.value[key] = void 0; + } else { + final.value[key] = result.value; } - confidence += Math.min(0.2, totalOverlap * 0.02); - return Math.min(1, confidence); } -function selectStrategy(options) { - const { - claim, - context, - hasCodebase = false, - hasMockups = false, - evidenceRepository, - // source: chosen heuristically — overlap dominates over raw expectedImprovement - // because matched claim characteristics correlate more strongly with success - // than abstract improvement claims. Tune from execution history. - overlapWeight = 0.6, - // source: chosen heuristically — strategies whose marginal improvement falls - // below 5 percentage points are filtered as not worth the cost overhead. - // Calibrate against (cost, accuracy_delta) pairs in evidence repository. - minimumImprovementThreshold = 0.05, - maxRequiredStrategies = 3 - } = options; - const analysis = analyzeClaim(claim, context); - const characteristics = new Set(analysis.characteristics); - if (hasCodebase) { - characteristics.add("codebase_integration"); - characteristics.add("tool_use"); - } - if (hasMockups) { - characteristics.add("visual_reasoning"); - characteristics.add("multimodal"); - } - let historicalAdjustments = /* @__PURE__ */ new Map(); - if (evidenceRepository) { - historicalAdjustments = evidenceRepository.getHistoricalAdjustments(); - } - const scored = scoreStrategies(characteristics, historicalAdjustments, overlapWeight, minimumImprovementThreshold); - const allowed = new Set(CAPABILITIES.allowedStrategies); - const allowedScored = scored.filter((s) => allowed.has(s.strategy)); - const constrained = applyComplexityConstraints(allowedScored, analysis.complexityTier); - const enrichedAnalysis = { - ...analysis, - characteristics: [...characteristics] - }; - const required2 = selectRequired(constrained, enrichedAnalysis, maxRequiredStrategies); - const optional2 = selectOptional(constrained, required2); - const forbidden = selectForbidden(analysis.complexityTier); - const allSelected = [...required2, ...optional2]; - const researchCitations = buildCitations(allSelected); - const expectedImprovement = calculateExpectedImprovement(required2, characteristics); - const assignmentConfidence = calculateAssignmentConfidence(required2, characteristics, analysis.complexityTier); - return { - required: required2, - optional: optional2, - forbidden, - expectedImprovement, - assignmentConfidence, - claimAnalysis: enrichedAnalysis, - researchCitations - }; -} -var StrategyAssignmentSchema, db; -var init_selector = __esm({ - async "packages/strategy/dist/selector.js"() { - "use strict"; - await init_dist(); - init_zod(); - await init_research_evidence_database(); - init_claim_analyzer(); - StrategyAssignmentSchema = external_exports.object({ - required: external_exports.array(ThinkingStrategySchema), - optional: external_exports.array(ThinkingStrategySchema), - forbidden: external_exports.array(ThinkingStrategySchema), - expectedImprovement: external_exports.number(), - assignmentConfidence: external_exports.number(), - claimAnalysis: ClaimAnalysisResultSchema, - researchCitations: external_exports.array(external_exports.string()) - }); - db = new ResearchEvidenceDatabase(); - } -}); - -// packages/strategy/dist/effectiveness-tracker.js -var ExecutionResultSchema, EffectivenessTracker; -var init_effectiveness_tracker = __esm({ - async "packages/strategy/dist/effectiveness-tracker.js"() { - "use strict"; - await init_dist(); - init_zod(); - await init_selector(); - ExecutionResultSchema = external_exports.object({ - strategy: ThinkingStrategySchema, - assignment: StrategyAssignmentSchema, - actualConfidenceGain: external_exports.number(), - wasCompliant: external_exports.boolean(), - retryCount: external_exports.number().int().nonnegative(), - prdContext: PRDContextSchema, - sessionId: external_exports.string().optional() - }); - EffectivenessTracker = class { - repository; - constructor(repository) { - this.repository = repository; - } - recordExecution(result) { - const execution = { - strategy: result.strategy, - claimCharacteristics: [...result.assignment.claimAnalysis.characteristics], - complexityTier: result.assignment.claimAnalysis.complexityTier, - expectedImprovement: result.assignment.expectedImprovement, - actualConfidenceGain: result.actualConfidenceGain, - wasCompliant: result.wasCompliant, - retryCount: result.retryCount, - prdContext: result.prdContext - }; - this.repository.recordStrategyExecution(execution, result.sessionId); - } - generateReport(minExecutions = 5) { - const summaries = this.repository.getStrategyPerformance(minExecutions); - const totalMeasurements = summaries.reduce((s, r) => s + r.executionCount, 0); - const averageConfidenceGain = totalMeasurements === 0 ? 0 : summaries.reduce((s, r) => s + r.avgActualGain * r.executionCount, 0) / totalMeasurements; - const overallComplianceRate = totalMeasurements === 0 ? 0 : summaries.reduce((s, r) => s + r.complianceRate * r.executionCount, 0) / totalMeasurements; - const underperforming = summaries.filter((s) => s.performanceDelta < -0.2 * Math.abs(s.avgExpectedImprovement)).map((s) => s.strategy); - const overperforming = summaries.filter((s) => s.performanceDelta > 0.2 * Math.abs(s.avgExpectedImprovement)).map((s) => s.strategy); - return { - totalMeasurements, - averageConfidenceGain, - overallComplianceRate, - underperformingStrategies: underperforming, - overperformingStrategies: overperforming - }; +var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { + $ZodType.init(inst, def); + const _normalized = cached(() => { + const keys = Object.keys(def.shape); + for (const k of keys) { + if (!(def.shape[k] instanceof $ZodType)) { + throw new Error(`Invalid element at key "${k}": expected a Zod schema`); } + } + const okeys = optionalKeys(def.shape); + return { + shape: def.shape, + keys, + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys) }; - } + }); + defineLazy(inst._zod, "propValues", () => { + const shape = def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + for (const v of field.values) + propValues[key].add(v); + } + } + return propValues; + }); + const generateFastpass = (shape) => { + const doc = new Doc(["shape", "payload", "ctx"]); + const normalized = _normalized.value; + const parseStr = (key) => { + const k = esc(key); + return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + }; + doc.write(`const input = payload.value;`); + const ids = /* @__PURE__ */ Object.create(null); + let counter = 0; + for (const key of normalized.keys) { + ids[key] = `key_${counter++}`; + } + doc.write(`const newResult = {}`); + for (const key of normalized.keys) { + if (normalized.optionalKeys.has(key)) { + const id = ids[key]; + doc.write(`const ${id} = ${parseStr(key)};`); + const k = esc(key); + doc.write(` + if (${id}.issues.length) { + if (input[${k}] === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + payload.issues = payload.issues.concat( + ${id}.issues.map((iss) => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}], + })) + ); + } + } else if (${id}.value === undefined) { + if (${k} in input) newResult[${k}] = undefined; + } else { + newResult[${k}] = ${id}.value; + } + `); + } else { + const id = ids[key]; + doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(` + if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}] + })));`); + doc.write(`newResult[${esc(key)}] = ${id}.value`); + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + const fn = doc.compile(); + return (payload, ctx) => fn(shape, payload, ctx); + }; + let fastpass; + const isObject4 = isObject; + const jit = !globalConfig.jitless; + const allowsEval2 = allowsEval; + const fastEnabled = jit && allowsEval2.value; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject4(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + if (!fastpass) + fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + } else { + payload.value = {}; + const shape = value.shape; + for (const key of value.keys) { + const el = shape[key]; + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional"; + if (r instanceof Promise) { + proms.push(r.then((r2) => isOptional ? handleOptionalObjectResult(r2, payload, key, input) : handleObjectResult(r2, payload, key))); + } else if (isOptional) { + handleOptionalObjectResult(r, payload, key, input); + } else { + handleObjectResult(r, payload, key); + } + } + } + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + const unrecognized = []; + const keySet = value.keySet; + const _catchall = catchall._zod; + const t = _catchall.def.type; + for (const key of Object.keys(input)) { + if (keySet.has(key)) + continue; + if (t === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r2) => handleObjectResult(r2, payload, key))); + } else { + handleObjectResult(r, payload, key); + } + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); + }; }); - -// packages/strategy/dist/index.js -var init_dist3 = __esm({ - async "packages/strategy/dist/index.js"() { - "use strict"; - await init_research_evidence_database(); - await init_selector(); - init_claim_analyzer(); - await init_effectiveness_tracker(); +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } } -}); - -// packages/orchestration/dist/types/state.js -function newPipelineState(input) { - const now = (/* @__PURE__ */ new Date()).toISOString(); - return PipelineStateSchema.parse({ - run_id: input.run_id, - current_step: "banner", - prd_context: null, - feature_description: input.feature_description, - codebase_path: input.codebase_path ?? null, - codebase_graph_path: null, - codebase_output_dir: null, - codebase_indexed: false, - preflight_status: input.skip_preflight ? "skipped" : null, - sections: [], - clarifications: [], - proceed_signal: false, - started_at: now, - updated_at: now, - errors: [], - written_files: [], - verification_plan: null, - strategy_executions: [] + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) }); + return final; } -function touch(state) { - return { ...state, updated_at: (/* @__PURE__ */ new Date()).toISOString() }; -} -function appendError(state, message, kind) { - return { - ...state, - errors: [...state.errors, message], - error_kinds: [...state.error_kinds, kind] - }; -} -var PipelineStepSchema, SectionStatusSchema, ClarificationTurnSchema, VerificationPlanSnapshotSchema, PipelineStateSchema; -var init_state = __esm({ - async "packages/orchestration/dist/types/state.js"() { - "use strict"; - init_zod(); - await init_dist(); - await init_dist3(); - PipelineStepSchema = external_exports.enum([ - "banner", - "preflight", - "context_detection", - "input_analysis", - "feasibility_gate", - "clarification", - "budget", - "section_generation", - "jira_generation", - "file_export", - "self_check", - "complete" - ]); - SectionStatusSchema = external_exports.object({ - section_type: SectionTypeSchema, - status: external_exports.enum([ - "pending", - "retrieving", - "generating", - "passed", - "failed" - ]), - attempt: external_exports.number().int().nonnegative(), - violation_count: external_exports.number().int().nonnegative(), - last_violations: external_exports.array(external_exports.string()).default([]), - /** Markdown content of the section — populated after generation passes validation */ - content: external_exports.string().optional(), - /** - * Strategy assignment chosen by `@prd-gen/strategy.selectStrategy` at the - * pending → retrieving transition. Persisted on the section so retries - * use the SAME strategies (not re-selecting per attempt) and so - * `EffectivenessTracker.recordExecution` has the assignment to attribute - * the outcome to. - * - * source: Phase 4 strategy-wiring (2026-04). Optional because the - * selection is gated by the orchestration layer; legacy state snapshots - * predating the wiring may be absent. - */ - strategy_assignment: StrategyAssignmentSchema.optional(), - /** - * Per-attempt observation log. One entry per draft attempt, recording - * exactly which violations were fed into the prompt for that attempt. - * - * Invariant: attempt_log.length === section.attempt at any stable point - * (after each validateAndAdvance call). The log is written BEFORE the - * next draft action is emitted, so the benchmark extraction reads it - * synchronously rather than inferring from terminal state only. - * - * Field semantics: - * attempt — 1-indexed attempt number. - * violations_fed — the violation strings actually passed to the - * engineer subagent prompt for this attempt. - * Empty ([]) on attempt 1 (no prior violations exist). - * For attempt k≥2: the last_violations from the - * previous attempt — OR [] if the run is in the - * without_prior_violations ablation arm (D1.C). - * `violations_fed` is the OBSERVED value, not inferred - * from the arm; this closes the Curie A2 observability - * gap flagged in retry-observations.ts TODO(C1). - * - * Defaults to [] for backward compatibility with state snapshots predating - * Wave D1.B. - * - * source: Phase 4.2 ablation design (PHASE_4_PLAN.md §4.2) — per-attempt - * precision required for Schoenfeld N≈2,070 analysis (curie cross-audit - * A2: instrumentation must observe behavior, not infer it). - */ - attempt_log: external_exports.array(external_exports.object({ - attempt: external_exports.number().int().positive(), - violations_fed: external_exports.array(external_exports.string()).readonly() - })).readonly().default([]) - }); - ClarificationTurnSchema = external_exports.object({ - round: external_exports.number().int().min(1), - question: external_exports.string(), - answer: external_exports.string().optional(), - asked_at: external_exports.string(), - answered_at: external_exports.string().optional() - }); - VerificationPlanSnapshotSchema = external_exports.object({ - batch_id: external_exports.string(), - /** Claim IDs in dispatch order — index = invocation slot. */ - claim_ids: external_exports.array(external_exports.string()), - /** Judge identities, parallel to claim_ids by index. */ - judges: external_exports.array(AgentIdentitySchema) - }).refine((s) => s.claim_ids.length === s.judges.length, { - message: "VerificationPlanSnapshot: claim_ids and judges must have the same length (positional invariant \u2014 see self-check.ts:parseVerdictsFromSnapshot).", - path: ["judges"] - }); - PipelineStateSchema = external_exports.object({ - run_id: external_exports.string(), - current_step: PipelineStepSchema, - prd_context: PRDContextSchema.nullable(), - feature_description: external_exports.string(), - codebase_path: external_exports.string().nullable(), - /** - * Filesystem path returned by automatised-pipeline `index_codebase` - * (response field `graph_path`). Subsequent graph-query tools (query_graph, - * get_symbol, etc.) use this as their `graph_path` argument. - */ - codebase_graph_path: external_exports.string().nullable(), - /** Output directory passed to `index_codebase` so retries are idempotent. */ - codebase_output_dir: external_exports.string().nullable(), - codebase_indexed: external_exports.boolean(), - /** - * Preflight gate state — `null` while preflight has not been attempted - * yet, `"ok"` once Cortex (and ai-architect, when a codebase is given) - * passed their liveness checks. Treated as a precondition: the runner - * may not enter section_generation while preflight is unset. - * - * source: missing-Cortex bug found 2026-04-26 — silent per-section - * recall failures should surface as ONE clear startup error, not as - * degraded generation across every section. - */ - preflight_status: external_exports.enum(["ok", "skipped"]).nullable().default(null), - sections: external_exports.array(SectionStatusSchema).default([]), - clarifications: external_exports.array(ClarificationTurnSchema).default([]), - /** - * Set when the user types "proceed" or clarification reaches max rounds. - * Read by handleBudget to sanity-check that clarification finished cleanly - * before generation starts. - */ - proceed_signal: external_exports.boolean().default(false), - started_at: external_exports.string(), - updated_at: external_exports.string(), - /** Genuine error messages only. NOT a progress log. */ - errors: external_exports.array(external_exports.string()).default([]), - /** - * Parallel to `errors[]` (same length, same order). Tags each error as - * one of three kinds. pipeline-kpis.ts:structural_error_count reads - * `"structural"` count DIRECTLY rather than deriving it by subtraction. - * - * "section_failure" — section validator failed after MAX_ATTEMPTS. - * 1-per-failed-section by convention. Section- - * level retries are not counted; only the final - * fail-out increments. KPI: section_fail_count. - * - * "structural" — handler bug, runner protocol violation, - * schema mismatch, uncaught exception. The KPI - * gate `structural_error_count_max=0` blocks - * any run with a structural defect. - * - * "upstream_failure" — recoverable failure in an external service - * the pipeline tolerates (jira-generation - * subagent fails → continue without JIRA; - * index_codebase tool fails → fail input_analysis - * but do not blame the handler). Counted - * separately so the structural gate does not - * fire spuriously on real-LLM runs where - * upstream services have realistic flake rates - * (cross-audit curie H1, Phase 3+4 follow-up, - * 2026-04). - * - * source: curie cross-audit H-2 (Phase 3+4, 2026-04) for the introduction - * of the parallel array; curie H1 (Phase 3+4 follow-up, 2026-04) for the - * upstream_failure split. - */ - error_kinds: external_exports.array(external_exports.enum(["section_failure", "structural", "upstream_failure"])).default([]), - /** Paths of files successfully written during file_export. Append-only. */ - written_files: external_exports.array(external_exports.string()).default([]), - /** - * Count of Cortex `recall` tool invocations that returned zero hits. - * A non-zero count indicates sections were generated without memory context, - * which degrades output quality. KPI gate: pipeline-kpis.ts reads this field - * directly to surface the metric without post-hoc regex parsing. - * - * Incremented in section-generation.ts at the retrieving→generating - * transition when summarizeRecall returns an empty string (data.results is - * absent, empty, or all entries have no content). - * - * source: shannon S-6 (Phase 3+4 cross-audit, 2026-04) — load-bearing - * quantity needed for recall-efficacy analysis. - */ - cortex_recall_empty_count: external_exports.number().int().nonnegative().default(0), - /** - * Verification plan dispatched in self-check Phase A. Set during Phase A; - * read in Phase B to attribute verdicts. Null until Phase A runs. - */ - verification_plan: VerificationPlanSnapshotSchema.nullable().default(null), - /** - * Append-only queue of strategy execution results, populated when a - * section transitions to a terminal status (passed/failed). The - * composition root (mcp-server) drains this queue after each step and - * forwards entries to `EffectivenessTracker.recordExecution` so the - * closed feedback loop populates `EvidenceRepository`. - * - * Decouples orchestration (pure reducer) from infrastructure (SQLite - * persistence) per §2.2: the reducer emits data; the composition - * root is the only layer that performs I/O. - * - * source: Phase 4 strategy-wiring (2026-04). - */ - strategy_executions: external_exports.array(ExecutionResultSchema).default([]), - /** - * Per-run retry policy injected by the composition root (mcp-server) before - * handing the state to the reducer. The reducer reads this field only — - * it never calls `getRetryArmForRun` or `getMaxAttemptsForRun` directly, - * preserving layer purity (§1.5 DIP / §2.2 layer rule: orchestration must - * not import from benchmark). - * - * Fields: - * maxAttempts — effective max attempts for this run (may differ from the - * baseline MAX_ATTEMPTS for calibration treatment runs). - * arm — ablation arm: "with_prior_violations" feeds last_violations - * to the retry prompt; "without_prior_violations" feeds []. - * - * Defaults to null (= use MAX_ATTEMPTS baseline, with_prior_violations arm) - * for backward compatibility. Wave D2 wires the composition root to populate - * this field using getRetryArmForRun + getMaxAttemptsForRun from the - * benchmark layer before starting the run. - * - * ADR (Wave D1.C, 2026-04-27): the seam is on the state object, not on a - * separate config argument, so that the runner's pure reducer signature - * (state → action) does not acquire a new parameter. State is the single - * authority for all reducer inputs. The composition root is the only site - * that calls benchmark-layer seams (§5.2 composition root pattern). - * - * source: Phase 4.2 ablation design (PHASE_4_PLAN.md §4.2). - * source: §1.5 DIP — high-level modules must not depend on low-level modules. - * source: §5.2 factory / composition root pattern. - */ - // B9 — RetryPolicy is colocated with PipelineState rather than in a standalone - // retry-policy.ts file because it is structurally dependent on the state shape: - // the Zod schema here is an inline object (not a named Schema reference) so - // it participates in PipelineStateSchema's refinement chain and Zod inference - // without a separate parse boundary. The D1.C spec referenced a standalone - // file; this was intentionally inlined during Wave D1 implementation to keep - // the type adjacent to its only consumer (PipelineState). Any future caller - // that needs the RetryPolicy type standalone can do: - // type RetryPolicy = NonNullable - // source: Wave D B9 ADR (2026-04-27). - retry_policy: external_exports.object({ - maxAttempts: external_exports.number().int().positive(), - arm: external_exports.enum(["with_prior_violations", "without_prior_violations"]) - }).nullable().default(null) - }).refine((s) => s.errors.length === s.error_kinds.length, { - message: "PipelineState: errors[] and error_kinds[] must have the same length (lockstep invariant \u2014 use appendError() to append, never spread directly).", - path: ["error_kinds"] +var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); + defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazy(inst._zod, "values", () => { + if (def.options.every((o) => o._zod.values)) { + return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + } + return void 0; + }); + defineLazy(inst._zod, "pattern", () => { + if (def.options.every((o) => o._zod.pattern)) { + const patterns = def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); + } + return void 0; + }); + inst._zod.parse = (payload, ctx) => { + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [] + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } else { + if (result.issues.length === 0) + return result; + results.push(result); + } + } + if (!async) + return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results2) => { + return handleUnionResults(results2, payload, inst, ctx); }); - } + }; }); - -// packages/orchestration/dist/types/actions.js -var AskUserActionSchema, CallPipelineToolActionSchema, CallCortexToolActionSchema, SpawnSubagentsActionSchema, WriteFileActionSchema, EmitMessageActionSchema, VerificationSummarySchema, DoneActionSchema, FailedActionSchema, HandlerActionSchema, NextActionSchema, UserAnswerSchema, ToolResultSchema, SubagentBatchResultSchema, FileWrittenSchema, ActionResultSchema; -var init_actions = __esm({ - async "packages/orchestration/dist/types/actions.js"() { - "use strict"; - init_zod(); - await init_dist(); - AskUserActionSchema = external_exports.object({ - kind: external_exports.literal("ask_user"), - /** Identifies the question so the host can map answer → state */ - question_id: external_exports.string(), - header: external_exports.string().describe("Short prompt header for AskUserQuestion tool"), - description: external_exports.string().describe("Body explaining what we need from the user"), - options: external_exports.array(external_exports.object({ - label: external_exports.string(), - description: external_exports.string().optional() - })).min(2).max(4).nullable().describe("Structured options for AskUserQuestion. Null = freeform answer."), - multi_select: external_exports.boolean().default(false) - }); - CallPipelineToolActionSchema = external_exports.object({ - kind: external_exports.literal("call_pipeline_tool"), - tool_name: external_exports.string().describe("automatised-pipeline MCP tool name"), - arguments: external_exports.record(external_exports.string(), external_exports.unknown()), - /** Opaque routing token — host echoes it back unchanged on the corresponding tool_result. */ - correlation_id: external_exports.string() - }); - CallCortexToolActionSchema = external_exports.object({ - kind: external_exports.literal("call_cortex_tool"), - tool_name: external_exports.string().describe("Cortex MCP tool name"), - arguments: external_exports.record(external_exports.string(), external_exports.unknown()), - /** Opaque routing token — host echoes it back unchanged on the corresponding tool_result. */ - correlation_id: external_exports.string() - }); - SpawnSubagentsActionSchema = external_exports.object({ - kind: external_exports.literal("spawn_subagents"), - /** Multiple invocations to run IN PARALLEL — host MUST issue them in one message */ - invocations: external_exports.array(external_exports.object({ - invocation_id: external_exports.string(), - subagent_type: external_exports.string(), - description: external_exports.string(), - prompt: external_exports.string(), - isolation: external_exports.enum(["worktree", "none"]).default("none") - })), - /** Identifies the batch so the runner can route the batch result on submission. */ - batch_id: external_exports.string(), - /** - * Observability label only — host dispatch logic MUST NOT branch on this - * field. It exists so logs and telemetry can attribute batches to a high- - * level intent (judging vs drafting vs reviewing). - */ - purpose: external_exports.enum(["judge", "draft", "review"]) - }); - WriteFileActionSchema = external_exports.object({ - kind: external_exports.literal("write_file"), - path: external_exports.string(), - content: external_exports.string() - }); - EmitMessageActionSchema = external_exports.object({ - kind: external_exports.literal("emit_message"), - message: external_exports.string(), - level: external_exports.enum(["info", "warn", "error"]).default("info") - }); - VerificationSummarySchema = external_exports.object({ - claims_evaluated: external_exports.number().int().nonnegative(), - distribution: external_exports.record(VerdictSchema, external_exports.number().int().nonnegative()), - distribution_suspicious: external_exports.boolean() - }); - DoneActionSchema = external_exports.object({ - kind: external_exports.literal("done"), - summary: external_exports.string(), - artifacts: external_exports.array(external_exports.string()).default([]), - /** - * Typed verification summary. Optional only because not every `done` - * emission has run the judge phase (zero-claim short-circuit, malformed - * input, etc.). When present, KPI extractors and tests MUST read this - * field — never regex-parse `summary`. - */ - verification: VerificationSummarySchema.optional() - }); - FailedActionSchema = external_exports.object({ - kind: external_exports.literal("failed"), - reason: external_exports.string(), - step: external_exports.string() - }); - HandlerActionSchema = external_exports.discriminatedUnion("kind", [ - AskUserActionSchema, - CallPipelineToolActionSchema, - CallCortexToolActionSchema, - SpawnSubagentsActionSchema, - WriteFileActionSchema, - EmitMessageActionSchema, - DoneActionSchema, - FailedActionSchema - ]); - NextActionSchema = external_exports.discriminatedUnion("kind", [ - AskUserActionSchema, - CallPipelineToolActionSchema, - CallCortexToolActionSchema, - SpawnSubagentsActionSchema, - WriteFileActionSchema, - DoneActionSchema, - FailedActionSchema - ]); - UserAnswerSchema = external_exports.object({ - kind: external_exports.literal("user_answer"), - question_id: external_exports.string(), - selected: external_exports.array(external_exports.string()).default([]), - freeform: external_exports.string().optional() - }); - ToolResultSchema = external_exports.object({ - kind: external_exports.literal("tool_result"), - correlation_id: external_exports.string(), - success: external_exports.boolean(), - data: external_exports.unknown(), - error: external_exports.string().optional() - }); - SubagentBatchResultSchema = external_exports.object({ - kind: external_exports.literal("subagent_batch_result"), - batch_id: external_exports.string(), - responses: external_exports.array(external_exports.object({ - invocation_id: external_exports.string(), - raw_text: external_exports.string().optional(), - error: external_exports.string().optional() - })) - }); - FileWrittenSchema = external_exports.object({ - kind: external_exports.literal("file_written"), - path: external_exports.string(), - bytes: external_exports.number().int().nonnegative() +var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + defineLazy(inst._zod, "propValues", () => { + const propValues = {}; + for (const option of def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv)) { + if (!propValues[k]) + propValues[k] = /* @__PURE__ */ new Set(); + for (const val of v) { + propValues[k].add(val); + } + } + } + return propValues; + }); + const disc = cached(() => { + const opts = def.options; + const map4 = /* @__PURE__ */ new Map(); + for (const o of opts) { + const values = o._zod.propValues[def.discriminator]; + if (!values || values.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); + for (const v of values) { + if (map4.has(v)) { + throw new Error(`Duplicate discriminator value "${String(v)}"`); + } + map4.set(v, o); + } + } + return map4; + }); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst + }); + return payload; + } + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) { + return opt._zod.run(payload, ctx); + } + if (def.unionFallback) { + return _super(payload, ctx); + } + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + input, + path: [def.discriminator], + inst }); - ActionResultSchema = external_exports.discriminatedUnion("kind", [ - UserAnswerSchema, - ToolResultSchema, - SubagentBatchResultSchema, - FileWrittenSchema - ]); - } + return payload; + }; }); - -// packages/orchestration/dist/section-plan.js -var SECTIONS_BY_CONTEXT, SECTION_RECALL_TEMPLATES; -var init_section_plan = __esm({ - "packages/orchestration/dist/section-plan.js"() { - "use strict"; - SECTIONS_BY_CONTEXT = { - proposal: [ - "overview", - "goals", - "requirements", - "user_stories", - "acceptance_criteria", - "timeline", - "risks" - ], - feature: [ - "overview", - "goals", - "requirements", - "user_stories", - "technical_specification", - "acceptance_criteria", - "data_model", - "api_specification", - "security_considerations", - "performance_requirements", - "testing" - ], - bug: [ - "overview", - "requirements", - "technical_specification", - "acceptance_criteria", - "testing", - "deployment" - ], - incident: [ - "overview", - "requirements", - "technical_specification", - "acceptance_criteria", - "security_considerations", - "testing", - "deployment", - "risks" - ], - poc: [ - "overview", - "goals", - "requirements", - "technical_specification", - "acceptance_criteria" - ], - mvp: [ - "overview", - "goals", - "requirements", - "user_stories", - "technical_specification", - "acceptance_criteria", - "testing", - "timeline" - ], - release: [ - "overview", - "goals", - "requirements", - "technical_specification", - "acceptance_criteria", - "security_considerations", - "performance_requirements", - "testing", - "deployment", - "timeline" - ], - cicd: [ - "overview", - "goals", - "requirements", - "technical_specification", - "acceptance_criteria", - "security_considerations", - "testing", - "deployment", - "timeline" - ] - }; - SECTION_RECALL_TEMPLATES = { - overview: "high-level architecture domain context for {feature}", - goals: "business goals success metrics KPIs for {feature}", - requirements: "public API surfaces exports interfaces contracts for {feature}", - user_stories: "user flows personas use cases for {feature}", - technical_specification: "architecture patterns module structure dependencies for {feature}", - acceptance_criteria: "test scenarios validation rules edge cases for {feature}", - data_model: "database schema tables relationships data types for {feature}", - api_specification: "REST GraphQL endpoints routes handlers middleware for {feature}", - security_considerations: "authentication authorization encryption validation secrets for {feature}", - performance_requirements: "latency throughput caching scalability targets for {feature}", - testing: "test patterns fixtures assertions coverage for {feature}", - deployment: "deployment configuration infrastructure CI/CD environments for {feature}", - risks: "error handling edge cases failure modes risks for {feature}", - timeline: "milestones phases release schedule for {feature}", - source_code: "implementation source code patterns for {feature}", - test_code: "test code patterns assertions for {feature}", - // jira_tickets is generated from the PRD itself, not from a Cortex query. - jira_tickets: "" - }; - } +var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left2, right2]) => { + return handleIntersectionResults(payload, left2, right2); + }); + } + return handleIntersectionResults(payload, left, right); + }; }); - -// packages/orchestration/dist/handlers/banner.js -var handleBanner; -var init_banner = __esm({ - async "packages/orchestration/dist/handlers/banner.js"() { - "use strict"; - await init_dist(); - handleBanner = ({ state }) => { - const message = [ - "PRD Spec Generator", - `Run ID: ${state.run_id}`, - `Allowed strategies: ${CAPABILITIES.allowedStrategies.length}`, - `Allowed PRD contexts: ${CAPABILITIES.allowedContextTypes.length}`, - "", - `Feature: ${state.feature_description}`, - state.codebase_path ? `Codebase: ${state.codebase_path}` : "Codebase: (none provided)" - ].join("\n"); - return { - state: { ...state, current_step: "preflight" }, - action: { - kind: "emit_message", - message, - level: "info" - } - }; - }; +function mergeValues2(a, b) { + if (a === b) { + return { valid: true, data: a }; } -}); - -// packages/orchestration/dist/handlers/preflight.js -function adviseCortexInstall() { - return [ - "Cortex MCP not reachable.", - "", - "The pipeline relies on Cortex for per-section memory recall during", - "section generation. Without it, every section is drafted without", - "prior-decision context \u2014 generation quality degrades silently.", - "", - "To install:", - " /plugin marketplace add cdeust/cortex", - " /plugin install cortex@cortex-plugins", - " /reload-plugins", - "", - "If you genuinely want to run without Cortex, re-invoke", - "start_pipeline with skip_preflight: true (degraded mode)." - ].join("\n"); -} -function adviseAiArchitectInstall() { - return [ - "automatised-pipeline (ai-architect) MCP not reachable.", - "", - "A codebase_path was supplied, which requires the automatised-pipeline", - "MCP for index_codebase + downstream graph queries.", - "", - "To install:", - " /plugin marketplace add cdeust/automatised-pipeline", - " /plugin install automatised-pipeline@automatised-pipeline-marketplace", - " /reload-plugins", - "", - "If you only need PRD generation without codebase analysis, omit", - "codebase_path on the next start_pipeline call." - ].join("\n"); -} -var CORTEX_PROBE_CORRELATION, AI_ARCHITECT_PROBE_CORRELATION, handlePreflight; -var init_preflight = __esm({ - async "packages/orchestration/dist/handlers/preflight.js"() { - "use strict"; - await init_state(); - CORTEX_PROBE_CORRELATION = "preflight_cortex_probe"; - AI_ARCHITECT_PROBE_CORRELATION = "preflight_ai_architect_probe"; - handlePreflight = ({ state, result }) => { - if (state.preflight_status === "skipped") { - return { - state: { ...state, current_step: "context_detection" }, - action: { - kind: "emit_message", - message: "Preflight skipped (skip_preflight=true). Section generation will proceed without Cortex recall context if Cortex is unavailable.", - level: "warn" - } - }; - } - if (state.preflight_status === "ok") { - return { - state: { ...state, current_step: "context_detection" }, - action: { - kind: "emit_message", - message: "Preflight already passed. Proceeding to context detection." - } - }; - } - if (result?.kind === "tool_result" && result.correlation_id === CORTEX_PROBE_CORRELATION) { - if (!result.success) { - return { - state: appendError(state, `preflight: cortex unreachable (${result.error ?? "unknown error"})`, "upstream_failure"), - action: { - kind: "failed", - reason: adviseCortexInstall(), - step: "preflight" - } - }; - } - if (state.codebase_path) { - return { - state, - action: { - kind: "call_pipeline_tool", - tool_name: "health_check", - arguments: {}, - correlation_id: AI_ARCHITECT_PROBE_CORRELATION - } - }; - } + if (a instanceof Date && b instanceof Date && +a === +b) { + return { valid: true, data: a }; + } + if (isPlainObject(a) && isPlainObject(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues2(a[key], b[key]); + if (!sharedValue.valid) { return { - state: { - ...state, - preflight_status: "ok", - current_step: "context_detection" - }, - action: { - kind: "emit_message", - message: "Preflight passed: Cortex reachable. (no codebase \u2192 ai-architect probe skipped)" - } + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath] }; } - if (result?.kind === "tool_result" && result.correlation_id === AI_ARCHITECT_PROBE_CORRELATION) { - if (!result.success) { - return { - state: appendError(state, `preflight: ai-architect unreachable (${result.error ?? "unknown error"})`, "upstream_failure"), - action: { - kind: "failed", - reason: adviseAiArchitectInstall(), - step: "preflight" - } - }; - } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return { valid: false, mergeErrorPath: [] }; + } + const newArray = []; + for (let index2 = 0; index2 < a.length; index2++) { + const itemA = a[index2]; + const itemB = b[index2]; + const sharedValue = mergeValues2(itemA, itemB); + if (!sharedValue.valid) { return { - state: { - ...state, - preflight_status: "ok", - current_step: "context_detection" - }, - action: { - kind: "emit_message", - message: "Preflight passed: Cortex + ai-architect reachable." - } + valid: false, + mergeErrorPath: [index2, ...sharedValue.mergeErrorPath] }; } - return { - state, - action: { - kind: "call_cortex_tool", - tool_name: "memory_stats", - arguments: {}, - correlation_id: CORTEX_PROBE_CORRELATION - } - }; - }; - } -}); - -// packages/orchestration/dist/handlers/context-detection.js -function detectFromText(text) { - const lower = text.toLowerCase(); - for (const [ctx, triggers] of Object.entries(TRIGGER_WORDS)) { - if (triggers.some((t) => lower.includes(t))) - return ctx; + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; } - return null; + return { valid: false, mergeErrorPath: [] }; } -var TRIGGER_WORDS, QUESTION_ID, handleContextDetection; -var init_context_detection = __esm({ - async "packages/orchestration/dist/handlers/context-detection.js"() { - "use strict"; - await init_dist(); - TRIGGER_WORDS = { - proposal: ["proposal", "pitch", "stakeholder"], - feature: ["feature", "build", "implement", "add support"], - bug: ["bug", "fix", "broken", "regression", "defect"], - incident: ["incident", "outage", "production issue", "p0", "p1"], - poc: ["poc", "proof of concept", "spike", "feasibility"], - mvp: ["mvp", "minimum viable", "v1"], - release: ["release", "ship", "production launch"], - cicd: ["ci", "cd", "ci/cd", "pipeline", "deploy automation"] - }; - QUESTION_ID = "prd_context"; - handleContextDetection = ({ state, result }) => { - if (state.prd_context) { - return { - state: { ...state, current_step: "input_analysis" }, - action: { - kind: "emit_message", - message: `PRD context: ${PRD_CONTEXT_CONFIGS[state.prd_context].displayName}` - } - }; - } - if (result?.kind === "user_answer" && result.question_id === QUESTION_ID) { - const choice = result.selected[0] ?? result.freeform ?? ""; - const parsed = PRDContextSchema.safeParse(choice); - if (!parsed.success) { - return { - state, - action: { - kind: "failed", - reason: `Invalid PRD context choice: ${choice}`, - step: "context_detection" +function handleIntersectionResults(result, left, right) { + if (left.issues.length) { + result.issues.push(...left.issues); + } + if (right.issues.length) { + result.issues.push(...right.issues); + } + if (aborted(result)) + return result; + const merged = mergeValues2(left.value, right.value); + if (!merged.valid) { + throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + if (def.keyType._zod.values) { + const values = def.keyType._zod.values; + payload.value = {}; + for (const key of values) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload.issues.push(...prefixIssues(key, result2.issues)); + } + payload.value[key] = result2.value; + })); + } else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); } - }; - } - return { - state: { - ...state, - prd_context: parsed.data, - current_step: "input_analysis" - }, - action: { - kind: "emit_message", - message: `PRD context: ${PRD_CONTEXT_CONFIGS[parsed.data].displayName}` - } - }; - } - const detected = detectFromText(state.feature_description); - const allowed = CAPABILITIES.allowedContextTypes; - if (detected && allowed.includes(detected)) { - return { - state: { - ...state, - prd_context: detected, - current_step: "input_analysis" - }, - action: { - kind: "emit_message", - message: `PRD context detected: ${PRD_CONTEXT_CONFIGS[detected].displayName} (from trigger words)` + payload.value[key] = result.value; } - }; + } } - const options = allowed.map((ctx) => ({ - label: ctx, - description: PRD_CONTEXT_CONFIGS[ctx].description - })); - return { - state, - action: { - kind: "ask_user", - question_id: QUESTION_ID, - header: "Which kind of PRD?", - description: "I couldn't infer the PRD type from your request. Pick the closest match \u2014 this configures clarification depth and section count.", - // source: protocol constraint. AskUserActionSchema.options enforces - // .max(4) at the schema level (types/actions.ts). Slicing here ensures - // a tier with >4 allowed contexts doesn't fail Zod parsing on the - // emitted action. Cross-audit code-reviewer H6 (Phase 3+4, 2026-04). - options: options.slice(0, 4), - multi_select: false + let unrecognized; + for (const key in input) { + if (!values.has(key)) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); } - }; - }; - } -}); - -// packages/orchestration/dist/handlers/input-analysis.js -import { join as join3 } from "node:path"; -function deriveOutputDir(codebasePath, runId) { - return join3(codebasePath, ".prd-gen", "graphs", runId); -} -var CORRELATION_ID, handleInputAnalysis; -var init_input_analysis = __esm({ - async "packages/orchestration/dist/handlers/input-analysis.js"() { - "use strict"; - await init_state(); - CORRELATION_ID = "input_analysis_index"; - handleInputAnalysis = ({ state, result }) => { - if (!state.codebase_path) { - return { - state: { ...state, current_step: "feasibility_gate" }, - action: { - kind: "emit_message", - message: "No codebase provided. Skipping codebase analysis." - } - }; } - if (state.codebase_indexed && state.codebase_graph_path) { - return { - state: { ...state, current_step: "feasibility_gate" }, - action: { - kind: "emit_message", - message: `Codebase indexed (graph: ${state.codebase_graph_path}).` - } - }; + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized + }); } - if (result?.kind === "tool_result" && result.correlation_id === CORRELATION_ID) { - if (!result.success) { - return { - state: appendError( - state, - `index_codebase failed: ${result.error ?? "unknown"}`, - // External tool failure — the pipeline gives up but it's not a - // handler bug. Cross-audit curie H1 (Phase 3+4 follow-up). - "upstream_failure" - ), - action: { - kind: "failed", - reason: `index_codebase failed: ${result.error ?? "unknown"}`, - step: "input_analysis" - } - }; + } else { + payload.value = {}; + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); } - const data = result.data ?? {}; - const graphPath = data.graph_path ?? null; - if (!graphPath) { - return { - state: appendError( - state, - `index_codebase succeeded but returned no graph_path`, - // The upstream tool advertised success but violated its own - // contract. From the orchestration layer's perspective this - // is the SAME class as the explicit-failure case above — - // a tool we can't act on. Tag it as upstream_failure so the - // structural gate doesn't conflate this with a handler bug. - "upstream_failure" - ), - action: { - kind: "failed", - reason: "index_codebase returned no graph_path", - step: "input_analysis" - } - }; + if (keyResult.issues.length) { + payload.issues.push({ + origin: "record", + code: "invalid_key", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + input: key, + path: [key], + inst + }); + payload.value[keyResult.value] = keyResult.value; + continue; } - return { - state: { - ...state, - codebase_indexed: true, - codebase_graph_path: graphPath, - current_step: "feasibility_gate" - }, - action: { - kind: "emit_message", - message: `Codebase indexed (graph: ${graphPath}).` + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload.issues.push(...prefixIssues(key, result2.issues)); + } + payload.value[keyResult.value] = result2.value; + })); + } else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); } - }; - } - const outputDir = state.codebase_output_dir ?? deriveOutputDir(state.codebase_path, state.run_id); - return { - state: { ...state, codebase_output_dir: outputDir }, - action: { - kind: "call_pipeline_tool", - tool_name: "index_codebase", - arguments: { - path: state.codebase_path, - output_dir: outputDir, - language: "auto" - }, - correlation_id: CORRELATION_ID + payload.value[keyResult.value] = result.value; } - }; - }; - } -}); - -// packages/orchestration/dist/handlers/feasibility-gate.js -function looksEpic(text) { - const matches = EPIC_SIGNALS.filter((re2) => re2.test(text)).length; - return matches >= 2; -} -var QUESTION_ID2, EPIC_SIGNALS, handleFeasibilityGate; -var init_feasibility_gate = __esm({ - "packages/orchestration/dist/handlers/feasibility-gate.js"() { - "use strict"; - QUESTION_ID2 = "feasibility_focus"; - EPIC_SIGNALS = [ - / and /i, - / & /, - /,\s*\w+\s*,/, - // multiple comma-separated items - /\bplus\b/i, - /\balso\b/i - ]; - handleFeasibilityGate = ({ state, result }) => { - if (result?.kind === "user_answer" && result.question_id === QUESTION_ID2) { - const focus = result.freeform ?? result.selected[0] ?? state.feature_description; - return { - state: { - ...state, - feature_description: focus, - current_step: "clarification" - }, - action: { - kind: "emit_message", - message: `Focused scope: ${focus}` - } - }; - } - if (looksEpic(state.feature_description)) { - return { - state, - action: { - kind: "ask_user", - question_id: QUESTION_ID2, - header: "This looks like an epic. Pick one focus.", - description: "Generating one PRD for multiple features at once produces shallow output. Which single piece should this PRD cover? Type a focused description.", - options: null, - multi_select: false - } - }; } - return { - state: { ...state, current_step: "clarification" }, - action: { - kind: "emit_message", - message: "Scope acceptable. Proceeding to clarification." - } - }; - }; - } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; }); - -// packages/meta-prompting/dist/section-prompts.js -function renderStrategiesBlock(assignment) { - if (!assignment) - return ""; - const lines = [ - ``, - `Apply the following research-evidence-backed reasoning strategies:`, - "" - ]; - if (assignment.required.length > 0) { - lines.push(`REQUIRED (apply all of these):`); - for (const s of assignment.required) - lines.push(` - ${s}`); - } - if (assignment.optional.length > 0) { - lines.push(`OPTIONAL (apply if natural for this section):`); - for (const s of assignment.optional) - lines.push(` - ${s}`); - } - if (assignment.forbidden.length > 0) { - lines.push(`FORBIDDEN (do NOT apply \u2014 these have been shown to harm this kind of claim):`); - for (const s of assignment.forbidden) - lines.push(` - ${s}`); - } - if (assignment.researchCitations.length > 0) { - lines.push(""); - lines.push(`Citations backing this assignment:`); - for (const c of assignment.researchCitations) - lines.push(` - ${c}`); - } - lines.push(`Research-evidence baseline (population aggregate, NOT a per-section prediction): ${(assignment.expectedImprovement * 100).toFixed(1)}%`); - lines.push(`Assignment confidence: ${(assignment.assignmentConfidence * 100).toFixed(1)}%`); - lines.push(``); - return lines.join("\n"); -} -function buildSectionPrompt(input) { - const display = SECTION_DISPLAY_NAMES[input.section_type]; - const contextConfig = PRD_CONTEXT_CONFIGS[input.prd_context]; - const sectionGuidance = PER_SECTION_GUIDANCE[input.section_type] ?? "Follow the section's standard structure."; - const clarificationLines = input.clarification_qa.filter((c) => c.answer).map((c) => `Q: ${c.question} -A: ${c.answer}`).join("\n\n"); - const violationsBlock = input.prior_violations.length ? [ - ``, - `Attempt ${input.attempt - 1} produced violations:`, - input.prior_violations.map((v) => `- ${v}`).join("\n"), - `Fix every violation in this attempt.`, - `` - ].join("\n") : ""; - const strategiesBlock = renderStrategiesBlock(input.strategy_assignment); - return [ - `You draft section "${display}" of a ${contextConfig.displayName} PRD.`, - "", - `${input.feature_description}`, - "", - ``, - `PRD type: ${contextConfig.displayName}`, - `Focus: ${contextConfig.description}`, - `Attempt: ${input.attempt}`, - ``, - "", - input.recall_summary ? ` -${input.recall_summary} - -` : "", - clarificationLines ? ` -${clarificationLines} - -` : "", - violationsBlock, - violationsBlock ? "" : "", - strategiesBlock, - strategiesBlock ? "" : "", - ``, - sectionGuidance, - ``, - "", - ``, - COMMON_RULES.join("\n"), - ``, - "", - `Produce the "${display}" section now. Markdown only.` - ].filter((line) => line !== "").join("\n"); -} -var COMMON_RULES, PER_SECTION_GUIDANCE; -var init_section_prompts = __esm({ - async "packages/meta-prompting/dist/section-prompts.js"() { - "use strict"; - await init_dist(); - COMMON_RULES = [ - "1. Output ONLY the section body. No surrounding prose, no JSON, no fences.", - "2. Start with `##
` exactly once.", - "3. Every Functional Requirement (FR-XXX) MUST cite a Source: user-request, clarification round, or codebase finding.", - "4. Acceptance Criteria use `AC-XXX` format starting from AC-001.", - "5. No `AnyCodable`, `AnyJSON` \u2014 heterogeneous JSON is an explicit type.", - "6. NFR claims (latency, throughput, fps, storage) MUST specify a measurement method.", - "7. Story-point totals must add up. No self-referencing dependencies.", - "8. Architectural patterns: ports/adapters in code examples, not frameworks in domain." - ]; - PER_SECTION_GUIDANCE = { - overview: "1-2 paragraphs. State problem, audience, success measure. No requirements here.", - goals: "Bulleted list of measurable goals. Each goal: outcome verb + target + measurement.", - requirements: "Markdown table: | ID | Requirement | Priority | Depends On | Source |. SP column FORBIDDEN here.", - user_stories: "Each story: As a , I want , so that . Include AC-XXX list per story.", - technical_specification: "Show ports (interfaces in domain) + adapters (impls in infrastructure) + composition root. No framework imports in domain.", - acceptance_criteria: "Numbered AC-001..AC-NNN. Each AC: Given/When/Then or one-line behaviour. Each AC must trace to one or more FR-XXX.", - data_model: "DDL for tables/types/enums. Every CREATE TYPE / CREATE TABLE must be referenced. NO `NOW()` in partial-index WHERE.", - api_specification: "Endpoint table: | Method | Path | Auth | Request | Response | Errors |. Match any HTTP-style ports from technical_specification.", - security_considerations: "Auth (mechanism), authz (matrix), data-at-rest, data-in-transit, secrets handling, audit logs. Cite STRIDE category per claim.", - performance_requirements: "p50/p95/p99 + measurement method (e.g., k6 script, prod APM). Verdict: SPEC-COMPLETE if method is named, NEEDS-RUNTIME otherwise.", - testing: "Coverage table: | Test name | Tests AC-XXX or FR-XXX | Type (unit/integration/e2e) | Status |. Real implementations only \u2014 no `// TODO` test bodies.", - deployment: "Phases (canary, full), rollback procedure, feature flags, monitoring/alerting hooks.", - risks: "Risk register: | Risk | Likelihood | Impact | Mitigation | Owner |. One row per risk.", - timeline: "Phases with sprint counts. Each phase total = sum of stories in that phase. Grand total = sum of phases." - }; - } +var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values = getEnumValues(def.entries); + inst._zod.values = new Set(values); + inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (inst._zod.values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values, + input, + inst + }); + return payload; + }; }); - -// packages/meta-prompting/dist/clarification-prompts.js -function buildClarificationPrompt(input) { - const ctx = PRD_CONTEXT_CONFIGS[input.prd_context]; - const priorBlock = input.prior_qa.length ? input.prior_qa.map((qa) => `Round ${input.round - input.prior_qa.length + 1}: -Q: ${qa.question} -A: ${qa.answer ?? "(no answer)"}`).join("\n\n") : "(no prior questions)"; - return [ - `You are eliciting requirements for a ${ctx.displayName} PRD.`, - "", - `${input.feature_description}`, - "", - `${input.round} of ${ctx.clarificationRange[1]}`, - "", - ``, - priorBlock, - ``, - "", - input.recall_summary ? ` -${input.recall_summary.slice(0, 2e3)} -` : "", - "", - ``, - `Generate ONE clarification question that:`, - `- Addresses the highest-uncertainty area not yet covered`, - `- Cannot be answered by reading prior answers or codebase context above`, - `- Has a concrete answer (not "tell me more about X")`, - ``, - "", - ``, - `Return EXACTLY ONE JSON object, nothing else:`, - `{`, - ` "question": "",`, - ` "options": ["` - ].filter((l) => l !== "").join("\n"); -} -var init_clarification_prompts = __esm({ - async "packages/meta-prompting/dist/clarification-prompts.js"() { - "use strict"; - await init_dist(); - } +var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.values = new Set(def.values); + inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? o.toString() : String(o)).join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (inst._zod.values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst + }); + return payload; + }; }); - -// packages/meta-prompting/dist/jira-prompts.js -function buildJiraPrompt(input) { - const sourceBlock = input.source_sections.filter((s) => s.content).map((s) => `## Source: ${s.section_type} - -${s.content}`).join("\n\n"); - return [ - `You generate JIRA tickets from a PRD.`, - "", - `${input.feature_description}`, - "", - ``, - sourceBlock, - ``, - "", - ``, - RULES.join("\n"), - ``, - "", - `Produce the JIRA ticket document now.` - ].join("\n"); -} -var RULES; -var init_jira_prompts = __esm({ - "packages/meta-prompting/dist/jira-prompts.js"() { - "use strict"; - RULES = [ - "1. Output ONLY a markdown document. No JSON, no preamble, no fences.", - "2. AC IDs MUST match the AC-XXX IDs in the source. NEVER create new AC numbering.", - "3. Each ticket: ID (TICKET-NNN), Title, Description, Acceptance Criteria (referencing AC-XXX), Story Points (Fibonacci), Depends On, Source.", - "4. SP totals: Epic SP = sum of story SPs. Phase SP = sum of stories in phase. Grand total = sum of phases.", - "5. NEVER list a ticket as a self-dependency.", - "6. Distribute SP unevenly \u2014 real complexity is uneven.", - "7. Group tickets into Phases (Phase 1, Phase 2, ...) reflecting delivery order.", - "8. End with a Summary table: | Phase | Story Count | Total SP |." - ]; - } +var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const _out = def.transform(payload.value, payload); + if (_ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output2) => { + payload.value = output2; + return payload; + }); + } + if (_out instanceof Promise) { + throw new $ZodAsyncError(); + } + payload.value = _out; + return payload; + }; }); - -// packages/meta-prompting/dist/index.js -var init_dist4 = __esm({ - async "packages/meta-prompting/dist/index.js"() { - "use strict"; - await init_section_prompts(); - await init_clarification_prompts(); - init_jira_prompts(); - } +var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + }); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (def.innerType._zod.optin === "optional") { + return def.innerType._zod.run(payload, ctx); + } + if (payload.value === void 0) { + return payload; + } + return def.innerType._zod.run(payload, ctx); + }; }); - -// packages/orchestration/dist/handlers/protocol-ids.js -function clarificationComposeInvocationId(round3) { - return `${CLARIFICATION_COMPOSE_INV_PREFIX}${round3}`; -} -var QUESTION_ID_CONTINUE, CLARIFICATION_COMPOSE_INV_PREFIX, SECTION_GENERATE_INV_PREFIX, SELF_CHECK_JUDGE_INV_PREFIX, JIRA_GENERATION_INV_ID; -var init_protocol_ids = __esm({ - "packages/orchestration/dist/handlers/protocol-ids.js"() { - "use strict"; - QUESTION_ID_CONTINUE = "clarification_continue"; - CLARIFICATION_COMPOSE_INV_PREFIX = "clarification_compose_inv_"; - SECTION_GENERATE_INV_PREFIX = "section_generate_"; - SELF_CHECK_JUDGE_INV_PREFIX = "self_check_judge_"; - JIRA_GENERATION_INV_ID = "jira_generation_engineer"; - } +var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; + }); + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === null) + return payload; + return def.innerType._zod.run(payload, ctx); + }; }); - -// packages/orchestration/dist/handlers/clarification.js -function composeBatchId(round3) { - return `${COMPOSE_BATCH_PREFIX}${round3}`; -} -function isComposeResult(result, round3) { - return result?.kind === "subagent_batch_result" && result.batch_id === composeBatchId(round3); -} -function tryParseGeneratedQuestion(rawText) { - try { - const obj = extractJsonObject(rawText); - if (typeof obj.question !== "string" || !obj.question.trim()) - return null; - const options = Array.isArray(obj.options) && obj.options.every((o) => typeof o === "string") ? obj.options : null; - const rationale = typeof obj.rationale === "string" ? obj.rationale : ""; - return { question: obj.question.trim(), options, rationale }; - } catch { - return null; +var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (payload.value === void 0) { + payload.value = def.defaultValue; + return payload; + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleDefaultResult(result2, def)); + } + return handleDefaultResult(result, def); + }; +}); +function handleDefaultResult(payload, def) { + if (payload.value === void 0) { + payload.value = def.defaultValue; } + return payload; } -function composeAction(state, round3) { - const prompt = buildClarificationPrompt({ - feature_description: state.feature_description, - prd_context: state.prd_context, - round: round3, - prior_qa: state.clarifications.map((c) => ({ - question: c.question, - answer: c.answer - })), - recall_summary: "" +var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (payload.value === void 0) { + payload.value = def.defaultValue; + } + return def.innerType._zod.run(payload, ctx); + }; +}); +var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => { + const v = def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; }); - return { - kind: "spawn_subagents", - purpose: "draft", - batch_id: composeBatchId(round3), - invocations: [ - { - invocation_id: composeInvocationId(round3), - subagent_type: "zetetic-team-subagents:engineer", - description: `Compose clarification question (round ${round3})`, - prompt, - isolation: "none" - } - ] + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleNonOptionalResult(result2, inst)); + } + return handleNonOptionalResult(result, inst); }; -} -function askComposedQuestion(turn) { - const optionsForUser = turn.options && turn.options.length >= 2 && turn.options.length <= 4 ? turn.options.map((o) => ({ label: o })) : null; - return { - kind: "ask_user", - question_id: QUESTION_ID_ANSWER, - header: `Round ${turn.round}: ${turn.question}`, - description: turn.rationale || "Answer freeform if no options listed.", - options: optionsForUser, - multi_select: false - }; -} -function computeBounds(state) { - const config5 = PRD_CONTEXT_CONFIGS[state.prd_context]; - const max3 = Math.min(config5.clarificationRange[1], CAPABILITIES.maxClarificationRounds); - const min3 = Math.min(config5.clarificationRange[0], max3); - return { min: min3, max: max3 }; -} -function handleProceedOrContinue(state, result) { - const choice = (result.freeform ?? result.selected[0] ?? "").toLowerCase(); - if (choice.includes("proceed") || choice === "yes") { - return { - state: { ...state, proceed_signal: true, current_step: "budget" }, - action: { - kind: "emit_message", - message: `Clarification complete (${state.clarifications.length} rounds).` - } - }; +}); +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === void 0) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst + }); } - return { - state, - action: composeAction(state, state.clarifications.length + 1) - }; + return payload; } -function recordAnswerAndDispatch(state, result, bounds) { - const lastTurn = state.clarifications[state.clarifications.length - 1]; - if (!lastTurn || lastTurn.answer !== void 0) - return null; - const updatedTurn = { - ...lastTurn, - answer: result.freeform ?? result.selected.join(", "), - answered_at: (/* @__PURE__ */ new Date()).toISOString() +var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => { + payload.value = result2.value; + if (result2.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + payload.issues = []; + } + return payload; + }); + } + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + payload.issues = []; + } + return payload; }; - const clarifications = [...state.clarifications.slice(0, -1), updatedTurn]; - const completed = clarifications.length; - if (completed >= bounds.max) { - return { - state: { - ...state, - clarifications, - proceed_signal: true, - current_step: "budget" - }, - action: { - kind: "emit_message", - message: `Reached max clarification rounds (${bounds.max}). Proceeding.` - } - }; - } - if (completed < bounds.min) { - return { - state: { ...state, clarifications }, - action: composeAction({ ...state, clarifications }, completed + 1) - }; - } - return { - state: { ...state, clarifications }, - action: { - kind: "ask_user", - question_id: QUESTION_ID_CONTINUE, - header: `Asked ${completed} questions. Proceed?`, - description: `Min for ${state.prd_context}: ${bounds.min}. Max: ${bounds.max}. 'proceed' to generate the PRD, 'continue' for more questions.`, - options: [ - { label: "proceed", description: "Generate the PRD now" }, - { label: "continue", description: "Ask another question" } - ], - multi_select: false +}); +var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => def.in._zod.values); + defineLazy(inst._zod, "optin", () => def.in._zod.optin); + defineLazy(inst._zod, "optout", () => def.out._zod.optout); + inst._zod.parse = (payload, ctx) => { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left2) => handlePipeResult(left2, def, ctx)); } + return handlePipeResult(left, def, ctx); }; +}); +function handlePipeResult(left, def, ctx) { + if (aborted(left)) { + return left; + } + return def.out._zod.run({ value: left.value, issues: left.issues }, ctx); } -function handleComposedQuestion(state, result, expectedRound) { - const response = result.responses.find((r) => r.invocation_id === composeInvocationId(expectedRound)); - const generated = response?.raw_text ? tryParseGeneratedQuestion(response.raw_text) : null; - const turn = generated ? { - round: expectedRound, - question: generated.question, - options: generated.options, - rationale: generated.rationale, - asked_at: (/* @__PURE__ */ new Date()).toISOString() - } : { - round: expectedRound, - question: response?.error ?? `What is the most important detail about "${state.feature_description}" that should drive this PRD?`, - options: null, - rationale: generated ? "" : "Subagent did not return a parseable question; using fallback.", - asked_at: (/* @__PURE__ */ new Date()).toISOString() +var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); + } + return handleReadonlyResult(result); }; - return appendTurnAndAsk(state, turn); +}); +function handleReadonlyResult(payload) { + payload.value = Object.freeze(payload.value); + return payload; } -function appendTurnAndAsk(state, turn) { - const clarifications = [ - ...state.clarifications, - { - round: turn.round, - question: turn.question, - asked_at: turn.asked_at +var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { + $ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) { + return r.then((r2) => handleRefineResult(r2, payload, input, inst)); } - ]; - return { - state: { ...state, clarifications }, - action: askComposedQuestion(turn) + handleRefineResult(r, payload, input, inst); + return; }; +}); +function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, + // incorporates params.error into issue reporting + path: [...inst._zod.def.path ?? []], + // incorporates params.error into issue reporting + continue: !inst._zod.def.abort + // params: inst._zod.def.params, + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + payload.issues.push(issue(_iss)); + } } -var QUESTION_ID_ANSWER, COMPOSE_BATCH_PREFIX, composeInvocationId, handleClarification; -var init_clarification2 = __esm({ - async "packages/orchestration/dist/handlers/clarification.js"() { - "use strict"; - await init_dist(); - await init_dist4(); - init_protocol_ids(); - QUESTION_ID_ANSWER = "clarification_answer"; - COMPOSE_BATCH_PREFIX = "clarification_compose_"; - composeInvocationId = clarificationComposeInvocationId; - handleClarification = ({ state, result }) => { - if (!state.prd_context) { - return { - state, - action: { - kind: "failed", - reason: "Clarification reached without PRD context", - step: "clarification" - } - }; - } - const bounds = computeBounds(state); - const expectedRound = state.clarifications.length + 1; - if (result?.kind === "user_answer" && result.question_id === QUESTION_ID_CONTINUE) { - return handleProceedOrContinue(state, result); + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/en.js +var parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; } - if (result?.kind === "user_answer" && result.question_id === QUESTION_ID_ANSWER) { - const out = recordAnswerAndDispatch(state, result, bounds); - if (out) - return out; + if (data === null) { + return "null"; } - if (isComposeResult(result, expectedRound)) { - return handleComposedQuestion(state, result, expectedRound); + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; } - return { state, action: composeAction(state, expectedRound) }; - }; + } } -}); - -// packages/orchestration/dist/handlers/budget.js -var handleBudget; -var init_budget = __esm({ - "packages/orchestration/dist/handlers/budget.js"() { - "use strict"; - handleBudget = ({ state }) => { - if (!state.proceed_signal) { - return { - state, - action: { - kind: "failed", - reason: "budget step reached without proceed_signal \u2014 clarification did not exit cleanly", - step: "budget" - } - }; + return t; +}; +var error = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Invalid input: expected ${issue2.expected}, received ${parsedType(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; + return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; } - return { - state: { ...state, current_step: "section_generation" }, - action: { - kind: "emit_message", - message: "Budget allocated. Starting section generation." + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; } - }; - }; - } -}); - -// packages/orchestration/dist/handlers/section-generation-constants.js -var MAX_ATTEMPTS; -var init_section_generation_constants = __esm({ - "packages/orchestration/dist/handlers/section-generation-constants.js"() { - "use strict"; - MAX_ATTEMPTS = 3; - } -}); - -// packages/orchestration/dist/handlers/section-generation/validate-and-advance.js -function replaceSection(state, next) { - return { - ...state, - sections: state.sections.map((s) => s.section_type === next.section_type ? next : s) + return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Invalid string: must start with "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") + return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue2.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue2.origin}`; + case "invalid_union": + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue2.origin}`; + default: + return `Invalid input`; + } }; -} -function buildExecutionResults(active, prdContext, passed) { - if (active.status !== "passed" && active.status !== "failed") - return []; - const assignment = active.strategy_assignment; - if (!assignment) - return []; - const strategies = assignment.required.length > 0 ? assignment.required : assignment.optional[0] ? [assignment.optional[0]] : []; - if (strategies.length === 0) - return []; - const attempts = Math.max(1, active.attempt); - const actualConfidenceGain = passed ? assignment.expectedImprovement : 0; - const retryCount = Math.max(0, attempts - 1); - return strategies.map((strategy) => ({ - strategy, - assignment, - actualConfidenceGain, - wasCompliant: passed, - retryCount, - prdContext - })); -} -function applyRetryArmPolicy(state, active, violations) { - const attemptLogEntry = { - attempt: active.attempt, - violations_fed: [...active.last_violations] +}; +function en_default2() { + return { + localeError: error() }; - const arm = state.retry_policy?.arm ?? "with_prior_violations"; - const violationsForNextAttempt = arm === "without_prior_violations" ? [] : [...violations]; - return { violationsForNextAttempt, attemptLogEntry }; } -function failSection(state, active, reason, draft, violations = []) { - const next = { - ...active, - status: "failed", - content: draft ?? active.content, - violation_count: violations.length || active.violation_count, - last_violations: [...violations] - }; - const stateWithSection = replaceSection(state, next); - let stateWithError = appendError(stateWithSection, `[section_generation:${active.section_type}] ${reason}`, "section_failure"); - if (state.prd_context) { - const execs = buildExecutionResults(next, state.prd_context, false); - if (execs.length > 0) { - stateWithError = { - ...stateWithError, - strategy_executions: [...stateWithError.strategy_executions, ...execs] - }; + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/registries.js +var $ZodRegistry = class { + constructor() { + this._map = /* @__PURE__ */ new Map(); + this._idmap = /* @__PURE__ */ new Map(); + } + add(schema2, ..._meta) { + const meta = _meta[0]; + this._map.set(schema2, meta); + if (meta && typeof meta === "object" && "id" in meta) { + if (this._idmap.has(meta.id)) { + throw new Error(`ID ${meta.id} already exists in the registry`); + } + this._idmap.set(meta.id, schema2); } + return this; } - return { - state: stateWithError, - action: { - kind: "emit_message", - level: "warn", - message: `\u2717 ${SECTION_DISPLAY_NAMES[active.section_type]}: ${reason}` + clear() { + this._map = /* @__PURE__ */ new Map(); + this._idmap = /* @__PURE__ */ new Map(); + return this; + } + remove(schema2) { + const meta = this._map.get(schema2); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.delete(meta.id); } - }; -} -function validateAndAdvance(state, active, draft, draftActionFn) { - const report = validateSection(draft, active.section_type); - const violations = report.violations.map((v) => `[${v.rule}] ${v.message}`); - const { violationsForNextAttempt, attemptLogEntry } = applyRetryArmPolicy(state, active, violations); - const activeWithLog = { - ...active, - attempt_log: [...active.attempt_log ?? [], attemptLogEntry] - }; - if (violations.length === 0) { - const next2 = { - ...activeWithLog, - status: "passed", - content: draft, - violation_count: 0, - last_violations: [] - }; - let stateWithSection = replaceSection(state, next2); - if (state.prd_context) { - const execs = buildExecutionResults(next2, state.prd_context, true); - if (execs.length > 0) { - stateWithSection = { - ...stateWithSection, - strategy_executions: [...stateWithSection.strategy_executions, ...execs] - }; - } + this._map.delete(schema2); + return this; + } + get(schema2) { + const p = schema2._zod.parent; + if (p) { + const pm = { ...this.get(p) ?? {} }; + delete pm.id; + return { ...pm, ...this._map.get(schema2) }; } - return { - state: stateWithSection, - action: { - kind: "emit_message", - message: `\u2713 ${SECTION_DISPLAY_NAMES[active.section_type]} passed validation (attempt ${active.attempt}).` - } - }; + return this._map.get(schema2); } - const effectiveMaxAttempts = state.retry_policy?.maxAttempts ?? MAX_ATTEMPTS; - if (activeWithLog.attempt >= effectiveMaxAttempts) { - return failSection(state, activeWithLog, `Failed validation after ${effectiveMaxAttempts} attempts. Violations: ${violations.join("; ")}`, draft, violations); + has(schema2) { + return this._map.has(schema2); } - const next = { - ...activeWithLog, - status: "generating", - content: draft, - attempt: activeWithLog.attempt + 1, - violation_count: violations.length, - last_violations: [...violationsForNextAttempt] - }; - const updatedState = replaceSection(state, next); - return { - state: updatedState, - action: draftActionFn(updatedState, next, "", violationsForNextAttempt) - }; +}; +function registry() { + return new $ZodRegistry(); } -var init_validate_and_advance = __esm({ - async "packages/orchestration/dist/handlers/section-generation/validate-and-advance.js"() { - "use strict"; - await init_state(); - await init_dist2(); - await init_dist(); - init_section_generation_constants(); - } -}); +var globalRegistry = /* @__PURE__ */ registry(); -// packages/orchestration/dist/handlers/section-generation.js -function correlationFor(prefix, sectionType) { - return `${prefix}${sectionType}`; +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/api.js +function _string(Class2, params) { + return new Class2({ + type: "string", + ...normalizeParams(params) + }); } -function ensureSectionsInitialized(state) { - if (state.sections.length > 0 || !state.prd_context) - return state; - const planned = SECTIONS_BY_CONTEXT[state.prd_context]; - const cap = CAPABILITIES.maxSections; - const allowed = planned.slice(0, cap); - const sections = allowed.map((section_type) => ({ - section_type, - status: "pending", - attempt: 0, - violation_count: 0, - last_violations: [], - attempt_log: [] - })); - return { ...state, sections }; -} -function findActiveSection(state) { - return state.sections.find((s) => s.status !== "passed" && s.status !== "failed"); +function _email(Class2, params) { + return new Class2({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -function recallAction(feature, sectionType) { - const template = SECTION_RECALL_TEMPLATES[sectionType]; - const query = template.replace("{feature}", feature); - return { - kind: "call_cortex_tool", - tool_name: "recall", - /** - * source: provisional heuristic. 8 results × ~500 tokens/memory ≈ 4K - * tokens of retrieval context per section, which fits comfortably - * inside the per-section retrieval budget computed by - * mcp-server/context-budget.ts (~2-5K depending on section weight). - * Cross-audit code-reviewer H6 (Phase 3+4, 2026-04). - */ - arguments: { query, max_results: 8 }, - correlation_id: correlationFor(RETRIEVE_PREFIX, sectionType) - }; +function _guid(Class2, params) { + return new Class2({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -function draftAction(state, section, recall_summary, prior_violations) { - const display = SECTION_DISPLAY_NAMES[section.section_type]; - if (!state.prd_context) { - throw new Error(`section-generation reached without prd_context`); - } - const prompt = buildSectionPrompt({ - section_type: section.section_type, - feature_description: state.feature_description, - prd_context: state.prd_context, - recall_summary, - clarification_qa: state.clarifications.filter((c) => Boolean(c.answer)).map((c) => ({ question: c.question, answer: c.answer })), - prior_violations: [...prior_violations], - attempt: section.attempt, - // Phase 4 strategy-wiring (2026-04): pass the persisted assignment - // so every retry uses the SAME strategies the selector chose at the - // pending → retrieving transition. - strategy_assignment: section.strategy_assignment +function _uuid(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params) }); - return { - kind: "spawn_subagents", - purpose: "draft", - batch_id: correlationFor(SECTION_GENERATE_INV_PREFIX, section.section_type), - invocations: [ - { - invocation_id: correlationFor(SECTION_GENERATE_INV_PREFIX, section.section_type), - subagent_type: "zetetic-team-subagents:engineer", - description: `Draft section: ${display}`, - prompt, - isolation: "none" - } - ] - }; } -function failNoPrdContext(state) { - return { - state: appendError(state, "[section_generation] prd_context is null", "structural"), - action: { - kind: "failed", - reason: "section_generation reached without prd_context", - step: "section_generation" - } - }; +function _uuidv4(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params) + }); } -function advanceToJira(init) { - return { - state: { ...init, current_step: "jira_generation" }, - action: { - kind: "emit_message", - message: "All sections processed. Generating JIRA tickets." - } - }; +function _uuidv6(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params) + }); } -function chooseStrategyForSection(state, section_type) { - const display = SECTION_DISPLAY_NAMES[section_type]; - return selectStrategy({ - claim: `${display}: ${state.feature_description}`, - context: section_type, - hasCodebase: state.codebase_indexed +function _uuidv7(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params) }); } -function startRetrieving(init, active) { - const assignment = active.strategy_assignment ?? chooseStrategyForSection(init, active.section_type); - const next = { - ...active, - status: "retrieving", - strategy_assignment: assignment - }; - return { - state: replaceSection(init, next), - action: recallAction(init.feature_description, active.section_type) - }; +function _url(Class2, params) { + return new Class2({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -function advanceFromRecall(init, active, data) { - const recallSummary = summarizeRecall(data); - const emptyRecall = recallSummary.length === 0; - const next = { - ...active, - status: "generating", - attempt: active.attempt + 1 - }; - const stateWithRecall = emptyRecall ? { - ...init, - cortex_recall_empty_count: init.cortex_recall_empty_count + 1 - } : init; - const updated = replaceSection(stateWithRecall, next); - return { - state: updated, - action: draftAction(updated, next, recallSummary, active.last_violations) - }; +function _emoji2(Class2, params) { + return new Class2({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -function processDraft(init, active, result) { - const draft = collectDraftText(result, active.section_type); - if (!draft) { - return failSection(init, active, "Subagent returned empty draft"); - } - return validateAndAdvance(init, active, draft, draftAction); +function _nanoid(Class2, params) { + return new Class2({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -function reissueStalled(init, active) { - if (active.status === "retrieving") { - return { - state: init, - action: recallAction(init.feature_description, active.section_type) - }; - } - return { - state: init, - action: draftAction(init, active, "", active.last_violations) - }; +function _cuid(Class2, params) { + return new Class2({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -function summarizeRecall(data) { - if (!data || typeof data !== "object") - return ""; - const results = data.results; - if (!Array.isArray(results)) - return ""; - return results.slice(0, RECALL_MAX_RESULTS_INCLUDED).map((r) => r.content).filter((c) => typeof c === "string" && c.length > 0).map((c) => c.length > RECALL_RESULT_TRUNCATE_CHARS ? c.slice(0, RECALL_RESULT_TRUNCATE_CHARS) + RECALL_TRUNCATION_MARKER : c).join("\n---\n"); +function _cuid2(Class2, params) { + return new Class2({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -function collectDraftText(result, sectionType) { - const expectedId = correlationFor(SECTION_GENERATE_INV_PREFIX, sectionType); - const response = result.responses.find((r) => r.invocation_id === expectedId); - if (!response) - return null; - if (response.error) - return null; - return response.raw_text?.trim() ?? null; +function _ulid(Class2, params) { + return new Class2({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -var RETRIEVE_PREFIX, handleSectionGeneration, RECALL_MAX_RESULTS_INCLUDED, RECALL_RESULT_TRUNCATE_CHARS, RECALL_TRUNCATION_MARKER; -var init_section_generation = __esm({ - async "packages/orchestration/dist/handlers/section-generation.js"() { - "use strict"; - await init_state(); - await init_dist(); - await init_dist4(); - await init_dist3(); - init_section_plan(); - await init_validate_and_advance(); - init_section_generation_constants(); - init_protocol_ids(); - RETRIEVE_PREFIX = "section_retrieve_"; - handleSectionGeneration = ({ state, result }) => { - if (!state.prd_context) { - return failNoPrdContext(state); - } - const init = ensureSectionsInitialized(state); - const active = findActiveSection(init); - if (!active) { - return advanceToJira(init); - } - if (active.status === "pending") { - return startRetrieving(init, active); - } - if (active.status === "retrieving" && result?.kind === "tool_result" && result.correlation_id === correlationFor(RETRIEVE_PREFIX, active.section_type)) { - return advanceFromRecall(init, active, result.data); - } - if (active.status === "generating" && result?.kind === "subagent_batch_result" && result.batch_id === correlationFor(SECTION_GENERATE_INV_PREFIX, active.section_type)) { - return processDraft(init, active, result); - } - return reissueStalled(init, active); - }; - RECALL_MAX_RESULTS_INCLUDED = 8; - RECALL_RESULT_TRUNCATE_CHARS = 800; - RECALL_TRUNCATION_MARKER = "..."; - } -}); - -// packages/orchestration/dist/handlers/jira-generation.js -function gatherSourceSections(state) { - const wanted = [ - "requirements", - "user_stories", - "acceptance_criteria" - ]; - return state.sections.filter((s) => wanted.includes(s.section_type) && s.content).map((s) => ({ - section_type: s.section_type, - content: s.content - })); +function _xid(Class2, params) { + return new Class2({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -var BATCH_ID, handleJiraGeneration; -var init_jira_generation = __esm({ - async "packages/orchestration/dist/handlers/jira-generation.js"() { - "use strict"; - await init_state(); - await init_dist4(); - init_protocol_ids(); - BATCH_ID = "jira_generation"; - handleJiraGeneration = ({ state, result }) => { - if (result?.kind === "subagent_batch_result" && result.batch_id === BATCH_ID) { - const response = result.responses.find((r) => r.invocation_id === JIRA_GENERATION_INV_ID); - if (!response || response.error || !response.raw_text) { - const withError = appendError( - state, - `[jira_generation] failed: ${response?.error ?? "no response"}`, - // The handler tolerates this (warns + continues to file_export). - // Tagging as "upstream_failure" keeps the structural-error gate - // from firing on a recoverable subagent flake (cross-audit - // curie H1, Phase 3+4 follow-up, 2026-04). - "upstream_failure" - ); - return { - state: { ...withError, current_step: "file_export" }, - action: { - kind: "emit_message", - level: "warn", - message: "JIRA generation failed; proceeding to file export anyway." - } - }; - } - const jiraMarkdown = response.raw_text.trim(); - const updated = { - ...state, - sections: [ - ...state.sections, - { - section_type: "jira_tickets", - status: "passed", - attempt: 1, - violation_count: 0, - last_violations: [], - attempt_log: [], - content: jiraMarkdown - } - ], - current_step: "file_export" - }; - return { - state: updated, - action: { - kind: "emit_message", - message: "JIRA tickets generated. Writing files." - } - }; - } - const sourceMaterial = gatherSourceSections(state); - if (sourceMaterial.length === 0) { - return { - state: { ...state, current_step: "file_export" }, - action: { - kind: "emit_message", - message: "No source sections for JIRA generation. Skipping." - } - }; - } - return { - state, - action: { - kind: "spawn_subagents", - purpose: "draft", - batch_id: BATCH_ID, - invocations: [ - { - invocation_id: JIRA_GENERATION_INV_ID, - subagent_type: "zetetic-team-subagents:engineer", - description: "Generate JIRA tickets from PRD", - prompt: buildJiraPrompt({ - feature_description: state.feature_description, - source_sections: sourceMaterial - }), - isolation: "none" - } - ] - } - }; - }; - } -}); - -// packages/orchestration/dist/handlers/file-export.js -function joinSections(state, types) { - return state.sections.filter((s) => types.includes(s.section_type) && s.content).sort((a, b) => SECTION_ORDER[a.section_type] - SECTION_ORDER[b.section_type]).map((s) => `## ${SECTION_DISPLAY_NAMES[s.section_type]} - -${s.content.trim()}`).join("\n\n"); +function _ksuid(Class2, params) { + return new Class2({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -function jiraContent(state) { - const last = [...state.sections].reverse().find((s) => s.section_type === "jira_tickets" && s.content); - return last?.content?.trim() ?? ""; +function _ipv4(Class2, params) { + return new Class2({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -function buildFileSet(state) { - const slug = state.run_id.slice(0, 8); - const base = `${OUTPUT_DIR}/${slug}`; - return [ - { - path: `${base}/01-prd.md`, - content: () => [ - `# PRD: ${state.feature_description}`, - "", - `Run ID: ${state.run_id}`, - `Context: ${state.prd_context ?? "unknown"}`, - "", - joinSections(state, [ - "overview", - "goals", - "requirements", - "user_stories", - "technical_specification", - "acceptance_criteria" - ]) - ].join("\n") - }, - { - path: `${base}/02-data-model.md`, - content: () => joinSections(state, ["data_model"]) || "_No data model section._" - }, - { - path: `${base}/03-api-spec.md`, - content: () => joinSections(state, ["api_specification"]) || "_No API spec section._" - }, - { - path: `${base}/04-security.md`, - content: () => joinSections(state, [ - "security_considerations", - "performance_requirements" - ]) || "_No security/performance sections._" - }, - { - path: `${base}/05-testing.md`, - content: () => joinSections(state, ["testing", "acceptance_criteria"]) || "_No testing section._" - }, - { - path: `${base}/06-deployment.md`, - content: () => joinSections(state, ["deployment", "timeline", "risks"]) || "_No deployment section._" - }, - { - path: `${base}/07-jira-tickets.md`, - content: () => jiraContent(state) || "_No JIRA tickets generated._" - }, - { - path: `${base}/08-source-code.md`, - content: () => joinSections(state, ["source_code"]) || "_Source code section not generated in this run._" - }, - { - path: `${base}/09-test-code.md`, - content: () => joinSections(state, ["test_code"]) || "_Test code section not generated in this run._" - } - ]; +function _ipv6(Class2, params) { + return new Class2({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -var OUTPUT_DIR, handleFileExport; -var init_file_export = __esm({ - async "packages/orchestration/dist/handlers/file-export.js"() { - "use strict"; - await init_state(); - await init_dist(); - OUTPUT_DIR = "prd-output"; - handleFileExport = ({ state, result }) => { - let nextState = state; - if (result && result.kind !== "file_written") { - nextState = appendError(state, `[file_export] unexpected result kind '${result.kind}'; re-issuing write`, "structural"); - } - if (result?.kind === "file_written") { - if (!state.written_files.includes(result.path)) { - nextState = { - ...state, - written_files: [...state.written_files, result.path] - }; - } - } - const files = buildFileSet(nextState); - const done = new Set(nextState.written_files); - const remaining = files.filter((f) => !done.has(f.path)); - if (remaining.length === 0) { - return { - state: { ...nextState, current_step: "self_check" }, - action: { - kind: "emit_message", - message: `All ${files.length} files written. Running self-check.` - } - }; - } - const next = remaining[0]; - return { - state: nextState, - action: { - kind: "write_file", - path: next.path, - content: next.content() - } - }; - }; - } -}); - -// packages/verification/dist/judge-selector.js -function genius(name315) { - return { kind: "genius", name: name315 }; +function _cidrv4(Class2, params) { + return new Class2({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -function team(name315) { - return { kind: "team", name: name315 }; +function _cidrv6(Class2, params) { + return new Class2({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -function selectJudges(claim) { - const panel = PANELS[claim.claim_type]; - return [...panel.genius, ...panel.team]; +function _base64(Class2, params) { + return new Class2({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -var PANELS; -var init_judge_selector = __esm({ - "packages/verification/dist/judge-selector.js"() { - "use strict"; - PANELS = { - // Substitutability, near-decomposability, pattern fit - architecture: { - genius: [genius("liskov"), genius("simon"), genius("alexander")], - team: [team("code-reviewer"), team("architect")], - high_stakes: true - }, - // Order-of-magnitude sanity, queuing limits, efficiency bounds - performance: { - genius: [genius("fermi"), genius("erlang"), genius("carnot")], - team: [team("code-reviewer")], - high_stakes: true - }, - // Invariant reasoning, happens-before, contract substitutability - correctness: { - genius: [genius("dijkstra"), genius("lamport"), genius("liskov")], - team: [team("test-engineer"), team("engineer")], - high_stakes: true - }, - // Correctness discipline, error archaeology, integrity audit - security: { - genius: [genius("dijkstra"), genius("wu"), genius("feynman")], - team: [team("security-auditor")], - high_stakes: true - }, - // Mass-balance accounting, contract substitutability, predictive table - data_model: { - genius: [genius("lavoisier"), genius("liskov"), genius("mendeleev")], - team: [team("dba"), team("code-reviewer")], - high_stakes: true - }, - // Falsifiability, integrity audit, error archaeology - test_coverage: { - genius: [genius("popper"), genius("feynman"), genius("wu")], - team: [team("test-engineer")], - high_stakes: false - }, - // Order-of-magnitude + conservation - story_point_arithmetic: { - genius: [genius("fermi"), genius("lavoisier")], - team: [], - high_stakes: false - }, - // Four-causes interrogation, claim-evidence-warrant chains - fr_traceability: { - genius: [genius("aristotle"), genius("toulmin")], - team: [team("code-reviewer")], - high_stakes: false - }, - // Fragility classification, debiasing, falsifiability - risk: { - genius: [genius("taleb"), genius("kahneman"), genius("popper")], - team: [], - high_stakes: false - }, - // Exhaustive-space audit, gaps-in-the-table - acceptance_criteria_completeness: { - genius: [genius("borges"), genius("mendeleev")], - team: [team("test-engineer")], - high_stakes: false - }, - // Generative consistency rules, exhaustive enumeration - cross_file_consistency: { - genius: [genius("panini"), genius("euler")], - team: [team("code-reviewer")], - high_stakes: true - } - }; - } -}); - -// packages/verification/dist/claim-extractor.js -function snippet2(content, line, before = 2, after = 2) { - const lines = content.split(/\r?\n/); - const idx = lines.findIndex((l) => l.trim() === line.trim()); - if (idx === -1) - return line; - const start = Math.max(0, idx - before); - const end = Math.min(lines.length, idx + after + 1); - return lines.slice(start, end).join("\n"); +function _base64url(Class2, params) { + return new Class2({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -function* matchAllLines(re2, content) { - for (const line of content.split(/\r?\n/)) { - const m = line.match(re2); - if (m) - yield m; - } +function _e164(Class2, params) { + return new Class2({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -function extractParagraphContaining(content, keyword) { - const lower = content.toLowerCase(); - const lowerKw = keyword.toLowerCase(); - const idx = lower.indexOf(lowerKw); - if (idx === -1) - return content.slice(0, 400); - const start = Math.max(0, content.lastIndexOf("\n\n", idx)); - let end = content.indexOf("\n\n", idx); - if (end === -1) - end = Math.min(content.length, idx + 400); - return content.slice(start, end).trim(); +function _jwt(Class2, params) { + return new Class2({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); } -function extractClaims(sectionType, content) { - const extractors = EXTRACTORS_BY_SECTION[sectionType] ?? []; - const claims = []; - for (const ex of extractors) { - claims.push(...ex({ section_type: sectionType, content })); - } - return dedupeById(claims); +function _isoDateTime(Class2, params) { + return new Class2({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params) + }); } -function extractClaimsFromDocument(sections) { - const claims = []; - for (const s of sections) { - claims.push(...extractClaims(s.type, s.content)); - } - return dedupeById(claims); +function _isoDate(Class2, params) { + return new Class2({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params) + }); } -function dedupeById(claims) { - const seen = /* @__PURE__ */ new Map(); - for (const c of claims) { - if (!seen.has(c.claim_id)) - seen.set(c.claim_id, c); - } - return Array.from(seen.values()); +function _isoTime(Class2, params) { + return new Class2({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params) + }); } -var FR_LINE_RE, extractRequirements, AC_LINE_RE, extractAcceptanceCriteria, NFR_PATTERNS, extractPerformance, ARCH_PATTERNS, extractArchitecture, SECURITY_KEYWORDS, extractSecurity, DDL_RE, extractDataModel, TEST_FN_RE, extractTests, RISK_LINE_RE, extractRisks, SP_TOTAL_RE, extractStoryPoints, EXTRACTORS_BY_SECTION; -var init_claim_extractor = __esm({ - "packages/verification/dist/claim-extractor.js"() { - "use strict"; - FR_LINE_RE = /^\s*(?:-|\*|\|)?\s*(FR-\d{3,})\s*[|:\-–—]\s*(.+?)\s*(?:\||$)/i; - extractRequirements = ({ content, section_type }) => { - const claims = []; - for (const m of matchAllLines(FR_LINE_RE, content)) { - const id = m[1].toUpperCase(); - const text = m[2].trim(); - if (!text) - continue; - claims.push({ - claim_id: id, - claim_type: "fr_traceability", - text: `Functional requirement: ${text}`, - evidence: snippet2(content, m[0]), - source_section: section_type - }); - } - return claims; - }; - AC_LINE_RE = /^\s*(?:-|\*|\|)?\s*(AC-\d{3,})\s*[|:\-–—]\s*(.+?)\s*(?:\||$)/i; - extractAcceptanceCriteria = ({ content, section_type }) => { - const claims = []; - for (const m of matchAllLines(AC_LINE_RE, content)) { - const id = m[1].toUpperCase(); - const text = m[2].trim(); - if (!text) - continue; - claims.push({ - claim_id: id, - claim_type: "acceptance_criteria_completeness", - text: `Acceptance criterion: ${text}`, - evidence: snippet2(content, m[0]), - source_section: section_type - }); - } - return claims; - }; - NFR_PATTERNS = [ - { re: /\b(?:p\d{2}|p99|p95|p50)\s*[<>=≤≥]+\s*(\d+(?:\.\d+)?\s*(?:ms|s|µs|us))/gi, subtype: "LATENCY" }, - { re: /\b(\d+(?:\.\d+)?\s*(?:rps|req\/s|qps|requests?\/(?:sec|second)))/gi, subtype: "THROUGHPUT" }, - { re: /\b(\d+(?:\.\d+)?\s*fps)/gi, subtype: "FRAMERATE" }, - { re: /\b(\d+(?:\.\d+)?\s*(?:GB|MB|TB|KB)\b)/gi, subtype: "STORAGE" } - ]; - extractPerformance = ({ content, section_type }) => { - const claims = []; - for (const { re: re2, subtype } of NFR_PATTERNS) { - let counter = 0; - for (const m of content.matchAll(re2)) { - counter += 1; - claims.push({ - claim_id: `NFR-${subtype}-${counter.toString().padStart(2, "0")}`, - claim_type: "performance", - text: `Performance target: ${m[0]}`, - evidence: snippet2(content, m[0], 1, 1), - source_section: section_type - }); - } - } - return claims; - }; - ARCH_PATTERNS = [ - { re: /ports?[\s\-]?(?:and|\/)?[\s\-]?adapters?/i, label: "ports-and-adapters" }, - { re: /clean\s+architecture/i, label: "clean-architecture" }, - { re: /hexagonal/i, label: "hexagonal" }, - { re: /domain[\s-]+driven\s+design|\bDDD\b/i, label: "ddd" }, - { re: /event[\s-]+driven/i, label: "event-driven" }, - { re: /micro[\s-]?services?/i, label: "microservices" }, - { re: /repository\s+pattern/i, label: "repository-pattern" }, - { re: /CQRS/i, label: "cqrs" } - ]; - extractArchitecture = ({ content, section_type }) => { - const claims = []; - for (const { re: re2, label } of ARCH_PATTERNS) { - if (re2.test(content)) { - const m = content.match(re2); - claims.push({ - claim_id: `ARCH-${label.toUpperCase()}`, - claim_type: "architecture", - text: `Architecture pattern claim: ${label}`, - evidence: snippet2(content, m[0], 3, 3), - source_section: section_type - }); - } - } - return claims; - }; - SECURITY_KEYWORDS = [ - "authentication", - "authorization", - "encryption", - "secrets", - "PII", - "OAuth", - "JWT", - "TLS", - "AES", - "SHA", - "hash", - "token", - "session" - ]; - extractSecurity = ({ content, section_type }) => { - const claims = []; - const lower = content.toLowerCase(); - let counter = 0; - for (const kw of SECURITY_KEYWORDS) { - if (lower.includes(kw.toLowerCase())) { - counter += 1; - claims.push({ - claim_id: `SEC-${counter.toString().padStart(2, "0")}-${kw.toUpperCase()}`, - claim_type: "security", - text: `Security claim involving ${kw}`, - evidence: extractParagraphContaining(content, kw), - source_section: section_type - }); - } - } - return claims; - }; - DDL_RE = /(CREATE\s+(?:TABLE|TYPE|ENUM|INDEX|VIEW)\s+\w+[\s\S]*?;)/gi; - extractDataModel = ({ content, section_type }) => { - const claims = []; - let counter = 0; - for (const m of content.matchAll(DDL_RE)) { - counter += 1; - const ddl = m[1]; - const nameMatch = ddl.match(/CREATE\s+(?:TABLE|TYPE|ENUM|INDEX|VIEW)\s+(\w+)/i); - const name315 = nameMatch?.[1] ?? "anonymous"; - claims.push({ - claim_id: `DDL-${counter.toString().padStart(2, "0")}-${name315.toUpperCase()}`, - claim_type: "data_model", - text: `Schema definition: ${name315}`, - evidence: ddl.slice(0, 600), - source_section: section_type - }); - } - return claims; - }; - TEST_FN_RE = /(?:func|def|fn|it|test)\s+(test_?\w+|\w*Test\w*)\s*\(/gi; - extractTests = ({ content, section_type }) => { - const claims = []; - let counter = 0; - for (const m of content.matchAll(TEST_FN_RE)) { - counter += 1; - claims.push({ - claim_id: `TEST-${counter.toString().padStart(3, "0")}-${m[1].slice(0, 32)}`, - claim_type: "test_coverage", - text: `Test function: ${m[1]}`, - evidence: snippet2(content, m[0], 2, 4), - source_section: section_type - }); - } - return claims; - }; - RISK_LINE_RE = /^\s*(?:-|\*)\s*(?:\*\*Risk\*\*[:|]?\s*)?(.+?(?:risk|failure|hazard|threat|attack|vulnerab).+)$/i; - extractRisks = ({ content, section_type }) => { - const claims = []; - let counter = 0; - for (const m of matchAllLines(RISK_LINE_RE, content)) { - counter += 1; - claims.push({ - claim_id: `RISK-${counter.toString().padStart(2, "0")}`, - claim_type: "risk", - text: m[1].trim(), - evidence: snippet2(content, m[0]), - source_section: section_type - }); - } - return claims; - }; - SP_TOTAL_RE = /total\s*[:|=]\s*(\d+)\s*(?:sp|story\s*points?)?/gi; - extractStoryPoints = ({ content, section_type }) => { - const claims = []; - let counter = 0; - for (const m of content.matchAll(SP_TOTAL_RE)) { - counter += 1; - claims.push({ - claim_id: `SP-TOTAL-${counter.toString().padStart(2, "0")}`, - claim_type: "story_point_arithmetic", - text: `Story-point total claim: ${m[0]}`, - evidence: snippet2(content, m[0]), - source_section: section_type - }); - } - return claims; - }; - EXTRACTORS_BY_SECTION = { - requirements: [extractRequirements], - user_stories: [extractStoryPoints], - technical_specification: [extractArchitecture], - acceptance_criteria: [extractAcceptanceCriteria], - data_model: [extractDataModel], - api_specification: [extractRequirements], - // FR-style endpoint claims - security_considerations: [extractSecurity], - performance_requirements: [extractPerformance], - testing: [extractTests], - test_code: [extractTests], - risks: [extractRisks], - timeline: [extractStoryPoints] - }; - } -}); - -// packages/verification/dist/consensus-strategy.js -function agentKey(agent) { - return `${agent.kind}:${agent.name}`; +function _isoDuration(Class2, params) { + return new Class2({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params) + }); } -function clampUnit(x) { - if (!Number.isFinite(x)) - return 0; - return Math.min(1, Math.max(0, x)); +function _number(Class2, params) { + return new Class2({ + type: "number", + checks: [], + ...normalizeParams(params) + }); } -function verdictToDirection(verdict) { - if (verdict === "PASS" || verdict === "SPEC-COMPLETE") { - return "specificity_arm"; - } - return "sensitivity_arm"; +function _int(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams(params) + }); } -function resolveReliability(judge, runId, claimType, direction, reliabilityProvider, reliabilityLookup, reliabilityMap) { - if (reliabilityProvider !== void 0 && runId !== void 0 && claimType !== void 0) { - const record2 = reliabilityProvider.getReliabilityForRun(runId, judge, claimType, direction); - if (record2 !== null) { - return clampUnit(record2.alpha / (record2.alpha + record2.beta)); - } - } - if (reliabilityLookup !== void 0 && claimType !== void 0) { - const record2 = reliabilityLookup(judge, claimType, direction); - if (record2 !== null) { - return clampUnit(record2.alpha / (record2.alpha + record2.beta)); - } - } - const key = agentKey(judge); - const mapped = reliabilityMap.get(key); - if (mapped !== void 0) { - return clampUnit(mapped); - } - return DEFAULT_RELIABILITY_PRIOR.alpha / (DEFAULT_RELIABILITY_PRIOR.alpha + DEFAULT_RELIABILITY_PRIOR.beta); +function _boolean(Class2, params) { + return new Class2({ + type: "boolean", + ...normalizeParams(params) + }); } -function uniformPrior() { - return { - PASS: 0.2, - "SPEC-COMPLETE": 0.2, - "NEEDS-RUNTIME": 0.2, - INCONCLUSIVE: 0.2, - FAIL: 0.2 - }; +function _null2(Class2, params) { + return new Class2({ + type: "null", + ...normalizeParams(params) + }); } -function updatePosterior(prior, observed, reliability) { - const r = clampUnit(reliability); - const likelihood = { - PASS: 0, - "SPEC-COMPLETE": 0, - "NEEDS-RUNTIME": 0, - INCONCLUSIVE: 0, - FAIL: 0 - }; - const other = (1 - r) / 4; - for (const v of VERDICTS) { - likelihood[v] = v === observed ? r : other; - } - const posterior = { - PASS: 0, - "SPEC-COMPLETE": 0, - "NEEDS-RUNTIME": 0, - INCONCLUSIVE: 0, - FAIL: 0 - }; - let total = 0; - for (const v of VERDICTS) { - posterior[v] = prior[v] * likelihood[v]; - total += posterior[v]; - } - if (total > 0) { - for (const v of VERDICTS) - posterior[v] /= total; - } - return posterior; +function _unknown(Class2) { + return new Class2({ + type: "unknown" + }); } -function pickMaxVerdict(d) { - let best = "PASS"; - let bestScore = -Infinity; - for (const v of VERDICTS) { - const s = d[v]; - if (s > bestScore || s === bestScore && VERDICT_SEVERITY[v] > VERDICT_SEVERITY[best]) { - best = v; - bestScore = s; - } - } - return best; +function _never(Class2, params) { + return new Class2({ + type: "never", + ...normalizeParams(params) + }); } -function bayesian(claim_id, verdicts, config5) { - let posterior = uniformPrior(); - const reliabilityMap = config5.reliability ?? /* @__PURE__ */ new Map(); - for (const v of verdicts) { - const direction = verdictToDirection(v.verdict); - const rawReliability = resolveReliability(v.judge, config5.runId, config5.claimType, direction, config5.reliabilityProvider, config5.reliabilityLookup, reliabilityMap); - const reliability = clampUnit(rawReliability); - const confidence2 = clampUnit(v.confidence); - const adjustedReliability = reliability * confidence2; - if (adjustedReliability <= NO_INFORMATION_FLOOR) { - continue; - } - posterior = updatePosterior(posterior, v.verdict, adjustedReliability); - } - const distribution = { - PASS: 0, - "SPEC-COMPLETE": 0, - "NEEDS-RUNTIME": 0, - INCONCLUSIVE: 0, - FAIL: 0 - }; - for (const v of VERDICTS) { - distribution[v] = posterior[v]; - } - const chosen = pickMaxVerdict(distribution); - const confidence = distribution[chosen]; - const unanimous = verdicts.every((v) => v.verdict === chosen); - const dissenting = verdicts.filter((v) => v.verdict !== chosen); - return { - claim_id, - verdict: chosen, - confidence, - unanimous, - dissenting, - distribution, - strategy: "bayesian", - judges: verdicts.map((v) => v.judge) - }; +function _lt(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: false + }); } -var VERDICTS, VERDICT_SEVERITY, NO_INFORMATION_FLOOR; -var init_consensus_strategy = __esm({ - async "packages/verification/dist/consensus-strategy.js"() { - "use strict"; - await init_dist(); - VERDICTS = [ - "PASS", - "SPEC-COMPLETE", - "NEEDS-RUNTIME", - "INCONCLUSIVE", - "FAIL" - ]; - VERDICT_SEVERITY = { - PASS: 0, - "SPEC-COMPLETE": 1, - "NEEDS-RUNTIME": 2, - INCONCLUSIVE: 3, - FAIL: 4 - }; - NO_INFORMATION_FLOOR = 0.2; - } -}); - -// packages/verification/dist/consensus.js -function clampUnit2(x) { - if (!Number.isFinite(x)) - return 0; - return Math.min(1, Math.max(0, x)); +function _lte(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: true + }); } -function consensus(claim_id, verdicts, config5 = {}) { - if (verdicts.length === 0) { - return { - claim_id, - verdict: "INCONCLUSIVE", - confidence: 0, - unanimous: false, - dissenting: [], - distribution: emptyDistribution(), - strategy: config5.strategy ?? DEFAULT_CONFIG.strategy, - judges: [] - }; - } - const strategy = config5.strategy ?? DEFAULT_CONFIG.strategy; - switch (strategy) { - case "weighted_average": - return weightedAverage(claim_id, verdicts, config5); - case "bayesian": - return bayesian(claim_id, verdicts, config5); - } +function _gt(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: false + }); } -function weightedAverage(claim_id, verdicts, config5) { - const distribution = emptyDistribution(); - let totalWeight = 0; - for (const v of verdicts) { - const w = clampUnit2(v.confidence); - distribution[v.verdict] += w; - totalWeight += w; - } - if (totalWeight === 0) { - for (const v of verdicts) - distribution[v.verdict] += 1; - totalWeight = verdicts.length; - } - const failThreshold = config5.fail_threshold ?? DEFAULT_CONFIG.fail_threshold; - const failWeight = distribution.FAIL; - const failFrac = totalWeight > 0 ? failWeight / totalWeight : 0; - let chosen; - if (failFrac >= failThreshold) { - chosen = "FAIL"; - } else { - chosen = pickMaxVerdict2(distribution); - } - const confidence = totalWeight > 0 ? distribution[chosen] / totalWeight : 0; - const unanimous = verdicts.every((v) => v.verdict === chosen); - const dissenting = verdicts.filter((v) => v.verdict !== chosen); - return { - claim_id, - verdict: chosen, - confidence, - unanimous, - dissenting, - distribution: normalizeDistribution(distribution, totalWeight), - strategy: "weighted_average", - judges: verdicts.map((v) => v.judge) - }; +function _gte(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: true + }); } -function emptyDistribution() { - return { - PASS: 0, - "SPEC-COMPLETE": 0, - "NEEDS-RUNTIME": 0, - INCONCLUSIVE: 0, - FAIL: 0 - }; +function _multipleOf(value, params) { + return new $ZodCheckMultipleOf({ + check: "multiple_of", + ...normalizeParams(params), + value + }); } -function normalizeDistribution(d, total) { - if (total <= 0) - return d; - const out = emptyDistribution(); - for (const v of VERDICTS2) - out[v] = d[v] / total; - return out; +function _maxLength(maximum, params) { + const ch = new $ZodCheckMaxLength({ + check: "max_length", + ...normalizeParams(params), + maximum + }); + return ch; } -function pickMaxVerdict2(d) { - let best = "PASS"; - let bestScore = -Infinity; - for (const v of VERDICTS2) { - const s = d[v]; - if (s > bestScore || s === bestScore && VERDICT_SEVERITY2[v] > VERDICT_SEVERITY2[best]) { - best = v; - bestScore = s; - } - } - return best; +function _minLength(minimum, params) { + return new $ZodCheckMinLength({ + check: "min_length", + ...normalizeParams(params), + minimum + }); } -var VERDICT_SEVERITY2, VERDICTS2, DEFAULT_CONFIG; -var init_consensus = __esm({ - async "packages/verification/dist/consensus.js"() { - "use strict"; - await init_consensus_strategy(); - await init_consensus_strategy(); - VERDICT_SEVERITY2 = { - PASS: 0, - "SPEC-COMPLETE": 1, - "NEEDS-RUNTIME": 2, - INCONCLUSIVE: 3, - FAIL: 4 - }; - VERDICTS2 = [ - "PASS", - "SPEC-COMPLETE", - "NEEDS-RUNTIME", - "INCONCLUSIVE", - "FAIL" - ]; - DEFAULT_CONFIG = { - strategy: "weighted_average", - // source: see ConsensusConfig.fail_threshold doc-comment. - fail_threshold: 0.5 - }; - } -}); - -// packages/verification/dist/orchestrator.js -function planSectionVerification(sectionType, content, options = {}) { - const claims = extractClaims(sectionType, content); - const judge_requests = buildRequests(claims, options, content); - return { claims, judge_requests }; +function _length(length, params) { + return new $ZodCheckLengthEquals({ + check: "length_equals", + ...normalizeParams(params), + length + }); } -function planDocumentVerification(sections, options = {}) { - const claims = extractClaimsFromDocument(sections); - const concatenated = sections.map((s) => `## ${s.type} - -${s.content}`).join("\n\n"); - const judge_requests = buildRequests(claims, options, concatenated); - return { claims, judge_requests }; +function _regex(pattern, params) { + return new $ZodCheckRegex({ + check: "string_format", + format: "regex", + ...normalizeParams(params), + pattern + }); } -function buildRequests(claims, options, prdExcerpt) { - const requests = []; - const includePrd = options.include_prd_excerpt !== false; - for (const claim of claims) { - const judges = selectJudges(claim); - for (const judge of judges) { - requests.push({ - judge, - claim, - context: { - prd_excerpt: includePrd ? prdExcerpt : void 0, - codebase_excerpts: [...options.codebase_excerpts ?? []], - memory_excerpts: [...options.memory_excerpts ?? []] - } - }); - } - } - return requests; +function _lowercase(params) { + return new $ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...normalizeParams(params) + }); } -function concludeSection(sectionType, verdicts, options = {}) { - return concludeFromVerdicts(sectionType, verdicts, options); +function _uppercase(params) { + return new $ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...normalizeParams(params) + }); } -function concludeDocument(verdicts, options = {}) { - return concludeFromVerdicts("document", verdicts, options); +function _includes(includes, params) { + return new $ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...normalizeParams(params), + includes + }); } -function groundTruthToIsFail(verdict) { - return verdict !== "PASS"; +function _startsWith(prefix, params) { + return new $ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...normalizeParams(params), + prefix + }); } -function concludeFromVerdicts(scope, verdicts, options) { - const byClaim = /* @__PURE__ */ new Map(); - for (const v of verdicts) { - const list = byClaim.get(v.claim_id) ?? []; - list.push(v); - byClaim.set(v.claim_id, list); - } - const results = []; - for (const [claim_id, vs] of byClaim) { - const claimType = options.claimTypes?.get(claim_id); - const batchConfig = claimType !== void 0 ? { ...options, claimType } : options; - const result = consensus(claim_id, vs, batchConfig); - results.push(result); - if (options.onObservation !== void 0 && claimType !== void 0) { - const groundTruthIsFail = groundTruthToIsFail(result.verdict); - const claim = options.claims?.get(claim_id); - const external_grounding = claim?.external_grounding; - for (const jv of vs) { - const judgeWasCorrect = groundTruthIsFail ? jv.verdict !== "PASS" && jv.verdict !== "SPEC-COMPLETE" : jv.verdict === "PASS" || jv.verdict === "SPEC-COMPLETE"; - try { - options.onObservation({ - claim_id, - judge: jv.judge, - claimType, - observation: { groundTruthIsFail, judgeWasCorrect }, - external_grounding - }); - } catch { - } - } - } - } - const distribution = { - PASS: 0, - "SPEC-COMPLETE": 0, - "NEEDS-RUNTIME": 0, - INCONCLUSIVE: 0, - FAIL: 0 - }; - for (const r of results) - distribution[r.verdict] += 1; - const failures = results.filter((r) => r.verdict === "FAIL"); - const warnings = results.filter((r) => r.verdict === "INCONCLUSIVE" || r.verdict === "NEEDS-RUNTIME" || r.verdict === "SPEC-COMPLETE"); - const passRate = results.length > 0 ? distribution.PASS / results.length : 0; - const SUSPICIOUS_MIN_CLUSTER = 5; - const SUSPICIOUS_PASS_RATE = 1; - const distribution_suspicious = results.length >= SUSPICIOUS_MIN_CLUSTER && passRate >= SUSPICIOUS_PASS_RATE; - return { - section_type: scope, - claims_evaluated: results.length, - judges_invoked: verdicts.length, - results, - distribution, - failures, - warnings, - distribution_suspicious - }; +function _endsWith(suffix, params) { + return new $ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...normalizeParams(params), + suffix + }); } -var init_orchestrator = __esm({ - async "packages/verification/dist/orchestrator.js"() { - "use strict"; - init_claim_extractor(); - init_judge_selector(); - await init_consensus(); - } -}); - -// packages/verification/dist/judge-prompt.js -function buildJudgePrompt(req) { - const { judge, claim, context } = req; - const judgeDescription = judge.kind === "genius" ? `Apply the ${judge.name} reasoning pattern to evaluate the claim.` : `Apply your ${judge.name} role expertise to evaluate the claim.`; - const prdExcerpt = context.prd_excerpt ? ` -${context.prd_excerpt} - - -` : ""; - const codebaseSection = context.codebase_excerpts.length ? ` -${context.codebase_excerpts.join("\n---\n")} - - -` : ""; - const memorySection = context.memory_excerpts.length ? ` -${context.memory_excerpts.join("\n---\n")} - - -` : ""; - const prompt = [ - `You are acting as a verification judge for a PRD.`, - judgeDescription, - "", - ``, - `id: ${claim.claim_id}`, - `type: ${claim.claim_type}`, - `source_section: ${claim.source_section ?? "(unspecified)"}`, - `text: ${claim.text}`, - ``, - "", - ``, - claim.evidence, - ``, - "", - prdExcerpt + codebaseSection + memorySection, - ``, - VERDICT_TAXONOMY, - ``, - "", - `Return EXACTLY ONE JSON object matching this schema and nothing else (no prose before or after, no markdown fences):`, - "", - RESPONSE_SCHEMA, - "", - `Constraints:`, - `- Do NOT default to PASS. If you would assign PASS to every claim of this type, you are not doing your job.`, - `- NFR claims (latency, throughput, fps, storage) MUST NOT receive PASS. Use SPEC-COMPLETE or NEEDS-RUNTIME.`, - `- "rationale" must be specific to THIS claim, not a generic rubric.`, - `- "confidence" reflects how sure you are about the verdict, not how confident you are about the claim.` - ].join("\n"); - return { - description: `Judge ${claim.claim_id} (${judge.kind}:${judge.name})`, - subagent_type: agentSubagentType(judge), - prompt - }; -} -var VERDICT_TAXONOMY, RESPONSE_SCHEMA; -var init_judge_prompt = __esm({ - async "packages/verification/dist/judge-prompt.js"() { - "use strict"; - await init_dist(); - VERDICT_TAXONOMY = ` -| Verdict | Meaning | When to use | -|---------|---------|-------------| -| PASS | Claim is structurally complete AND verifiable from the document | FR traceability, AC completeness, SP arithmetic, structural checks | -| SPEC-COMPLETE | A test or measurement method is specified, but runtime data is needed to confirm | NFR performance targets (latency, fps, throughput), scalability limits | -| NEEDS-RUNTIME | Claim cannot be verified at design time at all | Load test results, p95 latency under prod traffic, real-world storage usage | -| INCONCLUSIVE | Claim depends on an unresolved open question or external factor | Claims referencing OQ-XXX, vendor SLA, regulatory interpretation | -| FAIL | Claim is structurally invalid or contradicts other claims | Arithmetic errors, orphan references, circular dependencies | - -NFR claims about latency, fps, throughput, or storage MUST NOT receive PASS. -They receive SPEC-COMPLETE (if a test method is specified) or NEEDS-RUNTIME. -`.trim(); - RESPONSE_SCHEMA = ` -{ - "verdict": "PASS" | "SPEC-COMPLETE" | "NEEDS-RUNTIME" | "INCONCLUSIVE" | "FAIL", - "rationale": "", - "caveats": ["", "..."], - "confidence": -} -`.trim(); - } -}); - -// packages/verification/dist/index.js -var init_dist5 = __esm({ - async "packages/verification/dist/index.js"() { - "use strict"; - init_judge_selector(); - init_claim_extractor(); - await init_consensus(); - await init_orchestrator(); - await init_judge_prompt(); - } -}); - -// packages/orchestration/dist/handlers/self-check.js -function invocationIdFor(idx) { - return `${SELF_CHECK_JUDGE_INV_PREFIX}${idx.toString().padStart(4, "0")}`; +function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx + }); } -function gatherSections(state) { - return state.sections.filter((s) => s.content && s.section_type !== "jira_tickets").map((s) => ({ type: s.section_type, content: s.content })); +function _normalize(form) { + return _overwrite((input) => input.normalize(form)); } -function buildVerifyAction(requests) { - return { - kind: "spawn_subagents", - purpose: "judge", - batch_id: VERIFY_BATCH_ID, - invocations: requests.map((req, idx) => { - const built = buildJudgePrompt(req); - return { - invocation_id: invocationIdFor(idx), - subagent_type: agentSubagentType(req.judge), - description: built.description, - prompt: built.prompt, - isolation: "none" - }; - }) - }; +function _trim() { + return _overwrite((input) => input.trim()); } -function parseVerdicts(index2, batchResult) { - const byId = /* @__PURE__ */ new Map(); - for (const r of batchResult.responses) { - if (byId.has(r.invocation_id)) { - byId.set(r.invocation_id, { - invocation_id: r.invocation_id, - error: `duplicate invocation_id in batch: ${r.invocation_id}` - }); - } else { - byId.set(r.invocation_id, r); - } - } - const out = []; - for (const entry of index2) { - const response = byId.get(entry.invocation_id); - if (!response || response.error || !response.raw_text) { - out.push({ - judge: entry.request.judge, - claim_id: entry.request.claim.claim_id, - verdict: "INCONCLUSIVE", - rationale: response?.error ?? "no response", - caveats: ["judge_invocation_failed"], - confidence: 0 - }); - continue; - } - try { - const obj = extractJsonObject(response.raw_text); - const parsed = RawVerdictSchema.parse(obj); - out.push({ - judge: entry.request.judge, - claim_id: entry.request.claim.claim_id, - verdict: parsed.verdict, - rationale: parsed.rationale, - caveats: parsed.caveats, - confidence: parsed.confidence - }); - } catch (err) { - out.push({ - judge: entry.request.judge, - claim_id: entry.request.claim.claim_id, - verdict: "INCONCLUSIVE", - rationale: `parse failure: ${err.message}`, - caveats: ["parse_error"], - confidence: 0 - }); - } - } - return out; +function _toLowerCase() { + return _overwrite((input) => input.toLowerCase()); } -function finalize(state, verdicts = []) { - const sections = gatherSections(state); - const docReport = validateDocument(sections); - const verificationReport = concludeDocument(verdicts); - const sectionsPassed = state.sections.filter((s) => s.status === "passed").length; - const sectionsFailed = state.sections.filter((s) => s.status === "failed").length; - const sectionsTotal = state.sections.length; - const docCritical = docReport.violations.filter((v) => v.isCritical).length; - const summary = [ - `Self-check complete.`, - `Sections: ${sectionsPassed}/${sectionsTotal} passed, ${sectionsFailed} failed.`, - `Deterministic violations: ${docReport.violations.length} (${docCritical} critical)`, - `Hard-output score: ${docReport.totalScore.toFixed(2)} / 1.00`, - `Multi-judge claims: ${verificationReport.claims_evaluated}`, - ` PASS: ${verificationReport.distribution.PASS}`, - ` SPEC-COMPLETE: ${verificationReport.distribution["SPEC-COMPLETE"]}`, - ` NEEDS-RUNTIME: ${verificationReport.distribution["NEEDS-RUNTIME"]}`, - ` INCONCLUSIVE: ${verificationReport.distribution.INCONCLUSIVE}`, - ` FAIL: ${verificationReport.distribution.FAIL}`, - verificationReport.distribution_suspicious ? ` \u26A0 Distribution suspicious \u2014 100% PASS suggests confirmatory bias.` : "" - ].filter((l) => l !== "").join("\n"); - return { - state: { ...state, current_step: "complete" }, - action: { - kind: "done", - summary, - artifacts: state.sections.map((s) => `${s.section_type}: ${s.status}`), - // Typed verification surface (Phase 3+4 cross-audit closure). Callers - // MUST consume this field, not regex-parse `summary`. The string - // remains as a human-readable artifact only. - verification: { - claims_evaluated: verificationReport.claims_evaluated, - distribution: verificationReport.distribution, - distribution_suspicious: verificationReport.distribution_suspicious - } - } - }; +function _toUpperCase() { + return _overwrite((input) => input.toUpperCase()); } -function handleSelfCheckPhaseA(state) { - const sections = gatherSections(state); - if (sections.length === 0) { - return finalize(state); - } - const plan = planDocumentVerification(sections); - if (plan.judge_requests.length === 0) { - return finalize(state); - } - return { - state: { - ...state, - verification_plan: { - batch_id: VERIFY_BATCH_ID, - claim_ids: plan.judge_requests.map((r) => r.claim.claim_id), - judges: plan.judge_requests.map((r) => r.judge) - } - }, - action: buildVerifyAction(plan.judge_requests) - }; +function _array(Class2, element, params) { + return new Class2({ + type: "array", + element, + // get element() { + // return element; + // }, + ...normalizeParams(params) + }); } -function handleSelfCheckPhaseB(state, result) { - const snapshot = state.verification_plan; - if (!snapshot || snapshot.batch_id !== VERIFY_BATCH_ID) { - return finalize(state); - } - const verdicts = parseVerdictsFromSnapshot(snapshot, state, result); - let stateAfter = { ...state, verification_plan: null }; - const mismatchSeen = /* @__PURE__ */ new Set(); - for (const v of verdicts) { - for (const caveat of v.caveats) { - if (caveat.startsWith("mismatch_kind:") && !mismatchSeen.has(caveat)) { - mismatchSeen.add(caveat); - stateAfter = appendError(stateAfter, `[self_check] plan mismatch detected \u2014 ${caveat}`, "structural"); - } - } - } - return finalize(stateAfter, verdicts); +function _custom(Class2, fn, _params) { + const norm2 = normalizeParams(_params); + norm2.abort ?? (norm2.abort = true); + const schema2 = new Class2({ + type: "custom", + check: "custom", + fn, + ...norm2 + }); + return schema2; } -function parseVerdictsFromSnapshot(snapshot, state, batchResult) { - const sections = gatherSections(state); - const rederived = planDocumentVerification(sections).judge_requests; - const sameLength = rederived.length === snapshot.claim_ids.length; - const sameOrder = sameLength && rederived.every((r, i2) => r.claim.claim_id === snapshot.claim_ids[i2]); - if (sameOrder) { - const index2 = rederived.map((req, idx) => ({ - request: req, - invocation_id: invocationIdFor(idx) - })); - return parseVerdicts(index2, batchResult); - } - const snapshotSet = new Set(snapshot.claim_ids); - const rederivedIds = rederived.map((r) => r.claim.claim_id); - const sameSet = sameLength && rederivedIds.every((id) => snapshotSet.has(id)); - const mismatchKind = sameSet ? "ordering_regression" : "content_mutation"; - const byId = new Map(batchResult.responses.map((r) => [r.invocation_id, r])); - const out = []; - for (let idx = 0; idx < snapshot.claim_ids.length; idx++) { - const claim_id = snapshot.claim_ids[idx]; - const judge = snapshot.judges[idx]; - const response = byId.get(invocationIdFor(idx)); - out.push({ - judge, - claim_id, - verdict: "INCONCLUSIVE", - rationale: response?.error ?? "Plan mismatch between Phase A and Phase B \u2014 original verdict cannot be parsed without JudgeRequest context", - caveats: ["plan_mismatch", `mismatch_kind:${mismatchKind}`], - confidence: 0 - }); - } - return out; +function _refine(Class2, fn, _params) { + const schema2 = new Class2({ + type: "custom", + check: "custom", + fn, + ...normalizeParams(_params) + }); + return schema2; } -var VERIFY_BATCH_ID, RawVerdictSchema, handleSelfCheck; -var init_self_check = __esm({ - async "packages/orchestration/dist/handlers/self-check.js"() { - "use strict"; - await init_state(); - await init_dist2(); - await init_dist5(); - await init_dist(); - init_zod(); - init_protocol_ids(); - VERIFY_BATCH_ID = "self_check_verify"; - RawVerdictSchema = external_exports.object({ - verdict: VerdictSchema, - rationale: external_exports.string(), - caveats: external_exports.array(external_exports.string()).default([]), - confidence: external_exports.number().min(0).max(1) - }); - handleSelfCheck = ({ state, result }) => { - if (result?.kind === "subagent_batch_result" && result.batch_id === VERIFY_BATCH_ID) { - return handleSelfCheckPhaseB(state, result); - } - return handleSelfCheckPhaseA(state); - }; - } -}); -// packages/orchestration/dist/runner.js -function step(input) { - const messages = []; - let currentState = input.state; - let pendingResult = input.result; - for (let i2 = 0; i2 < COALESCE_CAP; i2++) { - const out = invoke(currentState, pendingResult); - currentState = out.state; - pendingResult = void 0; - if (out.action.kind === "emit_message") { - const level = out.action.level ?? "info"; - messages.push({ text: out.action.message, level }); - if (currentState.current_step === "complete") { - return { - state: touch(currentState), - action: terminalFromMessages(messages), - messages - }; - } - continue; - } - return { - state: touch(currentState), - action: out.action, - // narrowed: kind !== "emit_message" - messages - }; - } - const stateWithError = appendError(currentState, `[runner] coalesce cap (${COALESCE_CAP}) exceeded; suspected handler loop on step '${currentState.current_step}'`, "structural"); - return { - state: touch(stateWithError), - action: { - kind: "failed", - reason: `Runner exceeded emit_message coalesce cap (${COALESCE_CAP}). The pipeline may have an infinite handler loop on step '${currentState.current_step}'.`, - step: currentState.current_step - }, - messages - }; -} -function terminalFromMessages(messages) { - const errorMsgs = messages.filter((m) => m.level === "error"); - if (errorMsgs.length > 0) { - return { - kind: "failed", - reason: errorMsgs.map((m) => m.text).join("\n"), - step: "complete" - }; - } - const summary = messages.map((m) => m.level === "info" ? m.text : `[${m.level.toUpperCase()}] ${m.text}`).join("\n"); - return { kind: "done", summary, artifacts: [] }; -} -function invoke(state, result) { - const handler = HANDLERS[state.current_step]; - if (!handler) { - return { - state, - action: { - kind: "failed", - reason: `No handler for step '${state.current_step}'`, - step: state.current_step - } - }; - } - try { - return handler({ state, result }); - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - return { - state: appendError(state, `[${state.current_step}] ${message}`, "structural"), - action: { - kind: "failed", - reason: message, - step: state.current_step - } - }; +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/to-json-schema.js +var JSONSchemaGenerator = class { + constructor(params) { + this.counter = 0; + this.metadataRegistry = params?.metadata ?? globalRegistry; + this.target = params?.target ?? "draft-2020-12"; + this.unrepresentable = params?.unrepresentable ?? "throw"; + this.override = params?.override ?? (() => { + }); + this.io = params?.io ?? "output"; + this.seen = /* @__PURE__ */ new Map(); } -} -var HANDLERS, COALESCE_CAP; -var init_runner = __esm({ - async "packages/orchestration/dist/runner.js"() { - "use strict"; - await init_state(); - await init_banner(); - await init_preflight(); - await init_context_detection(); - await init_input_analysis(); - init_feasibility_gate(); - await init_clarification2(); - init_budget(); - await init_section_generation(); - await init_jira_generation(); - await init_file_export(); - await init_self_check(); - HANDLERS = { - banner: handleBanner, - preflight: handlePreflight, - context_detection: handleContextDetection, - input_analysis: handleInputAnalysis, - feasibility_gate: handleFeasibilityGate, - clarification: handleClarification, - budget: handleBudget, - section_generation: handleSectionGeneration, - jira_generation: handleJiraGeneration, - file_export: handleFileExport, - self_check: handleSelfCheck, - complete: ({ state }) => ({ - state, - action: { - kind: "done", - summary: "Pipeline already complete.", - artifacts: [] - } - }) + process(schema2, _params = { path: [], schemaPath: [] }) { + var _a; + const def = schema2._zod.def; + const formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "" + // do not set }; - COALESCE_CAP = 16; - } -}); - -// packages/orchestration/dist/run-store.js -var InMemoryRunStore; -var init_run_store = __esm({ - "packages/orchestration/dist/run-store.js"() { - "use strict"; - InMemoryRunStore = class { - runs = /* @__PURE__ */ new Map(); - get(runId) { - return this.runs.get(runId); - } - set(state) { - this.runs.set(state.run_id, state); - } - delete(runId) { - this.runs.delete(runId); - } - list() { - return Array.from(this.runs.values()); + const seen = this.seen.get(schema2); + if (seen) { + seen.count++; + const isCycle = _params.schemaPath.includes(schema2); + if (isCycle) { + seen.cycle = _params.path; } - }; - } -}); - -// packages/orchestration/dist/canned-dispatcher.js -function defaultFakeSectionDraft(section_type) { - const heading = `## ${section_type}`; - switch (section_type) { - case "requirements": - return [ - heading, - "", - "- FR-001: The system supports OAuth login via Google and GitHub.", - "- FR-002: The system stores session tokens in HttpOnly cookies." - ].join("\n"); - case "acceptance_criteria": - return [ - heading, - "", - "- AC-001: A user with valid Google credentials can sign in.", - "- AC-002: A user with invalid credentials sees an error message." - ].join("\n"); - case "technical_specification": - return [ - heading, - "", - "We use ports-and-adapters architecture. The OAuth domain port is", - "implemented by Google and GitHub adapters at the infrastructure layer." - ].join("\n"); - case "performance_requirements": - return [ - heading, - "", - "p95 < 250ms for token validation under nominal load." - ].join("\n"); - case "security_considerations": - return [ - heading, - "", - "All session tokens use AES-256-GCM. Authentication uses OAuth 2.0." - ].join("\n"); - default: - return [heading, "", "Canned synthetic content."].join("\n"); - } -} -function fakeJudgeVerdict() { - return JSON.stringify({ - verdict: "PASS", - rationale: "Canned synthetic verdict.", - caveats: [], - confidence: 0.9 - }); -} -function fakeClarificationQuestion() { - return JSON.stringify({ - question: "What is the primary success metric?", - options: null, - rationale: "Canned placeholder." - }); -} -function makeCannedDispatcher(opts = {}) { - const freeform_answer = opts.freeform_answer ?? "canned-answer"; - const graph_path = opts.graph_path ?? "/tmp/canned/graph"; - const fake_section_draft = opts.fake_section_draft ?? defaultFakeSectionDraft; - function pickFakeAgentResponse(invocation_id) { - if (invocation_id.startsWith(SELF_CHECK_JUDGE_INV_PREFIX)) { - return fakeJudgeVerdict(); - } - if (invocation_id.startsWith(CLARIFICATION_COMPOSE_INV_PREFIX)) { - return fakeClarificationQuestion(); - } - if (invocation_id.startsWith(SECTION_GENERATE_INV_PREFIX)) { - const section_type = invocation_id.slice(SECTION_GENERATE_INV_PREFIX.length); - return fake_section_draft(section_type); - } - if (invocation_id === JIRA_GENERATION_INV_ID) { - return "## JIRA Tickets\n\nCanned JIRA placeholder."; - } - return "Canned synthetic response."; - } - function craftUserAnswer(action) { - if (action.question_id === QUESTION_ID_CONTINUE) { - return { - kind: "user_answer", - question_id: action.question_id, - selected: ["proceed"] - }; + return seen.schema; } - if (action.options && action.options.length > 0) { - return { - kind: "user_answer", - question_id: action.question_id, - selected: [action.options[0].label] - }; - } - return { - kind: "user_answer", - question_id: action.question_id, - selected: [], - freeform: freeform_answer - }; - } - function craftPipelineToolResult(action) { - if (action.tool_name === "index_codebase") { - return { - kind: "tool_result", - correlation_id: action.correlation_id, - success: true, - data: { - graph_path, - symbols_indexed: 0, - files_parsed: 0, - duration_ms: 1 - } + const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; + this.seen.set(schema2, result); + const overrideSchema = schema2._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; + } else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema2], + path: _params.path }; + const parent = schema2._zod.parent; + if (parent) { + result.ref = parent; + this.process(parent, params); + this.seen.get(parent).isParent = true; + } else { + const _json = result.schema; + switch (def.type) { + case "string": { + const json2 = _json; + json2.type = "string"; + const { minimum, maximum, format: format5, patterns, contentEncoding } = schema2._zod.bag; + if (typeof minimum === "number") + json2.minLength = minimum; + if (typeof maximum === "number") + json2.maxLength = maximum; + if (format5) { + json2.format = formatMap[format5] ?? format5; + if (json2.format === "") + delete json2.format; + } + if (contentEncoding) + json2.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const regexes = [...patterns]; + if (regexes.length === 1) + json2.pattern = regexes[0].source; + else if (regexes.length > 1) { + result.schema.allOf = [ + ...regexes.map((regex) => ({ + ...this.target === "draft-7" ? { type: "string" } : {}, + pattern: regex.source + })) + ]; + } + } + break; + } + case "number": { + const json2 = _json; + const { minimum, maximum, format: format5, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema2._zod.bag; + if (typeof format5 === "string" && format5.includes("int")) + json2.type = "integer"; + else + json2.type = "number"; + if (typeof exclusiveMinimum === "number") + json2.exclusiveMinimum = exclusiveMinimum; + if (typeof minimum === "number") { + json2.minimum = minimum; + if (typeof exclusiveMinimum === "number") { + if (exclusiveMinimum >= minimum) + delete json2.minimum; + else + delete json2.exclusiveMinimum; + } + } + if (typeof exclusiveMaximum === "number") + json2.exclusiveMaximum = exclusiveMaximum; + if (typeof maximum === "number") { + json2.maximum = maximum; + if (typeof exclusiveMaximum === "number") { + if (exclusiveMaximum <= maximum) + delete json2.maximum; + else + delete json2.exclusiveMaximum; + } + } + if (typeof multipleOf === "number") + json2.multipleOf = multipleOf; + break; + } + case "boolean": { + const json2 = _json; + json2.type = "boolean"; + break; + } + case "bigint": { + if (this.unrepresentable === "throw") { + throw new Error("BigInt cannot be represented in JSON Schema"); + } + break; + } + case "symbol": { + if (this.unrepresentable === "throw") { + throw new Error("Symbols cannot be represented in JSON Schema"); + } + break; + } + case "null": { + _json.type = "null"; + break; + } + case "any": { + break; + } + case "unknown": { + break; + } + case "undefined": { + if (this.unrepresentable === "throw") { + throw new Error("Undefined cannot be represented in JSON Schema"); + } + break; + } + case "void": { + if (this.unrepresentable === "throw") { + throw new Error("Void cannot be represented in JSON Schema"); + } + break; + } + case "never": { + _json.not = {}; + break; + } + case "date": { + if (this.unrepresentable === "throw") { + throw new Error("Date cannot be represented in JSON Schema"); + } + break; + } + case "array": { + const json2 = _json; + const { minimum, maximum } = schema2._zod.bag; + if (typeof minimum === "number") + json2.minItems = minimum; + if (typeof maximum === "number") + json2.maxItems = maximum; + json2.type = "array"; + json2.items = this.process(def.element, { ...params, path: [...params.path, "items"] }); + break; + } + case "object": { + const json2 = _json; + json2.type = "object"; + json2.properties = {}; + const shape = def.shape; + for (const key in shape) { + json2.properties[key] = this.process(shape[key], { + ...params, + path: [...params.path, "properties", key] + }); + } + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([...allKeys].filter((key) => { + const v = def.shape[key]._zod; + if (this.io === "input") { + return v.optin === void 0; + } else { + return v.optout === void 0; + } + })); + if (requiredKeys.size > 0) { + json2.required = Array.from(requiredKeys); + } + if (def.catchall?._zod.def.type === "never") { + json2.additionalProperties = false; + } else if (!def.catchall) { + if (this.io === "output") + json2.additionalProperties = false; + } else if (def.catchall) { + json2.additionalProperties = this.process(def.catchall, { + ...params, + path: [...params.path, "additionalProperties"] + }); + } + break; + } + case "union": { + const json2 = _json; + json2.anyOf = def.options.map((x, i2) => this.process(x, { + ...params, + path: [...params.path, "anyOf", i2] + })); + break; + } + case "intersection": { + const json2 = _json; + const a = this.process(def.left, { + ...params, + path: [...params.path, "allOf", 0] + }); + const b = this.process(def.right, { + ...params, + path: [...params.path, "allOf", 1] + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...isSimpleIntersection(a) ? a.allOf : [a], + ...isSimpleIntersection(b) ? b.allOf : [b] + ]; + json2.allOf = allOf; + break; + } + case "tuple": { + const json2 = _json; + json2.type = "array"; + const prefixItems = def.items.map((x, i2) => this.process(x, { ...params, path: [...params.path, "prefixItems", i2] })); + if (this.target === "draft-2020-12") { + json2.prefixItems = prefixItems; + } else { + json2.items = prefixItems; + } + if (def.rest) { + const rest = this.process(def.rest, { + ...params, + path: [...params.path, "items"] + }); + if (this.target === "draft-2020-12") { + json2.items = rest; + } else { + json2.additionalItems = rest; + } + } + if (def.rest) { + json2.items = this.process(def.rest, { + ...params, + path: [...params.path, "items"] + }); + } + const { minimum, maximum } = schema2._zod.bag; + if (typeof minimum === "number") + json2.minItems = minimum; + if (typeof maximum === "number") + json2.maxItems = maximum; + break; + } + case "record": { + const json2 = _json; + json2.type = "object"; + json2.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, "propertyNames"] }); + json2.additionalProperties = this.process(def.valueType, { + ...params, + path: [...params.path, "additionalProperties"] + }); + break; + } + case "map": { + if (this.unrepresentable === "throw") { + throw new Error("Map cannot be represented in JSON Schema"); + } + break; + } + case "set": { + if (this.unrepresentable === "throw") { + throw new Error("Set cannot be represented in JSON Schema"); + } + break; + } + case "enum": { + const json2 = _json; + const values = getEnumValues(def.entries); + if (values.every((v) => typeof v === "number")) + json2.type = "number"; + if (values.every((v) => typeof v === "string")) + json2.type = "string"; + json2.enum = values; + break; + } + case "literal": { + const json2 = _json; + const vals = []; + for (const val of def.values) { + if (val === void 0) { + if (this.unrepresentable === "throw") { + throw new Error("Literal `undefined` cannot be represented in JSON Schema"); + } else { + } + } else if (typeof val === "bigint") { + if (this.unrepresentable === "throw") { + throw new Error("BigInt literals cannot be represented in JSON Schema"); + } else { + vals.push(Number(val)); + } + } else { + vals.push(val); + } + } + if (vals.length === 0) { + } else if (vals.length === 1) { + const val = vals[0]; + json2.type = val === null ? "null" : typeof val; + json2.const = val; + } else { + if (vals.every((v) => typeof v === "number")) + json2.type = "number"; + if (vals.every((v) => typeof v === "string")) + json2.type = "string"; + if (vals.every((v) => typeof v === "boolean")) + json2.type = "string"; + if (vals.every((v) => v === null)) + json2.type = "null"; + json2.enum = vals; + } + break; + } + case "file": { + const json2 = _json; + const file = { + type: "string", + format: "binary", + contentEncoding: "binary" + }; + const { minimum, maximum, mime } = schema2._zod.bag; + if (minimum !== void 0) + file.minLength = minimum; + if (maximum !== void 0) + file.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file.contentMediaType = mime[0]; + Object.assign(json2, file); + } else { + json2.anyOf = mime.map((m) => { + const mFile = { ...file, contentMediaType: m }; + return mFile; + }); + } + } else { + Object.assign(json2, file); + } + break; + } + case "transform": { + if (this.unrepresentable === "throw") { + throw new Error("Transforms cannot be represented in JSON Schema"); + } + break; + } + case "nullable": { + const inner = this.process(def.innerType, params); + _json.anyOf = [inner, { type: "null" }]; + break; + } + case "nonoptional": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "success": { + const json2 = _json; + json2.type = "boolean"; + break; + } + case "default": { + this.process(def.innerType, params); + result.ref = def.innerType; + _json.default = JSON.parse(JSON.stringify(def.defaultValue)); + break; + } + case "prefault": { + this.process(def.innerType, params); + result.ref = def.innerType; + if (this.io === "input") + _json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + break; + } + case "catch": { + this.process(def.innerType, params); + result.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(void 0); + } catch { + throw new Error("Dynamic catch values are not supported in JSON Schema"); + } + _json.default = catchValue; + break; + } + case "nan": { + if (this.unrepresentable === "throw") { + throw new Error("NaN cannot be represented in JSON Schema"); + } + break; + } + case "template_literal": { + const json2 = _json; + const pattern = schema2._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + json2.type = "string"; + json2.pattern = pattern.source; + break; + } + case "pipe": { + const innerType = this.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out; + this.process(innerType, params); + result.ref = innerType; + break; + } + case "readonly": { + this.process(def.innerType, params); + result.ref = def.innerType; + _json.readOnly = true; + break; + } + // passthrough types + case "promise": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "optional": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "lazy": { + const innerType = schema2._zod.innerType; + this.process(innerType, params); + result.ref = innerType; + break; + } + case "custom": { + if (this.unrepresentable === "throw") { + throw new Error("Custom types cannot be represented in JSON Schema"); + } + break; + } + default: { + def; + } + } + } } - return { - kind: "tool_result", - correlation_id: action.correlation_id, - success: true, - data: {} - }; - } - function craftCortexToolResult(action) { - if (action.tool_name === "recall") { - return { - kind: "tool_result", - correlation_id: action.correlation_id, - success: true, - data: { results: [], total: 0 } - }; + const meta = this.metadataRegistry.get(schema2); + if (meta) + Object.assign(result.schema, meta); + if (this.io === "input" && isTransforming(schema2)) { + delete result.schema.examples; + delete result.schema.default; } - return { - kind: "tool_result", - correlation_id: action.correlation_id, - success: true, - data: {} - }; - } - function craftSubagentBatchResult(action) { - const responses = action.invocations.map((inv2) => ({ - invocation_id: inv2.invocation_id, - raw_text: pickFakeAgentResponse(inv2.invocation_id) - })); - return { - kind: "subagent_batch_result", - batch_id: action.batch_id, - responses - }; + if (this.io === "input" && result.schema._prefault) + (_a = result.schema).default ?? (_a.default = result.schema._prefault); + delete result.schema._prefault; + const _result = this.seen.get(schema2); + return _result.schema; } - function craftFileWritten(action) { - return { - kind: "file_written", - path: action.path, - bytes: Buffer.byteLength(action.content, "utf8") + emit(schema2, _params) { + const params = { + cycles: _params?.cycles ?? "ref", + reused: _params?.reused ?? "inline", + // unrepresentable: _params?.unrepresentable ?? "throw", + // uri: _params?.uri ?? ((id) => `${id}`), + external: _params?.external ?? void 0 }; - } - return function dispatch(action) { - switch (action.kind) { - case "ask_user": - return craftUserAnswer(action); - case "call_pipeline_tool": - return craftPipelineToolResult(action); - case "call_cortex_tool": - return craftCortexToolResult(action); - case "spawn_subagents": - return craftSubagentBatchResult(action); - case "write_file": - return craftFileWritten(action); - case "done": - case "failed": - return void 0; - default: { - const _exhaustive = action; - throw new Error(`cannedDispatcher: unhandled action.kind=${action.kind}. Add a case to the dispatch switch.`); + const root = this.seen.get(schema2); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + const makeURI = (entry) => { + const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions"; + if (params.external) { + const externalId = params.external.registry.get(entry[0])?.id; + const uriGenerator = params.external.uri ?? ((id2) => id2); + if (externalId) { + return { ref: uriGenerator(externalId) }; + } + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`; + entry[1].defId = id; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; } - } - }; -} -var init_canned_dispatcher = __esm({ - "packages/orchestration/dist/canned-dispatcher.js"() { - "use strict"; - init_protocol_ids(); - } -}); + if (entry[1] === root) { + return { ref: "#" }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + const defId = entry[1].schema.id ?? `__schema${this.counter++}`; + return { defId, ref: defUriPrefix + defId }; + }; + const extractToDef = (entry) => { + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + if (defId) + seen.defId = defId; + const schema3 = seen.schema; + for (const key in schema3) { + delete schema3[key]; + } + schema3.$ref = ref; + }; + if (params.cycles === "throw") { + for (const entry of this.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) { + throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ -// packages/orchestration/dist/production-dispatcher.js -function makeProductionDispatcher(opts) { - if (opts.agentInvoker == null) { - throw new Error("makeProductionDispatcher: agentInvoker is required"); - } - const fallback = makeCannedDispatcher(opts.cannedOptions ?? {}); - const invoker = opts.agentInvoker; - return async function dispatch(action) { - switch (action.kind) { - case "spawn_subagents": { - const requests = action.invocations.map((inv2) => ({ - invocation_id: inv2.invocation_id, - purpose: action.purpose, - subagent_type: inv2.subagent_type, - prompt: inv2.prompt - })); - const responses = await invoker.invokeSubagentBatch(requests); - return { - kind: "subagent_batch_result", - batch_id: action.batch_id, - responses: responses.map((r) => ({ - invocation_id: r.invocation_id, - raw_text: r.raw_text - })) - }; +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); + } } - case "call_cortex_tool": { - if (action.tool_name === "recall") { - const args = action.arguments ?? {}; - const query = typeof args.query === "string" ? args.query : ""; - const recall = await invoker.invokeCortexRecall({ - correlation_id: action.correlation_id, - query - }); - return { - kind: "tool_result", - correlation_id: action.correlation_id, - success: true, - data: { results: recall.results, total: recall.total } - }; + } + for (const entry of this.seen.entries()) { + const seen = entry[1]; + if (schema2 === entry[0]) { + extractToDef(entry); + continue; + } + if (params.external) { + const ext = params.external.registry.get(entry[0])?.id; + if (schema2 !== entry[0] && ext) { + extractToDef(entry); + continue; } - return fallback(action); } - // Non-LLM actions — deterministic, no LLM cost, no production latency - // contribution worth simulating. Reuse the canned implementation. - case "ask_user": - case "call_pipeline_tool": - case "write_file": - return fallback(action); - case "done": - case "failed": - return void 0; - default: { - const _exhaustive = action; - throw new Error(`productionDispatcher: unhandled action.kind=${action.kind}. Add a case to the dispatch switch.`); + const id = this.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + if (seen.cycle) { + extractToDef(entry); + continue; + } + if (seen.count > 1) { + if (params.reused === "ref") { + extractToDef(entry); + continue; + } } } - }; -} -function makeStubAgentInvoker(opts = {}) { - const latencyMin = opts.latencyMinMs ?? DEFAULT_LATENCY_MIN_MS; - const latencyMax = opts.latencyMaxMs ?? DEFAULT_LATENCY_MAX_MS; - const warmHitProb = opts.warmCortexHitProbability ?? DEFAULT_WARM_HIT_PROB; - const rng = opts.rng ?? Math.random; - const sleep = opts.sleep ?? realSleep; - const rawTextFor = opts.rawTextFor ?? ((req) => `stub-response for invocation_id=${req.invocation_id}`); - function pickLatency() { - return latencyMin + Math.floor(rng() * Math.max(1, latencyMax - latencyMin)); - } - return { - async invokeSubagentBatch(requests) { - const ms = pickLatency(); - await sleep(ms); - return requests.map((r) => ({ - invocation_id: r.invocation_id, - raw_text: rawTextFor(r) - })); - }, - async invokeCortexRecall(request) { - await sleep(Math.max(10, Math.floor(pickLatency() / 5))); - const hit = rng() < warmHitProb; - if (!hit) { - return { results: [], total: 0 }; + const flattenRef = (zodSchema, params2) => { + const seen = this.seen.get(zodSchema); + const schema3 = seen.def ?? seen.schema; + const _cached = { ...schema3 }; + if (seen.ref === null) { + return; } - return { - results: [ - { - content: `stub-recall-hit for query="${request.query.slice(0, 80)}"`, - score: 0.5 + rng() * 0.5 - } - ], - total: 1 - }; + const ref = seen.ref; + seen.ref = null; + if (ref) { + flattenRef(ref, params2); + const refSchema = this.seen.get(ref).schema; + if (refSchema.$ref && params2.target === "draft-7") { + schema3.allOf = schema3.allOf ?? []; + schema3.allOf.push(refSchema); + } else { + Object.assign(schema3, refSchema); + Object.assign(schema3, _cached); + } + } + if (!seen.isParent) + this.override({ + zodSchema, + jsonSchema: schema3, + path: seen.path ?? [] + }); + }; + for (const entry of [...this.seen.entries()].reverse()) { + flattenRef(entry[0], { target: this.target }); + } + const result = {}; + if (this.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } else if (this.target === "draft-7") { + result.$schema = "http://json-schema.org/draft-07/schema#"; + } else { + console.warn(`Invalid target: ${this.target}`); + } + if (params.external?.uri) { + const id = params.external.registry.get(schema2)?.id; + if (!id) + throw new Error("Schema is missing an `id` property"); + result.$id = params.external.uri(id); + } + Object.assign(result, root.def); + const defs = params.external?.defs ?? {}; + for (const entry of this.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + defs[seen.defId] = seen.def; + } + } + if (params.external) { + } else { + if (Object.keys(defs).length > 0) { + if (this.target === "draft-2020-12") { + result.$defs = defs; + } else { + result.definitions = defs; + } + } + } + try { + return JSON.parse(JSON.stringify(result)); + } catch (_err) { + throw new Error("Error converting schema to JSON."); } - }; -} -var DEFAULT_LATENCY_MIN_MS, DEFAULT_LATENCY_MAX_MS, DEFAULT_WARM_HIT_PROB, realSleep; -var init_production_dispatcher = __esm({ - "packages/orchestration/dist/production-dispatcher.js"() { - "use strict"; - init_canned_dispatcher(); - DEFAULT_LATENCY_MIN_MS = 500; - DEFAULT_LATENCY_MAX_MS = 2e3; - DEFAULT_WARM_HIT_PROB = 0.7; - realSleep = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms)); } -}); - -// packages/orchestration/dist/index.js -var init_dist6 = __esm({ - async "packages/orchestration/dist/index.js"() { - "use strict"; - await init_dist(); - await init_state(); - await init_actions(); - init_section_plan(); - await init_runner(); - init_run_store(); - await init_section_generation(); - init_canned_dispatcher(); - init_production_dispatcher(); +}; +function toJSONSchema(input, _params) { + if (input instanceof $ZodRegistry) { + const gen2 = new JSONSchemaGenerator(_params); + const defs = {}; + for (const entry of input._idmap.entries()) { + const [_, schema2] = entry; + gen2.process(schema2); + } + const schemas = {}; + const external2 = { + registry: input, + uri: _params?.uri, + defs + }; + for (const entry of input._idmap.entries()) { + const [key, schema2] = entry; + schemas[key] = gen2.emit(schema2, { + ..._params, + external: external2 + }); + } + if (Object.keys(defs).length > 0) { + const defsSegment = gen2.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs + }; + } + return { schemas }; } -}); - -// packages/benchmark/dist/src/instrumentation.js -function isKnownKind(s) { - return KNOWN_MISMATCH_KINDS.includes(s); + const gen = new JSONSchemaGenerator(_params); + gen.process(input); + return gen.emit(input, _params); } -function extractMismatchEvents(state) { - const events = []; - for (const err of state.errors) { - if (!err.startsWith(MISMATCH_PREFIX)) - continue; - const kind = err.slice(MISMATCH_PREFIX.length).trim(); - if (!isKnownKind(kind)) { - throw new Error(`instrumentation: unknown mismatch_kind '${kind}' in state.errors. Update KNOWN_MISMATCH_KINDS or fix the handler emitter. Raw: ${err}`); +function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const schema2 = _schema; + const def = schema2._zod.def; + switch (def.type) { + case "string": + case "number": + case "bigint": + case "boolean": + case "date": + case "symbol": + case "undefined": + case "null": + case "any": + case "unknown": + case "never": + case "void": + case "literal": + case "enum": + case "nan": + case "file": + case "template_literal": + return false; + case "array": { + return isTransforming(def.element, ctx); } - events.push({ kind, raw: err }); + case "object": { + for (const key in def.shape) { + if (isTransforming(def.shape[key], ctx)) + return true; + } + return false; + } + case "union": { + for (const option of def.options) { + if (isTransforming(option, ctx)) + return true; + } + return false; + } + case "intersection": { + return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + } + case "tuple": { + for (const item of def.items) { + if (isTransforming(item, ctx)) + return true; + } + if (def.rest && isTransforming(def.rest, ctx)) + return true; + return false; + } + case "record": { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + case "map": { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + case "set": { + return isTransforming(def.valueType, ctx); + } + // inner types + case "promise": + case "optional": + case "nonoptional": + case "nullable": + case "readonly": + return isTransforming(def.innerType, ctx); + case "lazy": + return isTransforming(def.getter(), ctx); + case "default": { + return isTransforming(def.innerType, ctx); + } + case "prefault": { + return isTransforming(def.innerType, ctx); + } + case "custom": { + return false; + } + case "transform": { + return true; + } + case "pipe": { + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + case "success": { + return false; + } + case "catch": { + return false; + } + default: + def; } - const distinct = Array.from(new Set(events.map((e3) => e3.kind))); - return { - fired: events.length > 0, - distinctKinds: distinct, - events - }; + throw new Error(`Unknown schema type: ${def.type}`); } -var MISMATCH_PREFIX, KNOWN_MISMATCH_KINDS, MISMATCH_DIAGNOSTIC_PREFIX, MISMATCH_KINDS; -var init_instrumentation = __esm({ - "packages/benchmark/dist/src/instrumentation.js"() { - "use strict"; - MISMATCH_PREFIX = "[self_check] plan mismatch detected \u2014 mismatch_kind:"; - KNOWN_MISMATCH_KINDS = ["content_mutation", "ordering_regression"]; - MISMATCH_DIAGNOSTIC_PREFIX = MISMATCH_PREFIX; - MISMATCH_KINDS = KNOWN_MISMATCH_KINDS; - } -}); -// packages/benchmark/dist/src/pipeline-kpis.js -import { performance } from "node:perf_hooks"; -function measurePipeline(input) { - const cap = input.safety_cap ?? DEFAULT_SAFETY_CAP; - const dispatch = input.craftResult ?? defaultBenchmarkDispatcher; - const seed = newPipelineState({ - run_id: input.run_id, - feature_description: input.feature_description, - codebase_path: input.codebase_path - }); - const t0 = performance.now(); - const loop = runPipelineLoop(seed, dispatch, cap); - const wall_time_ms = performance.now() - t0; - const sectionKpis = extractSectionKpis(loop.state); - const summaryKpis = parseSummaryKpis(loop.lastOutput?.action); - const structural_error_count = loop.state.error_kinds.filter((k) => k === "structural").length; - const mismatchExtraction = extractMismatchEvents(loop.state); - return buildKpis({ - input, - loop, - cap, - wall_time_ms, - sectionKpis, - summaryKpis, - structural_error_count, - mismatchExtraction - }); -} -function buildKpis(args) { - const { input, loop, cap, wall_time_ms, sectionKpis, summaryKpis, structural_error_count, mismatchExtraction } = args; - return { - run_id: input.run_id, - final_action_kind: loop.lastOutput?.action.kind ?? "failed", - current_step: loop.state.current_step, - // source: test-engineer TE1, code-reviewer fix. Cap-exhaustion path: i - // is incremented past the last iteration before the loop test fails, so - // the count is `cap`, not `cap + 1`. Break path: i is the break index; - // count is `i + 1`. Same for the `pendingResult === undefined` exit - // (which the new code reports as a distinct exit reason). - iteration_count: loop.safety_cap_hit ? cap : loop.iterations, - wall_time_ms, - section_pass_rate: sectionKpis.pass_rate, - section_fail_count: sectionKpis.fail_count, - section_fail_ids: sectionKpis.fail_ids, - mean_section_attempts: sectionKpis.mean_attempts, - error_count: loop.state.errors.length, - structural_error_count, - judge_dispatch_count: summaryKpis.claims_evaluated, - distribution_pass_rate: summaryKpis.distribution_pass_rate, - written_files_count: loop.state.written_files.length, - safety_cap_hit: loop.safety_cap_hit, - mismatch_fired: mismatchExtraction.fired, - mismatch_kinds: mismatchExtraction.distinctKinds, - cortex_recall_empty_count: loop.state.cortex_recall_empty_count - }; -} -function runPipelineLoop(seed, dispatch, cap) { - let state = seed; - let pendingResult = void 0; - let lastOutput = null; - let iterations = 0; - for (let i2 = 0; i2 < cap; i2++) { - const out = step({ state, result: pendingResult }); - lastOutput = out; - state = out.state; - iterations = i2 + 1; - if (out.action.kind === "done" || out.action.kind === "failed") { - return { state, lastOutput, iterations, safety_cap_hit: false }; - } - pendingResult = dispatch(out.action); - if (pendingResult === void 0) { - return { state, lastOutput, iterations, safety_cap_hit: false }; - } - } - return { state, lastOutput, iterations: cap, safety_cap_hit: true }; -} -function extractSectionKpis(state) { - const sections = state.sections.filter((s) => s.section_type !== "jira_tickets"); - const passed = sections.filter((s) => s.status === "passed").length; - const failed = sections.filter((s) => s.status === "failed"); - const planned = sections.length; - return { - pass_rate: planned > 0 ? passed / planned : 0, - fail_count: failed.length, - fail_ids: failed.map((s) => s.section_type), - mean_attempts: planned > 0 ? sections.reduce((sum3, s) => sum3 + s.attempt, 0) / planned : 0 +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/mini/schemas.js +var ZodMiniType = /* @__PURE__ */ $constructor("ZodMiniType", (inst, def) => { + if (!inst._zod) + throw new Error("Uninitialized schema in ZodMiniType."); + $ZodType.init(inst, def); + inst.def = def; + inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse }); + inst.safeParse = (data, params) => safeParse(inst, data, params); + inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync }); + inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params); + inst.check = (...checks) => { + return inst.clone( + { + ...def, + checks: [ + ...def.checks ?? [], + ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + } + // { parent: true } + ); }; -} -function parseSummaryKpis(action) { - if (action?.kind !== "done" || !action.verification) { - return { - claims_evaluated: 0, - distribution_pass_rate: 0, - has_verification: false - }; - } - const v = action.verification; - const claims = v.claims_evaluated; - const passVotes = v.distribution.PASS ?? 0; - return { - claims_evaluated: claims, - distribution_pass_rate: claims > 0 ? passVotes / claims : 0, - has_verification: true + inst.clone = (_def, params) => clone(inst, _def, params); + inst.brand = () => inst; + inst.register = ((reg, meta) => { + reg.add(inst, meta); + return inst; + }); +}); +var ZodMiniObject = /* @__PURE__ */ $constructor("ZodMiniObject", (inst, def) => { + $ZodObject.init(inst, def); + ZodMiniType.init(inst, def); + util_exports.defineLazy(inst, "shape", () => def.shape); +}); +function object(shape, params) { + const def = { + type: "object", + get shape() { + util_exports.assignProp(this, "shape", { ...shape }); + return this.shape; + }, + ...util_exports.normalizeParams(params) }; + return new ZodMiniObject(def); } -var DEFAULT_SAFETY_CAP, defaultBenchmarkDispatcher, KPI_GATES; -var init_pipeline_kpis = __esm({ - async "packages/benchmark/dist/src/pipeline-kpis.js"() { - "use strict"; - await init_dist6(); - init_instrumentation(); - DEFAULT_SAFETY_CAP = 200; - defaultBenchmarkDispatcher = makeCannedDispatcher({ - freeform_answer: "benchmark-answer", - graph_path: "/tmp/benchmark/graph" - }); - KPI_GATES = { - /** - * source: provisional heuristic. Smoke baseline = 62 iterations on - * trial+codebase; cap is 100 (~60% headroom). dijkstra cross-audit derived - * a structural max of 9 emit_message hops; the substantive-action count - * builds on that. Phase 4.5 will replace with measured P95 + 1σ. - */ - iteration_count_max: 100, - /** - * source: provisional heuristic. Mac M-series canned-run baseline ≈ 5ms, - * with 100× margin to cover CI startup + locale variance. The previous - * 5000ms value mistook 5ms × 1000 = 5000 (not 5ms × 10 = 50). The 500ms - * gate retains 100× headroom while still failing on a 100× regression. - * Phase 4.5 will replace with measured P95 per machine class. - */ - wall_time_ms_max: 500, - /** - * source: provisional heuristic. Smoke baseline (canned content) shows 5 - * specific sections fail because canned drafts cannot satisfy stricter - * validators. Gate is set at the baseline so any *increase* surfaces; the - * known-failing-baseline assertion in smoke.test.ts catches identity - * drift. Phase 4.5 will tighten once canned content is enriched. - */ - section_fail_count_max: 5, - /** - * source: provisional heuristic. distribution_suspicious fires at ≥1.0 PASS - * rate (verification/orchestrator.ts). This gate at 0.95 catches the 95%+ - * confirmatory-bias warning band. NOTE: the canned dispatcher returns 100% - * PASS, so this gate ALWAYS fires on the canned path; the gate is - * meaningful only on real-ecosystem runs with mixed verdicts. Tests on - * canned input must set distribution_pass_rate threshold to 1.0 or skip - * this gate. Phase 4.5 will calibrate the gate against known-good vs - * known-bad PRDs to set a defensible threshold. - */ - distribution_pass_rate_max: 0.95, - /** - * source: provisional heuristic. error_count ≥ section_fail_count - * mechanically (each failed section appends one error). Gate at 5 matches - * section_fail_count_max. Phase 4.5 will split into structural_error_count - * (gate: 0) + section-failure errors (gate: matches section_fail_count_max). - */ - error_count_max: 5, - /** - * source: derived. safety_cap_hit means a runaway loop was caught; this is - * always a defect. No tuning required. - */ - safety_cap_hit_allowed: false, - /** - * source: provisional heuristic. mean_section_attempts of 1.0 means every - * section passes first try; 3.0 means every section needs all retries. - * Canned baseline measures 1.91 (5 of 11 trial sections exhaust 3 - * attempts because canned drafts cannot satisfy stricter validators). - * Gate at 2.5 catches a regression where retry rate climbs above 2 per - * section while accepting the canned-baseline floor. Phase 4.2 will - * calibrate against the pass-rate-by-attempt distribution from real - * LLM content (where mean should be near 1.0–1.2). - */ - mean_section_attempts_max: 2.5, - /** - * source: derived. Any structural error (handler bug, code-layer fault) is - * a defect. No tuning required. - */ - structural_error_count_max: 0, - /** - * source: provisional heuristic — to be calibrated in Phase 4.5. - * - * Rationale: a 9-section PRD run performs one Cortex recall per section in - * the retrieving→generating transition. An empty recall means that section - * was generated without memory context, degrading quality. A ceiling of 3 - * (≈ 33% of sections) is the threshold beyond which absent recall context - * becomes the majority driver of generation quality, rather than the LLM's - * base knowledge alone. This is a conservative first gate; Phase 4.5 will - * replace it with the measured P95 from K ≥ 100 production-shaped runs. - * See also: packages/orchestration/src/types/state.ts cortex_recall_empty_count. - */ - cortex_recall_empty_count_max: 3 - }; - } -}); -// packages/benchmark/dist/calibration/clopper-pearson.js -function logGamma(x) { - const cof = [ - 76.18009172947146, - -86.50532032941678, - 24.01409824083091, - -1.231739572450155, - 0.001208650973866179, - -5395239384953e-18 - ]; - let y = x; - let tmp = x + 5.5; - tmp -= (x + 0.5) * Math.log(tmp); - let ser = 1.000000000190015; - for (const c of cof) { - y += 1; - ser += c / y; - } - return -tmp + Math.log(2.5066282746310007 * ser / x); +// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js +function isZ4Schema(s) { + const schema2 = s; + return !!schema2._zod; } -function betacf(a, b, x) { - const qab = a + b; - const qap = a + 1; - const qam = a - 1; - let c = 1; - let d = 1 - qab * x / qap; - if (Math.abs(d) < FPMIN) - d = FPMIN; - d = 1 / d; - let h = d; - for (let m = 1; m <= MAX_ITER; m++) { - const m2 = 2 * m; - let aa = m * (b - m) * x / ((qam + m2) * (a + m2)); - d = 1 + aa * d; - if (Math.abs(d) < FPMIN) - d = FPMIN; - c = 1 + aa / c; - if (Math.abs(c) < FPMIN) - c = FPMIN; - d = 1 / d; - h *= d * c; - aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)); - d = 1 + aa * d; - if (Math.abs(d) < FPMIN) - d = FPMIN; - c = 1 + aa / c; - if (Math.abs(c) < FPMIN) - c = FPMIN; - d = 1 / d; - const del = d * c; - h *= del; - if (Math.abs(del - 1) < EPS) - return h; - } - return h; +function objectFromShape(shape) { + const values = Object.values(shape); + if (values.length === 0) + return object({}); + const allV4 = values.every(isZ4Schema); + const allV3 = values.every((s) => !isZ4Schema(s)); + if (allV4) + return object(shape); + if (allV3) + return objectType(shape); + throw new Error("Mixed Zod versions detected in object shape."); } -function betaiRegularized(a, b, x) { - if (x <= 0) - return 0; - if (x >= 1) - return 1; - const bt = Math.exp(logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log(1 - x)); - if (x < (a + 1) / (a + b + 2)) { - return bt * betacf(a, b, x) / a; +function safeParse2(schema2, data) { + if (isZ4Schema(schema2)) { + const result2 = safeParse(schema2, data); + return result2; } - return 1 - bt * betacf(b, a, 1 - x) / b; + const v3Schema = schema2; + const result = v3Schema.safeParse(data); + return result; } -function betaInv(p, a, b) { - if (p <= 0) - return 0; - if (p >= 1) - return 1; - let lo = 0; - let hi = 1; - for (let i2 = 0; i2 < 80; i2++) { - const mid = (lo + hi) / 2; - if (betaiRegularized(a, b, mid) < p) - lo = mid; - else - hi = mid; +async function safeParseAsync2(schema2, data) { + if (isZ4Schema(schema2)) { + const result2 = await safeParseAsync(schema2, data); + return result2; } - return (lo + hi) / 2; + const v3Schema = schema2; + const result = await v3Schema.safeParseAsync(data); + return result; } -function clopperPearson(successes, trials, confidence = 0.95) { - if (trials <= 0) { - throw new Error("trials must be > 0"); - } - if (successes < 0 || successes > trials) { - throw new Error(`successes must be in [0, trials]`); - } - const alpha = 1 - confidence; - const lower = successes === 0 ? 0 : betaInv(alpha / 2, successes, trials - successes + 1); - const upper = successes === trials ? 1 : betaInv(1 - alpha / 2, successes + 1, trials - successes); - return { - pointEstimate: successes / trials, - lower, - upper, - confidence, - successes, - trials - }; -} -var MAX_ITER, EPS, FPMIN; -var init_clopper_pearson = __esm({ - "packages/benchmark/dist/calibration/clopper-pearson.js"() { - "use strict"; - MAX_ITER = 100; - EPS = 1e-12; - FPMIN = 1e-300; - } -}); - -// packages/benchmark/dist/calibration/xmr.js -function computeLimits(baseline) { - if (baseline.length < 2) { - throw new Error("XmR requires at least 2 baseline points"); +function getObjectShape(schema2) { + if (!schema2) + return void 0; + let rawShape; + if (isZ4Schema(schema2)) { + const v4Schema = schema2; + rawShape = v4Schema._zod?.def?.shape; + } else { + const v3Schema = schema2; + rawShape = v3Schema.shape; } - const mean2 = baseline.reduce((s, v) => s + v, 0) / baseline.length; - const ranges = []; - for (let i2 = 1; i2 < baseline.length; i2++) { - ranges.push(Math.abs(baseline[i2] - baseline[i2 - 1])); + if (!rawShape) + return void 0; + if (typeof rawShape === "function") { + try { + return rawShape(); + } catch { + return void 0; + } } - const meanMR = ranges.reduce((s, v) => s + v, 0) / ranges.length; - const sigmaEstimate = meanMR / D2_FOR_N2; - const halfWidth = SIGMA_MULTIPLIER * sigmaEstimate; - return { - centerline: mean2, - upperControlLimit: mean2 + halfWidth, - lowerControlLimit: mean2 - halfWidth, - meanMovingRange: meanMR, - basePoints: baseline.length - }; + return rawShape; } -function scanSeries(series, limits) { - const signals = []; - for (let i2 = 0; i2 < series.length; i2++) { - const v = series[i2]; - if (v > limits.upperControlLimit || v < limits.lowerControlLimit) { - signals.push({ index: i2, value: v, rule: "outside_3sigma" }); +function normalizeObjectSchema(schema2) { + if (!schema2) + return void 0; + if (typeof schema2 === "object") { + const asV3 = schema2; + const asV4 = schema2; + if (!asV3._def && !asV4._zod) { + const values = Object.values(schema2); + if (values.length > 0 && values.every((v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function"))) { + return objectFromShape(schema2); + } } } - let runSide = null; - let runLength = 0; - for (let i2 = 0; i2 < series.length; i2++) { - const side = series[i2] > limits.centerline ? "above" : series[i2] < limits.centerline ? "below" : null; - if (side === null) { - runSide = null; - runLength = 0; - continue; - } - if (side === runSide) { - runLength += 1; - } else { - runSide = side; - runLength = 1; + if (isZ4Schema(schema2)) { + const v4Schema = schema2; + const def = v4Schema._zod?.def; + if (def && (def.type === "object" || def.shape !== void 0)) { + return schema2; } - if (runLength === RUN_LENGTH_THRESHOLD) { - signals.push({ index: i2, value: series[i2], rule: "run_of_8" }); + } else { + const v3Schema = schema2; + if (v3Schema.shape !== void 0) { + return schema2; } } - return { - limits, - signals, - inControl: signals.length === 0 - }; -} -function xmrAnalyze(series, baselineCount) { - if (baselineCount < 2 || baselineCount > series.length) { - throw new Error(`baselineCount must be in [2, series.length]; got ${baselineCount}`); - } - const limits = computeLimits(series.slice(0, baselineCount)); - return scanSeries(series, limits); + return void 0; } -var D2_FOR_N2, SIGMA_MULTIPLIER, RUN_LENGTH_THRESHOLD; -var init_xmr = __esm({ - "packages/benchmark/dist/calibration/xmr.js"() { - "use strict"; - D2_FOR_N2 = 1.128; - SIGMA_MULTIPLIER = 3; - RUN_LENGTH_THRESHOLD = 8; - } -}); - -// packages/benchmark/dist/calibration/machine-class.js -import { cpus, totalmem } from "node:os"; -function detectMachineClass() { - const cpuList = cpus(); - if (!cpuList || cpuList.length === 0) - return "ci_runner"; - const model = cpuList[0]?.model ?? ""; - const memBytes = totalmem(); - const memGB = memBytes / (1024 * 1024 * 1024); - if (/^Apple M/.test(model)) { - return memGB >= 32 ? "m_series_high" : "m_series_mid"; - } - if (/Intel\b/i.test(model)) - return "x86_intel"; - if (/AMD\b/i.test(model)) - return "x86_amd"; - return "ci_runner"; -} -var init_machine_class = __esm({ - "packages/benchmark/dist/calibration/machine-class.js"() { - "use strict"; +function getParseErrorMessage(error2) { + if (error2 && typeof error2 === "object") { + if ("message" in error2 && typeof error2.message === "string") { + return error2.message; + } + if ("issues" in error2 && Array.isArray(error2.issues) && error2.issues.length > 0) { + const firstIssue = error2.issues[0]; + if (firstIssue && typeof firstIssue === "object" && "message" in firstIssue) { + return String(firstIssue.message); + } + } + try { + return JSON.stringify(error2); + } catch { + return String(error2); + } } -}); - -// packages/benchmark/dist/calibration/gate-stats.js -function percentile(values, p) { - if (values.length === 0) - throw new Error("percentile: empty input"); - if (p < 0 || p > 1) - throw new Error(`percentile: p must be in [0,1]; got ${p}`); - const sorted = [...values].sort((a, b) => a - b); - const h = (sorted.length - 1) * p; - const lo = Math.floor(h); - const hi = Math.ceil(h); - if (lo === hi) - return sorted[lo]; - return sorted[lo] + (h - lo) * (sorted[hi] - sorted[lo]); -} -function buildXmrRecord(values) { - const baselineCount = Math.min(XMR_BASELINE_POINTS, values.length); - const baseline = values.slice(0, Math.max(2, baselineCount)); - const limits = computeLimits(baseline); - const report = scanSeries(values, limits); - return { - centerline: limits.centerline, - upperControlLimit: limits.upperControlLimit, - lowerControlLimit: limits.lowerControlLimit, - meanMovingRange: limits.meanMovingRange, - basePoints: limits.basePoints, - signals: report.signals.map((s) => ({ - index: s.index, - value: s.value, - rule: s.rule - })), - inControl: report.inControl, - series: [...values] - }; -} -function computeGateStats(values) { - if (values.length < 2) { - throw new Error(`computeGateStats: need \u22652 observations for XmR; got ${values.length}`); - } - const sorted = [...values].sort((a, b) => a - b); - const p95 = percentile(values, 0.95); - const p5 = percentile(values, 0.05); - const successes = values.filter((v) => v > p95).length; - const cp = clopperPearson(successes, values.length, 0.95); - const n = values.length; - const lowerRank = Math.max(0, Math.min(n - 1, Math.floor(cp.lower * n))); - const upperRank = Math.max(0, Math.min(n - 1, Math.ceil(cp.upper * n))); - return { - p95, - p5, - ci_lower: sorted[lowerRank], - ci_upper: sorted[upperRank], - xmr: buildXmrRecord(values) - }; + return String(error2); } -var XMR_BASELINE_POINTS; -var init_gate_stats = __esm({ - "packages/benchmark/dist/calibration/gate-stats.js"() { - "use strict"; - init_clopper_pearson(); - init_xmr(); - XMR_BASELINE_POINTS = 12; - } -}); - -// packages/benchmark/dist/calibration/event-rate.js -function measureEventRate(kpis) { - let totalAttempts = 0; - let events = 0; - for (const k of kpis) { - const failed = k.section_fail_count; - const passed = k.section_pass_rate >= 1 ? ( - // All passed — failed=0 by mass conservation; planned unknown without - // a side channel. Skip events for this run (events=0 by construction - // since failed=0 means every section passed first try ONLY if - // mean_attempts ≈ 1; if mean > 1, multi-attempt passes still - // contributed events that we cannot count from this surface). - // This is a documented under-count vs the true rate. - 0 - ) : Math.round(k.section_pass_rate * failed / Math.max(1 - k.section_pass_rate, 1e-9)); - const planned = passed + failed; - if (planned === 0) - continue; - const totalAttemptsThisRun = Math.round(k.mean_section_attempts * planned); - const eventsThisRun = Math.max(0, totalAttemptsThisRun - planned); - totalAttempts += totalAttemptsThisRun; - events += eventsThisRun; - } - return { totalAttempts, events }; +function getSchemaDescription(schema2) { + return schema2.description; } -var init_event_rate = __esm({ - "packages/benchmark/dist/calibration/event-rate.js"() { - "use strict"; +function isSchemaOptional(schema2) { + if (isZ4Schema(schema2)) { + const v4Schema = schema2; + return v4Schema._zod?.def?.type === "optional"; } -}); - -// packages/benchmark/dist/calibration/frozen-baseline.js -import { readFileSync as readFileSync5, existsSync as existsSync7 } from "node:fs"; -import { createHash } from "node:crypto"; -import { execSync } from "node:child_process"; -import { fileURLToPath } from "node:url"; -import { dirname as dirname3, resolve } from "node:path"; -function pipelineKpisPath() { - const here = fileURLToPath(import.meta.url); - let dir = dirname3(here); - for (let i2 = 0; i2 < 8; i2++) { - const sourceCandidate = resolve(dir, "src", "pipeline-kpis.ts"); - if (existsSync7(sourceCandidate)) - return sourceCandidate; - const distCandidate = resolve(dir, "src", "pipeline-kpis.js"); - if (existsSync7(distCandidate)) - return distCandidate; - const anchored = resolve(dir, "tsconfig.calibration.json"); - if (existsSync7(anchored)) { - return resolve(dir, "src", "pipeline-kpis.ts"); - } - const parent = resolve(dir, ".."); - if (parent === dir) - break; - dir = parent; + const v3Schema = schema2; + if (typeof schema2.isOptional === "function") { + return schema2.isOptional(); } - return resolve(dirname3(here), "..", "src", "pipeline-kpis.ts"); -} -function computePipelineKpisContentHash() { - const path = pipelineKpisPath(); - const content = readFileSync5(path, "utf8"); - return createHash("sha256").update(content).digest("hex"); + return v3Schema._def?.typeName === "ZodOptional"; } -function resolveFrozenBaselineCommit() { - try { - return execSync("git rev-parse HEAD", { encoding: "utf8" }).trim(); - } catch { - return "unknown"; +function getLiteralValue(schema2) { + if (isZ4Schema(schema2)) { + const v4Schema = schema2; + const def2 = v4Schema._zod?.def; + if (def2) { + if (def2.value !== void 0) + return def2.value; + if (Array.isArray(def2.values) && def2.values.length > 0) { + return def2.values[0]; + } + } } -} -var init_frozen_baseline = __esm({ - "packages/benchmark/dist/calibration/frozen-baseline.js"() { - "use strict"; + const v3Schema = schema2; + const def = v3Schema._def; + if (def) { + if (def.value !== void 0) + return def.value; + if (Array.isArray(def.values) && def.values.length > 0) { + return def.values[0]; + } } -}); + const directValue = schema2.value; + if (directValue !== void 0) + return directValue; + return void 0; +} -// packages/benchmark/dist/calibration/calibrate-gates-constants.js -var PRE_REGISTERED_SEED_45, PRE_REGISTERED_SEED_42, DEFAULT_K, DEFAULT_EVENT_RATE_K, EVENT_RATE_TOLERANCE, PROVISIONAL_EVENT_RATE; -var init_calibrate_gates_constants = __esm({ - "packages/benchmark/dist/calibration/calibrate-gates-constants.js"() { - "use strict"; - PRE_REGISTERED_SEED_45 = 263619; - PRE_REGISTERED_SEED_42 = 4020704; - DEFAULT_K = 100; - DEFAULT_EVENT_RATE_K = 50; - EVENT_RATE_TOLERANCE = 0.05; - PROVISIONAL_EVENT_RATE = 0.3; - } +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/iso.js +var iso_exports2 = {}; +__export(iso_exports2, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date2, + datetime: () => datetime2, + duration: () => duration2, + time: () => time2 }); - -// packages/benchmark/dist/calibration/calibrate-gates-cli.js -function parseFlag(argv, name315) { - const prefix = `--${name315}=`; - for (const a of argv) { - if (a.startsWith(prefix)) - return a.slice(prefix.length); - } - return null; -} -function hasFlag(argv, name315) { - return argv.includes(`--${name315}`); -} -function buildSummary(gc, er) { - const lines = [ - `K achieved: ${gc.k_achieved} / ${gc.k_target}`, - `Frozen baseline commit: ${gc.frozen_baseline_commit}`, - `Pipeline-KPIs content hash: ${gc.frozen_baseline_content_hash}`, - "", - "Per-gate provisional vs calibrated:" - ]; - for (const g of gc.gates) { - const dir = g.would_tighten ? "tighten" : g.would_loosen ? "loosen" : "hold"; - const pass = g.passes_threshold ? "[PASS-THRESHOLD]" : "[hold-provisional]"; - lines.push(` ${g.gate_name}: ${g.provisional} \u2192 ${g.calibrated.toFixed(3)} (${dir}) ${pass}`); - } - lines.push("", `Event-rate measurement (\xA74.2): ${er.measured_event_rate.toFixed(4)} (K=${er.k_observed}, attempts=${er.total_attempts}, events=${er.total_events})`, `Clopper-Pearson 95% CI: [${er.ci95_clopper_pearson.lower.toFixed(4)}, ${er.ci95_clopper_pearson.upper.toFixed(4)}]`); - if (er.diverges_beyond_tolerance) { - lines.push(`WARNING: measured event_rate diverges from provisional 0.30 by more than \xB1${EVENT_RATE_TOLERANCE}; per docs/PHASE_4_PLAN.md \xA74.2 the Schoenfeld N=823 must be recomputed via schoenfeldRequiredEvents() before any \xA74.2 study begins.`); - } else { - lines.push(`Event-rate within \xB1${EVENT_RATE_TOLERANCE} of provisional 0.30 anchor \u2014 no Schoenfeld recompute required.`); - } - return lines; +var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function datetime2(params) { + return _isoDateTime(ZodISODateTime, params); } -var init_calibrate_gates_cli = __esm({ - "packages/benchmark/dist/calibration/calibrate-gates-cli.js"() { - "use strict"; - init_calibrate_gates_constants(); - } +var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); }); - -// packages/benchmark/dist/src/pipeline-kpis-async.js -import { performance as performance2 } from "node:perf_hooks"; -async function measurePipelineAsync(input) { - if (input.dispatch == null) { - throw new Error("measurePipelineAsync: dispatch is required"); - } - const cap = input.safety_cap ?? DEFAULT_SAFETY_CAP2; - const seed = newPipelineState({ - run_id: input.run_id, - feature_description: input.feature_description, - codebase_path: input.codebase_path - }); - const t0 = performance2.now(); - const loop = await runAsyncPipelineLoop(seed, input.dispatch, cap); - const wall_time_ms = performance2.now() - t0; - const sectionKpis = extractAsyncSectionKpis(loop.state); - const summaryKpis = parseAsyncSummaryKpis(loop.lastOutput?.action); - const structural_error_count = loop.state.error_kinds.filter((k) => k === "structural").length; - const mismatchExtraction = extractMismatchEvents(loop.state); - return { - run_id: input.run_id, - final_action_kind: loop.lastOutput?.action.kind ?? "failed", - current_step: loop.state.current_step, - iteration_count: loop.safety_cap_hit ? cap : loop.iterations, - wall_time_ms, - section_pass_rate: sectionKpis.pass_rate, - section_fail_count: sectionKpis.fail_count, - section_fail_ids: sectionKpis.fail_ids, - mean_section_attempts: sectionKpis.mean_attempts, - error_count: loop.state.errors.length, - structural_error_count, - judge_dispatch_count: summaryKpis.claims_evaluated, - distribution_pass_rate: summaryKpis.distribution_pass_rate, - written_files_count: loop.state.written_files.length, - safety_cap_hit: loop.safety_cap_hit, - mismatch_fired: mismatchExtraction.fired, - mismatch_kinds: mismatchExtraction.distinctKinds, - cortex_recall_empty_count: loop.state.cortex_recall_empty_count - }; +function date2(params) { + return _isoDate(ZodISODate, params); } -async function runAsyncPipelineLoop(seed, dispatch, cap) { - let state = seed; - let pendingResult = void 0; - let lastOutput = null; - let iterations = 0; - for (let i2 = 0; i2 < cap; i2++) { - const out = step({ state, result: pendingResult }); - lastOutput = out; - state = out.state; - iterations = i2 + 1; - if (out.action.kind === "done" || out.action.kind === "failed") { - return { state, lastOutput, iterations, safety_cap_hit: false }; - } - pendingResult = await dispatch(out.action); - if (pendingResult === void 0) { - return { state, lastOutput, iterations, safety_cap_hit: false }; - } - } - return { state, lastOutput, iterations: cap, safety_cap_hit: true }; -} -function extractAsyncSectionKpis(state) { - const sections = state.sections.filter((s) => s.section_type !== "jira_tickets"); - const passed = sections.filter((s) => s.status === "passed").length; - const failed = sections.filter((s) => s.status === "failed"); - const planned = sections.length; - return { - pass_rate: planned > 0 ? passed / planned : 0, - fail_count: failed.length, - fail_ids: failed.map((s) => s.section_type), - mean_attempts: planned > 0 ? sections.reduce((sum3, s) => sum3 + s.attempt, 0) / planned : 0 - }; +var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function time2(params) { + return _isoTime(ZodISOTime, params); } -function parseAsyncSummaryKpis(action) { - if (action?.kind !== "done" || !action.verification) { - return { - claims_evaluated: 0, - distribution_pass_rate: 0, - has_verification: false - }; - } - const v = action.verification; - const claims = v.claims_evaluated; - const passVotes = v.distribution.PASS ?? 0; - return { - claims_evaluated: claims, - distribution_pass_rate: claims > 0 ? passVotes / claims : 0, - has_verification: true - }; +var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function duration2(params) { + return _isoDuration(ZodISODuration, params); } -var DEFAULT_SAFETY_CAP2; -var init_pipeline_kpis_async = __esm({ - async "packages/benchmark/dist/src/pipeline-kpis-async.js"() { - "use strict"; - await init_dist6(); - init_instrumentation(); - DEFAULT_SAFETY_CAP2 = 200; - } -}); - -// packages/benchmark/dist/calibration/production-artefacts-io.js -import { writeFileSync as writeFileSync3, mkdirSync as mkdirSync5, existsSync as existsSync8 } from "node:fs"; -import { dirname as dirname4, join as join6 } from "node:path"; -import { execSync as execSync2 } from "node:child_process"; -function buildProductionEventRateArtefact(options, headCommit, nowIso, dispatch) { - return driveProductionRuns({ - k: options.eventRateK, - seed: PRE_REGISTERED_SEED_42, - runIdPrefix: "phase42-eventrate-prod", - featureDescription: options.featureDescription, - codebasePath: options.codebasePath, - dispatch - }).then((eventRateKpis) => { - const { totalAttempts, events } = measureEventRate(eventRateKpis); - const measuredRate = totalAttempts > 0 ? events / totalAttempts : 0; - const cp = totalAttempts > 0 ? clopperPearson(events, totalAttempts, 0.95) : { lower: 0, upper: 0, pointEstimate: 0 }; - const diverges = Math.abs(measuredRate - PROVISIONAL_EVENT_RATE) > EVENT_RATE_TOLERANCE; - return { - schema_version: 1, - commit_hash: headCommit, - seed_used: PRE_REGISTERED_SEED_42, - timestamp: nowIso, - k_target: options.eventRateK, - k_observed: eventRateKpis.length, - total_attempts: totalAttempts, - total_events: events, - measured_event_rate: measuredRate, - ci95_clopper_pearson: { lower: cp.lower, upper: cp.upper }, - provisional_anchor: PROVISIONAL_EVENT_RATE, - diverges_beyond_tolerance: diverges, - recompute_recommended: diverges - }; + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/errors.js +var initializer2 = (inst, issues) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + Object.defineProperties(inst, { + format: { + value: (mapper) => formatError(inst, mapper) + // enumerable: false, + }, + flatten: { + value: (mapper) => flattenError(inst, mapper) + // enumerable: false, + }, + addIssue: { + value: (issue2) => inst.issues.push(issue2) + // enumerable: false, + }, + addIssues: { + value: (issues2) => inst.issues.push(...issues2) + // enumerable: false, + }, + isEmpty: { + get() { + return inst.issues.length === 0; + } + // enumerable: false, + } }); -} -function persistProductionArtefacts(result, outputDir) { - const gatePath = join6(outputDir, PRODUCTION_OUTPUT_BASENAME); - if (!existsSync8(dirname4(gatePath))) { - mkdirSync5(dirname4(gatePath), { recursive: true }); - } - writeFileSync3(gatePath, JSON.stringify(result.gateCalibration, null, 2) + "\n", "utf8"); - const erPath = join6(outputDir, "event-rate-K50-production.json"); - writeFileSync3(erPath, JSON.stringify(result.eventRate, null, 2) + "\n", "utf8"); - for (const xmr of result.xmrFiles) { - const dir = dirname4(xmr.path); - if (!existsSync8(dir)) - mkdirSync5(dir, { recursive: true }); - writeFileSync3(xmr.path, JSON.stringify(xmr.record, null, 2) + "\n", "utf8"); - } -} -function resolveHeadCommit() { - try { - return execSync2("git rev-parse HEAD", { encoding: "utf8" }).trim(); - } catch { - return "unknown"; - } -} -function buildProductionSummary(args) { - const { gc, er } = args; - const lines = [ - `[production-mode] data_source=${gc.data_source}`, - `[production-mode] agent_invoker_class=${gc.agent_invoker_class}`, - `K achieved: ${gc.k_achieved} / ${gc.k_target}`, - `Frozen baseline commit: ${gc.frozen_baseline_commit}`, - `Pipeline-KPIs content hash: ${gc.frozen_baseline_content_hash}`, - "", - "Per-gate provisional vs calibrated (production):" - ]; - for (const g of gc.gates) { - const dir = g.would_tighten ? "tighten" : g.would_loosen ? "loosen" : "hold"; - lines.push(` ${g.gate_name}: ${g.provisional} \u2192 ${g.calibrated.toFixed(3)} (${dir})`); - } - lines.push("", `Event-rate (production K=${er.k_observed}): ${er.measured_event_rate.toFixed(4)}`, `CI95: [${er.ci95_clopper_pearson.lower.toFixed(4)}, ${er.ci95_clopper_pearson.upper.toFixed(4)}]`); - return lines; -} -var init_production_artefacts_io = __esm({ - async "packages/benchmark/dist/calibration/production-artefacts-io.js"() { - "use strict"; - init_clopper_pearson(); - init_event_rate(); - init_calibrate_gates_constants(); - await init_calibrate_gates_production(); - } -}); - -// packages/benchmark/dist/calibration/calibrate-gates-production.js -import { join as join7 } from "node:path"; -function mulberry32(seed) { - let state = seed >>> 0; - return () => { - state = state + 1831565813 >>> 0; - let t = state; - t = Math.imul(t ^ t >>> 15, t | 1); - t ^= t + Math.imul(t ^ t >>> 7, t | 61); - return ((t ^ t >>> 14) >>> 0) / 4294967296; - }; -} -async function driveProductionRuns(args) { - const rng = mulberry32(args.seed); - const out = []; - for (let i2 = 0; i2 < args.k; i2++) { - const runId = `${args.runIdPrefix}-${i2}-${Math.floor(rng() * 4294967295).toString(16).padStart(8, "0")}`; - const kpis = await measurePipelineAsync({ - run_id: runId, - feature_description: args.featureDescription, - codebase_path: args.codebasePath, - dispatch: args.dispatch - }); - out.push(kpis); - } - return out; -} -function buildSuspendedEntry(gateName, k) { - const v = KPI_GATES[gateName]; - const numericV = typeof v === "boolean" ? v ? 1 : 0 : v; - return { - gate_name: gateName, - estimand_type: "p95", - k_observed: k, - provisional: numericV, - calibrated: numericV, - ci_upper: null, - ci_lower: null, - would_tighten: false, - would_loosen: false, - passes_threshold: false, - xmr_path: null, - machine_class: null +}; +var ZodError2 = $constructor("ZodError", initializer2); +var ZodRealError = $constructor("ZodError", initializer2, { + Parent: Error +}); + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/parse.js +var parse2 = /* @__PURE__ */ _parse(ZodRealError); +var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); +var safeParse3 = /* @__PURE__ */ _safeParse(ZodRealError); +var safeParseAsync3 = /* @__PURE__ */ _safeParseAsync(ZodRealError); + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/schemas.js +var ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + $ZodType.init(inst, def); + inst.def = def; + Object.defineProperty(inst, "_def", { value: def }); + inst.check = (...checks) => { + return inst.clone( + { + ...def, + checks: [ + ...def.checks ?? [], + ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + } + // { parent: true } + ); }; -} -function buildNumericEntry(args) { - const { gateName, values, machineClass, outputDir } = args; - if (values.length < 2) { - throw new Error(`buildNumericEntry: ${gateName} has <2 observations (K=${values.length})`); - } - const isWallTime = gateName === "wall_time_ms_max"; - const provisional = KPI_GATES[gateName]; - const stats = computeGateStats(values); - const calibrated = stats.p95; - const xmrFileName = isWallTime ? `${gateName}.${machineClass}.production.json` : `${gateName}.production.json`; - const xmrPath = join7(outputDir, "gate-calibration-K100-production.xmr", xmrFileName); - const entry = { - gate_name: gateName, - estimand_type: GATE_ESTIMAND[gateName] ?? "p95", - k_observed: values.length, - provisional, - calibrated, - ci_upper: stats.ci_upper, - ci_lower: stats.ci_lower, - would_tighten: calibrated < provisional, - would_loosen: calibrated > provisional, - passes_threshold: (stats.ci_upper < provisional || stats.ci_lower > provisional) && Math.abs(calibrated - provisional) / Math.max(provisional, 1e-9) >= 0.05, - xmr_path: xmrPath, - machine_class: isWallTime ? machineClass : null + inst.clone = (def2, params) => clone(inst, def2, params); + inst.brand = () => inst; + inst.register = ((reg, meta) => { + reg.add(inst, meta); + return inst; + }); + inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); + inst.safeParse = (data, params) => safeParse3(inst, data, params); + inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); + inst.safeParseAsync = async (data, params) => safeParseAsync3(inst, data, params); + inst.spa = inst.safeParseAsync; + inst.refine = (check2, params) => inst.check(refine(check2, params)); + inst.superRefine = (refinement) => inst.check(superRefine(refinement)); + inst.overwrite = (fn) => inst.check(_overwrite(fn)); + inst.optional = () => optional(inst); + inst.nullable = () => nullable(inst); + inst.nullish = () => optional(nullable(inst)); + inst.nonoptional = (params) => nonoptional(inst, params); + inst.array = () => array(inst); + inst.or = (arg2) => union([inst, arg2]); + inst.and = (arg2) => intersection(inst, arg2); + inst.transform = (tx) => pipe(inst, transform(tx)); + inst.default = (def2) => _default(inst, def2); + inst.prefault = (def2) => prefault(inst, def2); + inst.catch = (params) => _catch(inst, params); + inst.pipe = (target) => pipe(inst, target); + inst.readonly = () => readonly(inst); + inst.describe = (description) => { + const cl = inst.clone(); + globalRegistry.add(cl, { description }); + return cl; }; - return { entry, xmrFile: { path: xmrPath, record: stats.xmr } }; -} -function buildCalibrationEntries(args) { - const entries = []; - const xmrFiles = []; - for (const gateName of Object.keys(KPI_GATES)) { - const extractor = GATE_EXTRACTORS[gateName]; - if (extractor == null) { - entries.push(buildSuspendedEntry(gateName, args.kpis.length)); - continue; + Object.defineProperty(inst, "description", { + get() { + return globalRegistry.get(inst)?.description; + }, + configurable: true + }); + inst.meta = (...args) => { + if (args.length === 0) { + return globalRegistry.get(inst); } - const values = args.kpis.map((k) => extractor(k)); - const { entry, xmrFile } = buildNumericEntry({ - gateName, - values, - machineClass: args.machineClass, - outputDir: args.outputDir - }); - entries.push(entry); - xmrFiles.push(xmrFile); - } - return { entries, xmrFiles }; -} -async function runProductionCalibration(options) { - validateProductionOptions(options); - const dispatch = makeProductionDispatcher({ - agentInvoker: options.agentInvoker, - cannedOptions: { - freeform_answer: "production-mode-answer", - graph_path: "/tmp/benchmark-production/graph" - } - }); - const nowIso = (/* @__PURE__ */ new Date()).toISOString(); - const headCommit = resolveHeadCommit(); - const { gateCalibration, xmrFiles } = await assembleGateCalibration(options, dispatch, nowIso, headCommit); - const eventRate = await buildProductionEventRateArtefact(options, headCommit, nowIso, dispatch); - const summary = buildProductionSummary({ gc: gateCalibration, er: eventRate }); - if (!options.inMemoryOnly) { - persistProductionArtefacts({ gateCalibration, eventRate, xmrFiles }, options.outputDir); - } - return { gateCalibration, eventRate, xmrFiles, summary }; -} -function validateProductionOptions(options) { - if (options.k < 2) { - throw new Error(`runProductionCalibration: k must be \u2265 2 (got ${options.k})`); - } - if (options.eventRateK < 1) { - throw new Error(`runProductionCalibration: eventRateK must be \u2265 1 (got ${options.eventRateK})`); - } -} -async function assembleGateCalibration(options, dispatch, nowIso, headCommit) { - const currentHash = computePipelineKpisContentHash(); - const kpis = await driveProductionRuns({ - k: options.k, - seed: PRE_REGISTERED_SEED_45_PRODUCTION, - runIdPrefix: "phase45-prod", - featureDescription: options.featureDescription, - codebasePath: options.codebasePath, - dispatch - }); - const machineClass = detectMachineClass(); - const { entries, xmrFiles } = buildCalibrationEntries({ - kpis, - machineClass, - outputDir: options.outputDir - }); - const gateCalibration = { - schema_version: 1, - commit_hash: headCommit, - seed_used: PRE_REGISTERED_SEED_45_PRODUCTION, - timestamp: nowIso, - k_target: options.k, - k_achieved: kpis.length, - frozen_baseline_commit: options.frozenBaselineCommit, - frozen_baseline_content_hash: currentHash, - gates: [...entries], - data_source: `production_pilot_K=${kpis.length}`, - agent_invoker_class: options.agentInvokerClass + const cl = inst.clone(); + globalRegistry.add(cl, args[0]); + return cl; }; - return { gateCalibration, xmrFiles }; + inst.isOptional = () => inst.safeParse(void 0).success; + inst.isNullable = () => inst.safeParse(null).success; + return inst; +}); +var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { + $ZodString.init(inst, def); + ZodType2.init(inst, def); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; + inst.regex = (...args) => inst.check(_regex(...args)); + inst.includes = (...args) => inst.check(_includes(...args)); + inst.startsWith = (...args) => inst.check(_startsWith(...args)); + inst.endsWith = (...args) => inst.check(_endsWith(...args)); + inst.min = (...args) => inst.check(_minLength(...args)); + inst.max = (...args) => inst.check(_maxLength(...args)); + inst.length = (...args) => inst.check(_length(...args)); + inst.nonempty = (...args) => inst.check(_minLength(1, ...args)); + inst.lowercase = (params) => inst.check(_lowercase(params)); + inst.uppercase = (params) => inst.check(_uppercase(params)); + inst.trim = () => inst.check(_trim()); + inst.normalize = (...args) => inst.check(_normalize(...args)); + inst.toLowerCase = () => inst.check(_toLowerCase()); + inst.toUpperCase = () => inst.check(_toUpperCase()); +}); +var ZodString2 = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { + $ZodString.init(inst, def); + _ZodString.init(inst, def); + inst.email = (params) => inst.check(_email(ZodEmail, params)); + inst.url = (params) => inst.check(_url(ZodURL, params)); + inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); + inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); + inst.guid = (params) => inst.check(_guid(ZodGUID, params)); + inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); + inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); + inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); + inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); + inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); + inst.guid = (params) => inst.check(_guid(ZodGUID, params)); + inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); + inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); + inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); + inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); + inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); + inst.xid = (params) => inst.check(_xid(ZodXID, params)); + inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); + inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); + inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); + inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); + inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); + inst.e164 = (params) => inst.check(_e164(ZodE164, params)); + inst.datetime = (params) => inst.check(datetime2(params)); + inst.date = (params) => inst.check(date2(params)); + inst.time = (params) => inst.check(time2(params)); + inst.duration = (params) => inst.check(duration2(params)); +}); +function string2(params) { + return _string(ZodString2, params); } -var PRE_REGISTERED_SEED_45_PRODUCTION, DEFAULT_K_PRODUCTION, PRODUCTION_OUTPUT_BASENAME, GATE_ESTIMAND, GATE_EXTRACTORS, mulberry32ForCli; -var init_calibrate_gates_production = __esm({ - async "packages/benchmark/dist/calibration/calibrate-gates-production.js"() { - "use strict"; - await init_pipeline_kpis_async(); - await init_pipeline_kpis(); - await init_dist6(); - init_machine_class(); - init_gate_stats(); - init_frozen_baseline(); - await init_production_artefacts_io(); - PRE_REGISTERED_SEED_45_PRODUCTION = 67486719; - DEFAULT_K_PRODUCTION = 100; - PRODUCTION_OUTPUT_BASENAME = "gate-calibration-K100-production.json"; - GATE_ESTIMAND = { - iteration_count_max: "p95", - wall_time_ms_max: "p95", - section_fail_count_max: "p95", - error_count_max: "p95", - mean_section_attempts_max: "p95", - cortex_recall_empty_count_max: "p95" - }; - GATE_EXTRACTORS = { - iteration_count_max: (k) => k.iteration_count, - wall_time_ms_max: (k) => k.wall_time_ms, - section_fail_count_max: (k) => k.section_fail_count, - error_count_max: (k) => k.error_count, - mean_section_attempts_max: (k) => k.mean_section_attempts, - cortex_recall_empty_count_max: (k) => k.cortex_recall_empty_count, - distribution_pass_rate_max: null, - safety_cap_hit_allowed: null, - structural_error_count_max: null - }; - mulberry32ForCli = mulberry32; - } +var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); }); - -// packages/benchmark/dist/calibration/calibrate-gates-production-cli.js -var calibrate_gates_production_cli_exports = {}; -__export(calibrate_gates_production_cli_exports, { - runProductionFromCli: () => runProductionFromCli +var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { + $ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); }); -async function runProductionFromCli(args) { - const k = Number(parseFlag(args.argv, "k") ?? DEFAULT_K_PRODUCTION); - const eventRateK = Number(parseFlag(args.argv, "event-rate-k") ?? Math.min(50, k)); - const outputDir = parseFlag(args.argv, "output-dir") ?? "packages/benchmark/calibration/data"; - const frozenBaselineCommit = parseFlag(args.argv, "frozen-baseline-commit") ?? resolveFrozenBaselineCommit(); - const useStub = !hasFlag(args.argv, "real-host"); - const agentInvoker = useStub ? makeStubAgentInvoker({ rng: mulberry32ForCli(PRE_REGISTERED_SEED_45_PRODUCTION) }) : (() => { - throw new Error("production CLI: --real-host is reserved for the follow-up PR that wires the host-backed AgentInvoker. Until then, omit the flag to run the deterministic stub pilot. See production-calibration-runbook.md."); - })(); - const result = await runProductionCalibration({ - k, - eventRateK, - outputDir, - frozenBaselineCommit, - featureDescription: "build a feature for OAuth login", - codebasePath: "/tmp/benchmark-production", - inMemoryOnly: false, - agentInvoker, - agentInvokerClass: useStub ? "stub-deterministic-cli" : "host-real" - }); - for (const line of result.summary) - console.log(line); -} -var invokedDirectly; -var init_calibrate_gates_production_cli = __esm({ - async "packages/benchmark/dist/calibration/calibrate-gates-production-cli.js"() { - "use strict"; - await init_calibrate_gates_production(); - await init_dist6(); - init_frozen_baseline(); - init_calibrate_gates_cli(); - invokedDirectly = (() => { - try { - return typeof process !== "undefined" && Array.isArray(process.argv) && process.argv[1] !== void 0 && (process.argv[1].endsWith("calibrate-gates-production-cli.js") || process.argv[1].endsWith("calibrate-gates-production-cli.ts")); - } catch { - return false; - } - })(); - if (invokedDirectly) { - runProductionFromCli({ argv: process.argv.slice(2) }).catch((err) => { - console.error(err); - process.exit(1); - }); - } - } +var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { + $ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); }); - -// node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/extends.js -var require_extends = __commonJS({ - "node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/extends.js"(exports, module) { - function _extends8() { - return module.exports = _extends8 = Object.assign ? Object.assign.bind() : function(n) { - for (var e3 = 1; e3 < arguments.length; e3++) { - var t = arguments[e3]; - for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); - } - return n; - }, module.exports.__esModule = true, module.exports["default"] = module.exports, _extends8.apply(null, arguments); - } - module.exports = _extends8, module.exports.__esModule = true, module.exports["default"] = module.exports; - } +var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { + $ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); }); - -// node_modules/.pnpm/typed-function@4.2.2/node_modules/typed-function/lib/umd/typed-function.js -var require_typed_function = __commonJS({ - "node_modules/.pnpm/typed-function@4.2.2/node_modules/typed-function/lib/umd/typed-function.js"(exports, module) { - (function(global, factory2) { - typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory2() : typeof define === "function" && define.amd ? define(factory2) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, global.typed = factory2()); - })(exports, (function() { - "use strict"; - function ok() { - return true; - } - function notOk() { - return false; - } - function undef() { - return void 0; - } - const NOT_TYPED_FUNCTION = "Argument is not a typed-function."; - function create() { - function isPlainObject4(x) { - return typeof x === "object" && x !== null && x.constructor === Object; - } - const _types = [{ - name: "number", - test: function(x) { - return typeof x === "number"; - } - }, { - name: "string", - test: function(x) { - return typeof x === "string"; - } - }, { - name: "boolean", - test: function(x) { - return typeof x === "boolean"; - } - }, { - name: "Function", - test: function(x) { - return typeof x === "function"; - } - }, { - name: "Array", - test: Array.isArray - }, { - name: "Date", - test: function(x) { - return x instanceof Date; - } - }, { - name: "RegExp", - test: function(x) { - return x instanceof RegExp; - } - }, { - name: "Object", - test: isPlainObject4 - }, { - name: "null", - test: function(x) { - return x === null; - } - }, { - name: "undefined", - test: function(x) { - return x === void 0; - } - }]; - const anyType2 = { - name: "any", - test: ok, - isAny: true - }; - let typeMap; - let typeList; - let nConversions = 0; - let typed3 = { - createCount: 0 - }; - function findType(typeName) { - const type2 = typeMap.get(typeName); - if (type2) { - return type2; - } - let message = 'Unknown type "' + typeName + '"'; - const name315 = typeName.toLowerCase(); - let otherName; - for (otherName of typeList) { - if (otherName.toLowerCase() === name315) { - message += '. Did you mean "' + otherName + '" ?'; - break; - } - } - throw new TypeError(message); - } - function addTypes(types) { - let beforeSpec = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "any"; - const beforeIndex = beforeSpec ? findType(beforeSpec).index : typeList.length; - const newTypes = []; - for (let i2 = 0; i2 < types.length; ++i2) { - if (!types[i2] || typeof types[i2].name !== "string" || typeof types[i2].test !== "function") { - throw new TypeError("Object with properties {name: string, test: function} expected"); - } - const typeName = types[i2].name; - if (typeMap.has(typeName)) { - throw new TypeError('Duplicate type name "' + typeName + '"'); - } - newTypes.push(typeName); - typeMap.set(typeName, { - name: typeName, - test: types[i2].test, - isAny: types[i2].isAny, - index: beforeIndex + i2, - conversionsTo: [] - // Newly added type can't have any conversions to it - }); - } - const affectedTypes = typeList.slice(beforeIndex); - typeList = typeList.slice(0, beforeIndex).concat(newTypes).concat(affectedTypes); - for (let i2 = beforeIndex + newTypes.length; i2 < typeList.length; ++i2) { - typeMap.get(typeList[i2]).index = i2; - } - } - function clear() { - typeMap = /* @__PURE__ */ new Map(); - typeList = []; - nConversions = 0; - addTypes([anyType2], false); - } - clear(); - addTypes(_types); - function clearConversions() { - let typeName; - for (typeName of typeList) { - typeMap.get(typeName).conversionsTo = []; - } - nConversions = 0; - } - function findTypeNames(value) { - const matches = typeList.filter((name315) => { - const type2 = typeMap.get(name315); - return !type2.isAny && type2.test(value); - }); - if (matches.length) { - return matches; - } - return ["any"]; - } - function isTypedFunction(entity) { - return entity && typeof entity === "function" && "_typedFunctionData" in entity; - } - function findSignature(fn, signature, options) { - if (!isTypedFunction(fn)) { - throw new TypeError(NOT_TYPED_FUNCTION); - } - const exact = options && options.exact; - const stringSignature = Array.isArray(signature) ? signature.join(",") : signature; - const params = parseSignature(stringSignature); - const canonicalSignature = stringifyParams(params); - if (!exact || canonicalSignature in fn.signatures) { - const match = fn._typedFunctionData.signatureMap.get(canonicalSignature); - if (match) { - return match; - } - } - const nParams = params.length; - let remainingSignatures; - if (exact) { - remainingSignatures = []; - let name315; - for (name315 in fn.signatures) { - remainingSignatures.push(fn._typedFunctionData.signatureMap.get(name315)); - } - } else { - remainingSignatures = fn._typedFunctionData.signatures; - } - for (let i2 = 0; i2 < nParams; ++i2) { - const want = params[i2]; - const filteredSignatures = []; - let possibility; - for (possibility of remainingSignatures) { - const have = getParamAtIndex(possibility.params, i2); - if (!have || want.restParam && !have.restParam) { - continue; - } - if (!have.hasAny) { - const haveTypes = paramTypeSet(have); - if (want.types.some((wtype) => !haveTypes.has(wtype.name))) { - continue; - } - } - filteredSignatures.push(possibility); - } - remainingSignatures = filteredSignatures; - if (remainingSignatures.length === 0) break; - } - let candidate; - for (candidate of remainingSignatures) { - if (candidate.params.length <= nParams) { - return candidate; - } - } - throw new TypeError("Signature not found (signature: " + (fn.name || "unnamed") + "(" + stringifyParams(params, ", ") + "))"); - } - function find(fn, signature, options) { - return findSignature(fn, signature, options).implementation; - } - function convert(value, typeName) { - const type2 = findType(typeName); - if (type2.test(value)) { - return value; - } - const conversions = type2.conversionsTo; - if (conversions.length === 0) { - throw new Error("There are no conversions to " + typeName + " defined."); - } - for (let i2 = 0; i2 < conversions.length; i2++) { - const fromType = findType(conversions[i2].from); - if (fromType.test(value)) { - return conversions[i2].convert(value); - } - } - throw new Error("Cannot convert " + value + " to " + typeName); - } - function stringifyParams(params) { - let separator = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : ","; - return params.map((p) => p.name).join(separator); - } - function parseParam(param) { - const restParam = param.indexOf("...") === 0; - const types = !restParam ? param : param.length > 3 ? param.slice(3) : "any"; - const typeDefs = types.split("|").map((s) => findType(s.trim())); - let hasAny = false; - let paramName = restParam ? "..." : ""; - const exactTypes = typeDefs.map(function(type2) { - hasAny = type2.isAny || hasAny; - paramName += type2.name + "|"; - return { - name: type2.name, - typeIndex: type2.index, - test: type2.test, - isAny: type2.isAny, - conversion: null, - conversionIndex: -1 - }; - }); - return { - types: exactTypes, - name: paramName.slice(0, -1), - // remove trailing '|' from above - hasAny, - hasConversion: false, - restParam - }; - } - function expandParam(param) { - const typeNames = param.types.map((t) => t.name); - const matchingConversions = availableConversions(typeNames); - let hasAny = param.hasAny; - let newName = param.name; - const convertibleTypes = matchingConversions.map(function(conversion) { - const type2 = findType(conversion.from); - hasAny = type2.isAny || hasAny; - newName += "|" + conversion.from; - return { - name: conversion.from, - typeIndex: type2.index, - test: type2.test, - isAny: type2.isAny, - conversion, - conversionIndex: conversion.index - }; - }); - return { - types: param.types.concat(convertibleTypes), - name: newName, - hasAny, - hasConversion: convertibleTypes.length > 0, - restParam: param.restParam - }; - } - function paramTypeSet(param) { - if (!param.typeSet) { - param.typeSet = /* @__PURE__ */ new Set(); - param.types.forEach((type2) => param.typeSet.add(type2.name)); - } - return param.typeSet; - } - function parseSignature(rawSignature) { - const params = []; - if (typeof rawSignature !== "string") { - throw new TypeError("Signatures must be strings"); - } - const signature = rawSignature.trim(); - if (signature === "") { - return params; - } - const rawParams = signature.split(","); - for (let i2 = 0; i2 < rawParams.length; ++i2) { - const parsedParam = parseParam(rawParams[i2].trim()); - if (parsedParam.restParam && i2 !== rawParams.length - 1) { - throw new SyntaxError('Unexpected rest parameter "' + rawParams[i2] + '": only allowed for the last parameter'); - } - if (parsedParam.types.length === 0) { - return null; - } - params.push(parsedParam); - } - return params; - } - function hasRestParam(params) { - const param = last(params); - return param ? param.restParam : false; - } - function compileTest(param) { - if (!param || param.types.length === 0) { - return ok; - } else if (param.types.length === 1) { - return findType(param.types[0].name).test; - } else if (param.types.length === 2) { - const test0 = findType(param.types[0].name).test; - const test1 = findType(param.types[1].name).test; - return function or2(x) { - return test0(x) || test1(x); - }; - } else { - const tests = param.types.map(function(type2) { - return findType(type2.name).test; - }); - return function or2(x) { - for (let i2 = 0; i2 < tests.length; i2++) { - if (tests[i2](x)) { - return true; - } - } - return false; - }; - } - } - function compileTests(params) { - let tests, test0, test1; - if (hasRestParam(params)) { - tests = initial(params).map(compileTest); - const varIndex = tests.length; - const lastTest = compileTest(last(params)); - const testRestParam = function(args) { - for (let i2 = varIndex; i2 < args.length; i2++) { - if (!lastTest(args[i2])) { - return false; - } - } - return true; - }; - return function testArgs(args) { - for (let i2 = 0; i2 < tests.length; i2++) { - if (!tests[i2](args[i2])) { - return false; - } - } - return testRestParam(args) && args.length >= varIndex + 1; - }; - } else { - if (params.length === 0) { - return function testArgs(args) { - return args.length === 0; - }; - } else if (params.length === 1) { - test0 = compileTest(params[0]); - return function testArgs(args) { - return test0(args[0]) && args.length === 1; - }; - } else if (params.length === 2) { - test0 = compileTest(params[0]); - test1 = compileTest(params[1]); - return function testArgs(args) { - return test0(args[0]) && test1(args[1]) && args.length === 2; - }; - } else { - tests = params.map(compileTest); - return function testArgs(args) { - for (let i2 = 0; i2 < tests.length; i2++) { - if (!tests[i2](args[i2])) { - return false; - } - } - return args.length === tests.length; - }; - } - } - } - function getParamAtIndex(params, index2) { - return index2 < params.length ? params[index2] : hasRestParam(params) ? last(params) : null; - } - function getTypeSetAtIndex(params, index2) { - const param = getParamAtIndex(params, index2); - if (!param) { - return /* @__PURE__ */ new Set(); - } - return paramTypeSet(param); - } - function isExactType(type2) { - return type2.conversion === null || type2.conversion === void 0; - } - function mergeExpectedParams(signatures, index2) { - const typeSet = /* @__PURE__ */ new Set(); - signatures.forEach((signature) => { - const paramSet = getTypeSetAtIndex(signature.params, index2); - let name315; - for (name315 of paramSet) { - typeSet.add(name315); - } - }); - return typeSet.has("any") ? ["any"] : Array.from(typeSet); - } - function createError(name315, args, signatures) { - let err, expected; - const _name = name315 || "unnamed"; - let matchingSignatures = signatures; - let index2; - for (index2 = 0; index2 < args.length; index2++) { - const nextMatchingDefs = []; - matchingSignatures.forEach((signature) => { - const param = getParamAtIndex(signature.params, index2); - const test = compileTest(param); - if ((index2 < signature.params.length || hasRestParam(signature.params)) && test(args[index2])) { - nextMatchingDefs.push(signature); - } - }); - if (nextMatchingDefs.length === 0) { - expected = mergeExpectedParams(matchingSignatures, index2); - if (expected.length > 0) { - const actualTypes = findTypeNames(args[index2]); - err = new TypeError("Unexpected type of argument in function " + _name + " (expected: " + expected.join(" or ") + ", actual: " + actualTypes.join(" | ") + ", index: " + index2 + ")"); - err.data = { - category: "wrongType", - fn: _name, - index: index2, - actual: actualTypes, - expected - }; - return err; - } - } else { - matchingSignatures = nextMatchingDefs; - } - } - const lengths = matchingSignatures.map(function(signature) { - return hasRestParam(signature.params) ? Infinity : signature.params.length; - }); - if (args.length < Math.min.apply(null, lengths)) { - expected = mergeExpectedParams(matchingSignatures, index2); - err = new TypeError("Too few arguments in function " + _name + " (expected: " + expected.join(" or ") + ", index: " + args.length + ")"); - err.data = { - category: "tooFewArgs", - fn: _name, - index: args.length, - expected - }; - return err; - } - const maxLength = Math.max.apply(null, lengths); - if (args.length > maxLength) { - err = new TypeError("Too many arguments in function " + _name + " (expected: " + maxLength + ", actual: " + args.length + ")"); - err.data = { - category: "tooManyArgs", - fn: _name, - index: args.length, - expectedLength: maxLength - }; - return err; - } - const argTypes = []; - for (let i2 = 0; i2 < args.length; ++i2) { - argTypes.push(findTypeNames(args[i2]).join("|")); - } - err = new TypeError('Arguments of type "' + argTypes.join(", ") + '" do not match any of the defined signatures of function ' + _name + "."); - err.data = { - category: "mismatch", - actual: argTypes - }; - return err; - } - function getLowestTypeIndex(param) { - let min3 = typeList.length + 1; - for (let i2 = 0; i2 < param.types.length; i2++) { - min3 = Math.min(min3, param.types[i2].typeIndex); - } - return min3; - } - function getLowestConversionIndex(param) { - let min3 = nConversions + 1; - for (let i2 = 0; i2 < param.types.length; i2++) { - if (!isExactType(param.types[i2])) { - min3 = Math.min(min3, param.types[i2].conversionIndex); - } - } - return min3; - } - function compareParams(param1, param2) { - if (param1.hasAny) { - if (!param2.hasAny) { - return 0.1; - } - } else if (param2.hasAny) { - return -0.1; - } - if (param1.restParam) { - if (!param2.restParam) { - return 0.01; - } - } else if (param2.restParam) { - return -0.01; - } - const typeDiff = getLowestTypeIndex(param1) - getLowestTypeIndex(param2); - if (typeDiff < 0) { - return -1e-3; - } - if (typeDiff > 0) { - return 1e-3; - } - const conv1 = getLowestConversionIndex(param1); - const conv2 = getLowestConversionIndex(param2); - if (param1.hasConversion) { - if (!param2.hasConversion) { - return (1 + conv1) * 1e-6; - } - } else if (param2.hasConversion) { - return -(1 + conv2) * 1e-6; - } - const convDiff = conv1 - conv2; - if (convDiff < 0) { - return -1e-7; - } - if (convDiff > 0) { - return 1e-7; - } - return 0; - } - function compareSignatures(signature1, signature2) { - const pars1 = signature1.params; - const pars2 = signature2.params; - const last1 = last(pars1); - const last2 = last(pars2); - const hasRest1 = hasRestParam(pars1); - const hasRest2 = hasRestParam(pars2); - if (hasRest1 && last1.hasAny) { - if (!hasRest2 || !last2.hasAny) { - return 1e7; - } - } else if (hasRest2 && last2.hasAny) { - return -1e7; - } - let any1 = 0; - let conv1 = 0; - let par; - for (par of pars1) { - if (par.hasAny) ++any1; - if (par.hasConversion) ++conv1; - } - let any2 = 0; - let conv2 = 0; - for (par of pars2) { - if (par.hasAny) ++any2; - if (par.hasConversion) ++conv2; - } - if (any1 !== any2) { - return (any1 - any2) * 1e6; - } - if (hasRest1 && last1.hasConversion) { - if (!hasRest2 || !last2.hasConversion) { - return 1e5; - } - } else if (hasRest2 && last2.hasConversion) { - return -1e5; - } - if (conv1 !== conv2) { - return (conv1 - conv2) * 1e4; - } - if (hasRest1) { - if (!hasRest2) { - return 1e3; - } - } else if (hasRest2) { - return -1e3; - } - const lengthCriterion = (pars1.length - pars2.length) * (hasRest1 ? -100 : 100); - if (lengthCriterion !== 0) { - return lengthCriterion; - } - const comparisons = []; - let tc = 0; - for (let i2 = 0; i2 < pars1.length; ++i2) { - const thisComparison = compareParams(pars1[i2], pars2[i2]); - comparisons.push(thisComparison); - tc += thisComparison; - } - if (tc !== 0) { - return (tc < 0 ? -10 : 10) + tc; - } - let c; - let bonus = 9; - const decrement = bonus / (comparisons.length + 1); - for (c of comparisons) { - if (c !== 0) { - return (c < 0 ? -bonus : bonus) + c; - } - bonus -= decrement; - } - return 0; - } - function availableConversions(typeNames) { - if (typeNames.length === 0) { - return []; - } - const types = typeNames.map(findType); - if (typeNames.length === 1) return types[0].conversionsTo; - const knownTypes = new Set(typeNames); - const convertibleTypes = /* @__PURE__ */ new Set(); - for (let i2 = 0; i2 < types.length; ++i2) { - for (const match of types[i2].conversionsTo) { - if (!knownTypes.has(match.from)) convertibleTypes.add(match.from); - } - } - const matches = []; - for (const typeName of convertibleTypes) { - let bestIndex = nConversions + 1; - let bestConversion = null; - for (let i2 = 0; i2 < types.length; ++i2) { - for (const match of types[i2].conversionsTo) { - if (match.from === typeName && match.index < bestIndex) { - bestIndex = match.index; - bestConversion = match; - } - } - } - matches.push(bestConversion); - } - return matches; - } - function compileArgsPreprocessing(params, fn) { - let fnConvert = fn; - let name315 = ""; - if (params.some((p) => p.hasConversion)) { - const restParam = hasRestParam(params); - const compiledConversions = params.map(compileArgConversion); - name315 = compiledConversions.map((conv) => conv.name).join(";"); - fnConvert = function convertArgs() { - const args = []; - const last2 = restParam ? arguments.length - 1 : arguments.length; - for (let i2 = 0; i2 < last2; i2++) { - args[i2] = compiledConversions[i2](arguments[i2]); - } - if (restParam) { - args[last2] = arguments[last2].map(compiledConversions[last2]); - } - return fn.apply(this, args); - }; - } - let fnPreprocess = fnConvert; - if (hasRestParam(params)) { - const offset = params.length - 1; - fnPreprocess = function preprocessRestParams() { - return fnConvert.apply(this, slice(arguments, 0, offset).concat([slice(arguments, offset)])); - }; - } - if (name315) Object.defineProperty(fnPreprocess, "name", { - value: name315 - }); - return fnPreprocess; - } - function compileArgConversion(param) { - let test0, test1, conversion0, conversion1; - const tests = []; - const conversions = []; - let name315 = ""; - param.types.forEach(function(type2) { - if (type2.conversion) { - name315 += type2.conversion.from + "~>" + type2.conversion.to + ","; - tests.push(findType(type2.conversion.from).test); - conversions.push(type2.conversion.convert); - } - }); - if (name315) name315 = name315.slice(0, -1); - else name315 = "pass"; - let convertor = (arg2) => arg2; - switch (conversions.length) { - case 0: - break; - case 1: - test0 = tests[0]; - conversion0 = conversions[0]; - convertor = function convertArg(arg2) { - if (test0(arg2)) { - return conversion0(arg2); - } - return arg2; - }; - break; - case 2: - test0 = tests[0]; - test1 = tests[1]; - conversion0 = conversions[0]; - conversion1 = conversions[1]; - convertor = function convertArg(arg2) { - if (test0(arg2)) { - return conversion0(arg2); - } - if (test1(arg2)) { - return conversion1(arg2); - } - return arg2; - }; - break; - default: - convertor = function convertArg(arg2) { - for (let i2 = 0; i2 < conversions.length; i2++) { - if (tests[i2](arg2)) { - return conversions[i2](arg2); - } - } - return arg2; - }; - } - Object.defineProperty(convertor, "name", { - value: name315 - }); - return convertor; - } - function splitParams(params) { - function _splitParams(params2, index2, paramsSoFar) { - if (index2 < params2.length) { - const param = params2[index2]; - let resultingParams = []; - if (param.restParam) { - const exactTypes = param.types.filter(isExactType); - if (exactTypes.length < param.types.length) { - resultingParams.push({ - types: exactTypes, - name: "..." + exactTypes.map((t) => t.name).join("|"), - hasAny: exactTypes.some((t) => t.isAny), - hasConversion: false, - restParam: true - }); - } - resultingParams.push(param); - } else { - resultingParams = param.types.map(function(type2) { - return { - types: [type2], - name: type2.name, - hasAny: type2.isAny, - hasConversion: type2.conversion, - restParam: false - }; - }); - } - return flatMap(resultingParams, function(nextParam) { - return _splitParams(params2, index2 + 1, paramsSoFar.concat([nextParam])); - }); - } else { - return [paramsSoFar]; - } - } - return _splitParams(params, 0, []); - } - function conflicting(params1, params2) { - const ii = Math.max(params1.length, params2.length); - for (let i2 = 0; i2 < ii; i2++) { - const typeSet1 = getTypeSetAtIndex(params1, i2); - const typeSet2 = getTypeSetAtIndex(params2, i2); - let overlap = false; - let name315; - for (name315 of typeSet2) { - if (typeSet1.has(name315)) { - overlap = true; - break; - } - } - if (!overlap) { - return false; - } - } - const len1 = params1.length; - const len2 = params2.length; - const restParam1 = hasRestParam(params1); - const restParam2 = hasRestParam(params2); - return restParam1 ? restParam2 ? len1 === len2 : len2 >= len1 : restParam2 ? len1 >= len2 : len1 === len2; - } - function clearResolutions(functionList) { - return functionList.map((fn) => { - if (isReferToSelf(fn)) { - return referToSelf(fn.referToSelf.callback); - } - if (isReferTo(fn)) { - return makeReferTo(fn.referTo.references, fn.referTo.callback); - } - return fn; - }); - } - function collectResolutions(references, functionList, signatureMap) { - const resolvedReferences = []; - let reference; - for (reference of references) { - let resolution = signatureMap[reference]; - if (typeof resolution !== "number") { - throw new TypeError('No definition for referenced signature "' + reference + '"'); - } - resolution = functionList[resolution]; - if (typeof resolution !== "function") { - return false; - } - resolvedReferences.push(resolution); - } - return resolvedReferences; - } - function resolveReferences(functionList, signatureMap, self2) { - const resolvedFunctions = clearResolutions(functionList); - const isResolved = new Array(resolvedFunctions.length).fill(false); - let leftUnresolved = true; - while (leftUnresolved) { - leftUnresolved = false; - let nothingResolved = true; - for (let i2 = 0; i2 < resolvedFunctions.length; ++i2) { - if (isResolved[i2]) continue; - const fn = resolvedFunctions[i2]; - if (isReferToSelf(fn)) { - resolvedFunctions[i2] = fn.referToSelf.callback(self2); - resolvedFunctions[i2].referToSelf = fn.referToSelf; - isResolved[i2] = true; - nothingResolved = false; - } else if (isReferTo(fn)) { - const resolvedReferences = collectResolutions(fn.referTo.references, resolvedFunctions, signatureMap); - if (resolvedReferences) { - resolvedFunctions[i2] = fn.referTo.callback.apply(this, resolvedReferences); - resolvedFunctions[i2].referTo = fn.referTo; - isResolved[i2] = true; - nothingResolved = false; - } else { - leftUnresolved = true; - } - } - } - if (nothingResolved && leftUnresolved) { - throw new SyntaxError("Circular reference detected in resolving typed.referTo"); - } - } - return resolvedFunctions; - } - function validateDeprecatedThis(signaturesMap) { - const deprecatedThisRegex = /\bthis(\(|\.signatures\b)/; - Object.keys(signaturesMap).forEach((signature) => { - const fn = signaturesMap[signature]; - if (deprecatedThisRegex.test(fn.toString())) { - throw new SyntaxError("Using `this` to self-reference a function is deprecated since typed-function@3. Use typed.referTo and typed.referToSelf instead."); - } - }); - } - function createTypedFunction(name315, rawSignaturesMap) { - typed3.createCount++; - if (Object.keys(rawSignaturesMap).length === 0) { - throw new SyntaxError("No signatures provided"); - } - if (typed3.warnAgainstDeprecatedThis) { - validateDeprecatedThis(rawSignaturesMap); - } - const parsedParams = []; - const originalFunctions = []; - const signaturesMap = {}; - const preliminarySignatures = []; - let signature; - for (signature in rawSignaturesMap) { - if (!Object.prototype.hasOwnProperty.call(rawSignaturesMap, signature)) { - continue; - } - const params = parseSignature(signature); - if (!params) continue; - parsedParams.forEach(function(pp) { - if (conflicting(pp, params)) { - throw new TypeError('Conflicting signatures "' + stringifyParams(pp) + '" and "' + stringifyParams(params) + '".'); - } - }); - parsedParams.push(params); - const functionIndex = originalFunctions.length; - originalFunctions.push(rawSignaturesMap[signature]); - const conversionParams = params.map(expandParam); - let sp; - for (sp of splitParams(conversionParams)) { - const spName = stringifyParams(sp); - preliminarySignatures.push({ - params: sp, - name: spName, - fn: functionIndex - }); - if (sp.every((p) => !p.hasConversion)) { - signaturesMap[spName] = functionIndex; - } - } - } - preliminarySignatures.sort(compareSignatures); - const resolvedFunctions = resolveReferences(originalFunctions, signaturesMap, theTypedFn); - let s; - for (s in signaturesMap) { - if (Object.prototype.hasOwnProperty.call(signaturesMap, s)) { - signaturesMap[s] = resolvedFunctions[signaturesMap[s]]; - } - } - const signatures = []; - const internalSignatureMap = /* @__PURE__ */ new Map(); - for (s of preliminarySignatures) { - if (!internalSignatureMap.has(s.name)) { - s.fn = resolvedFunctions[s.fn]; - signatures.push(s); - internalSignatureMap.set(s.name, s); - } - } - const ok0 = signatures[0] && signatures[0].params.length <= 2 && !hasRestParam(signatures[0].params); - const ok1 = signatures[1] && signatures[1].params.length <= 2 && !hasRestParam(signatures[1].params); - const ok2 = signatures[2] && signatures[2].params.length <= 2 && !hasRestParam(signatures[2].params); - const ok3 = signatures[3] && signatures[3].params.length <= 2 && !hasRestParam(signatures[3].params); - const ok4 = signatures[4] && signatures[4].params.length <= 2 && !hasRestParam(signatures[4].params); - const ok5 = signatures[5] && signatures[5].params.length <= 2 && !hasRestParam(signatures[5].params); - const allOk = ok0 && ok1 && ok2 && ok3 && ok4 && ok5; - for (let i2 = 0; i2 < signatures.length; ++i2) { - signatures[i2].test = compileTests(signatures[i2].params); - } - const test00 = ok0 ? compileTest(signatures[0].params[0]) : notOk; - const test10 = ok1 ? compileTest(signatures[1].params[0]) : notOk; - const test20 = ok2 ? compileTest(signatures[2].params[0]) : notOk; - const test30 = ok3 ? compileTest(signatures[3].params[0]) : notOk; - const test40 = ok4 ? compileTest(signatures[4].params[0]) : notOk; - const test50 = ok5 ? compileTest(signatures[5].params[0]) : notOk; - const test01 = ok0 ? compileTest(signatures[0].params[1]) : notOk; - const test11 = ok1 ? compileTest(signatures[1].params[1]) : notOk; - const test21 = ok2 ? compileTest(signatures[2].params[1]) : notOk; - const test31 = ok3 ? compileTest(signatures[3].params[1]) : notOk; - const test41 = ok4 ? compileTest(signatures[4].params[1]) : notOk; - const test51 = ok5 ? compileTest(signatures[5].params[1]) : notOk; - for (let i2 = 0; i2 < signatures.length; ++i2) { - signatures[i2].implementation = compileArgsPreprocessing(signatures[i2].params, signatures[i2].fn); - } - const fn0 = ok0 ? signatures[0].implementation : undef; - const fn1 = ok1 ? signatures[1].implementation : undef; - const fn2 = ok2 ? signatures[2].implementation : undef; - const fn3 = ok3 ? signatures[3].implementation : undef; - const fn4 = ok4 ? signatures[4].implementation : undef; - const fn5 = ok5 ? signatures[5].implementation : undef; - const len0 = ok0 ? signatures[0].params.length : -1; - const len1 = ok1 ? signatures[1].params.length : -1; - const len2 = ok2 ? signatures[2].params.length : -1; - const len3 = ok3 ? signatures[3].params.length : -1; - const len4 = ok4 ? signatures[4].params.length : -1; - const len5 = ok5 ? signatures[5].params.length : -1; - const iStart = allOk ? 6 : 0; - const iEnd = signatures.length; - const tests = signatures.map((s2) => s2.test); - const fns = signatures.map((s2) => s2.implementation); - const generic = function generic2() { - for (let i2 = iStart; i2 < iEnd; i2++) { - if (tests[i2](arguments)) { - return fns[i2].apply(this, arguments); - } - } - return typed3.onMismatch(name315, arguments, signatures); - }; - function theTypedFn(arg0, arg1) { - if (arguments.length === len0 && test00(arg0) && test01(arg1)) { - return fn0.apply(this, arguments); - } - if (arguments.length === len1 && test10(arg0) && test11(arg1)) { - return fn1.apply(this, arguments); - } - if (arguments.length === len2 && test20(arg0) && test21(arg1)) { - return fn2.apply(this, arguments); - } - if (arguments.length === len3 && test30(arg0) && test31(arg1)) { - return fn3.apply(this, arguments); - } - if (arguments.length === len4 && test40(arg0) && test41(arg1)) { - return fn4.apply(this, arguments); - } - if (arguments.length === len5 && test50(arg0) && test51(arg1)) { - return fn5.apply(this, arguments); - } - return generic.apply(this, arguments); - } - try { - Object.defineProperty(theTypedFn, "name", { - value: name315 - }); - } catch (err) { - } - theTypedFn.signatures = signaturesMap; - theTypedFn._typedFunctionData = { - signatures, - signatureMap: internalSignatureMap - }; - return theTypedFn; - } - function _onMismatch(name315, args, signatures) { - throw createError(name315, args, signatures); - } - function initial(arr) { - return slice(arr, 0, arr.length - 1); - } - function last(arr) { - return arr[arr.length - 1]; - } - function slice(arr, start, end) { - return Array.prototype.slice.call(arr, start, end); - } - function findInArray(arr, test) { - for (let i2 = 0; i2 < arr.length; i2++) { - if (test(arr[i2])) { - return arr[i2]; - } - } - return void 0; - } - function flatMap(arr, callback) { - return Array.prototype.concat.apply([], arr.map(callback)); - } - function referTo() { - const references = initial(arguments).map((s) => stringifyParams(parseSignature(s))); - const callback = last(arguments); - if (typeof callback !== "function") { - throw new TypeError("Callback function expected as last argument"); - } - return makeReferTo(references, callback); - } - function makeReferTo(references, callback) { - return { - referTo: { - references, - callback - } - }; - } - function referToSelf(callback) { - if (typeof callback !== "function") { - throw new TypeError("Callback function expected as first argument"); - } - return { - referToSelf: { - callback - } - }; - } - function isReferTo(objectOrFn) { - return objectOrFn && typeof objectOrFn.referTo === "object" && Array.isArray(objectOrFn.referTo.references) && typeof objectOrFn.referTo.callback === "function"; - } - function isReferToSelf(objectOrFn) { - return objectOrFn && typeof objectOrFn.referToSelf === "object" && typeof objectOrFn.referToSelf.callback === "function"; - } - function checkName(nameSoFar, newName) { - if (!nameSoFar) { - return newName; - } - if (newName && newName !== nameSoFar) { - const err = new Error("Function names do not match (expected: " + nameSoFar + ", actual: " + newName + ")"); - err.data = { - actual: newName, - expected: nameSoFar - }; - throw err; - } - return nameSoFar; - } - function getObjectName(obj) { - let name315; - for (const key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key) && (isTypedFunction(obj[key]) || typeof obj[key].signature === "string")) { - name315 = checkName(name315, obj[key].name); - } - } - return name315; - } - function mergeSignatures(dest, source) { - let key; - for (key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - if (key in dest) { - if (source[key] !== dest[key]) { - const err = new Error('Signature "' + key + '" is defined twice'); - err.data = { - signature: key, - sourceFunction: source[key], - destFunction: dest[key] - }; - throw err; - } - } - dest[key] = source[key]; - } - } - } - const saveTyped = typed3; - typed3 = function(maybeName) { - const named = typeof maybeName === "string"; - const start = named ? 1 : 0; - let name315 = named ? maybeName : ""; - const allSignatures = {}; - for (let i2 = start; i2 < arguments.length; ++i2) { - const item = arguments[i2]; - let theseSignatures = {}; - let thisName; - if (typeof item === "function") { - thisName = item.name; - if (typeof item.signature === "string") { - theseSignatures[item.signature] = item; - } else if (isTypedFunction(item)) { - theseSignatures = item.signatures; - } - } else if (isPlainObject4(item)) { - theseSignatures = item; - if (!named) { - thisName = getObjectName(item); - } - } - if (Object.keys(theseSignatures).length === 0) { - const err = new TypeError("Argument to 'typed' at index " + i2 + " is not a (typed) function, nor an object with signatures as keys and functions as values."); - err.data = { - index: i2, - argument: item - }; - throw err; - } - if (!named) { - name315 = checkName(name315, thisName); - } - mergeSignatures(allSignatures, theseSignatures); - } - return createTypedFunction(name315 || "", allSignatures); - }; - typed3.create = create; - typed3.createCount = saveTyped.createCount; - typed3.onMismatch = _onMismatch; - typed3.throwMismatchError = _onMismatch; - typed3.createError = createError; - typed3.clear = clear; - typed3.clearConversions = clearConversions; - typed3.addTypes = addTypes; - typed3._findType = findType; - typed3.referTo = referTo; - typed3.referToSelf = referToSelf; - typed3.convert = convert; - typed3.findSignature = findSignature; - typed3.find = find; - typed3.isTypedFunction = isTypedFunction; - typed3.warnAgainstDeprecatedThis = true; - typed3.addType = function(type2, beforeObjectTest) { - let before = "any"; - if (beforeObjectTest !== false && typeMap.has("Object")) { - before = "Object"; - } - typed3.addTypes([type2], before); - }; - function _validateConversion(conversion) { - if (!conversion || typeof conversion.from !== "string" || typeof conversion.to !== "string" || typeof conversion.convert !== "function") { - throw new TypeError("Object with properties {from: string, to: string, convert: function} expected"); - } - if (conversion.to === conversion.from) { - throw new SyntaxError('Illegal to define conversion from "' + conversion.from + '" to itself.'); - } - } - typed3.addConversion = function(conversion) { - let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : { - override: false - }; - _validateConversion(conversion); - const to2 = findType(conversion.to); - const existing = to2.conversionsTo.find((other) => other.from === conversion.from); - if (existing) { - if (options && options.override) { - typed3.removeConversion({ - from: existing.from, - to: conversion.to, - convert: existing.convert - }); - } else { - throw new Error('There is already a conversion from "' + conversion.from + '" to "' + to2.name + '"'); - } - } - to2.conversionsTo.push({ - from: conversion.from, - to: to2.name, - convert: conversion.convert, - index: nConversions++ - }); - }; - typed3.addConversions = function(conversions, options) { - conversions.forEach((conversion) => typed3.addConversion(conversion, options)); - }; - typed3.removeConversion = function(conversion) { - _validateConversion(conversion); - const to2 = findType(conversion.to); - const existingConversion = findInArray(to2.conversionsTo, (c) => c.from === conversion.from); - if (!existingConversion) { - throw new Error("Attempt to remove nonexistent conversion from " + conversion.from + " to " + conversion.to); - } - if (existingConversion.convert !== conversion.convert) { - throw new Error("Conversion to remove does not match existing conversion"); - } - const index2 = to2.conversionsTo.indexOf(existingConversion); - to2.conversionsTo.splice(index2, 1); - }; - typed3.resolve = function(tf, argList) { - if (!isTypedFunction(tf)) { - throw new TypeError(NOT_TYPED_FUNCTION); - } - const sigs = tf._typedFunctionData.signatures; - for (let i2 = 0; i2 < sigs.length; ++i2) { - if (sigs[i2].test(argList)) { - return sigs[i2]; - } - } - return null; - }; - return typed3; - } - var typedFunction2 = create(); - return typedFunction2; - })); - } -}); - -// node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/typeof.js -var require_typeof = __commonJS({ - "node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/typeof.js"(exports, module) { - function _typeof(o) { - "@babel/helpers - typeof"; - return module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) { - return typeof o2; - } : function(o2) { - return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2; - }, module.exports.__esModule = true, module.exports["default"] = module.exports, _typeof(o); - } - module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports; - } -}); - -// node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/toPrimitive.js -var require_toPrimitive = __commonJS({ - "node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/toPrimitive.js"(exports, module) { - var _typeof = require_typeof()["default"]; - function toPrimitive(t, r) { - if ("object" != _typeof(t) || !t) return t; - var e3 = t[Symbol.toPrimitive]; - if (void 0 !== e3) { - var i2 = e3.call(t, r || "default"); - if ("object" != _typeof(i2)) return i2; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return ("string" === r ? String : Number)(t); - } - module.exports = toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports; - } -}); - -// node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/toPropertyKey.js -var require_toPropertyKey = __commonJS({ - "node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/toPropertyKey.js"(exports, module) { - var _typeof = require_typeof()["default"]; - var toPrimitive = require_toPrimitive(); - function toPropertyKey(t) { - var i2 = toPrimitive(t, "string"); - return "symbol" == _typeof(i2) ? i2 : i2 + ""; - } - module.exports = toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports; - } -}); - -// node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/defineProperty.js -var require_defineProperty = __commonJS({ - "node_modules/.pnpm/@babel+runtime@7.29.2/node_modules/@babel/runtime/helpers/defineProperty.js"(exports, module) { - var toPropertyKey = require_toPropertyKey(); - function _defineProperty18(e3, r, t) { - return (r = toPropertyKey(r)) in e3 ? Object.defineProperty(e3, r, { - value: t, - enumerable: true, - configurable: true, - writable: true - }) : e3[r] = t, e3; - } - module.exports = _defineProperty18, module.exports.__esModule = true, module.exports["default"] = module.exports; - } -}); - -// node_modules/.pnpm/javascript-natural-sort@0.7.1/node_modules/javascript-natural-sort/naturalSort.js -var require_naturalSort = __commonJS({ - "node_modules/.pnpm/javascript-natural-sort@0.7.1/node_modules/javascript-natural-sort/naturalSort.js"(exports, module) { - module.exports = function naturalSort2(a, b) { - "use strict"; - var re2 = /(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi, sre = /(^[ ]*|[ ]*$)/g, dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/, hre = /^0x[0-9a-f]+$/i, ore = /^0/, i2 = function(s) { - return naturalSort2.insensitive && ("" + s).toLowerCase() || "" + s; - }, x = i2(a).replace(sre, "") || "", y = i2(b).replace(sre, "") || "", xN = x.replace(re2, "\0$1\0").replace(/\0$/, "").replace(/^\0/, "").split("\0"), yN = y.replace(re2, "\0$1\0").replace(/\0$/, "").replace(/^\0/, "").split("\0"), xD = parseInt(x.match(hre), 16) || xN.length !== 1 && x.match(dre) && Date.parse(x), yD = parseInt(y.match(hre), 16) || xD && y.match(dre) && Date.parse(y) || null, oFxNcL, oFyNcL; - if (yD) { - if (xD < yD) { - return -1; - } else if (xD > yD) { - return 1; - } - } - for (var cLoc = 0, numS = Math.max(xN.length, yN.length); cLoc < numS; cLoc++) { - oFxNcL = !(xN[cLoc] || "").match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0; - oFyNcL = !(yN[cLoc] || "").match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0; - if (isNaN(oFxNcL) !== isNaN(oFyNcL)) { - return isNaN(oFxNcL) ? 1 : -1; - } else if (typeof oFxNcL !== typeof oFyNcL) { - oFxNcL += ""; - oFyNcL += ""; - } - if (oFxNcL < oFyNcL) { - return -1; - } - if (oFxNcL > oFyNcL) { - return 1; - } - } - return 0; - }; - } -}); - -// node_modules/.pnpm/escape-latex@1.2.0/node_modules/escape-latex/dist/index.js -var require_dist2 = __commonJS({ - "node_modules/.pnpm/escape-latex@1.2.0/node_modules/escape-latex/dist/index.js"(exports, module) { - "use strict"; - var _extends8 = Object.assign || function(target) { - for (var i2 = 1; i2 < arguments.length; i2++) { - var source = arguments[i2]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - return target; - }; - var defaultEscapes = { - "{": "\\{", - "}": "\\}", - "\\": "\\textbackslash{}", - "#": "\\#", - $: "\\$", - "%": "\\%", - "&": "\\&", - "^": "\\textasciicircum{}", - _: "\\_", - "~": "\\textasciitilde{}" - }; - var formatEscapes = { - "\u2013": "\\--", - "\u2014": "\\---", - " ": "~", - " ": "\\qquad{}", - "\r\n": "\\newline{}", - "\n": "\\newline{}" - }; - var defaultEscapeMapFn = function defaultEscapeMapFn2(defaultEscapes2, formatEscapes2) { - return _extends8({}, defaultEscapes2, formatEscapes2); - }; - module.exports = function(str2) { - var _ref = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, _ref$preserveFormatti = _ref.preserveFormatting, preserveFormatting = _ref$preserveFormatti === void 0 ? false : _ref$preserveFormatti, _ref$escapeMapFn = _ref.escapeMapFn, escapeMapFn = _ref$escapeMapFn === void 0 ? defaultEscapeMapFn : _ref$escapeMapFn; - var runningStr = String(str2); - var result = ""; - var escapes = escapeMapFn(_extends8({}, defaultEscapes), preserveFormatting ? _extends8({}, formatEscapes) : {}); - var escapeKeys = Object.keys(escapes); - var _loop = function _loop2() { - var specialCharFound = false; - escapeKeys.forEach(function(key, index2) { - if (specialCharFound) { - return; - } - if (runningStr.length >= key.length && runningStr.slice(0, key.length) === key) { - result += escapes[escapeKeys[index2]]; - runningStr = runningStr.slice(key.length, runningStr.length); - specialCharFound = true; - } - }); - if (!specialCharFound) { - result += runningStr.slice(0, 1); - runningStr = runningStr.slice(1, runningStr.length); - } - }; - while (runningStr) { - _loop(); - } - return result; - }; - } -}); - -// node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js -var require_alea = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/alea.js"(exports, module) { - (function(global, module2, define2) { - function Alea(seed) { - var me = this, mash = Mash(); - me.next = function() { - var t = 2091639 * me.s0 + me.c * 23283064365386963e-26; - me.s0 = me.s1; - me.s1 = me.s2; - return me.s2 = t - (me.c = t | 0); - }; - me.c = 1; - me.s0 = mash(" "); - me.s1 = mash(" "); - me.s2 = mash(" "); - me.s0 -= mash(seed); - if (me.s0 < 0) { - me.s0 += 1; - } - me.s1 -= mash(seed); - if (me.s1 < 0) { - me.s1 += 1; - } - me.s2 -= mash(seed); - if (me.s2 < 0) { - me.s2 += 1; - } - mash = null; - } - function copy(f, t) { - t.c = f.c; - t.s0 = f.s0; - t.s1 = f.s1; - t.s2 = f.s2; - return t; - } - function impl(seed, opts) { - var xg = new Alea(seed), state = opts && opts.state, prng = xg.next; - prng.int32 = function() { - return xg.next() * 4294967296 | 0; - }; - prng.double = function() { - return prng() + (prng() * 2097152 | 0) * 11102230246251565e-32; - }; - prng.quick = prng; - if (state) { - if (typeof state == "object") copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - function Mash() { - var n = 4022871197; - var mash = function(data) { - data = String(data); - for (var i2 = 0; i2 < data.length; i2++) { - n += data.charCodeAt(i2); - var h = 0.02519603282416938 * n; - n = h >>> 0; - h -= n; - h *= n; - n = h >>> 0; - h -= n; - n += h * 4294967296; - } - return (n >>> 0) * 23283064365386963e-26; - }; - return mash; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.alea = impl; - } - })( - exports, - typeof module == "object" && module, - // present in node.js - typeof define == "function" && define - // present with an AMD loader - ); - } -}); - -// node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js -var require_xor128 = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor128.js"(exports, module) { - (function(global, module2, define2) { - function XorGen(seed) { - var me = this, strseed = ""; - me.x = 0; - me.y = 0; - me.z = 0; - me.w = 0; - me.next = function() { - var t = me.x ^ me.x << 11; - me.x = me.y; - me.y = me.z; - me.z = me.w; - return me.w ^= me.w >>> 19 ^ t ^ t >>> 8; - }; - if (seed === (seed | 0)) { - me.x = seed; - } else { - strseed += seed; - } - for (var k = 0; k < strseed.length + 64; k++) { - me.x ^= strseed.charCodeAt(k) | 0; - me.next(); - } - } - function copy(f, t) { - t.x = f.x; - t.y = f.y; - t.z = f.z; - t.w = f.w; - return t; - } - function impl(seed, opts) { - var xg = new XorGen(seed), state = opts && opts.state, prng = function() { - return (xg.next() >>> 0) / 4294967296; - }; - prng.double = function() { - do { - var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (typeof state == "object") copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.xor128 = impl; - } - })( - exports, - typeof module == "object" && module, - // present in node.js - typeof define == "function" && define - // present with an AMD loader - ); - } -}); - -// node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js -var require_xorwow = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorwow.js"(exports, module) { - (function(global, module2, define2) { - function XorGen(seed) { - var me = this, strseed = ""; - me.next = function() { - var t = me.x ^ me.x >>> 2; - me.x = me.y; - me.y = me.z; - me.z = me.w; - me.w = me.v; - return (me.d = me.d + 362437 | 0) + (me.v = me.v ^ me.v << 4 ^ (t ^ t << 1)) | 0; - }; - me.x = 0; - me.y = 0; - me.z = 0; - me.w = 0; - me.v = 0; - if (seed === (seed | 0)) { - me.x = seed; - } else { - strseed += seed; - } - for (var k = 0; k < strseed.length + 64; k++) { - me.x ^= strseed.charCodeAt(k) | 0; - if (k == strseed.length) { - me.d = me.x << 10 ^ me.x >>> 4; - } - me.next(); - } - } - function copy(f, t) { - t.x = f.x; - t.y = f.y; - t.z = f.z; - t.w = f.w; - t.v = f.v; - t.d = f.d; - return t; - } - function impl(seed, opts) { - var xg = new XorGen(seed), state = opts && opts.state, prng = function() { - return (xg.next() >>> 0) / 4294967296; - }; - prng.double = function() { - do { - var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (typeof state == "object") copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.xorwow = impl; - } - })( - exports, - typeof module == "object" && module, - // present in node.js - typeof define == "function" && define - // present with an AMD loader - ); - } -}); - -// node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js -var require_xorshift7 = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xorshift7.js"(exports, module) { - (function(global, module2, define2) { - function XorGen(seed) { - var me = this; - me.next = function() { - var X = me.x, i2 = me.i, t, v, w; - t = X[i2]; - t ^= t >>> 7; - v = t ^ t << 24; - t = X[i2 + 1 & 7]; - v ^= t ^ t >>> 10; - t = X[i2 + 3 & 7]; - v ^= t ^ t >>> 3; - t = X[i2 + 4 & 7]; - v ^= t ^ t << 7; - t = X[i2 + 7 & 7]; - t = t ^ t << 13; - v ^= t ^ t << 9; - X[i2] = v; - me.i = i2 + 1 & 7; - return v; - }; - function init(me2, seed2) { - var j, w, X = []; - if (seed2 === (seed2 | 0)) { - w = X[0] = seed2; - } else { - seed2 = "" + seed2; - for (j = 0; j < seed2.length; ++j) { - X[j & 7] = X[j & 7] << 15 ^ seed2.charCodeAt(j) + X[j + 1 & 7] << 13; - } - } - while (X.length < 8) X.push(0); - for (j = 0; j < 8 && X[j] === 0; ++j) ; - if (j == 8) w = X[7] = -1; - else w = X[j]; - me2.x = X; - me2.i = 0; - for (j = 256; j > 0; --j) { - me2.next(); - } - } - init(me, seed); - } - function copy(f, t) { - t.x = f.x.slice(); - t.i = f.i; - return t; - } - function impl(seed, opts) { - if (seed == null) seed = +/* @__PURE__ */ new Date(); - var xg = new XorGen(seed), state = opts && opts.state, prng = function() { - return (xg.next() >>> 0) / 4294967296; - }; - prng.double = function() { - do { - var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (state.x) copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.xorshift7 = impl; - } - })( - exports, - typeof module == "object" && module, - // present in node.js - typeof define == "function" && define - // present with an AMD loader - ); - } -}); - -// node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js -var require_xor4096 = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/xor4096.js"(exports, module) { - (function(global, module2, define2) { - function XorGen(seed) { - var me = this; - me.next = function() { - var w = me.w, X = me.X, i2 = me.i, t, v; - me.w = w = w + 1640531527 | 0; - v = X[i2 + 34 & 127]; - t = X[i2 = i2 + 1 & 127]; - v ^= v << 13; - t ^= t << 17; - v ^= v >>> 15; - t ^= t >>> 12; - v = X[i2] = v ^ t; - me.i = i2; - return v + (w ^ w >>> 16) | 0; - }; - function init(me2, seed2) { - var t, v, i2, j, w, X = [], limit = 128; - if (seed2 === (seed2 | 0)) { - v = seed2; - seed2 = null; - } else { - seed2 = seed2 + "\0"; - v = 0; - limit = Math.max(limit, seed2.length); - } - for (i2 = 0, j = -32; j < limit; ++j) { - if (seed2) v ^= seed2.charCodeAt((j + 32) % seed2.length); - if (j === 0) w = v; - v ^= v << 10; - v ^= v >>> 15; - v ^= v << 4; - v ^= v >>> 13; - if (j >= 0) { - w = w + 1640531527 | 0; - t = X[j & 127] ^= v + w; - i2 = 0 == t ? i2 + 1 : 0; - } - } - if (i2 >= 128) { - X[(seed2 && seed2.length || 0) & 127] = -1; - } - i2 = 127; - for (j = 4 * 128; j > 0; --j) { - v = X[i2 + 34 & 127]; - t = X[i2 = i2 + 1 & 127]; - v ^= v << 13; - t ^= t << 17; - v ^= v >>> 15; - t ^= t >>> 12; - X[i2] = v ^ t; - } - me2.w = w; - me2.X = X; - me2.i = i2; - } - init(me, seed); - } - function copy(f, t) { - t.i = f.i; - t.w = f.w; - t.X = f.X.slice(); - return t; - } - ; - function impl(seed, opts) { - if (seed == null) seed = +/* @__PURE__ */ new Date(); - var xg = new XorGen(seed), state = opts && opts.state, prng = function() { - return (xg.next() >>> 0) / 4294967296; - }; - prng.double = function() { - do { - var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (state.X) copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.xor4096 = impl; - } - })( - exports, - // window object or global - typeof module == "object" && module, - // present in node.js - typeof define == "function" && define - // present with an AMD loader - ); - } -}); - -// node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js -var require_tychei = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/lib/tychei.js"(exports, module) { - (function(global, module2, define2) { - function XorGen(seed) { - var me = this, strseed = ""; - me.next = function() { - var b = me.b, c = me.c, d = me.d, a = me.a; - b = b << 25 ^ b >>> 7 ^ c; - c = c - d | 0; - d = d << 24 ^ d >>> 8 ^ a; - a = a - b | 0; - me.b = b = b << 20 ^ b >>> 12 ^ c; - me.c = c = c - d | 0; - me.d = d << 16 ^ c >>> 16 ^ a; - return me.a = a - b | 0; - }; - me.a = 0; - me.b = 0; - me.c = 2654435769 | 0; - me.d = 1367130551; - if (seed === Math.floor(seed)) { - me.a = seed / 4294967296 | 0; - me.b = seed | 0; - } else { - strseed += seed; - } - for (var k = 0; k < strseed.length + 20; k++) { - me.b ^= strseed.charCodeAt(k) | 0; - me.next(); - } - } - function copy(f, t) { - t.a = f.a; - t.b = f.b; - t.c = f.c; - t.d = f.d; - return t; - } - ; - function impl(seed, opts) { - var xg = new XorGen(seed), state = opts && opts.state, prng = function() { - return (xg.next() >>> 0) / 4294967296; - }; - prng.double = function() { - do { - var top = xg.next() >>> 11, bot = (xg.next() >>> 0) / 4294967296, result = (top + bot) / (1 << 21); - } while (result === 0); - return result; - }; - prng.int32 = xg.next; - prng.quick = prng; - if (state) { - if (typeof state == "object") copy(state, xg); - prng.state = function() { - return copy(xg, {}); - }; - } - return prng; - } - if (module2 && module2.exports) { - module2.exports = impl; - } else if (define2 && define2.amd) { - define2(function() { - return impl; - }); - } else { - this.tychei = impl; - } - })( - exports, - typeof module == "object" && module, - // present in node.js - typeof define == "function" && define - // present with an AMD loader - ); - } -}); - -// node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js -var require_seedrandom = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/seedrandom.js"(exports, module) { - (function(global, pool, math2) { - var width = 256, chunks = 6, digits2 = 52, rngname = "random", startdenom = math2.pow(width, chunks), significance = math2.pow(2, digits2), overflow = significance * 2, mask = width - 1, nodecrypto; - function seedrandom2(seed, options, callback) { - var key = []; - options = options == true ? { entropy: true } : options || {}; - var shortseed = mixkey(flatten3( - options.entropy ? [seed, tostring(pool)] : seed == null ? autoseed() : seed, - 3 - ), key); - var arc4 = new ARC4(key); - var prng = function() { - var n = arc4.g(chunks), d = startdenom, x = 0; - while (n < significance) { - n = (n + x) * width; - d *= width; - x = arc4.g(1); - } - while (n >= overflow) { - n /= 2; - d /= 2; - x >>>= 1; - } - return (n + x) / d; - }; - prng.int32 = function() { - return arc4.g(4) | 0; - }; - prng.quick = function() { - return arc4.g(4) / 4294967296; - }; - prng.double = prng; - mixkey(tostring(arc4.S), pool); - return (options.pass || callback || function(prng2, seed2, is_math_call, state) { - if (state) { - if (state.S) { - copy(state, arc4); - } - prng2.state = function() { - return copy(arc4, {}); - }; - } - if (is_math_call) { - math2[rngname] = prng2; - return seed2; - } else return prng2; - })( - prng, - shortseed, - "global" in options ? options.global : this == math2, - options.state - ); - } - function ARC4(key) { - var t, keylen = key.length, me = this, i2 = 0, j = me.i = me.j = 0, s = me.S = []; - if (!keylen) { - key = [keylen++]; - } - while (i2 < width) { - s[i2] = i2++; - } - for (i2 = 0; i2 < width; i2++) { - s[i2] = s[j = mask & j + key[i2 % keylen] + (t = s[i2])]; - s[j] = t; - } - (me.g = function(count2) { - var t2, r = 0, i3 = me.i, j2 = me.j, s2 = me.S; - while (count2--) { - t2 = s2[i3 = mask & i3 + 1]; - r = r * width + s2[mask & (s2[i3] = s2[j2 = mask & j2 + t2]) + (s2[j2] = t2)]; - } - me.i = i3; - me.j = j2; - return r; - })(width); - } - function copy(f, t) { - t.i = f.i; - t.j = f.j; - t.S = f.S.slice(); - return t; - } - ; - function flatten3(obj, depth) { - var result = [], typ = typeof obj, prop; - if (depth && typ == "object") { - for (prop in obj) { - try { - result.push(flatten3(obj[prop], depth - 1)); - } catch (e3) { - } - } - } - return result.length ? result : typ == "string" ? obj : obj + "\0"; - } - function mixkey(seed, key) { - var stringseed = seed + "", smear, j = 0; - while (j < stringseed.length) { - key[mask & j] = mask & (smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++); - } - return tostring(key); - } - function autoseed() { - try { - var out; - if (nodecrypto && (out = nodecrypto.randomBytes)) { - out = out(width); - } else { - out = new Uint8Array(width); - (global.crypto || global.msCrypto).getRandomValues(out); - } - return tostring(out); - } catch (e3) { - var browser = global.navigator, plugins = browser && browser.plugins; - return [+/* @__PURE__ */ new Date(), global, plugins, global.screen, tostring(pool)]; - } - } - function tostring(a) { - return String.fromCharCode.apply(0, a); - } - mixkey(math2.random(), pool); - if (typeof module == "object" && module.exports) { - module.exports = seedrandom2; - try { - nodecrypto = __require("crypto"); - } catch (ex) { - } - } else if (typeof define == "function" && define.amd) { - define(function() { - return seedrandom2; - }); - } else { - math2["seed" + rngname] = seedrandom2; - } - })( - // global: `self` in browsers (including strict mode and web workers), - // otherwise `this` in Node and other environments - typeof self !== "undefined" ? self : exports, - [], - // pool: entropy pool starts empty - Math - // math: package containing random, pow, and seedrandom - ); - } -}); - -// node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/index.js -var require_seedrandom2 = __commonJS({ - "node_modules/.pnpm/seedrandom@3.0.5/node_modules/seedrandom/index.js"(exports, module) { - var alea = require_alea(); - var xor128 = require_xor128(); - var xorwow = require_xorwow(); - var xorshift7 = require_xorshift7(); - var xor4096 = require_xor4096(); - var tychei = require_tychei(); - var sr = require_seedrandom(); - sr.alea = alea; - sr.xor128 = xor128; - sr.xorwow = xorwow; - sr.xorshift7 = xorshift7; - sr.xor4096 = xor4096; - sr.tychei = tychei; - module.exports = sr; - } -}); - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/core.js -var NEVER2 = Object.freeze({ - status: "aborted" -}); -// @__NO_SIDE_EFFECTS__ -function $constructor(name315, initializer3, params) { - function init(inst, def) { - var _a; - Object.defineProperty(inst, "_zod", { - value: inst._zod ?? {}, - enumerable: false - }); - (_a = inst._zod).traits ?? (_a.traits = /* @__PURE__ */ new Set()); - inst._zod.traits.add(name315); - initializer3(inst, def); - for (const k in _.prototype) { - if (!(k in inst)) - Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) }); - } - inst._zod.constr = _; - inst._zod.def = def; - } - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name315 }); - function _(def) { - var _a; - const inst = params?.Parent ? new Definition() : this; - init(inst, def); - (_a = inst._zod).deferred ?? (_a.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); - } - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name315); - } - }); - Object.defineProperty(_, "name", { value: name315 }); - return _; -} -var $ZodAsyncError = class extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -}; -var globalConfig = {}; -function config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/util.js -var util_exports = {}; -__export(util_exports, { - BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, - Class: () => Class, - NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, - aborted: () => aborted, - allowsEval: () => allowsEval, - assert: () => assert, - assertEqual: () => assertEqual, - assertIs: () => assertIs, - assertNever: () => assertNever, - assertNotEqual: () => assertNotEqual, - assignProp: () => assignProp, - cached: () => cached, - captureStackTrace: () => captureStackTrace, - cleanEnum: () => cleanEnum, - cleanRegex: () => cleanRegex, - clone: () => clone, - createTransparentProxy: () => createTransparentProxy, - defineLazy: () => defineLazy, - esc: () => esc, - escapeRegex: () => escapeRegex, - extend: () => extend, - finalizeIssue: () => finalizeIssue, - floatSafeRemainder: () => floatSafeRemainder2, - getElementAtPath: () => getElementAtPath, - getEnumValues: () => getEnumValues, - getLengthableOrigin: () => getLengthableOrigin, - getParsedType: () => getParsedType2, - getSizableOrigin: () => getSizableOrigin, - isObject: () => isObject, - isPlainObject: () => isPlainObject, - issue: () => issue, - joinValues: () => joinValues, - jsonStringifyReplacer: () => jsonStringifyReplacer, - merge: () => merge, - normalizeParams: () => normalizeParams, - nullish: () => nullish, - numKeys: () => numKeys, - omit: () => omit, - optionalKeys: () => optionalKeys, - partial: () => partial, - pick: () => pick, - prefixIssues: () => prefixIssues, - primitiveTypes: () => primitiveTypes, - promiseAllObject: () => promiseAllObject, - propertyKeyTypes: () => propertyKeyTypes, - randomString: () => randomString, - required: () => required, - stringifyPrimitive: () => stringifyPrimitive, - unwrapMessage: () => unwrapMessage -}); -function assertEqual(val) { - return val; -} -function assertNotEqual(val) { - return val; -} -function assertIs(_arg) { -} -function assertNever(_x) { - throw new Error(); -} -function assert(_) { -} -function getEnumValues(entries) { - const numericValues = Object.values(entries).filter((v) => typeof v === "number"); - const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); - return values; -} -function joinValues(array2, separator = "|") { - return array2.map((val) => stringifyPrimitive(val)).join(separator); -} -function jsonStringifyReplacer(_, value) { - if (typeof value === "bigint") - return value.toString(); - return value; -} -function cached(getter) { - const set2 = false; - return { - get value() { - if (!set2) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); - } - }; -} -function nullish(input) { - return input === null || input === void 0; -} -function cleanRegex(source) { - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - return source.slice(start, end); -} -function floatSafeRemainder2(val, step2) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step2.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step2.toFixed(decCount).replace(".", "")); - return valInt % stepInt / 10 ** decCount; -} -function defineLazy(object3, key, getter) { - const set2 = false; - Object.defineProperty(object3, key, { - get() { - if (!set2) { - const value = getter(); - object3[key] = value; - return value; - } - throw new Error("cached value already set"); - }, - set(v) { - Object.defineProperty(object3, key, { - value: v - // configurable: true, - }); - }, - configurable: true - }); -} -function assignProp(target, prop, value) { - Object.defineProperty(target, prop, { - value, - writable: true, - enumerable: true, - configurable: true - }); -} -function getElementAtPath(obj, path) { - if (!path) - return obj; - return path.reduce((acc, key) => acc?.[key], obj); -} -function promiseAllObject(promisesObj) { - const keys = Object.keys(promisesObj); - const promises = keys.map((key) => promisesObj[key]); - return Promise.all(promises).then((results) => { - const resolvedObj = {}; - for (let i2 = 0; i2 < keys.length; i2++) { - resolvedObj[keys[i2]] = results[i2]; - } - return resolvedObj; - }); -} -function randomString(length = 10) { - const chars = "abcdefghijklmnopqrstuvwxyz"; - let str2 = ""; - for (let i2 = 0; i2 < length; i2++) { - str2 += chars[Math.floor(Math.random() * chars.length)]; - } - return str2; -} -function esc(str2) { - return JSON.stringify(str2); -} -var captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => { -}; -function isObject(data) { - return typeof data === "object" && data !== null && !Array.isArray(data); -} -var allowsEval = cached(() => { - if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { - return false; - } - try { - const F = Function; - new F(""); - return true; - } catch (_) { - return false; - } -}); -function isPlainObject(o) { - if (isObject(o) === false) - return false; - const ctor = o.constructor; - if (ctor === void 0) - return true; - const prot = ctor.prototype; - if (isObject(prot) === false) - return false; - if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { - return false; - } - return true; -} -function numKeys(data) { - let keyCount = 0; - for (const key in data) { - if (Object.prototype.hasOwnProperty.call(data, key)) { - keyCount++; - } - } - return keyCount; -} -var getParsedType2 = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return "undefined"; - case "string": - return "string"; - case "number": - return Number.isNaN(data) ? "nan" : "number"; - case "boolean": - return "boolean"; - case "function": - return "function"; - case "bigint": - return "bigint"; - case "symbol": - return "symbol"; - case "object": - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return "promise"; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return "map"; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return "set"; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return "date"; - } - if (typeof File !== "undefined" && data instanceof File) { - return "file"; - } - return "object"; - default: - throw new Error(`Unknown data type: ${t}`); - } -}; -var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); -var primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); -function escapeRegex(str2) { - return str2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -function clone(inst, def, params) { - const cl = new inst._zod.constr(def ?? inst._zod.def); - if (!def || params?.parent) - cl._zod.parent = inst; - return cl; -} -function normalizeParams(_params) { - const params = _params; - if (!params) - return {}; - if (typeof params === "string") - return { error: () => params }; - if (params?.message !== void 0) { - if (params?.error !== void 0) - throw new Error("Cannot specify both `message` and `error` params"); - params.error = params.message; - } - delete params.message; - if (typeof params.error === "string") - return { ...params, error: () => params.error }; - return params; -} -function createTransparentProxy(getter) { - let target; - return new Proxy({}, { - get(_, prop, receiver) { - target ?? (target = getter()); - return Reflect.get(target, prop, receiver); - }, - set(_, prop, value, receiver) { - target ?? (target = getter()); - return Reflect.set(target, prop, value, receiver); - }, - has(_, prop) { - target ?? (target = getter()); - return Reflect.has(target, prop); - }, - deleteProperty(_, prop) { - target ?? (target = getter()); - return Reflect.deleteProperty(target, prop); - }, - ownKeys(_) { - target ?? (target = getter()); - return Reflect.ownKeys(target); - }, - getOwnPropertyDescriptor(_, prop) { - target ?? (target = getter()); - return Reflect.getOwnPropertyDescriptor(target, prop); - }, - defineProperty(_, prop, descriptor) { - target ?? (target = getter()); - return Reflect.defineProperty(target, prop, descriptor); - } - }); -} -function stringifyPrimitive(value) { - if (typeof value === "bigint") - return value.toString() + "n"; - if (typeof value === "string") - return `"${value}"`; - return `${value}`; -} -function optionalKeys(shape) { - return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; - }); -} -var NUMBER_FORMAT_RANGES = { - safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], - int32: [-2147483648, 2147483647], - uint32: [0, 4294967295], - float32: [-34028234663852886e22, 34028234663852886e22], - float64: [-Number.MAX_VALUE, Number.MAX_VALUE] -}; -var BIGINT_FORMAT_RANGES = { - int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], - uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] -}; -function pick(schema2, mask) { - const newShape = {}; - const currDef = schema2._zod.def; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - newShape[key] = currDef.shape[key]; - } - return clone(schema2, { - ...schema2._zod.def, - shape: newShape, - checks: [] - }); -} -function omit(schema2, mask) { - const newShape = { ...schema2._zod.def.shape }; - const currDef = schema2._zod.def; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - return clone(schema2, { - ...schema2._zod.def, - shape: newShape, - checks: [] - }); -} -function extend(schema2, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to extend: expected a plain object"); - } - const def = { - ...schema2._zod.def, - get shape() { - const _shape = { ...schema2._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); - return _shape; - }, - checks: [] - // delete existing checks - }; - return clone(schema2, def); -} -function merge(a, b) { - return clone(a, { - ...a._zod.def, - get shape() { - const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; - assignProp(this, "shape", _shape); - return _shape; - }, - catchall: b._zod.def.catchall, - checks: [] - // delete existing checks - }); -} -function partial(Class2, schema2, mask) { - const oldShape = schema2._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } else { - for (const key in oldShape) { - shape[key] = Class2 ? new Class2({ - type: "optional", - innerType: oldShape[key] - }) : oldShape[key]; - } - } - return clone(schema2, { - ...schema2._zod.def, - shape, - checks: [] - }); -} -function required(Class2, schema2, mask) { - const oldShape = schema2._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } else { - for (const key in oldShape) { - shape[key] = new Class2({ - type: "nonoptional", - innerType: oldShape[key] - }); - } - } - return clone(schema2, { - ...schema2._zod.def, - shape, - // optional: [], - checks: [] - }); -} -function aborted(x, startIndex = 0) { - for (let i2 = startIndex; i2 < x.issues.length; i2++) { - if (x.issues[i2]?.continue !== true) - return true; - } - return false; -} -function prefixIssues(path, issues) { - return issues.map((iss) => { - var _a; - (_a = iss).path ?? (_a.path = []); - iss.path.unshift(path); - return iss; - }); -} -function unwrapMessage(message) { - return typeof message === "string" ? message : message?.message; -} -function finalizeIssue(iss, ctx, config5) { - const full = { ...iss, path: iss.path ?? [] }; - if (!iss.message) { - const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config5.customError?.(iss)) ?? unwrapMessage(config5.localeError?.(iss)) ?? "Invalid input"; - full.message = message; - } - delete full.inst; - delete full.continue; - if (!ctx?.reportInput) { - delete full.input; - } - return full; -} -function getSizableOrigin(input) { - if (input instanceof Set) - return "set"; - if (input instanceof Map) - return "map"; - if (input instanceof File) - return "file"; - return "unknown"; -} -function getLengthableOrigin(input) { - if (Array.isArray(input)) - return "array"; - if (typeof input === "string") - return "string"; - return "unknown"; -} -function issue(...args) { - const [iss, input, inst] = args; - if (typeof iss === "string") { - return { - message: iss, - code: "custom", - input, - inst - }; - } - return { ...iss }; -} -function cleanEnum(obj) { - return Object.entries(obj).filter(([k, _]) => { - return Number.isNaN(Number.parseInt(k, 10)); - }).map((el) => el[1]); -} -var Class = class { - constructor(..._args) { - } -}; - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/errors.js -var initializer = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false - }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false - }); - Object.defineProperty(inst, "message", { - get() { - return JSON.stringify(def, jsonStringifyReplacer, 2); - }, - enumerable: true - // configurable: false, - }); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false - }); -}; -var $ZodError = $constructor("$ZodError", initializer); -var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); -function flattenError(error2, mapper = (issue2) => issue2.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub2 of error2.issues) { - if (sub2.path.length > 0) { - fieldErrors[sub2.path[0]] = fieldErrors[sub2.path[0]] || []; - fieldErrors[sub2.path[0]].push(mapper(sub2)); - } else { - formErrors.push(mapper(sub2)); - } - } - return { formErrors, fieldErrors }; -} -function formatError(error2, _mapper) { - const mapper = _mapper || function(issue2) { - return issue2.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error3) => { - for (const issue2 of error3.issues) { - if (issue2.code === "invalid_union" && issue2.errors.length) { - issue2.errors.map((issues) => processError({ issues })); - } else if (issue2.code === "invalid_key") { - processError({ issues: issue2.issues }); - } else if (issue2.code === "invalid_element") { - processError({ issues: issue2.issues }); - } else if (issue2.path.length === 0) { - fieldErrors._errors.push(mapper(issue2)); - } else { - let curr = fieldErrors; - let i2 = 0; - while (i2 < issue2.path.length) { - const el = issue2.path[i2]; - const terminal = i2 === issue2.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue2)); - } - curr = curr[el]; - i2++; - } - } - } - }; - processError(error2); - return fieldErrors; -} - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/parse.js -var _parse = (_Err) => (schema2, value, _ctx, _params) => { - const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; - const result = schema2._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e3 = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e3, _params?.callee); - throw e3; - } - return result.value; -}; -var parse = /* @__PURE__ */ _parse($ZodRealError); -var _parseAsync = (_Err) => async (schema2, value, _ctx, params) => { - const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; - let result = schema2._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e3 = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e3, params?.callee); - throw e3; - } - return result.value; -}; -var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); -var _safeParse = (_Err) => (schema2, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema2._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - return result.issues.length ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; -}; -var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); -var _safeParseAsync = (_Err) => async (schema2, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; - let result = schema2._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - } : { success: true, data: result.value }; -}; -var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/regexes.js -var cuid = /^[cC][^\s-]{8,}$/; -var cuid2 = /^[0-9a-z]+$/; -var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; -var xid = /^[0-9a-vA-V]{20}$/; -var ksuid = /^[A-Za-z0-9]{27}$/; -var nanoid = /^[a-zA-Z0-9_-]{21}$/; -var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; -var 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})$/; -var uuid = (version4) => { - if (!version4) - return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/; - return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version4}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); -}; -var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; -var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -function emoji() { - return new RegExp(_emoji, "u"); -} -var 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])$/; -var ipv6 = /^(([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})$/; -var 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])$/; -var 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])$/; -var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -var base64url = /^[A-Za-z0-9_-]*$/; -var hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; -var e164 = /^\+(?:[0-9]){6,14}[0-9]$/; -var 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])))`; -var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); -function timeSource(args) { - const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = 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+)?)?`; - return regex; -} -function time(args) { - return new RegExp(`^${timeSource(args)}$`); -} -function datetime(args) { - const time3 = timeSource({ precision: args.precision }); - const opts = ["Z"]; - if (args.local) - opts.push(""); - if (args.offset) - opts.push(`([+-]\\d{2}:\\d{2})`); - const timeRegex2 = `${time3}(?:${opts.join("|")})`; - return new RegExp(`^${dateSource}T(?:${timeRegex2})$`); -} -var string = (params) => { - const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; - return new RegExp(`^${regex}$`); -}; -var integer = /^\d+$/; -var number = /^-?\d+(?:\.\d+)?/i; -var boolean = /true|false/i; -var _null = /null/i; -var lowercase = /^[^A-Z]*$/; -var uppercase = /^[^a-z]*$/; - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/checks.js -var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { - var _a; - inst._zod ?? (inst._zod = {}); - inst._zod.def = def; - (_a = inst._zod).onattach ?? (_a.onattach = []); -}); -var numericOriginMap = { - number: "number", - bigint: "bigint", - object: "date" -}; -var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { - return; - } - payload.issues.push({ - origin, - code: "too_big", - maximum: def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { - return; - } - payload.issues.push({ - origin, - code: "too_small", - minimum: def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - var _a; - (_a = inst2._zod.bag).multipleOf ?? (_a.multipleOf = def.value); - }); - inst._zod.check = (payload) => { - if (typeof payload.value !== typeof def.value) - throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder2(payload.value, def.value) === 0; - if (isMultiple) - return; - payload.issues.push({ - origin: typeof payload.value, - code: "not_multiple_of", - divisor: def.value, - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => { - $ZodCheck.init(inst, def); - def.format = def.format || "float64"; - const isInt = def.format?.includes("int"); - const origin = isInt ? "int" : "number"; - const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (isInt) { - if (!Number.isInteger(input)) { - payload.issues.push({ - expected: origin, - format: def.format, - code: "invalid_type", - input, - inst - }); - return; - } - if (!Number.isSafeInteger(input)) { - if (input > 0) { - payload.issues.push({ - input, - code: "too_big", - maximum: Number.MAX_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - continue: !def.abort - }); - } else { - payload.issues.push({ - input, - code: "too_small", - minimum: Number.MIN_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - continue: !def.abort - }); - } - return; - } - } - if (input < minimum) { - payload.issues.push({ - origin: "number", - input, - code: "too_small", - minimum, - inclusive: true, - inst, - continue: !def.abort - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "number", - input, - code: "too_big", - maximum, - inst - }); - } - }; -}); -var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; - if (def.maximum < curr) - inst2._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - if (length <= def.maximum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; - if (def.minimum > curr) - inst2._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - if (length >= def.minimum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== void 0; - }); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - if (length === def.length) - return; - const origin = getLengthableOrigin(input); - const tooBig = length > def.length; - payload.issues.push({ - origin, - ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }, - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { - var _a, _b; - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(def.pattern); - } - }); - if (def.pattern) - (_a = inst._zod).check ?? (_a.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: def.format, - input: payload.value, - ...def.pattern ? { pattern: def.pattern.toString() } : {}, - inst, - continue: !def.abort - }); - }); - else - (_b = inst._zod).check ?? (_b.check = () => { - }); -}); -var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - inst._zod.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "regex", - input: payload.value, - pattern: def.pattern.toString(), - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => { - def.pattern ?? (def.pattern = lowercase); - $ZodCheckStringFormat.init(inst, def); -}); -var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => { - def.pattern ?? (def.pattern = uppercase); - $ZodCheckStringFormat.init(inst, def); -}); -var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { - $ZodCheck.init(inst, def); - const escapedRegex = escapeRegex(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); - def.pattern = pattern; - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.includes(def.includes, def.position)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "includes", - includes: def.includes, - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.startsWith(def.prefix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "starts_with", - prefix: def.prefix, - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.endsWith(def.suffix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "ends_with", - suffix: def.suffix, - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - payload.value = def.tx(payload.value); - }; -}); - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/doc.js -var Doc = class { - constructor(args = []) { - this.content = []; - this.indent = 0; - if (this) - this.args = args; - } - indented(fn) { - this.indent += 1; - fn(this); - this.indent -= 1; - } - write(arg2) { - if (typeof arg2 === "function") { - arg2(this, { execution: "sync" }); - arg2(this, { execution: "async" }); - return; - } - const content = arg2; - const lines = content.split("\n").filter((x) => x); - const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); - const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); - for (const line of dedented) { - this.content.push(line); - } - } - compile() { - const F = Function; - const args = this?.args; - const content = this?.content ?? [``]; - const lines = [...content.map((x) => ` ${x}`)]; - return new F(...args, lines.join("\n")); - } -}; - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/versions.js -var version = { - major: 4, - minor: 0, - patch: 0 -}; - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/schemas.js -var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { - var _a; - inst ?? (inst = {}); - inst._zod.def = def; - inst._zod.bag = inst._zod.bag || {}; - inst._zod.version = version; - const checks = [...inst._zod.def.checks ?? []]; - if (inst._zod.traits.has("$ZodCheck")) { - checks.unshift(inst); - } - for (const ch of checks) { - for (const fn of ch._zod.onattach) { - fn(inst); - } - } - if (checks.length === 0) { - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred?.push(() => { - inst._zod.run = inst._zod.parse; - }); - } else { - const runChecks = (payload, checks2, ctx) => { - let isAborted2 = aborted(payload); - let asyncResult; - for (const ch of checks2) { - if (ch._zod.def.when) { - const shouldRun = ch._zod.def.when(payload); - if (!shouldRun) - continue; - } else if (isAborted2) { - continue; - } - const currLen = payload.issues.length; - const _ = ch._zod.check(payload); - if (_ instanceof Promise && ctx?.async === false) { - throw new $ZodAsyncError(); - } - if (asyncResult || _ instanceof Promise) { - asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { - await _; - const nextLen = payload.issues.length; - if (nextLen === currLen) - return; - if (!isAborted2) - isAborted2 = aborted(payload, currLen); - }); - } else { - const nextLen = payload.issues.length; - if (nextLen === currLen) - continue; - if (!isAborted2) - isAborted2 = aborted(payload, currLen); - } - } - if (asyncResult) { - return asyncResult.then(() => { - return payload; - }); - } - return payload; - }; - inst._zod.run = (payload, ctx) => { - const result = inst._zod.parse(payload, ctx); - if (result instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return result.then((result2) => runChecks(result2, checks, ctx)); - } - return runChecks(result, checks, ctx); - }; - } - inst["~standard"] = { - validate: (value) => { - try { - const r = safeParse(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; - } catch (_) { - return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); - } - }, - vendor: "zod", - version: 1 - }; -}); -var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); - inst._zod.parse = (payload, _) => { - if (def.coerce) - try { - payload.value = String(payload.value); - } catch (_2) { - } - if (typeof payload.value === "string") - return payload; - payload.issues.push({ - expected: "string", - code: "invalid_type", - input: payload.value, - inst - }); - return payload; - }; -}); -var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - $ZodString.init(inst, def); -}); -var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => { - def.pattern ?? (def.pattern = guid); - $ZodStringFormat.init(inst, def); -}); -var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => { - if (def.version) { - const versionMap = { - v1: 1, - v2: 2, - v3: 3, - v4: 4, - v5: 5, - v6: 6, - v7: 7, - v8: 8 - }; - const v = versionMap[def.version]; - if (v === void 0) - throw new Error(`Invalid UUID version: "${def.version}"`); - def.pattern ?? (def.pattern = uuid(v)); - } else - def.pattern ?? (def.pattern = uuid()); - $ZodStringFormat.init(inst, def); -}); -var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { - def.pattern ?? (def.pattern = email); - $ZodStringFormat.init(inst, def); -}); -var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - try { - const orig = payload.value; - const url = new URL(orig); - const href = url.href; - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: hostname.source, - input: payload.value, - inst, - continue: !def.abort - }); - } - } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort - }); - } - } - if (!orig.endsWith("/") && href.endsWith("/")) { - payload.value = href.slice(0, -1); - } else { - payload.value = href; - } - return; - } catch (_) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort - }); - } - }; -}); -var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { - def.pattern ?? (def.pattern = emoji()); - $ZodStringFormat.init(inst, def); -}); -var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid); - $ZodStringFormat.init(inst, def); -}); -var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { - def.pattern ?? (def.pattern = cuid); - $ZodStringFormat.init(inst, def); -}); -var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => { - def.pattern ?? (def.pattern = cuid2); - $ZodStringFormat.init(inst, def); -}); -var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => { - def.pattern ?? (def.pattern = ulid); - $ZodStringFormat.init(inst, def); -}); -var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => { - def.pattern ?? (def.pattern = xid); - $ZodStringFormat.init(inst, def); -}); -var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => { - def.pattern ?? (def.pattern = ksuid); - $ZodStringFormat.init(inst, def); -}); -var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => { - def.pattern ?? (def.pattern = datetime(def)); - $ZodStringFormat.init(inst, def); -}); -var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => { - def.pattern ?? (def.pattern = date); - $ZodStringFormat.init(inst, def); -}); -var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => { - def.pattern ?? (def.pattern = time(def)); - $ZodStringFormat.init(inst, def); -}); -var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => { - def.pattern ?? (def.pattern = duration); - $ZodStringFormat.init(inst, def); -}); -var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { - def.pattern ?? (def.pattern = ipv4); - $ZodStringFormat.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = `ipv4`; - }); -}); -var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { - def.pattern ?? (def.pattern = ipv6); - $ZodStringFormat.init(inst, def); - inst._zod.onattach.push((inst2) => { - const bag = inst2._zod.bag; - bag.format = `ipv6`; - }); - inst._zod.check = (payload) => { - try { - new URL(`http://[${payload.value}]`); - } catch { - payload.issues.push({ - code: "invalid_format", - format: "ipv6", - input: payload.value, - inst, - continue: !def.abort - }); - } - }; -}); -var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { - def.pattern ?? (def.pattern = cidrv4); - $ZodStringFormat.init(inst, def); -}); -var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { - def.pattern ?? (def.pattern = cidrv6); - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - const [address, prefix] = payload.value.split("/"); - try { - if (!prefix) - throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - throw new Error(); - if (prefixNum < 0 || prefixNum > 128) - throw new Error(); - new URL(`http://[${address}]`); - } catch { - payload.issues.push({ - code: "invalid_format", - format: "cidrv6", - input: payload.value, - inst, - continue: !def.abort - }); - } - }; -}); -function isValidBase64(data) { - if (data === "") - return true; - if (data.length % 4 !== 0) - return false; - try { - atob(data); - return true; - } catch { - return false; - } -} -var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64); - $ZodStringFormat.init(inst, def); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.contentEncoding = "base64"; - }); - inst._zod.check = (payload) => { - if (isValidBase64(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64", - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -function isValidBase64URL(data) { - if (!base64url.test(data)) - return false; - const base642 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); - const padded = base642.padEnd(Math.ceil(base642.length / 4) * 4, "="); - return isValidBase64(padded); -} -var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url); - $ZodStringFormat.init(inst, def); - inst._zod.onattach.push((inst2) => { - inst2._zod.bag.contentEncoding = "base64url"; - }); - inst._zod.check = (payload) => { - if (isValidBase64URL(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64url", - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { - def.pattern ?? (def.pattern = e164); - $ZodStringFormat.init(inst, def); -}); -function isValidJWT2(token, algorithm = null) { - try { - const tokensParts = token.split("."); - if (tokensParts.length !== 3) - return false; - const [header] = tokensParts; - if (!header) - return false; - const parsedHeader = JSON.parse(atob(header)); - if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") - return false; - if (!parsedHeader.alg) - return false; - if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) - return false; - return true; - } catch { - return false; - } -} -var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidJWT2(payload.value, def.alg)) - return; - payload.issues.push({ - code: "invalid_format", - format: "jwt", - input: payload.value, - inst, - continue: !def.abort - }); - }; -}); -var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Number(payload.value); - } catch (_) { - } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { - return payload; - } - const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; - payload.issues.push({ - expected: "number", - code: "invalid_type", - input, - inst, - ...received ? { received } : {} - }); - return payload; - }; -}); -var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { - $ZodCheckNumberFormat.init(inst, def); - $ZodNumber.init(inst, def); -}); -var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = boolean; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Boolean(payload.value); - } catch (_) { - } - const input = payload.value; - if (typeof input === "boolean") - return payload; - payload.issues.push({ - expected: "boolean", - code: "invalid_type", - input, - inst - }); - return payload; - }; -}); -var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _null; - inst._zod.values = /* @__PURE__ */ new Set([null]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) - return payload; - payload.issues.push({ - expected: "null", - code: "invalid_type", - input, - inst - }); - return payload; - }; -}); -var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - payload.issues.push({ - expected: "never", - code: "invalid_type", - input: payload.value, - inst - }); - return payload; - }; -}); -function handleArrayResult(result, final, index2) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index2, result.issues)); - } - final.value[index2] = result.value; -} -var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - expected: "array", - code: "invalid_type", - input, - inst - }); - return payload; - } - payload.value = Array(input.length); - const proms = []; - for (let i2 = 0; i2 < input.length; i2++) { - const item = input[i2]; - const result = def.element._zod.run({ - value: item, - issues: [] - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => handleArrayResult(result2, payload, i2))); - } else { - handleArrayResult(result, payload, i2); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; - }; -}); -function handleObjectResult(result, final, key) { - if (result.issues.length) { - final.issues.push(...prefixIssues(key, result.issues)); - } - final.value[key] = result.value; -} -function handleOptionalObjectResult(result, final, key, input) { - if (result.issues.length) { - if (input[key] === void 0) { - if (key in input) { - final.value[key] = void 0; - } else { - final.value[key] = result.value; - } - } else { - final.issues.push(...prefixIssues(key, result.issues)); - } - } else if (result.value === void 0) { - if (key in input) - final.value[key] = void 0; - } else { - final.value[key] = result.value; - } -} -var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { - $ZodType.init(inst, def); - const _normalized = cached(() => { - const keys = Object.keys(def.shape); - for (const k of keys) { - if (!(def.shape[k] instanceof $ZodType)) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); - } - } - const okeys = optionalKeys(def.shape); - return { - shape: def.shape, - keys, - keySet: new Set(keys), - numKeys: keys.length, - optionalKeys: new Set(okeys) - }; - }); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; - const propValues = {}; - for (const key in shape) { - const field = shape[key]._zod; - if (field.values) { - propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); - for (const v of field.values) - propValues[key].add(v); - } - } - return propValues; - }); - const generateFastpass = (shape) => { - const doc = new Doc(["shape", "payload", "ctx"]); - const normalized = _normalized.value; - const parseStr = (key) => { - const k = esc(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; - doc.write(`const input = payload.value;`); - const ids = /* @__PURE__ */ Object.create(null); - let counter = 0; - for (const key of normalized.keys) { - ids[key] = `key_${counter++}`; - } - doc.write(`const newResult = {}`); - for (const key of normalized.keys) { - if (normalized.optionalKeys.has(key)) { - const id = ids[key]; - doc.write(`const ${id} = ${parseStr(key)};`); - const k = esc(key); - doc.write(` - if (${id}.issues.length) { - if (input[${k}] === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } - } else { - payload.issues = payload.issues.concat( - ${id}.issues.map((iss) => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}], - })) - ); - } - } else if (${id}.value === undefined) { - if (${k} in input) newResult[${k}] = undefined; - } else { - newResult[${k}] = ${id}.value; - } - `); - } else { - const id = ids[key]; - doc.write(`const ${id} = ${parseStr(key)};`); - doc.write(` - if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}] - })));`); - doc.write(`newResult[${esc(key)}] = ${id}.value`); - } - } - doc.write(`payload.value = newResult;`); - doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); - }; - let fastpass; - const isObject4 = isObject; - const jit = !globalConfig.jitless; - const allowsEval2 = allowsEval; - const fastEnabled = jit && allowsEval2.value; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject4(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst - }); - return payload; - } - const proms = []; - if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { - if (!fastpass) - fastpass = generateFastpass(def.shape); - payload = fastpass(payload, ctx); - } else { - payload.value = {}; - const shape = value.shape; - for (const key of value.keys) { - const el = shape[key]; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); - const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional"; - if (r instanceof Promise) { - proms.push(r.then((r2) => isOptional ? handleOptionalObjectResult(r2, payload, key, input) : handleObjectResult(r2, payload, key))); - } else if (isOptional) { - handleOptionalObjectResult(r, payload, key, input); - } else { - handleObjectResult(r, payload, key); - } - } - } - if (!catchall) { - return proms.length ? Promise.all(proms).then(() => payload) : payload; - } - const unrecognized = []; - const keySet = value.keySet; - const _catchall = catchall._zod; - const t = _catchall.def.type; - for (const key of Object.keys(input)) { - if (keySet.has(key)) - continue; - if (t === "never") { - unrecognized.push(key); - continue; - } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r2) => handleObjectResult(r2, payload, key))); - } else { - handleObjectResult(r, payload, key); - } - } - if (unrecognized.length) { - payload.issues.push({ - code: "unrecognized_keys", - keys: unrecognized, - input, - inst - }); - } - if (!proms.length) - return payload; - return Promise.all(proms).then(() => { - return payload; - }); - }; -}); -function handleUnionResults(results, final, inst, ctx) { - for (const result of results) { - if (result.issues.length === 0) { - final.value = result.value; - return final; - } - } - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) - }); - return final; -} -var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); - } - return void 0; - }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); - return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); - } - return void 0; - }); - inst._zod.parse = (payload, ctx) => { - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [] - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } else { - if (result.issues.length === 0) - return result; - results.push(result); - } - } - if (!async) - return handleUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results2) => { - return handleUnionResults(results2, payload, inst, ctx); - }); - }; -}); -var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { - $ZodUnion.init(inst, def); - const _super = inst._zod.parse; - defineLazy(inst._zod, "propValues", () => { - const propValues = {}; - for (const option of def.options) { - const pv = option._zod.propValues; - if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); - for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) - propValues[k] = /* @__PURE__ */ new Set(); - for (const val of v) { - propValues[k].add(val); - } - } - } - return propValues; - }); - const disc = cached(() => { - const opts = def.options; - const map4 = /* @__PURE__ */ new Map(); - for (const o of opts) { - const values = o._zod.propValues[def.discriminator]; - if (!values || values.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values) { - if (map4.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map4.set(v, o); - } - } - return map4; - }); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - code: "invalid_type", - expected: "object", - input, - inst - }); - return payload; - } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { - return opt._zod.run(payload, ctx); - } - if (def.unionFallback) { - return _super(payload, ctx); - } - payload.issues.push({ - code: "invalid_union", - errors: [], - note: "No matching discriminator", - input, - path: [def.discriminator], - inst - }); - return payload; - }; -}); -var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); - const async = left instanceof Promise || right instanceof Promise; - if (async) { - return Promise.all([left, right]).then(([left2, right2]) => { - return handleIntersectionResults(payload, left2, right2); - }); - } - return handleIntersectionResults(payload, left, right); - }; -}); -function mergeValues2(a, b) { - if (a === b) { - return { valid: true, data: a }; - } - if (a instanceof Date && b instanceof Date && +a === +b) { - return { valid: true, data: a }; - } - if (isPlainObject(a) && isPlainObject(b)) { - const bKeys = Object.keys(b); - const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues2(a[key], b[key]); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [key, ...sharedValue.mergeErrorPath] - }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) { - return { valid: false, mergeErrorPath: [] }; - } - const newArray = []; - for (let index2 = 0; index2 < a.length; index2++) { - const itemA = a[index2]; - const itemB = b[index2]; - const sharedValue = mergeValues2(itemA, itemB); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [index2, ...sharedValue.mergeErrorPath] - }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } - return { valid: false, mergeErrorPath: [] }; -} -function handleIntersectionResults(result, left, right) { - if (left.issues.length) { - result.issues.push(...left.issues); - } - if (right.issues.length) { - result.issues.push(...right.issues); - } - if (aborted(result)) - return result; - const merged = mergeValues2(left.value, right.value); - if (!merged.valid) { - throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); - } - result.value = merged.data; - return result; -} -var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { - payload.issues.push({ - expected: "record", - code: "invalid_type", - input, - inst - }); - return payload; - } - const proms = []; - if (def.keyType._zod.values) { - const values = def.keyType._zod.values; - payload.value = {}; - for (const key of values) { - if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => { - if (result2.issues.length) { - payload.issues.push(...prefixIssues(key, result2.issues)); - } - payload.value[key] = result2.value; - })); - } else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[key] = result.value; - } - } - } - let unrecognized; - for (const key in input) { - if (!values.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized - }); - } - } else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { - if (key === "__proto__") - continue; - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (keyResult.issues.length) { - payload.issues.push({ - origin: "record", - code: "invalid_key", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), - input: key, - path: [key], - inst - }); - payload.value[keyResult.value] = keyResult.value; - continue; - } - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result2) => { - if (result2.issues.length) { - payload.issues.push(...prefixIssues(key, result2.issues)); - } - payload.value[keyResult.value] = result2.value; - })); - } else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[keyResult.value] = result.value; - } - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; - }; -}); -var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { - $ZodType.init(inst, def); - const values = getEnumValues(def.entries); - inst._zod.values = new Set(values); - inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (inst._zod.values.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values, - input, - inst - }); - return payload; - }; -}); -var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.values = new Set(def.values); - inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? o.toString() : String(o)).join("|")})$`); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (inst._zod.values.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values: def.values, - input, - inst - }); - return payload; - }; -}); -var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const _out = def.transform(payload.value, payload); - if (_ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output2) => { - payload.value = output2; - return payload; - }); - } - if (_out instanceof Promise) { - throw new $ZodAsyncError(); - } - payload.value = _out; - return payload; - }; -}); -var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; - }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; - }); - inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - return def.innerType._zod.run(payload, ctx); - } - if (payload.value === void 0) { - return payload; - } - return def.innerType._zod.run(payload, ctx); - }; -}); -var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; - }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; - }); - inst._zod.parse = (payload, ctx) => { - if (payload.value === null) - return payload; - return def.innerType._zod.run(payload, ctx); - }; -}); -var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (payload.value === void 0) { - payload.value = def.defaultValue; - return payload; - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result2) => handleDefaultResult(result2, def)); - } - return handleDefaultResult(result, def); - }; -}); -function handleDefaultResult(payload, def) { - if (payload.value === void 0) { - payload.value = def.defaultValue; - } - return payload; -} -var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (payload.value === void 0) { - payload.value = def.defaultValue; - } - return def.innerType._zod.run(payload, ctx); - }; -}); -var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; - return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; - }); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result2) => handleNonOptionalResult(result2, inst)); - } - return handleNonOptionalResult(result, inst); - }; -}); -function handleNonOptionalResult(payload, inst) { - if (!payload.issues.length && payload.value === void 0) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: payload.value, - inst - }); - } - return payload; -} -var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result2) => { - payload.value = result2.value; - if (result2.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - } - return payload; - }); - } - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) - }, - input: payload.value - }); - payload.issues = []; - } - return payload; - }; -}); -var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - inst._zod.parse = (payload, ctx) => { - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left2) => handlePipeResult(left2, def, ctx)); - } - return handlePipeResult(left, def, ctx); - }; -}); -function handlePipeResult(left, def, ctx) { - if (aborted(left)) { - return left; - } - return def.out._zod.run({ value: left.value, issues: left.issues }, ctx); -} -var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then(handleReadonlyResult); - } - return handleReadonlyResult(result); - }; -}); -function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); - return payload; -} -var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { - $ZodCheck.init(inst, def); - $ZodType.init(inst, def); - inst._zod.parse = (payload, _) => { - return payload; - }; - inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); - if (r instanceof Promise) { - return r.then((r2) => handleRefineResult(r2, payload, input, inst)); - } - handleRefineResult(r, payload, input, inst); - return; - }; -}); -function handleRefineResult(result, payload, input, inst) { - if (!result) { - const _iss = { - code: "custom", - input, - inst, - // incorporates params.error into issue reporting - path: [...inst._zod.def.path ?? []], - // incorporates params.error into issue reporting - continue: !inst._zod.def.abort - // params: inst._zod.def.params, - }; - if (inst._zod.def.params) - _iss.params = inst._zod.def.params; - payload.issues.push(issue(_iss)); - } -} - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/locales/en.js -var parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; -}; -var error = () => { - const Sizable = { - string: { unit: "characters", verb: "to have" }, - file: { unit: "bytes", verb: "to have" }, - array: { unit: "items", verb: "to have" }, - set: { unit: "items", verb: "to have" } - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const Nouns = { - regex: "input", - email: "email address", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datetime", - date: "ISO date", - time: "ISO time", - duration: "ISO duration", - ipv4: "IPv4 address", - ipv6: "IPv6 address", - cidrv4: "IPv4 range", - cidrv6: "IPv6 range", - base64: "base64-encoded string", - base64url: "base64url-encoded string", - json_string: "JSON string", - e164: "E.164 number", - jwt: "JWT", - template_literal: "input" - }; - return (issue2) => { - switch (issue2.code) { - case "invalid_type": - return `Invalid input: expected ${issue2.expected}, received ${parsedType(issue2.input)}`; - case "invalid_value": - if (issue2.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; - return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; - case "too_big": { - const adj = issue2.inclusive ? "<=" : "<"; - const sizing = getSizing(issue2.origin); - if (sizing) - return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; - } - case "too_small": { - const adj = issue2.inclusive ? ">=" : ">"; - const sizing = getSizing(issue2.origin); - if (sizing) { - return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; - } - return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue2; - if (_issue.format === "starts_with") { - return `Invalid string: must start with "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Invalid string: must end with "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Invalid string: must include "${_issue.includes}"`; - if (_issue.format === "regex") - return `Invalid string: must match pattern ${_issue.pattern}`; - return `Invalid ${Nouns[_issue.format] ?? issue2.format}`; - } - case "not_multiple_of": - return `Invalid number: must be a multiple of ${issue2.divisor}`; - case "unrecognized_keys": - return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; - case "invalid_key": - return `Invalid key in ${issue2.origin}`; - case "invalid_union": - return "Invalid input"; - case "invalid_element": - return `Invalid value in ${issue2.origin}`; - default: - return `Invalid input`; - } - }; -}; -function en_default2() { - return { - localeError: error() - }; -} - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/registries.js -var $ZodRegistry = class { - constructor() { - this._map = /* @__PURE__ */ new Map(); - this._idmap = /* @__PURE__ */ new Map(); - } - add(schema2, ..._meta) { - const meta = _meta[0]; - this._map.set(schema2, meta); - if (meta && typeof meta === "object" && "id" in meta) { - if (this._idmap.has(meta.id)) { - throw new Error(`ID ${meta.id} already exists in the registry`); - } - this._idmap.set(meta.id, schema2); - } - return this; - } - clear() { - this._map = /* @__PURE__ */ new Map(); - this._idmap = /* @__PURE__ */ new Map(); - return this; - } - remove(schema2) { - const meta = this._map.get(schema2); - if (meta && typeof meta === "object" && "id" in meta) { - this._idmap.delete(meta.id); - } - this._map.delete(schema2); - return this; - } - get(schema2) { - const p = schema2._zod.parent; - if (p) { - const pm = { ...this.get(p) ?? {} }; - delete pm.id; - return { ...pm, ...this._map.get(schema2) }; - } - return this._map.get(schema2); - } - has(schema2) { - return this._map.has(schema2); - } -}; -function registry() { - return new $ZodRegistry(); -} -var globalRegistry = /* @__PURE__ */ registry(); - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/api.js -function _string(Class2, params) { - return new Class2({ - type: "string", - ...normalizeParams(params) - }); -} -function _email(Class2, params) { - return new Class2({ - type: "string", - format: "email", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _guid(Class2, params) { - return new Class2({ - type: "string", - format: "guid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _uuid(Class2, params) { - return new Class2({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _uuidv4(Class2, params) { - return new Class2({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v4", - ...normalizeParams(params) - }); -} -function _uuidv6(Class2, params) { - return new Class2({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v6", - ...normalizeParams(params) - }); -} -function _uuidv7(Class2, params) { - return new Class2({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v7", - ...normalizeParams(params) - }); -} -function _url(Class2, params) { - return new Class2({ - type: "string", - format: "url", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _emoji2(Class2, params) { - return new Class2({ - type: "string", - format: "emoji", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _nanoid(Class2, params) { - return new Class2({ - type: "string", - format: "nanoid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _cuid(Class2, params) { - return new Class2({ - type: "string", - format: "cuid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _cuid2(Class2, params) { - return new Class2({ - type: "string", - format: "cuid2", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _ulid(Class2, params) { - return new Class2({ - type: "string", - format: "ulid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _xid(Class2, params) { - return new Class2({ - type: "string", - format: "xid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _ksuid(Class2, params) { - return new Class2({ - type: "string", - format: "ksuid", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _ipv4(Class2, params) { - return new Class2({ - type: "string", - format: "ipv4", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _ipv6(Class2, params) { - return new Class2({ - type: "string", - format: "ipv6", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _cidrv4(Class2, params) { - return new Class2({ - type: "string", - format: "cidrv4", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _cidrv6(Class2, params) { - return new Class2({ - type: "string", - format: "cidrv6", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _base64(Class2, params) { - return new Class2({ - type: "string", - format: "base64", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _base64url(Class2, params) { - return new Class2({ - type: "string", - format: "base64url", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _e164(Class2, params) { - return new Class2({ - type: "string", - format: "e164", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _jwt(Class2, params) { - return new Class2({ - type: "string", - format: "jwt", - check: "string_format", - abort: false, - ...normalizeParams(params) - }); -} -function _isoDateTime(Class2, params) { - return new Class2({ - type: "string", - format: "datetime", - check: "string_format", - offset: false, - local: false, - precision: null, - ...normalizeParams(params) - }); -} -function _isoDate(Class2, params) { - return new Class2({ - type: "string", - format: "date", - check: "string_format", - ...normalizeParams(params) - }); -} -function _isoTime(Class2, params) { - return new Class2({ - type: "string", - format: "time", - check: "string_format", - precision: null, - ...normalizeParams(params) - }); -} -function _isoDuration(Class2, params) { - return new Class2({ - type: "string", - format: "duration", - check: "string_format", - ...normalizeParams(params) - }); -} -function _number(Class2, params) { - return new Class2({ - type: "number", - checks: [], - ...normalizeParams(params) - }); -} -function _int(Class2, params) { - return new Class2({ - type: "number", - check: "number_format", - abort: false, - format: "safeint", - ...normalizeParams(params) - }); -} -function _boolean(Class2, params) { - return new Class2({ - type: "boolean", - ...normalizeParams(params) - }); -} -function _null2(Class2, params) { - return new Class2({ - type: "null", - ...normalizeParams(params) - }); -} -function _unknown(Class2) { - return new Class2({ - type: "unknown" - }); -} -function _never(Class2, params) { - return new Class2({ - type: "never", - ...normalizeParams(params) - }); -} -function _lt(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: false - }); -} -function _lte(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: true - }); -} -function _gt(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: false - }); -} -function _gte(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: true - }); -} -function _multipleOf(value, params) { - return new $ZodCheckMultipleOf({ - check: "multiple_of", - ...normalizeParams(params), - value - }); -} -function _maxLength(maximum, params) { - const ch = new $ZodCheckMaxLength({ - check: "max_length", - ...normalizeParams(params), - maximum - }); - return ch; -} -function _minLength(minimum, params) { - return new $ZodCheckMinLength({ - check: "min_length", - ...normalizeParams(params), - minimum - }); -} -function _length(length, params) { - return new $ZodCheckLengthEquals({ - check: "length_equals", - ...normalizeParams(params), - length - }); -} -function _regex(pattern, params) { - return new $ZodCheckRegex({ - check: "string_format", - format: "regex", - ...normalizeParams(params), - pattern - }); -} -function _lowercase(params) { - return new $ZodCheckLowerCase({ - check: "string_format", - format: "lowercase", - ...normalizeParams(params) - }); -} -function _uppercase(params) { - return new $ZodCheckUpperCase({ - check: "string_format", - format: "uppercase", - ...normalizeParams(params) - }); -} -function _includes(includes, params) { - return new $ZodCheckIncludes({ - check: "string_format", - format: "includes", - ...normalizeParams(params), - includes - }); -} -function _startsWith(prefix, params) { - return new $ZodCheckStartsWith({ - check: "string_format", - format: "starts_with", - ...normalizeParams(params), - prefix - }); -} -function _endsWith(suffix, params) { - return new $ZodCheckEndsWith({ - check: "string_format", - format: "ends_with", - ...normalizeParams(params), - suffix - }); -} -function _overwrite(tx) { - return new $ZodCheckOverwrite({ - check: "overwrite", - tx - }); +var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { + $ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => { + $ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => { + $ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => { + $ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => { + $ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => { + $ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => { + $ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => { + $ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => { + $ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => { + $ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => { + $ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => { + $ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { + $ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { + $ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { + $ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { + $ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodNumber2 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { + $ZodNumber.init(inst, def); + ZodType2.init(inst, def); + inst.gt = (value, params) => inst.check(_gt(value, params)); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.lt = (value, params) => inst.check(_lt(value, params)); + inst.lte = (value, params) => inst.check(_lte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + inst.int = (params) => inst.check(int(params)); + inst.safe = (params) => inst.check(int(params)); + inst.positive = (params) => inst.check(_gt(0, params)); + inst.nonnegative = (params) => inst.check(_gte(0, params)); + inst.negative = (params) => inst.check(_lt(0, params)); + inst.nonpositive = (params) => inst.check(_lte(0, params)); + inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); + inst.step = (value, params) => inst.check(_multipleOf(value, params)); + inst.finite = () => inst; + const bag = inst._zod.bag; + inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; + inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); + inst.isFinite = true; + inst.format = bag.format ?? null; +}); +function number2(params) { + return _number(ZodNumber2, params); } -function _normalize(form) { - return _overwrite((input) => input.normalize(form)); +var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { + $ZodNumberFormat.init(inst, def); + ZodNumber2.init(inst, def); +}); +function int(params) { + return _int(ZodNumberFormat, params); } -function _trim() { - return _overwrite((input) => input.trim()); +var ZodBoolean2 = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { + $ZodBoolean.init(inst, def); + ZodType2.init(inst, def); +}); +function boolean2(params) { + return _boolean(ZodBoolean2, params); } -function _toLowerCase() { - return _overwrite((input) => input.toLowerCase()); +var ZodNull2 = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { + $ZodNull.init(inst, def); + ZodType2.init(inst, def); +}); +function _null3(params) { + return _null2(ZodNull2, params); } -function _toUpperCase() { - return _overwrite((input) => input.toUpperCase()); +var ZodUnknown2 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { + $ZodUnknown.init(inst, def); + ZodType2.init(inst, def); +}); +function unknown() { + return _unknown(ZodUnknown2); } -function _array(Class2, element, params) { - return new Class2({ - type: "array", - element, - // get element() { - // return element; - // }, - ...normalizeParams(params) - }); +var ZodNever2 = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { + $ZodNever.init(inst, def); + ZodType2.init(inst, def); +}); +function never(params) { + return _never(ZodNever2, params); } -function _custom(Class2, fn, _params) { - const norm2 = normalizeParams(_params); - norm2.abort ?? (norm2.abort = true); - const schema2 = new Class2({ - type: "custom", - check: "custom", - fn, - ...norm2 - }); - return schema2; +var ZodArray2 = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + $ZodArray.init(inst, def); + ZodType2.init(inst, def); + inst.element = def.element; + inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); + inst.nonempty = (params) => inst.check(_minLength(1, params)); + inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); + inst.length = (len, params) => inst.check(_length(len, params)); + inst.unwrap = () => inst.element; +}); +function array(element, params) { + return _array(ZodArray2, element, params); } -function _refine(Class2, fn, _params) { - const schema2 = new Class2({ - type: "custom", - check: "custom", - fn, - ...normalizeParams(_params) - }); - return schema2; +var ZodObject2 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + $ZodObject.init(inst, def); + ZodType2.init(inst, def); + util_exports.defineLazy(inst, "shape", () => def.shape); + inst.keyof = () => _enum(Object.keys(inst._zod.def.shape)); + inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall }); + inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); + inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 }); + inst.extend = (incoming) => { + return util_exports.extend(inst, incoming); + }; + inst.merge = (other) => util_exports.merge(inst, other); + inst.pick = (mask) => util_exports.pick(inst, mask); + inst.omit = (mask) => util_exports.omit(inst, mask); + inst.partial = (...args) => util_exports.partial(ZodOptional2, inst, args[0]); + inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]); +}); +function object2(shape, params) { + const def = { + type: "object", + get shape() { + util_exports.assignProp(this, "shape", { ...shape }); + return this.shape; + }, + ...util_exports.normalizeParams(params) + }; + return new ZodObject2(def); } - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/core/to-json-schema.js -var JSONSchemaGenerator = class { - constructor(params) { - this.counter = 0; - this.metadataRegistry = params?.metadata ?? globalRegistry; - this.target = params?.target ?? "draft-2020-12"; - this.unrepresentable = params?.unrepresentable ?? "throw"; - this.override = params?.override ?? (() => { - }); - this.io = params?.io ?? "output"; - this.seen = /* @__PURE__ */ new Map(); - } - process(schema2, _params = { path: [], schemaPath: [] }) { - var _a; - const def = schema2._zod.def; - const formatMap = { - guid: "uuid", - url: "uri", - datetime: "date-time", - json_string: "json-string", - regex: "" - // do not set - }; - const seen = this.seen.get(schema2); - if (seen) { - seen.count++; - const isCycle = _params.schemaPath.includes(schema2); - if (isCycle) { - seen.cycle = _params.path; - } - return seen.schema; - } - const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; - this.seen.set(schema2, result); - const overrideSchema = schema2._zod.toJSONSchema?.(); - if (overrideSchema) { - result.schema = overrideSchema; - } else { - const params = { - ..._params, - schemaPath: [..._params.schemaPath, schema2], - path: _params.path - }; - const parent = schema2._zod.parent; - if (parent) { - result.ref = parent; - this.process(parent, params); - this.seen.get(parent).isParent = true; - } else { - const _json = result.schema; - switch (def.type) { - case "string": { - const json2 = _json; - json2.type = "string"; - const { minimum, maximum, format: format5, patterns, contentEncoding } = schema2._zod.bag; - if (typeof minimum === "number") - json2.minLength = minimum; - if (typeof maximum === "number") - json2.maxLength = maximum; - if (format5) { - json2.format = formatMap[format5] ?? format5; - if (json2.format === "") - delete json2.format; - } - if (contentEncoding) - json2.contentEncoding = contentEncoding; - if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json2.pattern = regexes[0].source; - else if (regexes.length > 1) { - result.schema.allOf = [ - ...regexes.map((regex) => ({ - ...this.target === "draft-7" ? { type: "string" } : {}, - pattern: regex.source - })) - ]; - } - } - break; - } - case "number": { - const json2 = _json; - const { minimum, maximum, format: format5, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema2._zod.bag; - if (typeof format5 === "string" && format5.includes("int")) - json2.type = "integer"; - else - json2.type = "number"; - if (typeof exclusiveMinimum === "number") - json2.exclusiveMinimum = exclusiveMinimum; - if (typeof minimum === "number") { - json2.minimum = minimum; - if (typeof exclusiveMinimum === "number") { - if (exclusiveMinimum >= minimum) - delete json2.minimum; - else - delete json2.exclusiveMinimum; - } - } - if (typeof exclusiveMaximum === "number") - json2.exclusiveMaximum = exclusiveMaximum; - if (typeof maximum === "number") { - json2.maximum = maximum; - if (typeof exclusiveMaximum === "number") { - if (exclusiveMaximum <= maximum) - delete json2.maximum; - else - delete json2.exclusiveMaximum; - } - } - if (typeof multipleOf === "number") - json2.multipleOf = multipleOf; - break; - } - case "boolean": { - const json2 = _json; - json2.type = "boolean"; - break; - } - case "bigint": { - if (this.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } - break; - } - case "symbol": { - if (this.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } - break; - } - case "null": { - _json.type = "null"; - break; - } - case "any": { - break; - } - case "unknown": { - break; - } - case "undefined": { - if (this.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } - break; - } - case "void": { - if (this.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } - break; - } - case "never": { - _json.not = {}; - break; - } - case "date": { - if (this.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } - break; - } - case "array": { - const json2 = _json; - const { minimum, maximum } = schema2._zod.bag; - if (typeof minimum === "number") - json2.minItems = minimum; - if (typeof maximum === "number") - json2.maxItems = maximum; - json2.type = "array"; - json2.items = this.process(def.element, { ...params, path: [...params.path, "items"] }); - break; - } - case "object": { - const json2 = _json; - json2.type = "object"; - json2.properties = {}; - const shape = def.shape; - for (const key in shape) { - json2.properties[key] = this.process(shape[key], { - ...params, - path: [...params.path, "properties", key] - }); - } - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v = def.shape[key]._zod; - if (this.io === "input") { - return v.optin === void 0; - } else { - return v.optout === void 0; - } - })); - if (requiredKeys.size > 0) { - json2.required = Array.from(requiredKeys); - } - if (def.catchall?._zod.def.type === "never") { - json2.additionalProperties = false; - } else if (!def.catchall) { - if (this.io === "output") - json2.additionalProperties = false; - } else if (def.catchall) { - json2.additionalProperties = this.process(def.catchall, { - ...params, - path: [...params.path, "additionalProperties"] - }); - } - break; - } - case "union": { - const json2 = _json; - json2.anyOf = def.options.map((x, i2) => this.process(x, { - ...params, - path: [...params.path, "anyOf", i2] - })); - break; - } - case "intersection": { - const json2 = _json; - const a = this.process(def.left, { - ...params, - path: [...params.path, "allOf", 0] - }); - const b = this.process(def.right, { - ...params, - path: [...params.path, "allOf", 1] - }); - const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; - const allOf = [ - ...isSimpleIntersection(a) ? a.allOf : [a], - ...isSimpleIntersection(b) ? b.allOf : [b] - ]; - json2.allOf = allOf; - break; - } - case "tuple": { - const json2 = _json; - json2.type = "array"; - const prefixItems = def.items.map((x, i2) => this.process(x, { ...params, path: [...params.path, "prefixItems", i2] })); - if (this.target === "draft-2020-12") { - json2.prefixItems = prefixItems; - } else { - json2.items = prefixItems; - } - if (def.rest) { - const rest = this.process(def.rest, { - ...params, - path: [...params.path, "items"] - }); - if (this.target === "draft-2020-12") { - json2.items = rest; - } else { - json2.additionalItems = rest; - } - } - if (def.rest) { - json2.items = this.process(def.rest, { - ...params, - path: [...params.path, "items"] - }); - } - const { minimum, maximum } = schema2._zod.bag; - if (typeof minimum === "number") - json2.minItems = minimum; - if (typeof maximum === "number") - json2.maxItems = maximum; - break; - } - case "record": { - const json2 = _json; - json2.type = "object"; - json2.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, "propertyNames"] }); - json2.additionalProperties = this.process(def.valueType, { - ...params, - path: [...params.path, "additionalProperties"] - }); - break; - } - case "map": { - if (this.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } - break; - } - case "set": { - if (this.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } - break; - } - case "enum": { - const json2 = _json; - const values = getEnumValues(def.entries); - if (values.every((v) => typeof v === "number")) - json2.type = "number"; - if (values.every((v) => typeof v === "string")) - json2.type = "string"; - json2.enum = values; - break; - } - case "literal": { - const json2 = _json; - const vals = []; - for (const val of def.values) { - if (val === void 0) { - if (this.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } else { - } - } else if (typeof val === "bigint") { - if (this.unrepresentable === "throw") { - throw new Error("BigInt literals cannot be represented in JSON Schema"); - } else { - vals.push(Number(val)); - } - } else { - vals.push(val); - } - } - if (vals.length === 0) { - } else if (vals.length === 1) { - const val = vals[0]; - json2.type = val === null ? "null" : typeof val; - json2.const = val; - } else { - if (vals.every((v) => typeof v === "number")) - json2.type = "number"; - if (vals.every((v) => typeof v === "string")) - json2.type = "string"; - if (vals.every((v) => typeof v === "boolean")) - json2.type = "string"; - if (vals.every((v) => v === null)) - json2.type = "null"; - json2.enum = vals; - } - break; - } - case "file": { - const json2 = _json; - const file = { - type: "string", - format: "binary", - contentEncoding: "binary" - }; - const { minimum, maximum, mime } = schema2._zod.bag; - if (minimum !== void 0) - file.minLength = minimum; - if (maximum !== void 0) - file.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file.contentMediaType = mime[0]; - Object.assign(json2, file); - } else { - json2.anyOf = mime.map((m) => { - const mFile = { ...file, contentMediaType: m }; - return mFile; - }); - } - } else { - Object.assign(json2, file); - } - break; - } - case "transform": { - if (this.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } - break; - } - case "nullable": { - const inner = this.process(def.innerType, params); - _json.anyOf = [inner, { type: "null" }]; - break; - } - case "nonoptional": { - this.process(def.innerType, params); - result.ref = def.innerType; - break; - } - case "success": { - const json2 = _json; - json2.type = "boolean"; - break; - } - case "default": { - this.process(def.innerType, params); - result.ref = def.innerType; - _json.default = JSON.parse(JSON.stringify(def.defaultValue)); - break; - } - case "prefault": { - this.process(def.innerType, params); - result.ref = def.innerType; - if (this.io === "input") - _json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); - break; - } - case "catch": { - this.process(def.innerType, params); - result.ref = def.innerType; - let catchValue; - try { - catchValue = def.catchValue(void 0); - } catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); - } - _json.default = catchValue; - break; - } - case "nan": { - if (this.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } - break; - } - case "template_literal": { - const json2 = _json; - const pattern = schema2._zod.pattern; - if (!pattern) - throw new Error("Pattern not found in template literal"); - json2.type = "string"; - json2.pattern = pattern.source; - break; - } - case "pipe": { - const innerType = this.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out; - this.process(innerType, params); - result.ref = innerType; - break; - } - case "readonly": { - this.process(def.innerType, params); - result.ref = def.innerType; - _json.readOnly = true; - break; - } - // passthrough types - case "promise": { - this.process(def.innerType, params); - result.ref = def.innerType; - break; - } - case "optional": { - this.process(def.innerType, params); - result.ref = def.innerType; - break; - } - case "lazy": { - const innerType = schema2._zod.innerType; - this.process(innerType, params); - result.ref = innerType; - break; - } - case "custom": { - if (this.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } - break; - } - default: { - def; - } - } - } - } - const meta = this.metadataRegistry.get(schema2); - if (meta) - Object.assign(result.schema, meta); - if (this.io === "input" && isTransforming(schema2)) { - delete result.schema.examples; - delete result.schema.default; +function looseObject(shape, params) { + return new ZodObject2({ + type: "object", + get shape() { + util_exports.assignProp(this, "shape", { ...shape }); + return this.shape; + }, + catchall: unknown(), + ...util_exports.normalizeParams(params) + }); +} +var ZodUnion2 = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { + $ZodUnion.init(inst, def); + ZodType2.init(inst, def); + inst.options = def.options; +}); +function union(options, params) { + return new ZodUnion2({ + type: "union", + options, + ...util_exports.normalizeParams(params) + }); +} +var ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { + ZodUnion2.init(inst, def); + $ZodDiscriminatedUnion.init(inst, def); +}); +function discriminatedUnion(discriminator, options, params) { + return new ZodDiscriminatedUnion2({ + type: "union", + options, + discriminator, + ...util_exports.normalizeParams(params) + }); +} +var ZodIntersection2 = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { + $ZodIntersection.init(inst, def); + ZodType2.init(inst, def); +}); +function intersection(left, right) { + return new ZodIntersection2({ + type: "intersection", + left, + right + }); +} +var ZodRecord2 = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + $ZodRecord.init(inst, def); + ZodType2.init(inst, def); + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); +function record(keyType, valueType, params) { + return new ZodRecord2({ + type: "record", + keyType, + valueType, + ...util_exports.normalizeParams(params) + }); +} +var ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { + $ZodEnum.init(inst, def); + ZodType2.init(inst, def); + inst.enum = def.entries; + inst.options = Object.values(def.entries); + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values, params) => { + const newEntries = {}; + for (const value of values) { + if (keys.has(value)) { + newEntries[value] = def.entries[value]; + } else + throw new Error(`Key ${value} not found in enum`); } - if (this.io === "input" && result.schema._prefault) - (_a = result.schema).default ?? (_a.default = result.schema._prefault); - delete result.schema._prefault; - const _result = this.seen.get(schema2); - return _result.schema; - } - emit(schema2, _params) { - const params = { - cycles: _params?.cycles ?? "ref", - reused: _params?.reused ?? "inline", - // unrepresentable: _params?.unrepresentable ?? "throw", - // uri: _params?.uri ?? ((id) => `${id}`), - external: _params?.external ?? void 0 - }; - const root = this.seen.get(schema2); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - const makeURI = (entry) => { - const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions"; - if (params.external) { - const externalId = params.external.registry.get(entry[0])?.id; - const uriGenerator = params.external.uri ?? ((id2) => id2); - if (externalId) { - return { ref: uriGenerator(externalId) }; - } - const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`; - entry[1].defId = id; - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; - } - if (entry[1] === root) { - return { ref: "#" }; - } - const uriPrefix = `#`; - const defUriPrefix = `${uriPrefix}/${defsSegment}/`; - const defId = entry[1].schema.id ?? `__schema${this.counter++}`; - return { defId, ref: defUriPrefix + defId }; - }; - const extractToDef = (entry) => { - if (entry[1].schema.$ref) { - return; - } - const seen = entry[1]; - const { ref, defId } = makeURI(entry); - seen.def = { ...seen.schema }; - if (defId) - seen.defId = defId; - const schema3 = seen.schema; - for (const key in schema3) { - delete schema3[key]; - } - schema3.$ref = ref; - }; - if (params.cycles === "throw") { - for (const entry of this.seen.entries()) { - const seen = entry[1]; - if (seen.cycle) { - throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ - -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); - } - } + return new ZodEnum2({ + ...def, + checks: [], + ...util_exports.normalizeParams(params), + entries: newEntries + }); + }; + inst.exclude = (values, params) => { + const newEntries = { ...def.entries }; + for (const value of values) { + if (keys.has(value)) { + delete newEntries[value]; + } else + throw new Error(`Key ${value} not found in enum`); } - for (const entry of this.seen.entries()) { - const seen = entry[1]; - if (schema2 === entry[0]) { - extractToDef(entry); - continue; - } - if (params.external) { - const ext = params.external.registry.get(entry[0])?.id; - if (schema2 !== entry[0] && ext) { - extractToDef(entry); - continue; - } - } - const id = this.metadataRegistry.get(entry[0])?.id; - if (id) { - extractToDef(entry); - continue; - } - if (seen.cycle) { - extractToDef(entry); - continue; - } - if (seen.count > 1) { - if (params.reused === "ref") { - extractToDef(entry); - continue; - } + return new ZodEnum2({ + ...def, + checks: [], + ...util_exports.normalizeParams(params), + entries: newEntries + }); + }; +}); +function _enum(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new ZodEnum2({ + type: "enum", + entries, + ...util_exports.normalizeParams(params) + }); +} +var ZodLiteral2 = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { + $ZodLiteral.init(inst, def); + ZodType2.init(inst, def); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get() { + if (def.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); } + return def.values[0]; } - const flattenRef = (zodSchema, params2) => { - const seen = this.seen.get(zodSchema); - const schema3 = seen.def ?? seen.schema; - const _cached = { ...schema3 }; - if (seen.ref === null) { - return; - } - const ref = seen.ref; - seen.ref = null; - if (ref) { - flattenRef(ref, params2); - const refSchema = this.seen.get(ref).schema; - if (refSchema.$ref && params2.target === "draft-7") { - schema3.allOf = schema3.allOf ?? []; - schema3.allOf.push(refSchema); - } else { - Object.assign(schema3, refSchema); - Object.assign(schema3, _cached); - } + }); +}); +function literal(value, params) { + return new ZodLiteral2({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util_exports.normalizeParams(params) + }); +} +var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { + $ZodTransform.init(inst, def); + ZodType2.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.addIssue = (issue2) => { + if (typeof issue2 === "string") { + payload.issues.push(util_exports.issue(issue2, payload.value, def)); + } else { + const _issue = issue2; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = inst); + _issue.continue ?? (_issue.continue = true); + payload.issues.push(util_exports.issue(_issue)); } - if (!seen.isParent) - this.override({ - zodSchema, - jsonSchema: schema3, - path: seen.path ?? [] - }); }; - for (const entry of [...this.seen.entries()].reverse()) { - flattenRef(entry[0], { target: this.target }); - } - const result = {}; - if (this.target === "draft-2020-12") { - result.$schema = "https://json-schema.org/draft/2020-12/schema"; - } else if (this.target === "draft-7") { - result.$schema = "http://json-schema.org/draft-07/schema#"; - } else { - console.warn(`Invalid target: ${this.target}`); + const output = def.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output2) => { + payload.value = output2; + return payload; + }); } - if (params.external?.uri) { - const id = params.external.registry.get(schema2)?.id; - if (!id) - throw new Error("Schema is missing an `id` property"); - result.$id = params.external.uri(id); + payload.value = output; + return payload; + }; +}); +function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn + }); +} +var ZodOptional2 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { + $ZodOptional.init(inst, def); + ZodType2.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; +}); +function optional(innerType) { + return new ZodOptional2({ + type: "optional", + innerType + }); +} +var ZodNullable2 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { + $ZodNullable.init(inst, def); + ZodType2.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nullable(innerType) { + return new ZodNullable2({ + type: "nullable", + innerType + }); +} +var ZodDefault2 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { + $ZodDefault.init(inst, def); + ZodType2.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; +}); +function _default(innerType, defaultValue) { + return new ZodDefault2({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : defaultValue; } - Object.assign(result, root.def); - const defs = params.external?.defs ?? {}; - for (const entry of this.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - defs[seen.defId] = seen.def; - } + }); +} +var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { + $ZodPrefault.init(inst, def); + ZodType2.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; +}); +function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : defaultValue; } - if (params.external) { - } else { - if (Object.keys(defs).length > 0) { - if (this.target === "draft-2020-12") { - result.$defs = defs; - } else { - result.definitions = defs; - } + }); +} +var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { + $ZodNonOptional.init(inst, def); + ZodType2.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType, + ...util_exports.normalizeParams(params) + }); +} +var ZodCatch2 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { + $ZodCatch.init(inst, def); + ZodType2.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; +}); +function _catch(innerType, catchValue) { + return new ZodCatch2({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + }); +} +var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { + $ZodPipe.init(inst, def); + ZodType2.init(inst, def); + inst.in = def.in; + inst.out = def.out; +}); +function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out + // ...util.normalizeParams(params), + }); +} +var ZodReadonly2 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { + $ZodReadonly.init(inst, def); + ZodType2.init(inst, def); +}); +function readonly(innerType) { + return new ZodReadonly2({ + type: "readonly", + innerType + }); +} +var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { + $ZodCustom.init(inst, def); + ZodType2.init(inst, def); +}); +function check(fn) { + const ch = new $ZodCheck({ + check: "custom" + // ...util.normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +function custom2(fn, _params) { + return _custom(ZodCustom, fn ?? (() => true), _params); +} +function refine(fn, _params = {}) { + return _refine(ZodCustom, fn, _params); +} +function superRefine(fn) { + const ch = check((payload) => { + payload.addIssue = (issue2) => { + if (typeof issue2 === "string") { + payload.issues.push(util_exports.issue(issue2, payload.value, ch._zod.def)); + } else { + const _issue = issue2; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); + payload.issues.push(util_exports.issue(_issue)); } + }; + return fn(payload.value, payload); + }); + return ch; +} +function preprocess(fn, schema2) { + return pipe(transform(fn), schema2); +} + +// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/external.js +config(en_default2()); + +// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js +var LATEST_PROTOCOL_VERSION = "2025-11-25"; +var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"]; +var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; +var JSONRPC_VERSION = "2.0"; +var AssertObjectSchema = custom2((v) => v !== null && (typeof v === "object" || typeof v === "function")); +var ProgressTokenSchema = union([string2(), number2().int()]); +var CursorSchema = string2(); +var TaskCreationParamsSchema = looseObject({ + /** + * Requested duration in milliseconds to retain task from creation. + */ + ttl: number2().optional(), + /** + * Time in milliseconds to wait between task status requests. + */ + pollInterval: number2().optional() +}); +var TaskMetadataSchema = object2({ + ttl: number2().optional() +}); +var RelatedTaskMetadataSchema = object2({ + taskId: string2() +}); +var RequestMetaSchema = looseObject({ + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken: ProgressTokenSchema.optional(), + /** + * If specified, this request is related to the provided task. + */ + [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() +}); +var BaseRequestParamsSchema = object2({ + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta: RequestMetaSchema.optional() +}); +var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * If specified, the caller is requesting task-augmented execution for this request. + * The request will return a CreateTaskResult immediately, and the actual result can be + * retrieved later via tasks/result. + * + * Task augmentation is subject to capability negotiation - receivers MUST declare support + * for task augmentation of specific request types in their capabilities. + */ + task: TaskMetadataSchema.optional() +}); +var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; +var RequestSchema = object2({ + method: string2(), + params: BaseRequestParamsSchema.loose().optional() +}); +var NotificationsParamsSchema = object2({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: RequestMetaSchema.optional() +}); +var NotificationSchema = object2({ + method: string2(), + params: NotificationsParamsSchema.loose().optional() +}); +var ResultSchema = looseObject({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: RequestMetaSchema.optional() +}); +var RequestIdSchema = union([string2(), number2().int()]); +var JSONRPCRequestSchema = object2({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + ...RequestSchema.shape +}).strict(); +var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; +var JSONRPCNotificationSchema = object2({ + jsonrpc: literal(JSONRPC_VERSION), + ...NotificationSchema.shape +}).strict(); +var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; +var JSONRPCResultResponseSchema = object2({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + result: ResultSchema +}).strict(); +var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; +var ErrorCode; +(function(ErrorCode2) { + ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed"; + ErrorCode2[ErrorCode2["RequestTimeout"] = -32001] = "RequestTimeout"; + ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError"; + ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest"; + ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound"; + ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams"; + ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError"; + ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; +})(ErrorCode || (ErrorCode = {})); +var JSONRPCErrorResponseSchema = object2({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema.optional(), + error: object2({ + /** + * The error type that occurred. + */ + code: number2().int(), + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: string2(), + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data: unknown().optional() + }) +}).strict(); +var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; +var JSONRPCMessageSchema = union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResultResponseSchema, + JSONRPCErrorResponseSchema +]); +var JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); +var EmptyResultSchema = ResultSchema.strict(); +var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: RequestIdSchema.optional(), + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason: string2().optional() +}); +var CancelledNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema +}); +var IconSchema = object2({ + /** + * URL or data URI for the icon. + */ + src: string2(), + /** + * Optional MIME type for the icon. + */ + mimeType: string2().optional(), + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes: array(string2()).optional(), + /** + * Optional specifier for the theme this icon is designed for. `light` indicates + * the icon is designed to be used with a light background, and `dark` indicates + * the icon is designed to be used with a dark background. + * + * If not provided, the client should assume the icon can be used with any theme. + */ + theme: _enum(["light", "dark"]).optional() +}); +var IconsSchema = object2({ + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons: array(IconSchema).optional() +}); +var BaseMetadataSchema = object2({ + /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ + name: string2(), + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title: string2().optional() +}); +var ImplementationSchema = BaseMetadataSchema.extend({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + version: string2(), + /** + * An optional URL of the website for this implementation. + */ + websiteUrl: string2().optional(), + /** + * An optional human-readable description of what this implementation does. + * + * This can be used by clients or servers to provide context about their purpose + * and capabilities. For example, a server might describe the types of resources + * or tools it provides, while a client might describe its intended use case. + */ + description: string2().optional() +}); +var FormElicitationCapabilitySchema = intersection(object2({ + applyDefaults: boolean2().optional() +}), record(string2(), unknown())); +var ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value)) { + if (Object.keys(value).length === 0) { + return { form: {} }; } - try { - return JSON.parse(JSON.stringify(result)); - } catch (_err) { - throw new Error("Error converting schema to JSON."); - } } -}; -function toJSONSchema(input, _params) { - if (input instanceof $ZodRegistry) { - const gen2 = new JSONSchemaGenerator(_params); - const defs = {}; - for (const entry of input._idmap.entries()) { - const [_, schema2] = entry; - gen2.process(schema2); - } - const schemas = {}; - const external2 = { - registry: input, - uri: _params?.uri, - defs - }; - for (const entry of input._idmap.entries()) { - const [key, schema2] = entry; - schemas[key] = gen2.emit(schema2, { - ..._params, - external: external2 - }); - } - if (Object.keys(defs).length > 0) { - const defsSegment = gen2.target === "draft-2020-12" ? "$defs" : "definitions"; - schemas.__shared = { - [defsSegment]: defs - }; - } - return { schemas }; + return value; +}, intersection(object2({ + form: FormElicitationCapabilitySchema.optional(), + url: AssertObjectSchema.optional() +}), record(string2(), unknown()).optional())); +var ClientTasksCapabilitySchema = looseObject({ + /** + * Present if the client supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the client supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: looseObject({ + /** + * Task support for sampling requests. + */ + sampling: looseObject({ + createMessage: AssertObjectSchema.optional() + }).optional(), + /** + * Task support for elicitation requests. + */ + elicitation: looseObject({ + create: AssertObjectSchema.optional() + }).optional() + }).optional() +}); +var ServerTasksCapabilitySchema = looseObject({ + /** + * Present if the server supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the server supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: looseObject({ + /** + * Task support for tool requests. + */ + tools: looseObject({ + call: AssertObjectSchema.optional() + }).optional() + }).optional() +}); +var ClientCapabilitiesSchema = object2({ + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental: record(string2(), AssertObjectSchema).optional(), + /** + * Present if the client supports sampling from an LLM. + */ + sampling: object2({ + /** + * Present if the client supports context inclusion via includeContext parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context: AssertObjectSchema.optional(), + /** + * Present if the client supports tool use via tools and toolChoice parameters. + */ + tools: AssertObjectSchema.optional() + }).optional(), + /** + * Present if the client supports eliciting user input. + */ + elicitation: ElicitationCapabilitySchema.optional(), + /** + * Present if the client supports listing roots. + */ + roots: object2({ + /** + * Whether the client supports issuing notifications for changes to the roots list. + */ + listChanged: boolean2().optional() + }).optional(), + /** + * Present if the client supports task creation. + */ + tasks: ClientTasksCapabilitySchema.optional(), + /** + * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name). + */ + extensions: record(string2(), AssertObjectSchema).optional() +}); +var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: string2(), + capabilities: ClientCapabilitiesSchema, + clientInfo: ImplementationSchema +}); +var InitializeRequestSchema = RequestSchema.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema +}); +var ServerCapabilitiesSchema = object2({ + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental: record(string2(), AssertObjectSchema).optional(), + /** + * Present if the server supports sending log messages to the client. + */ + logging: AssertObjectSchema.optional(), + /** + * Present if the server supports sending completions to the client. + */ + completions: AssertObjectSchema.optional(), + /** + * Present if the server offers any prompt templates. + */ + prompts: object2({ + /** + * Whether this server supports issuing notifications for changes to the prompt list. + */ + listChanged: boolean2().optional() + }).optional(), + /** + * Present if the server offers any resources to read. + */ + resources: object2({ + /** + * Whether this server supports clients subscribing to resource updates. + */ + subscribe: boolean2().optional(), + /** + * Whether this server supports issuing notifications for changes to the resource list. + */ + listChanged: boolean2().optional() + }).optional(), + /** + * Present if the server offers any tools to call. + */ + tools: object2({ + /** + * Whether this server supports issuing notifications for changes to the tool list. + */ + listChanged: boolean2().optional() + }).optional(), + /** + * Present if the server supports task creation. + */ + tasks: ServerTasksCapabilitySchema.optional(), + /** + * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name). + */ + extensions: record(string2(), AssertObjectSchema).optional() +}); +var InitializeResultSchema = ResultSchema.extend({ + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: string2(), + capabilities: ServerCapabilitiesSchema, + serverInfo: ImplementationSchema, + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions: string2().optional() +}); +var InitializedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema.optional() +}); +var PingRequestSchema = RequestSchema.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema.optional() +}); +var ProgressSchema = object2({ + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + */ + progress: number2(), + /** + * Total number of items to process (or total progress required), if known. + */ + total: optional(number2()), + /** + * An optional message describing the current progress. + */ + message: optional(string2()) +}); +var ProgressNotificationParamsSchema = object2({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressTokenSchema +}); +var ProgressNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema +}); +var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor: CursorSchema.optional() +}); +var PaginatedRequestSchema = RequestSchema.extend({ + params: PaginatedRequestParamsSchema.optional() +}); +var PaginatedResultSchema = ResultSchema.extend({ + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor: CursorSchema.optional() +}); +var TaskStatusSchema = _enum(["working", "input_required", "completed", "failed", "cancelled"]); +var TaskSchema = object2({ + taskId: string2(), + status: TaskStatusSchema, + /** + * Time in milliseconds to keep task results available after completion. + * If null, the task has unlimited lifetime until manually cleaned up. + */ + ttl: union([number2(), _null3()]), + /** + * ISO 8601 timestamp when the task was created. + */ + createdAt: string2(), + /** + * ISO 8601 timestamp when the task was last updated. + */ + lastUpdatedAt: string2(), + pollInterval: optional(number2()), + /** + * Optional diagnostic message for failed tasks or other status information. + */ + statusMessage: optional(string2()) +}); +var CreateTaskResultSchema = ResultSchema.extend({ + task: TaskSchema +}); +var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); +var TaskStatusNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema +}); +var GetTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema.extend({ + taskId: string2() + }) +}); +var GetTaskResultSchema = ResultSchema.merge(TaskSchema); +var GetTaskPayloadRequestSchema = RequestSchema.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema.extend({ + taskId: string2() + }) +}); +var GetTaskPayloadResultSchema = ResultSchema.loose(); +var ListTasksRequestSchema = PaginatedRequestSchema.extend({ + method: literal("tasks/list") +}); +var ListTasksResultSchema = PaginatedResultSchema.extend({ + tasks: array(TaskSchema) +}); +var CancelTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema.extend({ + taskId: string2() + }) +}); +var CancelTaskResultSchema = ResultSchema.merge(TaskSchema); +var ResourceContentsSchema = object2({ + /** + * The URI of this resource. + */ + uri: string2(), + /** + * The MIME type of this resource, if known. + */ + mimeType: optional(string2()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var TextResourceContentsSchema = ResourceContentsSchema.extend({ + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: string2() +}); +var Base64Schema = string2().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } +}, { message: "Invalid Base64 string" }); +var BlobResourceContentsSchema = ResourceContentsSchema.extend({ + /** + * A base64-encoded string representing the binary data of the item. + */ + blob: Base64Schema +}); +var RoleSchema = _enum(["user", "assistant"]); +var AnnotationsSchema = object2({ + /** + * Intended audience(s) for the resource. + */ + audience: array(RoleSchema).optional(), + /** + * Importance hint for the resource, from 0 (least) to 1 (most). + */ + priority: number2().min(0).max(1).optional(), + /** + * ISO 8601 timestamp for the most recent modification. + */ + lastModified: iso_exports2.datetime({ offset: true }).optional() +}); +var ResourceSchema = object2({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * The URI of this resource. + */ + uri: string2(), + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: optional(string2()), + /** + * The MIME type of this resource, if known. + */ + mimeType: optional(string2()), + /** + * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. + * + * This can be used by Hosts to display file sizes and estimate context window usage. + */ + size: optional(number2()), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: optional(looseObject({})) +}); +var ResourceTemplateSchema = object2({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + */ + uriTemplate: string2(), + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: optional(string2()), + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType: optional(string2()), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: optional(looseObject({})) +}); +var ListResourcesRequestSchema = PaginatedRequestSchema.extend({ + method: literal("resources/list") +}); +var ListResourcesResultSchema = PaginatedResultSchema.extend({ + resources: array(ResourceSchema) +}); +var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ + method: literal("resources/templates/list") +}); +var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ + resourceTemplates: array(ResourceTemplateSchema) +}); +var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string2() +}); +var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; +var ReadResourceRequestSchema = RequestSchema.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema +}); +var ReadResourceResultSchema = ResultSchema.extend({ + contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema])) +}); +var ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema.optional() +}); +var SubscribeRequestParamsSchema = ResourceRequestParamsSchema; +var SubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema +}); +var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; +var UnsubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema +}); +var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + */ + uri: string2() +}); +var ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema +}); +var PromptArgumentSchema = object2({ + /** + * The name of the argument. + */ + name: string2(), + /** + * A human-readable description of the argument. + */ + description: optional(string2()), + /** + * Whether this argument must be provided. + */ + required: optional(boolean2()) +}); +var PromptSchema = object2({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * An optional description of what this prompt provides + */ + description: optional(string2()), + /** + * A list of arguments to use for templating the prompt. + */ + arguments: optional(array(PromptArgumentSchema)), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: optional(looseObject({})) +}); +var ListPromptsRequestSchema = PaginatedRequestSchema.extend({ + method: literal("prompts/list") +}); +var ListPromptsResultSchema = PaginatedResultSchema.extend({ + prompts: array(PromptSchema) +}); +var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The name of the prompt or prompt template. + */ + name: string2(), + /** + * Arguments to use for templating the prompt. + */ + arguments: record(string2(), string2()).optional() +}); +var GetPromptRequestSchema = RequestSchema.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema +}); +var TextContentSchema = object2({ + type: literal("text"), + /** + * The text content of the message. + */ + text: string2(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var ImageContentSchema = object2({ + type: literal("image"), + /** + * The base64-encoded image data. + */ + data: Base64Schema, + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: string2(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var AudioContentSchema = object2({ + type: literal("audio"), + /** + * The base64-encoded audio data. + */ + data: Base64Schema, + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: string2(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var ToolUseContentSchema = object2({ + type: literal("tool_use"), + /** + * The name of the tool to invoke. + * Must match a tool name from the request's tools array. + */ + name: string2(), + /** + * Unique identifier for this tool call. + * Used to correlate with ToolResultContent in subsequent messages. + */ + id: string2(), + /** + * Arguments to pass to the tool. + * Must conform to the tool's inputSchema. + */ + input: record(string2(), unknown()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var EmbeddedResourceSchema = object2({ + type: literal("resource"), + resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var ResourceLinkSchema = ResourceSchema.extend({ + type: literal("resource_link") +}); +var ContentBlockSchema = union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceLinkSchema, + EmbeddedResourceSchema +]); +var PromptMessageSchema = object2({ + role: RoleSchema, + content: ContentBlockSchema +}); +var GetPromptResultSchema = ResultSchema.extend({ + /** + * An optional description for the prompt. + */ + description: string2().optional(), + messages: array(PromptMessageSchema) +}); +var PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema.optional() +}); +var ToolAnnotationsSchema = object2({ + /** + * A human-readable title for the tool. + */ + title: string2().optional(), + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint: boolean2().optional(), + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint: boolean2().optional(), + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on the its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint: boolean2().optional(), + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint: boolean2().optional() +}); +var ToolExecutionSchema = object2({ + /** + * Indicates the tool's preference for task-augmented execution. + * - "required": Clients MUST invoke the tool as a task + * - "optional": Clients MAY invoke the tool as a task or normal request + * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task + * + * If not present, defaults to "forbidden". + */ + taskSupport: _enum(["required", "optional", "forbidden"]).optional() +}); +var ToolSchema = object2({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A human-readable description of the tool. + */ + description: string2().optional(), + /** + * A JSON Schema 2020-12 object defining the expected parameters for the tool. + * Must have type: 'object' at the root level per MCP spec. + */ + inputSchema: object2({ + type: literal("object"), + properties: record(string2(), AssertObjectSchema).optional(), + required: array(string2()).optional() + }).catchall(unknown()), + /** + * An optional JSON Schema 2020-12 object defining the structure of the tool's output + * returned in the structuredContent field of a CallToolResult. + * Must have type: 'object' at the root level per MCP spec. + */ + outputSchema: object2({ + type: literal("object"), + properties: record(string2(), AssertObjectSchema).optional(), + required: array(string2()).optional() + }).catchall(unknown()).optional(), + /** + * Optional additional tool information. + */ + annotations: ToolAnnotationsSchema.optional(), + /** + * Execution-related properties for this tool. + */ + execution: ToolExecutionSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var ListToolsRequestSchema = PaginatedRequestSchema.extend({ + method: literal("tools/list") +}); +var ListToolsResultSchema = PaginatedResultSchema.extend({ + tools: array(ToolSchema) +}); +var CallToolResultSchema = ResultSchema.extend({ + /** + * A list of content objects that represent the result of the tool call. + * + * If the Tool does not define an outputSchema, this field MUST be present in the result. + * For backwards compatibility, this field is always present, but it may be empty. + */ + content: array(ContentBlockSchema).default([]), + /** + * An object containing structured tool output. + * + * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. + */ + structuredContent: record(string2(), unknown()).optional(), + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError: boolean2().optional() +}); +var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ + toolResult: unknown() +})); +var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The name of the tool to call. + */ + name: string2(), + /** + * Arguments to pass to the tool. + */ + arguments: record(string2(), unknown()).optional() +}); +var CallToolRequestSchema = RequestSchema.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema +}); +var ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema.optional() +}); +var ListChangedOptionsBaseSchema = object2({ + /** + * If true, the list will be refreshed automatically when a list changed notification is received. + * The callback will be called with the updated list. + * + * If false, the callback will be called with null items, allowing manual refresh. + * + * @default true + */ + autoRefresh: boolean2().default(true), + /** + * Debounce time in milliseconds for list changed notification processing. + * + * Multiple notifications received within this timeframe will only trigger one refresh. + * Set to 0 to disable debouncing. + * + * @default 300 + */ + debounceMs: number2().int().nonnegative().default(300) +}); +var LoggingLevelSchema = _enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]); +var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. + */ + level: LoggingLevelSchema +}); +var SetLevelRequestSchema = RequestSchema.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema +}); +var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The severity of this log message. + */ + level: LoggingLevelSchema, + /** + * An optional name of the logger issuing this message. + */ + logger: string2().optional(), + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: unknown() +}); +var LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema +}); +var ModelHintSchema = object2({ + /** + * A hint for a model name. + */ + name: string2().optional() +}); +var ModelPreferencesSchema = object2({ + /** + * Optional hints to use for model selection. + */ + hints: array(ModelHintSchema).optional(), + /** + * How much to prioritize cost when selecting a model. + */ + costPriority: number2().min(0).max(1).optional(), + /** + * How much to prioritize sampling speed (latency) when selecting a model. + */ + speedPriority: number2().min(0).max(1).optional(), + /** + * How much to prioritize intelligence and capabilities when selecting a model. + */ + intelligencePriority: number2().min(0).max(1).optional() +}); +var ToolChoiceSchema = object2({ + /** + * Controls when tools are used: + * - "auto": Model decides whether to use tools (default) + * - "required": Model MUST use at least one tool before completing + * - "none": Model MUST NOT use any tools + */ + mode: _enum(["auto", "required", "none"]).optional() +}); +var ToolResultContentSchema = object2({ + type: literal("tool_result"), + toolUseId: string2().describe("The unique identifier for the corresponding tool call."), + content: array(ContentBlockSchema).default([]), + structuredContent: object2({}).loose().optional(), + isError: boolean2().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]); +var SamplingMessageContentBlockSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema +]); +var SamplingMessageSchema = object2({ + role: RoleSchema, + content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + messages: array(SamplingMessageSchema), + /** + * The server's preferences for which model to select. The client MAY modify or omit this request. + */ + modelPreferences: ModelPreferencesSchema.optional(), + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt: string2().optional(), + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client + * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + */ + includeContext: _enum(["none", "thisServer", "allServers"]).optional(), + temperature: number2().optional(), + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: number2().int(), + stopSequences: array(string2()).optional(), + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata: AssertObjectSchema.optional(), + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + */ + tools: array(ToolSchema).optional(), + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice: ToolChoiceSchema.optional() +}); +var CreateMessageRequestSchema = RequestSchema.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema +}); +var CreateMessageResultSchema = ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: string2(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens"]).or(string2())), + role: RoleSchema, + /** + * Response content. Single content block (text, image, or audio). + */ + content: SamplingContentSchema +}); +var CreateMessageResultWithToolsSchema = ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: string2(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * - "toolUse": The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())), + role: RoleSchema, + /** + * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse". + */ + content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]) +}); +var BooleanSchemaSchema = object2({ + type: literal("boolean"), + title: string2().optional(), + description: string2().optional(), + default: boolean2().optional() +}); +var StringSchemaSchema = object2({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + minLength: number2().optional(), + maxLength: number2().optional(), + format: _enum(["email", "uri", "date", "date-time"]).optional(), + default: string2().optional() +}); +var NumberSchemaSchema = object2({ + type: _enum(["number", "integer"]), + title: string2().optional(), + description: string2().optional(), + minimum: number2().optional(), + maximum: number2().optional(), + default: number2().optional() +}); +var UntitledSingleSelectEnumSchemaSchema = object2({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + default: string2().optional() +}); +var TitledSingleSelectEnumSchemaSchema = object2({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + oneOf: array(object2({ + const: string2(), + title: string2() + })), + default: string2().optional() +}); +var LegacyTitledEnumSchemaSchema = object2({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + enumNames: array(string2()).optional(), + default: string2().optional() +}); +var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); +var UntitledMultiSelectEnumSchemaSchema = object2({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object2({ + type: literal("string"), + enum: array(string2()) + }), + default: array(string2()).optional() +}); +var TitledMultiSelectEnumSchemaSchema = object2({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object2({ + anyOf: array(object2({ + const: string2(), + title: string2() + })) + }), + default: array(string2()).optional() +}); +var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); +var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); +var PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); +var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + * + * Optional for backward compatibility. Clients MUST treat missing mode as "form". + */ + mode: literal("form").optional(), + /** + * The message to present to the user describing what information is being requested. + */ + message: string2(), + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: object2({ + type: literal("object"), + properties: record(string2(), PrimitiveSchemaDefinitionSchema), + required: array(string2()).optional() + }) +}); +var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + */ + mode: literal("url"), + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: string2(), + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: string2(), + /** + * The URL that the user should navigate to. + */ + url: string2().url() +}); +var ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); +var ElicitRequestSchema = RequestSchema.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema +}); +var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the elicitation that completed. + */ + elicitationId: string2() +}); +var ElicitationCompleteNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema +}); +var ElicitResultSchema = ResultSchema.extend({ + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: _enum(["accept", "decline", "cancel"]), + /** + * The submitted form data, only present when action is "accept". + * Contains values matching the requested schema. + * Per MCP spec, content is "typically omitted" for decline/cancel actions. + * We normalize null to undefined for leniency while maintaining type compatibility. + */ + content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional()) +}); +var ResourceTemplateReferenceSchema = object2({ + type: literal("ref/resource"), + /** + * The URI or URI template of the resource. + */ + uri: string2() +}); +var PromptReferenceSchema = object2({ + type: literal("ref/prompt"), + /** + * The name of the prompt or prompt template + */ + name: string2() +}); +var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + /** + * The argument's information + */ + argument: object2({ + /** + * The name of the argument + */ + name: string2(), + /** + * The value of the argument to use for completion matching. + */ + value: string2() + }), + context: object2({ + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments: record(string2(), string2()).optional() + }).optional() +}); +var CompleteRequestSchema = RequestSchema.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema +}); +function assertCompleteRequestPrompt(request) { + if (request.params.ref.type !== "ref/prompt") { + throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); + } + void request; +} +function assertCompleteRequestResourceTemplate(request) { + if (request.params.ref.type !== "ref/resource") { + throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); } - const gen = new JSONSchemaGenerator(_params); - gen.process(input); - return gen.emit(input, _params); + void request; } -function isTransforming(_schema, _ctx) { - const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; - if (ctx.seen.has(_schema)) - return false; - ctx.seen.add(_schema); - const schema2 = _schema; - const def = schema2._zod.def; - switch (def.type) { - case "string": - case "number": - case "bigint": - case "boolean": - case "date": - case "symbol": - case "undefined": - case "null": - case "any": - case "unknown": - case "never": - case "void": - case "literal": - case "enum": - case "nan": - case "file": - case "template_literal": - return false; - case "array": { - return isTransforming(def.element, ctx); - } - case "object": { - for (const key in def.shape) { - if (isTransforming(def.shape[key], ctx)) - return true; - } - return false; - } - case "union": { - for (const option of def.options) { - if (isTransforming(option, ctx)) - return true; - } - return false; - } - case "intersection": { - return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); - } - case "tuple": { - for (const item of def.items) { - if (isTransforming(item, ctx)) - return true; - } - if (def.rest && isTransforming(def.rest, ctx)) - return true; - return false; - } - case "record": { - return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); - } - case "map": { - return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); - } - case "set": { - return isTransforming(def.valueType, ctx); - } - // inner types - case "promise": - case "optional": - case "nonoptional": - case "nullable": - case "readonly": - return isTransforming(def.innerType, ctx); - case "lazy": - return isTransforming(def.getter(), ctx); - case "default": { - return isTransforming(def.innerType, ctx); - } - case "prefault": { - return isTransforming(def.innerType, ctx); - } - case "custom": { - return false; - } - case "transform": { - return true; - } - case "pipe": { - return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); - } - case "success": { - return false; - } - case "catch": { - return false; +var CompleteResultSchema = ResultSchema.extend({ + completion: looseObject({ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: array(string2()).max(100), + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: optional(number2().int()), + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: optional(boolean2()) + }) +}); +var RootSchema = object2({ + /** + * The URI identifying the root. This *must* start with file:// for now. + */ + uri: string2().startsWith("file://"), + /** + * An optional name for the root. + */ + name: string2().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var ListRootsRequestSchema = RequestSchema.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema.optional() +}); +var ListRootsResultSchema = ResultSchema.extend({ + roots: array(RootSchema) +}); +var RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema.optional() +}); +var ClientRequestSchema = union([ + PingRequestSchema, + InitializeRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema, + GetTaskRequestSchema, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + CancelTaskRequestSchema +]); +var ClientNotificationSchema = union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + InitializedNotificationSchema, + RootsListChangedNotificationSchema, + TaskStatusNotificationSchema +]); +var ClientResultSchema = union([ + EmptyResultSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + ElicitResultSchema, + ListRootsResultSchema, + GetTaskResultSchema, + ListTasksResultSchema, + CreateTaskResultSchema +]); +var ServerRequestSchema = union([ + PingRequestSchema, + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema, + GetTaskRequestSchema, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + CancelTaskRequestSchema +]); +var ServerNotificationSchema = union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + TaskStatusNotificationSchema, + ElicitationCompleteNotificationSchema +]); +var ServerResultSchema = union([ + EmptyResultSchema, + InitializeResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + CallToolResultSchema, + ListToolsResultSchema, + GetTaskResultSchema, + ListTasksResultSchema, + CreateTaskResultSchema +]); +var McpError = class _McpError extends Error { + constructor(code, message, data) { + super(`MCP error ${code}: ${message}`); + this.code = code; + this.data = data; + this.name = "McpError"; + } + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code, message, data) { + if (code === ErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) { + return new UrlElicitationRequiredError(errorData.elicitations, message); + } } - default: - def; + return new _McpError(code, message, data); } - throw new Error(`Unknown schema type: ${def.type}`); +}; +var UrlElicitationRequiredError = class extends McpError { + constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { + super(ErrorCode.UrlElicitationRequired, message, { + elicitations + }); + } + get elicitations() { + return this.data?.elicitations ?? []; + } +}; + +// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js +function isTerminal(status) { + return status === "completed" || status === "failed" || status === "cancelled"; } -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/mini/schemas.js -var ZodMiniType = /* @__PURE__ */ $constructor("ZodMiniType", (inst, def) => { - if (!inst._zod) - throw new Error("Uninitialized schema in ZodMiniType."); - $ZodType.init(inst, def); - inst.def = def; - inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params); - inst.check = (...checks) => { - return inst.clone( +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/Options.js +var ignoreOverride = /* @__PURE__ */ Symbol("Let zodToJsonSchema decide on which parser to use"); +var defaultOptions = { + name: void 0, + $refStrategy: "root", + basePath: ["#"], + effectStrategy: "input", + pipeStrategy: "all", + dateStrategy: "format:date-time", + mapStrategy: "entries", + removeAdditionalStrategy: "passthrough", + allowedAdditionalProperties: true, + rejectedAdditionalProperties: false, + definitionPath: "definitions", + target: "jsonSchema7", + strictUnions: false, + definitions: {}, + errorMessages: false, + markdownDescription: false, + patternStrategy: "escape", + applyRegexFlags: false, + emailStrategy: "format:email", + base64Strategy: "contentEncoding:base64", + nameStrategy: "ref", + openAiAnyTypeName: "OpenAiAnyType" +}; +var getDefaultOptions = (options) => typeof options === "string" ? { + ...defaultOptions, + name: options +} : { + ...defaultOptions, + ...options +}; + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/Refs.js +var getRefs = (options) => { + const _options = getDefaultOptions(options); + const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; + return { + ..._options, + flags: { hasReferencedOpenAiAnyType: false }, + currentPath, + propertyPath: void 0, + seen: new Map(Object.entries(_options.definitions).map(([name315, def]) => [ + def._def, { - ...def, - checks: [ - ...def.checks ?? [], - ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) - ] + def: def._def, + path: [..._options.basePath, _options.definitionPath, name315], + // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. + jsonSchema: void 0 } - // { parent: true } - ); - }; - inst.clone = (_def, params) => clone(inst, _def, params); - inst.brand = () => inst; - inst.register = ((reg, meta) => { - reg.add(inst, meta); - return inst; - }); -}); -var ZodMiniObject = /* @__PURE__ */ $constructor("ZodMiniObject", (inst, def) => { - $ZodObject.init(inst, def); - ZodMiniType.init(inst, def); - util_exports.defineLazy(inst, "shape", () => def.shape); -}); -function object(shape, params) { - const def = { - type: "object", - get shape() { - util_exports.assignProp(this, "shape", { ...shape }); - return this.shape; - }, - ...util_exports.normalizeParams(params) + ])) }; - return new ZodMiniObject(def); -} +}; -// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js -function isZ4Schema(s) { - const schema2 = s; - return !!schema2._zod; +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/errorMessages.js +function addErrorMessage(res, key, errorMessage, refs) { + if (!refs?.errorMessages) + return; + if (errorMessage) { + res.errorMessage = { + ...res.errorMessage, + [key]: errorMessage + }; + } } -function objectFromShape(shape) { - const values = Object.values(shape); - if (values.length === 0) - return object({}); - const allV4 = values.every(isZ4Schema); - const allV3 = values.every((s) => !isZ4Schema(s)); - if (allV4) - return object(shape); - if (allV3) - return objectType(shape); - throw new Error("Mixed Zod versions detected in object shape."); +function setResponseValueAndErrors(res, key, value, errorMessage, refs) { + res[key] = value; + addErrorMessage(res, key, errorMessage, refs); } -function safeParse2(schema2, data) { - if (isZ4Schema(schema2)) { - const result2 = safeParse(schema2, data); - return result2; + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js +var getRelativePath = (pathA, pathB) => { + let i2 = 0; + for (; i2 < pathA.length && i2 < pathB.length; i2++) { + if (pathA[i2] !== pathB[i2]) + break; } - const v3Schema = schema2; - const result = v3Schema.safeParse(data); - return result; -} -async function safeParseAsync2(schema2, data) { - if (isZ4Schema(schema2)) { - const result2 = await safeParseAsync(schema2, data); - return result2; + return [(pathA.length - i2).toString(), ...pathB.slice(i2)].join("/"); +}; + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/any.js +function parseAnyDef(refs) { + if (refs.target !== "openAi") { + return {}; } - const v3Schema = schema2; - const result = await v3Schema.safeParseAsync(data); - return result; + const anyDefinitionPath = [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName + ]; + refs.flags.hasReferencedOpenAiAnyType = true; + return { + $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/") + }; } -function getObjectShape(schema2) { - if (!schema2) - return void 0; - let rawShape; - if (isZ4Schema(schema2)) { - const v4Schema = schema2; - rawShape = v4Schema._zod?.def?.shape; - } else { - const v3Schema = schema2; - rawShape = v3Schema.shape; + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/array.js +function parseArrayDef(def, refs) { + const res = { + type: "array" + }; + if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) { + res.items = parseDef(def.type._def, { + ...refs, + currentPath: [...refs.currentPath, "items"] + }); } - if (!rawShape) - return void 0; - if (typeof rawShape === "function") { - try { - return rawShape(); - } catch { - return void 0; - } + if (def.minLength) { + setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); } - return rawShape; -} -function normalizeObjectSchema(schema2) { - if (!schema2) - return void 0; - if (typeof schema2 === "object") { - const asV3 = schema2; - const asV4 = schema2; - if (!asV3._def && !asV4._zod) { - const values = Object.values(schema2); - if (values.length > 0 && values.every((v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function"))) { - return objectFromShape(schema2); - } - } + if (def.maxLength) { + setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); } - if (isZ4Schema(schema2)) { - const v4Schema = schema2; - const def = v4Schema._zod?.def; - if (def && (def.type === "object" || def.shape !== void 0)) { - return schema2; - } - } else { - const v3Schema = schema2; - if (v3Schema.shape !== void 0) { - return schema2; - } + if (def.exactLength) { + setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); + setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); } - return void 0; + return res; } -function getParseErrorMessage(error2) { - if (error2 && typeof error2 === "object") { - if ("message" in error2 && typeof error2.message === "string") { - return error2.message; - } - if ("issues" in error2 && Array.isArray(error2.issues) && error2.issues.length > 0) { - const firstIssue = error2.issues[0]; - if (firstIssue && typeof firstIssue === "object" && "message" in firstIssue) { - return String(firstIssue.message); - } - } - try { - return JSON.stringify(error2); - } catch { - return String(error2); + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js +function parseBigintDef(def, refs) { + const res = { + type: "integer", + format: "int64" + }; + if (!def.checks) + return res; + for (const check2 of def.checks) { + switch (check2.kind) { + case "min": + if (refs.target === "jsonSchema7") { + if (check2.inclusive) { + setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); + } else { + setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs); + } + } else { + if (!check2.inclusive) { + res.exclusiveMinimum = true; + } + setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") { + if (check2.inclusive) { + setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); + } else { + setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs); + } + } else { + if (!check2.inclusive) { + res.exclusiveMaximum = true; + } + setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); + } + break; + case "multipleOf": + setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs); + break; } } - return String(error2); + return res; } -function getSchemaDescription(schema2) { - return schema2.description; + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js +function parseBooleanDef() { + return { + type: "boolean" + }; } -function isSchemaOptional(schema2) { - if (isZ4Schema(schema2)) { - const v4Schema = schema2; - return v4Schema._zod?.def?.type === "optional"; + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js +function parseBrandedDef(_def, refs) { + return parseDef(_def.type._def, refs); +} + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js +var parseCatchDef = (def, refs) => { + return parseDef(def.innerType._def, refs); +}; + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/date.js +function parseDateDef(def, refs, overrideDateStrategy) { + const strategy = overrideDateStrategy ?? refs.dateStrategy; + if (Array.isArray(strategy)) { + return { + anyOf: strategy.map((item, i2) => parseDateDef(def, refs, item)) + }; } - const v3Schema = schema2; - if (typeof schema2.isOptional === "function") { - return schema2.isOptional(); + switch (strategy) { + case "string": + case "format:date-time": + return { + type: "string", + format: "date-time" + }; + case "format:date": + return { + type: "string", + format: "date" + }; + case "integer": + return integerDateParser(def, refs); } - return v3Schema._def?.typeName === "ZodOptional"; } -function getLiteralValue(schema2) { - if (isZ4Schema(schema2)) { - const v4Schema = schema2; - const def2 = v4Schema._zod?.def; - if (def2) { - if (def2.value !== void 0) - return def2.value; - if (Array.isArray(def2.values) && def2.values.length > 0) { - return def2.values[0]; - } - } +var integerDateParser = (def, refs) => { + const res = { + type: "integer", + format: "unix-time" + }; + if (refs.target === "openApi3") { + return res; } - const v3Schema = schema2; - const def = v3Schema._def; - if (def) { - if (def.value !== void 0) - return def.value; - if (Array.isArray(def.values) && def.values.length > 0) { - return def.values[0]; + for (const check2 of def.checks) { + switch (check2.kind) { + case "min": + setResponseValueAndErrors( + res, + "minimum", + check2.value, + // This is in milliseconds + check2.message, + refs + ); + break; + case "max": + setResponseValueAndErrors( + res, + "maximum", + check2.value, + // This is in milliseconds + check2.message, + refs + ); + break; } } - const directValue = schema2.value; - if (directValue !== void 0) - return directValue; - return void 0; -} + return res; +}; -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/iso.js -var iso_exports2 = {}; -__export(iso_exports2, { - ZodISODate: () => ZodISODate, - ZodISODateTime: () => ZodISODateTime, - ZodISODuration: () => ZodISODuration, - ZodISOTime: () => ZodISOTime, - date: () => date2, - datetime: () => datetime2, - duration: () => duration2, - time: () => time2 -}); -var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function datetime2(params) { - return _isoDateTime(ZodISODateTime, params); -} -var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function date2(params) { - return _isoDate(ZodISODate, params); -} -var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function time2(params) { - return _isoTime(ZodISOTime, params); -} -var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function duration2(params) { - return _isoDuration(ZodISODuration, params); +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/default.js +function parseDefaultDef(_def, refs) { + return { + ...parseDef(_def.innerType._def, refs), + default: _def.defaultValue() + }; } -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/errors.js -var initializer2 = (inst, issues) => { - $ZodError.init(inst, issues); - inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError(inst, mapper) - // enumerable: false, - }, - flatten: { - value: (mapper) => flattenError(inst, mapper) - // enumerable: false, - }, - addIssue: { - value: (issue2) => inst.issues.push(issue2) - // enumerable: false, - }, - addIssues: { - value: (issues2) => inst.issues.push(...issues2) - // enumerable: false, - }, - isEmpty: { - get() { - return inst.issues.length === 0; - } - // enumerable: false, - } - }); -}; -var ZodError2 = $constructor("ZodError", initializer2); -var ZodRealError = $constructor("ZodError", initializer2, { - Parent: Error -}); - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/parse.js -var parse2 = /* @__PURE__ */ _parse(ZodRealError); -var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); -var safeParse3 = /* @__PURE__ */ _safeParse(ZodRealError); -var safeParseAsync3 = /* @__PURE__ */ _safeParseAsync(ZodRealError); +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js +function parseEffectsDef(_def, refs) { + return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs); +} -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/schemas.js -var ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { - $ZodType.init(inst, def); - inst.def = def; - Object.defineProperty(inst, "_def", { value: def }); - inst.check = (...checks) => { - return inst.clone( - { - ...def, - checks: [ - ...def.checks ?? [], - ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) - ] - } - // { parent: true } - ); +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js +function parseEnumDef(def) { + return { + type: "string", + enum: Array.from(def.values) }; - inst.clone = (def2, params) => clone(inst, def2, params); - inst.brand = () => inst; - inst.register = ((reg, meta) => { - reg.add(inst, meta); - return inst; +} + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js +var isJsonSchema7AllOfType = (type2) => { + if ("type" in type2 && type2.type === "string") + return false; + return "allOf" in type2; +}; +function parseIntersectionDef(def, refs) { + const allOf = [ + parseDef(def.left._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "0"] + }), + parseDef(def.right._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "1"] + }) + ].filter((x) => !!x); + let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0; + const mergedAllOf = []; + allOf.forEach((schema2) => { + if (isJsonSchema7AllOfType(schema2)) { + mergedAllOf.push(...schema2.allOf); + if (schema2.unevaluatedProperties === void 0) { + unevaluatedProperties = void 0; + } + } else { + let nestedSchema = schema2; + if ("additionalProperties" in schema2 && schema2.additionalProperties === false) { + const { additionalProperties, ...rest } = schema2; + nestedSchema = rest; + } else { + unevaluatedProperties = void 0; + } + mergedAllOf.push(nestedSchema); + } }); - inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => safeParse3(inst, data, params); - inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => safeParseAsync3(inst, data, params); - inst.spa = inst.safeParseAsync; - inst.refine = (check2, params) => inst.check(refine(check2, params)); - inst.superRefine = (refinement) => inst.check(superRefine(refinement)); - inst.overwrite = (fn) => inst.check(_overwrite(fn)); - inst.optional = () => optional(inst); - inst.nullable = () => nullable(inst); - inst.nullish = () => optional(nullable(inst)); - inst.nonoptional = (params) => nonoptional(inst, params); - inst.array = () => array(inst); - inst.or = (arg2) => union([inst, arg2]); - inst.and = (arg2) => intersection(inst, arg2); - inst.transform = (tx) => pipe(inst, transform(tx)); - inst.default = (def2) => _default(inst, def2); - inst.prefault = (def2) => prefault(inst, def2); - inst.catch = (params) => _catch(inst, params); - inst.pipe = (target) => pipe(inst, target); - inst.readonly = () => readonly(inst); - inst.describe = (description) => { - const cl = inst.clone(); - globalRegistry.add(cl, { description }); - return cl; + return mergedAllOf.length ? { + allOf: mergedAllOf, + ...unevaluatedProperties + } : void 0; +} + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js +function parseLiteralDef(def, refs) { + const parsedType2 = typeof def.value; + if (parsedType2 !== "bigint" && parsedType2 !== "number" && parsedType2 !== "boolean" && parsedType2 !== "string") { + return { + type: Array.isArray(def.value) ? "array" : "object" + }; + } + if (refs.target === "openApi3") { + return { + type: parsedType2 === "bigint" ? "integer" : parsedType2, + enum: [def.value] + }; + } + return { + type: parsedType2 === "bigint" ? "integer" : parsedType2, + const: def.value }; - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true - }); - inst.meta = (...args) => { - if (args.length === 0) { - return globalRegistry.get(inst); +} + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/string.js +var emojiRegex2 = void 0; +var zodPatterns = { + /** + * `c` was changed to `[cC]` to replicate /i flag + */ + cuid: /^[cC][^\s-]{8,}$/, + cuid2: /^[0-9a-z]+$/, + ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, + /** + * `a-z` was added to replicate /i flag + */ + email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, + /** + * Constructed a valid Unicode RegExp + * + * Lazily instantiate since this type of regex isn't supported + * in all envs (e.g. React Native). + * + * See: + * https://github.com/colinhacks/zod/issues/2433 + * Fix in Zod: + * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b + */ + emoji: () => { + if (emojiRegex2 === void 0) { + emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); } - const cl = inst.clone(); - globalRegistry.add(cl, args[0]); - return cl; + return emojiRegex2; + }, + /** + * Unused + */ + uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, + /** + * Unused + */ + 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])$/, + ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, + /** + * Unused + */ + ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, + ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, + base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, + base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, + nanoid: /^[a-zA-Z0-9_-]{21}$/, + jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ +}; +function parseStringDef(def, refs) { + const res = { + type: "string" }; - inst.isOptional = () => inst.safeParse(void 0).success; - inst.isNullable = () => inst.safeParse(null).success; - return inst; -}); -var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType2.init(inst, def); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - inst.regex = (...args) => inst.check(_regex(...args)); - inst.includes = (...args) => inst.check(_includes(...args)); - inst.startsWith = (...args) => inst.check(_startsWith(...args)); - inst.endsWith = (...args) => inst.check(_endsWith(...args)); - inst.min = (...args) => inst.check(_minLength(...args)); - inst.max = (...args) => inst.check(_maxLength(...args)); - inst.length = (...args) => inst.check(_length(...args)); - inst.nonempty = (...args) => inst.check(_minLength(1, ...args)); - inst.lowercase = (params) => inst.check(_lowercase(params)); - inst.uppercase = (params) => inst.check(_uppercase(params)); - inst.trim = () => inst.check(_trim()); - inst.normalize = (...args) => inst.check(_normalize(...args)); - inst.toLowerCase = () => inst.check(_toLowerCase()); - inst.toUpperCase = () => inst.check(_toUpperCase()); -}); -var ZodString2 = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { - $ZodString.init(inst, def); - _ZodString.init(inst, def); - inst.email = (params) => inst.check(_email(ZodEmail, params)); - inst.url = (params) => inst.check(_url(ZodURL, params)); - inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(_xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(_e164(ZodE164, params)); - inst.datetime = (params) => inst.check(datetime2(params)); - inst.date = (params) => inst.check(date2(params)); - inst.time = (params) => inst.check(time2(params)); - inst.duration = (params) => inst.check(duration2(params)); -}); -function string2(params) { - return _string(ZodString2, params); -} -var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - _ZodString.init(inst, def); -}); -var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { - $ZodEmail.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { - $ZodGUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { - $ZodUUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { - $ZodURL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => { - $ZodEmoji.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => { - $ZodNanoID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => { - $ZodCUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => { - $ZodCUID2.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => { - $ZodULID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => { - $ZodXID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => { - $ZodKSUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => { - $ZodIPv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => { - $ZodIPv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => { - $ZodCIDRv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => { - $ZodCIDRv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { - $ZodBase64.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { - $ZodBase64URL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { - $ZodE164.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { - $ZodJWT.init(inst, def); - ZodStringFormat.init(inst, def); -}); -var ZodNumber2 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType2.init(inst, def); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.int = (params) => inst.check(int(params)); - inst.safe = (params) => inst.check(int(params)); - inst.positive = (params) => inst.check(_gt(0, params)); - inst.nonnegative = (params) => inst.check(_gte(0, params)); - inst.negative = (params) => inst.check(_lt(0, params)); - inst.nonpositive = (params) => inst.check(_lte(0, params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - inst.step = (value, params) => inst.check(_multipleOf(value, params)); - inst.finite = () => inst; - const bag = inst._zod.bag; - inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}); -function number2(params) { - return _number(ZodNumber2, params); -} -var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { - $ZodNumberFormat.init(inst, def); - ZodNumber2.init(inst, def); -}); -function int(params) { - return _int(ZodNumberFormat, params); -} -var ZodBoolean2 = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { - $ZodBoolean.init(inst, def); - ZodType2.init(inst, def); -}); -function boolean2(params) { - return _boolean(ZodBoolean2, params); + if (def.checks) { + for (const check2 of def.checks) { + switch (check2.kind) { + case "min": + setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs); + break; + case "max": + setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs); + break; + case "email": + switch (refs.emailStrategy) { + case "format:email": + addFormat(res, "email", check2.message, refs); + break; + case "format:idn-email": + addFormat(res, "idn-email", check2.message, refs); + break; + case "pattern:zod": + addPattern(res, zodPatterns.email, check2.message, refs); + break; + } + break; + case "url": + addFormat(res, "uri", check2.message, refs); + break; + case "uuid": + addFormat(res, "uuid", check2.message, refs); + break; + case "regex": + addPattern(res, check2.regex, check2.message, refs); + break; + case "cuid": + addPattern(res, zodPatterns.cuid, check2.message, refs); + break; + case "cuid2": + addPattern(res, zodPatterns.cuid2, check2.message, refs); + break; + case "startsWith": + addPattern(res, RegExp(`^${escapeLiteralCheckValue(check2.value, refs)}`), check2.message, refs); + break; + case "endsWith": + addPattern(res, RegExp(`${escapeLiteralCheckValue(check2.value, refs)}$`), check2.message, refs); + break; + case "datetime": + addFormat(res, "date-time", check2.message, refs); + break; + case "date": + addFormat(res, "date", check2.message, refs); + break; + case "time": + addFormat(res, "time", check2.message, refs); + break; + case "duration": + addFormat(res, "duration", check2.message, refs); + break; + case "length": + setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs); + setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs); + break; + case "includes": { + addPattern(res, RegExp(escapeLiteralCheckValue(check2.value, refs)), check2.message, refs); + break; + } + case "ip": { + if (check2.version !== "v6") { + addFormat(res, "ipv4", check2.message, refs); + } + if (check2.version !== "v4") { + addFormat(res, "ipv6", check2.message, refs); + } + break; + } + case "base64url": + addPattern(res, zodPatterns.base64url, check2.message, refs); + break; + case "jwt": + addPattern(res, zodPatterns.jwt, check2.message, refs); + break; + case "cidr": { + if (check2.version !== "v6") { + addPattern(res, zodPatterns.ipv4Cidr, check2.message, refs); + } + if (check2.version !== "v4") { + addPattern(res, zodPatterns.ipv6Cidr, check2.message, refs); + } + break; + } + case "emoji": + addPattern(res, zodPatterns.emoji(), check2.message, refs); + break; + case "ulid": { + addPattern(res, zodPatterns.ulid, check2.message, refs); + break; + } + case "base64": { + switch (refs.base64Strategy) { + case "format:binary": { + addFormat(res, "binary", check2.message, refs); + break; + } + case "contentEncoding:base64": { + setResponseValueAndErrors(res, "contentEncoding", "base64", check2.message, refs); + break; + } + case "pattern:zod": { + addPattern(res, zodPatterns.base64, check2.message, refs); + break; + } + } + break; + } + case "nanoid": { + addPattern(res, zodPatterns.nanoid, check2.message, refs); + } + case "toLowerCase": + case "toUpperCase": + case "trim": + break; + default: + /* @__PURE__ */ ((_) => { + })(check2); + } + } + } + return res; } -var ZodNull2 = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { - $ZodNull.init(inst, def); - ZodType2.init(inst, def); -}); -function _null3(params) { - return _null2(ZodNull2, params); +function escapeLiteralCheckValue(literal2, refs) { + return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal2) : literal2; } -var ZodUnknown2 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { - $ZodUnknown.init(inst, def); - ZodType2.init(inst, def); -}); -function unknown() { - return _unknown(ZodUnknown2); +var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); +function escapeNonAlphaNumeric(source) { + let result = ""; + for (let i2 = 0; i2 < source.length; i2++) { + if (!ALPHA_NUMERIC.has(source[i2])) { + result += "\\"; + } + result += source[i2]; + } + return result; } -var ZodNever2 = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { - $ZodNever.init(inst, def); - ZodType2.init(inst, def); -}); -function never(params) { - return _never(ZodNever2, params); +function addFormat(schema2, value, message, refs) { + if (schema2.format || schema2.anyOf?.some((x) => x.format)) { + if (!schema2.anyOf) { + schema2.anyOf = []; + } + if (schema2.format) { + schema2.anyOf.push({ + format: schema2.format, + ...schema2.errorMessage && refs.errorMessages && { + errorMessage: { format: schema2.errorMessage.format } + } + }); + delete schema2.format; + if (schema2.errorMessage) { + delete schema2.errorMessage.format; + if (Object.keys(schema2.errorMessage).length === 0) { + delete schema2.errorMessage; + } + } + } + schema2.anyOf.push({ + format: value, + ...message && refs.errorMessages && { errorMessage: { format: message } } + }); + } else { + setResponseValueAndErrors(schema2, "format", value, message, refs); + } } -var ZodArray2 = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { - $ZodArray.init(inst, def); - ZodType2.init(inst, def); - inst.element = def.element; - inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); - inst.nonempty = (params) => inst.check(_minLength(1, params)); - inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); - inst.length = (len, params) => inst.check(_length(len, params)); - inst.unwrap = () => inst.element; -}); -function array(element, params) { - return _array(ZodArray2, element, params); +function addPattern(schema2, regex, message, refs) { + if (schema2.pattern || schema2.allOf?.some((x) => x.pattern)) { + if (!schema2.allOf) { + schema2.allOf = []; + } + if (schema2.pattern) { + schema2.allOf.push({ + pattern: schema2.pattern, + ...schema2.errorMessage && refs.errorMessages && { + errorMessage: { pattern: schema2.errorMessage.pattern } + } + }); + delete schema2.pattern; + if (schema2.errorMessage) { + delete schema2.errorMessage.pattern; + if (Object.keys(schema2.errorMessage).length === 0) { + delete schema2.errorMessage; + } + } + } + schema2.allOf.push({ + pattern: stringifyRegExpWithFlags(regex, refs), + ...message && refs.errorMessages && { errorMessage: { pattern: message } } + }); + } else { + setResponseValueAndErrors(schema2, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); + } } -var ZodObject2 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { - $ZodObject.init(inst, def); - ZodType2.init(inst, def); - util_exports.defineLazy(inst, "shape", () => def.shape); - inst.keyof = () => _enum(Object.keys(inst._zod.def.shape)); - inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall }); - inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); - inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); - inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); - inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 }); - inst.extend = (incoming) => { - return util_exports.extend(inst, incoming); - }; - inst.merge = (other) => util_exports.merge(inst, other); - inst.pick = (mask) => util_exports.pick(inst, mask); - inst.omit = (mask) => util_exports.omit(inst, mask); - inst.partial = (...args) => util_exports.partial(ZodOptional2, inst, args[0]); - inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]); -}); -function object2(shape, params) { - const def = { - type: "object", - get shape() { - util_exports.assignProp(this, "shape", { ...shape }); - return this.shape; - }, - ...util_exports.normalizeParams(params) +function stringifyRegExpWithFlags(regex, refs) { + if (!refs.applyRegexFlags || !regex.flags) { + return regex.source; + } + const flags = { + i: regex.flags.includes("i"), + m: regex.flags.includes("m"), + s: regex.flags.includes("s") + // `.` matches newlines }; - return new ZodObject2(def); + const source = flags.i ? regex.source.toLowerCase() : regex.source; + let pattern = ""; + let isEscaped = false; + let inCharGroup = false; + let inCharRange = false; + for (let i2 = 0; i2 < source.length; i2++) { + if (isEscaped) { + pattern += source[i2]; + isEscaped = false; + continue; + } + if (flags.i) { + if (inCharGroup) { + if (source[i2].match(/[a-z]/)) { + if (inCharRange) { + pattern += source[i2]; + pattern += `${source[i2 - 2]}-${source[i2]}`.toUpperCase(); + inCharRange = false; + } else if (source[i2 + 1] === "-" && source[i2 + 2]?.match(/[a-z]/)) { + pattern += source[i2]; + inCharRange = true; + } else { + pattern += `${source[i2]}${source[i2].toUpperCase()}`; + } + continue; + } + } else if (source[i2].match(/[a-z]/)) { + pattern += `[${source[i2]}${source[i2].toUpperCase()}]`; + continue; + } + } + if (flags.m) { + if (source[i2] === "^") { + pattern += `(^|(?<=[\r +]))`; + continue; + } else if (source[i2] === "$") { + pattern += `($|(?=[\r +]))`; + continue; + } + } + if (flags.s && source[i2] === ".") { + pattern += inCharGroup ? `${source[i2]}\r +` : `[${source[i2]}\r +]`; + continue; + } + pattern += source[i2]; + if (source[i2] === "\\") { + isEscaped = true; + } else if (inCharGroup && source[i2] === "]") { + inCharGroup = false; + } else if (!inCharGroup && source[i2] === "[") { + inCharGroup = true; + } + } + try { + new RegExp(pattern); + } catch { + console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); + return regex.source; + } + return pattern; } -function looseObject(shape, params) { - return new ZodObject2({ + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/record.js +function parseRecordDef(def, refs) { + if (refs.target === "openAi") { + console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); + } + if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { + return { + type: "object", + required: def.keyType._def.values, + properties: def.keyType._def.values.reduce((acc, key) => ({ + ...acc, + [key]: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "properties", key] + }) ?? parseAnyDef(refs) + }), {}), + additionalProperties: refs.rejectedAdditionalProperties + }; + } + const schema2 = { type: "object", - get shape() { - util_exports.assignProp(this, "shape", { ...shape }); - return this.shape; - }, - catchall: unknown(), - ...util_exports.normalizeParams(params) - }); + additionalProperties: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }) ?? refs.allowedAdditionalProperties + }; + if (refs.target === "openApi3") { + return schema2; + } + if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { + const { type: type2, ...keyType } = parseStringDef(def.keyType._def, refs); + return { + ...schema2, + propertyNames: keyType + }; + } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { + return { + ...schema2, + propertyNames: { + enum: def.keyType._def.values + } + }; + } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) { + const { type: type2, ...keyType } = parseBrandedDef(def.keyType._def, refs); + return { + ...schema2, + propertyNames: keyType + }; + } + return schema2; } -var ZodUnion2 = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { - $ZodUnion.init(inst, def); - ZodType2.init(inst, def); - inst.options = def.options; -}); -function union(options, params) { - return new ZodUnion2({ - type: "union", - options, - ...util_exports.normalizeParams(params) - }); + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/map.js +function parseMapDef(def, refs) { + if (refs.mapStrategy === "record") { + return parseRecordDef(def, refs); + } + const keys = parseDef(def.keyType._def, { + ...refs, + currentPath: [...refs.currentPath, "items", "items", "0"] + }) || parseAnyDef(refs); + const values = parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items", "items", "1"] + }) || parseAnyDef(refs); + return { + type: "array", + maxItems: 125, + items: { + type: "array", + items: [keys, values], + minItems: 2, + maxItems: 2 + } + }; } -var ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { - ZodUnion2.init(inst, def); - $ZodDiscriminatedUnion.init(inst, def); -}); -function discriminatedUnion(discriminator, options, params) { - return new ZodDiscriminatedUnion2({ - type: "union", - options, - discriminator, - ...util_exports.normalizeParams(params) + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js +function parseNativeEnumDef(def) { + const object3 = def.values; + const actualKeys = Object.keys(def.values).filter((key) => { + return typeof object3[object3[key]] !== "number"; }); + const actualValues = actualKeys.map((key) => object3[key]); + const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); + return { + type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], + enum: actualValues + }; } -var ZodIntersection2 = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { - $ZodIntersection.init(inst, def); - ZodType2.init(inst, def); -}); -function intersection(left, right) { - return new ZodIntersection2({ - type: "intersection", - left, - right - }); + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/never.js +function parseNeverDef(refs) { + return refs.target === "openAi" ? void 0 : { + not: parseAnyDef({ + ...refs, + currentPath: [...refs.currentPath, "not"] + }) + }; } -var ZodRecord2 = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { - $ZodRecord.init(inst, def); - ZodType2.init(inst, def); - inst.keyType = def.keyType; - inst.valueType = def.valueType; -}); -function record(keyType, valueType, params) { - return new ZodRecord2({ - type: "record", - keyType, - valueType, - ...util_exports.normalizeParams(params) - }); + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/null.js +function parseNullDef(refs) { + return refs.target === "openApi3" ? { + enum: ["null"], + nullable: true + } : { + type: "null" + }; } -var ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { - $ZodEnum.init(inst, def); - ZodType2.init(inst, def); - inst.enum = def.entries; - inst.options = Object.values(def.entries); - const keys = new Set(Object.keys(def.entries)); - inst.extract = (values, params) => { - const newEntries = {}; - for (const value of values) { - if (keys.has(value)) { - newEntries[value] = def.entries[value]; - } else - throw new Error(`Key ${value} not found in enum`); + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/union.js +var primitiveMappings = { + ZodString: "string", + ZodNumber: "number", + ZodBigInt: "integer", + ZodBoolean: "boolean", + ZodNull: "null" +}; +function parseUnionDef(def, refs) { + if (refs.target === "openApi3") + return asAnyOf(def, refs); + const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; + if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) { + const types = options.reduce((types2, x) => { + const type2 = primitiveMappings[x._def.typeName]; + return type2 && !types2.includes(type2) ? [...types2, type2] : types2; + }, []); + return { + type: types.length > 1 ? types : types[0] + }; + } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { + const types = options.reduce((acc, x) => { + const type2 = typeof x._def.value; + switch (type2) { + case "string": + case "number": + case "boolean": + return [...acc, type2]; + case "bigint": + return [...acc, "integer"]; + case "object": + if (x._def.value === null) + return [...acc, "null"]; + case "symbol": + case "undefined": + case "function": + default: + return acc; + } + }, []); + if (types.length === options.length) { + const uniqueTypes = types.filter((x, i2, a) => a.indexOf(x) === i2); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], + enum: options.reduce((acc, x) => { + return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; + }, []) + }; } - return new ZodEnum2({ - ...def, - checks: [], - ...util_exports.normalizeParams(params), - entries: newEntries - }); - }; - inst.exclude = (values, params) => { - const newEntries = { ...def.entries }; - for (const value of values) { - if (keys.has(value)) { - delete newEntries[value]; - } else - throw new Error(`Key ${value} not found in enum`); + } else if (options.every((x) => x._def.typeName === "ZodEnum")) { + return { + type: "string", + enum: options.reduce((acc, x) => [ + ...acc, + ...x._def.values.filter((x2) => !acc.includes(x2)) + ], []) + }; + } + return asAnyOf(def, refs); +} +var asAnyOf = (def, refs) => { + const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i2) => parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", `${i2}`] + })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)); + return anyOf.length ? { anyOf } : void 0; +}; + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js +function parseNullableDef(def, refs) { + if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { + if (refs.target === "openApi3") { + return { + type: primitiveMappings[def.innerType._def.typeName], + nullable: true + }; } - return new ZodEnum2({ - ...def, - checks: [], - ...util_exports.normalizeParams(params), - entries: newEntries + return { + type: [ + primitiveMappings[def.innerType._def.typeName], + "null" + ] + }; + } + if (refs.target === "openApi3") { + const base2 = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath] }); - }; -}); -function _enum(values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - return new ZodEnum2({ - type: "enum", - entries, - ...util_exports.normalizeParams(params) + if (base2 && "$ref" in base2) + return { allOf: [base2], nullable: true }; + return base2 && { ...base2, nullable: true }; + } + const base = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", "0"] }); + return base && { anyOf: [base, { type: "null" }] }; } -var ZodLiteral2 = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { - $ZodLiteral.init(inst, def); - ZodType2.init(inst, def); - inst.values = new Set(def.values); - Object.defineProperty(inst, "value", { - get() { - if (def.values.length > 1) { - throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); - } - return def.values[0]; + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/number.js +function parseNumberDef(def, refs) { + const res = { + type: "number" + }; + if (!def.checks) + return res; + for (const check2 of def.checks) { + switch (check2.kind) { + case "int": + res.type = "integer"; + addErrorMessage(res, "type", check2.message, refs); + break; + case "min": + if (refs.target === "jsonSchema7") { + if (check2.inclusive) { + setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); + } else { + setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs); + } + } else { + if (!check2.inclusive) { + res.exclusiveMinimum = true; + } + setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") { + if (check2.inclusive) { + setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); + } else { + setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs); + } + } else { + if (!check2.inclusive) { + res.exclusiveMaximum = true; + } + setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); + } + break; + case "multipleOf": + setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs); + break; } - }); -}); -function literal(value, params) { - return new ZodLiteral2({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...util_exports.normalizeParams(params) - }); + } + return res; } -var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { - $ZodTransform.init(inst, def); - ZodType2.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - payload.addIssue = (issue2) => { - if (typeof issue2 === "string") { - payload.issues.push(util_exports.issue(issue2, payload.value, def)); - } else { - const _issue = issue2; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = inst); - _issue.continue ?? (_issue.continue = true); - payload.issues.push(util_exports.issue(_issue)); + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/object.js +function parseObjectDef(def, refs) { + const forceOptionalIntoNullable = refs.target === "openAi"; + const result = { + type: "object", + properties: {} + }; + const required2 = []; + const shape = def.shape(); + for (const propName in shape) { + let propDef = shape[propName]; + if (propDef === void 0 || propDef._def === void 0) { + continue; + } + let propOptional = safeIsOptional(propDef); + if (propOptional && forceOptionalIntoNullable) { + if (propDef._def.typeName === "ZodOptional") { + propDef = propDef._def.innerType; } - }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output2) => { - payload.value = output2; - return payload; - }); + if (!propDef.isNullable()) { + propDef = propDef.nullable(); + } + propOptional = false; } - payload.value = output; - return payload; - }; -}); -function transform(fn) { - return new ZodTransform({ - type: "transform", - transform: fn - }); -} -var ZodOptional2 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { - $ZodOptional.init(inst, def); - ZodType2.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; -}); -function optional(innerType) { - return new ZodOptional2({ - type: "optional", - innerType - }); -} -var ZodNullable2 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { - $ZodNullable.init(inst, def); - ZodType2.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nullable(innerType) { - return new ZodNullable2({ - type: "nullable", - innerType - }); -} -var ZodDefault2 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { - $ZodDefault.init(inst, def); - ZodType2.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeDefault = inst.unwrap; -}); -function _default(innerType, defaultValue) { - return new ZodDefault2({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : defaultValue; + const parsedDef = parseDef(propDef._def, { + ...refs, + currentPath: [...refs.currentPath, "properties", propName], + propertyPath: [...refs.currentPath, "properties", propName] + }); + if (parsedDef === void 0) { + continue; } - }); -} -var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { - $ZodPrefault.init(inst, def); - ZodType2.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; -}); -function prefault(innerType, defaultValue) { - return new ZodPrefault({ - type: "prefault", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : defaultValue; + result.properties[propName] = parsedDef; + if (!propOptional) { + required2.push(propName); } - }); -} -var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { - $ZodNonOptional.init(inst, def); - ZodType2.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nonoptional(innerType, params) { - return new ZodNonOptional({ - type: "nonoptional", - innerType, - ...util_exports.normalizeParams(params) - }); + } + if (required2.length) { + result.required = required2; + } + const additionalProperties = decideAdditionalProperties(def, refs); + if (additionalProperties !== void 0) { + result.additionalProperties = additionalProperties; + } + return result; } -var ZodCatch2 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { - $ZodCatch.init(inst, def); - ZodType2.init(inst, def); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeCatch = inst.unwrap; -}); -function _catch(innerType, catchValue) { - return new ZodCatch2({ - type: "catch", - innerType, - catchValue: typeof catchValue === "function" ? catchValue : () => catchValue - }); +function decideAdditionalProperties(def, refs) { + if (def.catchall._def.typeName !== "ZodNever") { + return parseDef(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }); + } + switch (def.unknownKeys) { + case "passthrough": + return refs.allowedAdditionalProperties; + case "strict": + return refs.rejectedAdditionalProperties; + case "strip": + return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; + } } -var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { - $ZodPipe.init(inst, def); - ZodType2.init(inst, def); - inst.in = def.in; - inst.out = def.out; -}); -function pipe(in_, out) { - return new ZodPipe({ - type: "pipe", - in: in_, - out - // ...util.normalizeParams(params), - }); +function safeIsOptional(schema2) { + try { + return schema2.isOptional(); + } catch { + return true; + } } -var ZodReadonly2 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { - $ZodReadonly.init(inst, def); - ZodType2.init(inst, def); -}); -function readonly(innerType) { - return new ZodReadonly2({ - type: "readonly", - innerType + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js +var parseOptionalDef = (def, refs) => { + if (refs.currentPath.toString() === refs.propertyPath?.toString()) { + return parseDef(def.innerType._def, refs); + } + const innerSchema = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", "1"] }); -} -var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { - $ZodCustom.init(inst, def); - ZodType2.init(inst, def); -}); -function check(fn) { - const ch = new $ZodCheck({ - check: "custom" - // ...util.normalizeParams(params), + return innerSchema ? { + anyOf: [ + { + not: parseAnyDef(refs) + }, + innerSchema + ] + } : parseAnyDef(refs); +}; + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js +var parsePipelineDef = (def, refs) => { + if (refs.pipeStrategy === "input") { + return parseDef(def.in._def, refs); + } else if (refs.pipeStrategy === "output") { + return parseDef(def.out._def, refs); + } + const a = parseDef(def.in._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "0"] }); - ch._zod.check = fn; - return ch; -} -function custom2(fn, _params) { - return _custom(ZodCustom, fn ?? (() => true), _params); -} -function refine(fn, _params = {}) { - return _refine(ZodCustom, fn, _params); -} -function superRefine(fn) { - const ch = check((payload) => { - payload.addIssue = (issue2) => { - if (typeof issue2 === "string") { - payload.issues.push(util_exports.issue(issue2, payload.value, ch._zod.def)); - } else { - const _issue = issue2; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = ch); - _issue.continue ?? (_issue.continue = !ch._zod.def.abort); - payload.issues.push(util_exports.issue(_issue)); - } - }; - return fn(payload.value, payload); + const b = parseDef(def.out._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"] }); - return ch; -} -function preprocess(fn, schema2) { - return pipe(transform(fn), schema2); -} - -// node_modules/.pnpm/zod@3.25.76/node_modules/zod/v4/classic/external.js -config(en_default2()); + return { + allOf: [a, b].filter((x) => x !== void 0) + }; +}; -// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js -var LATEST_PROTOCOL_VERSION = "2025-11-25"; -var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"]; -var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; -var JSONRPC_VERSION = "2.0"; -var AssertObjectSchema = custom2((v) => v !== null && (typeof v === "object" || typeof v === "function")); -var ProgressTokenSchema = union([string2(), number2().int()]); -var CursorSchema = string2(); -var TaskCreationParamsSchema = looseObject({ - /** - * Requested duration in milliseconds to retain task from creation. - */ - ttl: number2().optional(), - /** - * Time in milliseconds to wait between task status requests. - */ - pollInterval: number2().optional() -}); -var TaskMetadataSchema = object2({ - ttl: number2().optional() -}); -var RelatedTaskMetadataSchema = object2({ - taskId: string2() -}); -var RequestMetaSchema = looseObject({ - /** - * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. - */ - progressToken: ProgressTokenSchema.optional(), - /** - * If specified, this request is related to the provided task. - */ - [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() -}); -var BaseRequestParamsSchema = object2({ - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta: RequestMetaSchema.optional() -}); -var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * If specified, the caller is requesting task-augmented execution for this request. - * The request will return a CreateTaskResult immediately, and the actual result can be - * retrieved later via tasks/result. - * - * Task augmentation is subject to capability negotiation - receivers MUST declare support - * for task augmentation of specific request types in their capabilities. - */ - task: TaskMetadataSchema.optional() -}); -var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; -var RequestSchema = object2({ - method: string2(), - params: BaseRequestParamsSchema.loose().optional() -}); -var NotificationsParamsSchema = object2({ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: RequestMetaSchema.optional() -}); -var NotificationSchema = object2({ - method: string2(), - params: NotificationsParamsSchema.loose().optional() -}); -var ResultSchema = looseObject({ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: RequestMetaSchema.optional() -}); -var RequestIdSchema = union([string2(), number2().int()]); -var JSONRPCRequestSchema = object2({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - ...RequestSchema.shape -}).strict(); -var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; -var JSONRPCNotificationSchema = object2({ - jsonrpc: literal(JSONRPC_VERSION), - ...NotificationSchema.shape -}).strict(); -var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; -var JSONRPCResultResponseSchema = object2({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - result: ResultSchema -}).strict(); -var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; -var ErrorCode; -(function(ErrorCode2) { - ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed"; - ErrorCode2[ErrorCode2["RequestTimeout"] = -32001] = "RequestTimeout"; - ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError"; - ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest"; - ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound"; - ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams"; - ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError"; - ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; -})(ErrorCode || (ErrorCode = {})); -var JSONRPCErrorResponseSchema = object2({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema.optional(), - error: object2({ - /** - * The error type that occurred. - */ - code: number2().int(), - /** - * A short description of the error. The message SHOULD be limited to a concise single sentence. - */ - message: string2(), - /** - * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). - */ - data: unknown().optional() - }) -}).strict(); -var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; -var JSONRPCMessageSchema = union([ - JSONRPCRequestSchema, - JSONRPCNotificationSchema, - JSONRPCResultResponseSchema, - JSONRPCErrorResponseSchema -]); -var JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); -var EmptyResultSchema = ResultSchema.strict(); -var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The ID of the request to cancel. - * - * This MUST correspond to the ID of a request previously issued in the same direction. - */ - requestId: RequestIdSchema.optional(), - /** - * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. - */ - reason: string2().optional() -}); -var CancelledNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema -}); -var IconSchema = object2({ - /** - * URL or data URI for the icon. - */ - src: string2(), - /** - * Optional MIME type for the icon. - */ - mimeType: string2().optional(), - /** - * Optional array of strings that specify sizes at which the icon can be used. - * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. - * - * If not provided, the client should assume that the icon can be used at any size. - */ - sizes: array(string2()).optional(), - /** - * Optional specifier for the theme this icon is designed for. `light` indicates - * the icon is designed to be used with a light background, and `dark` indicates - * the icon is designed to be used with a dark background. - * - * If not provided, the client should assume the icon can be used with any theme. - */ - theme: _enum(["light", "dark"]).optional() -}); -var IconsSchema = object2({ - /** - * Optional set of sized icons that the client can display in a user interface. - * - * Clients that support rendering icons MUST support at least the following MIME types: - * - `image/png` - PNG images (safe, universal compatibility) - * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) - * - * Clients that support rendering icons SHOULD also support: - * - `image/svg+xml` - SVG images (scalable but requires security precautions) - * - `image/webp` - WebP images (modern, efficient format) - */ - icons: array(IconSchema).optional() -}); -var BaseMetadataSchema = object2({ - /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ - name: string2(), - /** - * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, - * even by those unfamiliar with domain-specific terminology. - * - * If not provided, the name should be used for display (except for Tool, - * where `annotations.title` should be given precedence over using `name`, - * if present). - */ - title: string2().optional() -}); -var ImplementationSchema = BaseMetadataSchema.extend({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - version: string2(), - /** - * An optional URL of the website for this implementation. - */ - websiteUrl: string2().optional(), - /** - * An optional human-readable description of what this implementation does. - * - * This can be used by clients or servers to provide context about their purpose - * and capabilities. For example, a server might describe the types of resources - * or tools it provides, while a client might describe its intended use case. - */ - description: string2().optional() -}); -var FormElicitationCapabilitySchema = intersection(object2({ - applyDefaults: boolean2().optional() -}), record(string2(), unknown())); -var ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value)) { - if (Object.keys(value).length === 0) { - return { form: {} }; +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js +function parsePromiseDef(def, refs) { + return parseDef(def.type._def, refs); +} + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/set.js +function parseSetDef(def, refs) { + const items = parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items"] + }); + const schema2 = { + type: "array", + uniqueItems: true, + items + }; + if (def.minSize) { + setResponseValueAndErrors(schema2, "minItems", def.minSize.value, def.minSize.message, refs); + } + if (def.maxSize) { + setResponseValueAndErrors(schema2, "maxItems", def.maxSize.value, def.maxSize.message, refs); + } + return schema2; +} + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js +function parseTupleDef(def, refs) { + if (def.rest) { + return { + type: "array", + minItems: def.items.length, + items: def.items.map((x, i2) => parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, "items", `${i2}`] + })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []), + additionalItems: parseDef(def.rest._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalItems"] + }) + }; + } else { + return { + type: "array", + minItems: def.items.length, + maxItems: def.items.length, + items: def.items.map((x, i2) => parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, "items", `${i2}`] + })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []) + }; + } +} + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js +function parseUndefinedDef(refs) { + return { + not: parseAnyDef(refs) + }; +} + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js +function parseUnknownDef(refs) { + return parseAnyDef(refs); +} + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js +var parseReadonlyDef = (def, refs) => { + return parseDef(def.innerType._def, refs); +}; + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/selectParser.js +var selectParser = (def, typeName, refs) => { + switch (typeName) { + case ZodFirstPartyTypeKind.ZodString: + return parseStringDef(def, refs); + case ZodFirstPartyTypeKind.ZodNumber: + return parseNumberDef(def, refs); + case ZodFirstPartyTypeKind.ZodObject: + return parseObjectDef(def, refs); + case ZodFirstPartyTypeKind.ZodBigInt: + return parseBigintDef(def, refs); + case ZodFirstPartyTypeKind.ZodBoolean: + return parseBooleanDef(); + case ZodFirstPartyTypeKind.ZodDate: + return parseDateDef(def, refs); + case ZodFirstPartyTypeKind.ZodUndefined: + return parseUndefinedDef(refs); + case ZodFirstPartyTypeKind.ZodNull: + return parseNullDef(refs); + case ZodFirstPartyTypeKind.ZodArray: + return parseArrayDef(def, refs); + case ZodFirstPartyTypeKind.ZodUnion: + case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: + return parseUnionDef(def, refs); + case ZodFirstPartyTypeKind.ZodIntersection: + return parseIntersectionDef(def, refs); + case ZodFirstPartyTypeKind.ZodTuple: + return parseTupleDef(def, refs); + case ZodFirstPartyTypeKind.ZodRecord: + return parseRecordDef(def, refs); + case ZodFirstPartyTypeKind.ZodLiteral: + return parseLiteralDef(def, refs); + case ZodFirstPartyTypeKind.ZodEnum: + return parseEnumDef(def); + case ZodFirstPartyTypeKind.ZodNativeEnum: + return parseNativeEnumDef(def); + case ZodFirstPartyTypeKind.ZodNullable: + return parseNullableDef(def, refs); + case ZodFirstPartyTypeKind.ZodOptional: + return parseOptionalDef(def, refs); + case ZodFirstPartyTypeKind.ZodMap: + return parseMapDef(def, refs); + case ZodFirstPartyTypeKind.ZodSet: + return parseSetDef(def, refs); + case ZodFirstPartyTypeKind.ZodLazy: + return () => def.getter()._def; + case ZodFirstPartyTypeKind.ZodPromise: + return parsePromiseDef(def, refs); + case ZodFirstPartyTypeKind.ZodNaN: + case ZodFirstPartyTypeKind.ZodNever: + return parseNeverDef(refs); + case ZodFirstPartyTypeKind.ZodEffects: + return parseEffectsDef(def, refs); + case ZodFirstPartyTypeKind.ZodAny: + return parseAnyDef(refs); + case ZodFirstPartyTypeKind.ZodUnknown: + return parseUnknownDef(refs); + case ZodFirstPartyTypeKind.ZodDefault: + return parseDefaultDef(def, refs); + case ZodFirstPartyTypeKind.ZodBranded: + return parseBrandedDef(def, refs); + case ZodFirstPartyTypeKind.ZodReadonly: + return parseReadonlyDef(def, refs); + case ZodFirstPartyTypeKind.ZodCatch: + return parseCatchDef(def, refs); + case ZodFirstPartyTypeKind.ZodPipeline: + return parsePipelineDef(def, refs); + case ZodFirstPartyTypeKind.ZodFunction: + case ZodFirstPartyTypeKind.ZodVoid: + case ZodFirstPartyTypeKind.ZodSymbol: + return void 0; + default: + return /* @__PURE__ */ ((_) => void 0)(typeName); + } +}; + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parseDef.js +function parseDef(def, refs, forceResolution = false) { + const seenItem = refs.seen.get(def); + if (refs.override) { + const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); + if (overrideResult !== ignoreOverride) { + return overrideResult; } } - return value; -}, intersection(object2({ - form: FormElicitationCapabilitySchema.optional(), - url: AssertObjectSchema.optional() -}), record(string2(), unknown()).optional())); -var ClientTasksCapabilitySchema = looseObject({ - /** - * Present if the client supports listing tasks. - */ - list: AssertObjectSchema.optional(), - /** - * Present if the client supports cancelling tasks. - */ - cancel: AssertObjectSchema.optional(), - /** - * Capabilities for task creation on specific request types. - */ - requests: looseObject({ - /** - * Task support for sampling requests. - */ - sampling: looseObject({ - createMessage: AssertObjectSchema.optional() - }).optional(), - /** - * Task support for elicitation requests. - */ - elicitation: looseObject({ - create: AssertObjectSchema.optional() - }).optional() - }).optional() -}); -var ServerTasksCapabilitySchema = looseObject({ - /** - * Present if the server supports listing tasks. - */ - list: AssertObjectSchema.optional(), - /** - * Present if the server supports cancelling tasks. - */ - cancel: AssertObjectSchema.optional(), - /** - * Capabilities for task creation on specific request types. - */ - requests: looseObject({ - /** - * Task support for tool requests. - */ - tools: looseObject({ - call: AssertObjectSchema.optional() - }).optional() - }).optional() -}); -var ClientCapabilitiesSchema = object2({ - /** - * Experimental, non-standard capabilities that the client supports. - */ - experimental: record(string2(), AssertObjectSchema).optional(), - /** - * Present if the client supports sampling from an LLM. - */ - sampling: object2({ - /** - * Present if the client supports context inclusion via includeContext parameter. - * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). - */ - context: AssertObjectSchema.optional(), - /** - * Present if the client supports tool use via tools and toolChoice parameters. - */ - tools: AssertObjectSchema.optional() - }).optional(), - /** - * Present if the client supports eliciting user input. - */ - elicitation: ElicitationCapabilitySchema.optional(), - /** - * Present if the client supports listing roots. - */ - roots: object2({ - /** - * Whether the client supports issuing notifications for changes to the roots list. - */ - listChanged: boolean2().optional() - }).optional(), - /** - * Present if the client supports task creation. - */ - tasks: ClientTasksCapabilitySchema.optional(), - /** - * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name). - */ - extensions: record(string2(), AssertObjectSchema).optional() -}); -var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. - */ - protocolVersion: string2(), - capabilities: ClientCapabilitiesSchema, - clientInfo: ImplementationSchema -}); -var InitializeRequestSchema = RequestSchema.extend({ - method: literal("initialize"), - params: InitializeRequestParamsSchema -}); -var ServerCapabilitiesSchema = object2({ - /** - * Experimental, non-standard capabilities that the server supports. - */ - experimental: record(string2(), AssertObjectSchema).optional(), - /** - * Present if the server supports sending log messages to the client. - */ - logging: AssertObjectSchema.optional(), - /** - * Present if the server supports sending completions to the client. - */ - completions: AssertObjectSchema.optional(), - /** - * Present if the server offers any prompt templates. - */ - prompts: object2({ - /** - * Whether this server supports issuing notifications for changes to the prompt list. - */ - listChanged: boolean2().optional() - }).optional(), - /** - * Present if the server offers any resources to read. - */ - resources: object2({ - /** - * Whether this server supports clients subscribing to resource updates. - */ - subscribe: boolean2().optional(), - /** - * Whether this server supports issuing notifications for changes to the resource list. - */ - listChanged: boolean2().optional() - }).optional(), - /** - * Present if the server offers any tools to call. - */ - tools: object2({ - /** - * Whether this server supports issuing notifications for changes to the tool list. - */ - listChanged: boolean2().optional() - }).optional(), - /** - * Present if the server supports task creation. - */ - tasks: ServerTasksCapabilitySchema.optional(), - /** - * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name). - */ - extensions: record(string2(), AssertObjectSchema).optional() -}); -var InitializeResultSchema = ResultSchema.extend({ - /** - * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. - */ - protocolVersion: string2(), - capabilities: ServerCapabilitiesSchema, - serverInfo: ImplementationSchema, - /** - * Instructions describing how to use the server and its features. - * - * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. - */ - instructions: string2().optional() -}); -var InitializedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/initialized"), - params: NotificationsParamsSchema.optional() -}); -var PingRequestSchema = RequestSchema.extend({ - method: literal("ping"), - params: BaseRequestParamsSchema.optional() -}); -var ProgressSchema = object2({ - /** - * The progress thus far. This should increase every time progress is made, even if the total is unknown. - */ - progress: number2(), - /** - * Total number of items to process (or total progress required), if known. - */ - total: optional(number2()), - /** - * An optional message describing the current progress. - */ - message: optional(string2()) -}); -var ProgressNotificationParamsSchema = object2({ - ...NotificationsParamsSchema.shape, - ...ProgressSchema.shape, - /** - * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. - */ - progressToken: ProgressTokenSchema -}); -var ProgressNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema -}); -var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * An opaque token representing the current pagination position. - * If provided, the server should return results starting after this cursor. - */ - cursor: CursorSchema.optional() -}); -var PaginatedRequestSchema = RequestSchema.extend({ - params: PaginatedRequestParamsSchema.optional() -}); -var PaginatedResultSchema = ResultSchema.extend({ - /** - * An opaque token representing the pagination position after the last returned result. - * If present, there may be more results available. - */ - nextCursor: CursorSchema.optional() -}); -var TaskStatusSchema = _enum(["working", "input_required", "completed", "failed", "cancelled"]); -var TaskSchema = object2({ - taskId: string2(), - status: TaskStatusSchema, - /** - * Time in milliseconds to keep task results available after completion. - * If null, the task has unlimited lifetime until manually cleaned up. - */ - ttl: union([number2(), _null3()]), - /** - * ISO 8601 timestamp when the task was created. - */ - createdAt: string2(), - /** - * ISO 8601 timestamp when the task was last updated. - */ - lastUpdatedAt: string2(), - pollInterval: optional(number2()), - /** - * Optional diagnostic message for failed tasks or other status information. - */ - statusMessage: optional(string2()) -}); -var CreateTaskResultSchema = ResultSchema.extend({ - task: TaskSchema -}); -var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); -var TaskStatusNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/tasks/status"), - params: TaskStatusNotificationParamsSchema -}); -var GetTaskRequestSchema = RequestSchema.extend({ - method: literal("tasks/get"), - params: BaseRequestParamsSchema.extend({ - taskId: string2() - }) -}); -var GetTaskResultSchema = ResultSchema.merge(TaskSchema); -var GetTaskPayloadRequestSchema = RequestSchema.extend({ - method: literal("tasks/result"), - params: BaseRequestParamsSchema.extend({ - taskId: string2() - }) -}); -var GetTaskPayloadResultSchema = ResultSchema.loose(); -var ListTasksRequestSchema = PaginatedRequestSchema.extend({ - method: literal("tasks/list") -}); -var ListTasksResultSchema = PaginatedResultSchema.extend({ - tasks: array(TaskSchema) -}); -var CancelTaskRequestSchema = RequestSchema.extend({ - method: literal("tasks/cancel"), - params: BaseRequestParamsSchema.extend({ - taskId: string2() - }) -}); -var CancelTaskResultSchema = ResultSchema.merge(TaskSchema); -var ResourceContentsSchema = object2({ - /** - * The URI of this resource. - */ - uri: string2(), - /** - * The MIME type of this resource, if known. - */ - mimeType: optional(string2()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: record(string2(), unknown()).optional() -}); -var TextResourceContentsSchema = ResourceContentsSchema.extend({ - /** - * The text of the item. This must only be set if the item can actually be represented as text (not binary data). - */ - text: string2() -}); -var Base64Schema = string2().refine((val) => { - try { - atob(val); + if (seenItem && !forceResolution) { + const seenSchema = get$ref(seenItem, refs); + if (seenSchema !== void 0) { + return seenSchema; + } + } + const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; + refs.seen.set(def, newItem); + const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); + const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; + if (jsonSchema) { + addMeta(def, refs, jsonSchema); + } + if (refs.postProcess) { + const postProcessResult = refs.postProcess(jsonSchema, def, refs); + newItem.jsonSchema = jsonSchema; + return postProcessResult; + } + newItem.jsonSchema = jsonSchema; + return jsonSchema; +} +var get$ref = (item, refs) => { + switch (refs.$refStrategy) { + case "root": + return { $ref: item.path.join("/") }; + case "relative": + return { $ref: getRelativePath(refs.currentPath, item.path) }; + case "none": + case "seen": { + if (item.path.length < refs.currentPath.length && item.path.every((value, index2) => refs.currentPath[index2] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); + return parseAnyDef(refs); + } + return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0; + } + } +}; +var addMeta = (def, refs, jsonSchema) => { + if (def.description) { + jsonSchema.description = def.description; + if (refs.markdownDescription) { + jsonSchema.markdownDescription = def.description; + } + } + return jsonSchema; +}; + +// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js +var zodToJsonSchema = (schema2, options) => { + const refs = getRefs(options); + let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name316, schema3]) => ({ + ...acc, + [name316]: parseDef(schema3._def, { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name316] + }, true) ?? parseAnyDef(refs) + }), {}) : void 0; + const name315 = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name; + const main3 = parseDef(schema2._def, name315 === void 0 ? refs : { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name315] + }, false) ?? parseAnyDef(refs); + const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; + if (title !== void 0) { + main3.title = title; + } + if (refs.flags.hasReferencedOpenAiAnyType) { + if (!definitions) { + definitions = {}; + } + if (!definitions[refs.openAiAnyTypeName]) { + definitions[refs.openAiAnyTypeName] = { + // Skipping "object" as no properties can be defined and additionalProperties must be "false" + type: ["string", "number", "integer", "boolean", "array", "null"], + items: { + $ref: refs.$refStrategy === "relative" ? "1" : [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName + ].join("/") + } + }; + } + } + const combined = name315 === void 0 ? definitions ? { + ...main3, + [refs.definitionPath]: definitions + } : main3 : { + $ref: [ + ...refs.$refStrategy === "relative" ? [] : refs.basePath, + refs.definitionPath, + name315 + ].join("/"), + [refs.definitionPath]: { + ...definitions, + [name315]: main3 + } + }; + if (refs.target === "jsonSchema7") { + combined.$schema = "http://json-schema.org/draft-07/schema#"; + } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { + combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; + } + if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) { + console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); + } + return combined; +}; + +// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js +function mapMiniTarget(t) { + if (!t) + return "draft-7"; + if (t === "jsonSchema7" || t === "draft-7") + return "draft-7"; + if (t === "jsonSchema2019-09" || t === "draft-2020-12") + return "draft-2020-12"; + return "draft-7"; +} +function toJsonSchemaCompat(schema2, opts) { + if (isZ4Schema(schema2)) { + return toJSONSchema(schema2, { + target: mapMiniTarget(opts?.target), + io: opts?.pipeStrategy ?? "input" + }); + } + return zodToJsonSchema(schema2, { + strictUnions: opts?.strictUnions ?? true, + pipeStrategy: opts?.pipeStrategy ?? "input" + }); +} +function getMethodLiteral(schema2) { + const shape = getObjectShape(schema2); + const methodSchema = shape?.method; + if (!methodSchema) { + throw new Error("Schema is missing a method literal"); + } + const value = getLiteralValue(methodSchema); + if (typeof value !== "string") { + throw new Error("Schema method literal must be a string"); + } + return value; +} +function parseWithCompat(schema2, data) { + const result = safeParse2(schema2, data); + if (!result.success) { + throw result.error; + } + return result.data; +} + +// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js +var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; +var Protocol = class { + constructor(_options) { + this._options = _options; + this._requestMessageId = 0; + this._requestHandlers = /* @__PURE__ */ new Map(); + this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + this._notificationHandlers = /* @__PURE__ */ new Map(); + this._responseHandlers = /* @__PURE__ */ new Map(); + this._progressHandlers = /* @__PURE__ */ new Map(); + this._timeoutInfo = /* @__PURE__ */ new Map(); + this._pendingDebouncedNotifications = /* @__PURE__ */ new Set(); + this._taskProgressTokens = /* @__PURE__ */ new Map(); + this._requestResolvers = /* @__PURE__ */ new Map(); + this.setNotificationHandler(CancelledNotificationSchema, (notification) => { + this._oncancel(notification); + }); + this.setNotificationHandler(ProgressNotificationSchema, (notification) => { + this._onprogress(notification); + }); + this.setRequestHandler( + PingRequestSchema, + // Automatic pong by default. + (_request) => ({}) + ); + this._taskStore = _options?.taskStore; + this._taskMessageQueue = _options?.taskMessageQueue; + if (this._taskStore) { + this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => { + const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found"); + } + return { + ...task + }; + }); + this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => { + const handleTaskResult = async () => { + const taskId = request.params.taskId; + if (this._taskMessageQueue) { + let queuedMessage; + while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) { + if (queuedMessage.type === "response" || queuedMessage.type === "error") { + const message = queuedMessage.message; + const requestId = message.id; + const resolver = this._requestResolvers.get(requestId); + if (resolver) { + this._requestResolvers.delete(requestId); + if (queuedMessage.type === "response") { + resolver(message); + } else { + const errorMessage = message; + const error2 = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data); + resolver(error2); + } + } else { + const messageType = queuedMessage.type === "response" ? "Response" : "Error"; + this._onerror(new Error(`${messageType} handler missing for request ${requestId}`)); + } + continue; + } + await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId }); + } + } + const task = await this._taskStore.getTask(taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`); + } + if (!isTerminal(task.status)) { + await this._waitForTaskUpdate(taskId, extra.signal); + return await handleTaskResult(); + } + if (isTerminal(task.status)) { + const result = await this._taskStore.getTaskResult(taskId, extra.sessionId); + this._clearTaskQueue(taskId); + return { + ...result, + _meta: { + ...result._meta, + [RELATED_TASK_META_KEY]: { + taskId + } + } + }; + } + return await handleTaskResult(); + }; + return await handleTaskResult(); + }); + this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => { + try { + const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId); + return { + tasks, + nextCursor, + _meta: {} + }; + } catch (error2) { + throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error2 instanceof Error ? error2.message : String(error2)}`); + } + }); + this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => { + try { + const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`); + } + if (isTerminal(task.status)) { + throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`); + } + await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId); + this._clearTaskQueue(request.params.taskId); + const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!cancelledTask) { + throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`); + } + return { + _meta: {}, + ...cancelledTask + }; + } catch (error2) { + if (error2 instanceof McpError) { + throw error2; + } + throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error2 instanceof Error ? error2.message : String(error2)}`); + } + }); + } + } + async _oncancel(notification) { + if (!notification.params.requestId) { + return; + } + const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); + controller?.abort(notification.params.reason); + } + _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { + this._timeoutInfo.set(messageId, { + timeoutId: setTimeout(onTimeout, timeout), + startTime: Date.now(), + timeout, + maxTotalTimeout, + resetTimeoutOnProgress, + onTimeout + }); + } + _resetTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (!info) + return false; + const totalElapsed = Date.now() - info.startTime; + if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { + this._timeoutInfo.delete(messageId); + throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", { + maxTotalTimeout: info.maxTotalTimeout, + totalElapsed + }); + } + clearTimeout(info.timeoutId); + info.timeoutId = setTimeout(info.onTimeout, info.timeout); return true; - } catch { - return false; } -}, { message: "Invalid Base64 string" }); -var BlobResourceContentsSchema = ResourceContentsSchema.extend({ - /** - * A base64-encoded string representing the binary data of the item. - */ - blob: Base64Schema -}); -var RoleSchema = _enum(["user", "assistant"]); -var AnnotationsSchema = object2({ - /** - * Intended audience(s) for the resource. - */ - audience: array(RoleSchema).optional(), - /** - * Importance hint for the resource, from 0 (least) to 1 (most). - */ - priority: number2().min(0).max(1).optional(), + _cleanupTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (info) { + clearTimeout(info.timeoutId); + this._timeoutInfo.delete(messageId); + } + } /** - * ISO 8601 timestamp for the most recent modification. + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. */ - lastModified: iso_exports2.datetime({ offset: true }).optional() -}); -var ResourceSchema = object2({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, + async connect(transport) { + if (this._transport) { + throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection."); + } + this._transport = transport; + const _onclose = this.transport?.onclose; + this._transport.onclose = () => { + _onclose?.(); + this._onclose(); + }; + const _onerror = this.transport?.onerror; + this._transport.onerror = (error2) => { + _onerror?.(error2); + this._onerror(error2); + }; + const _onmessage = this._transport?.onmessage; + this._transport.onmessage = (message, extra) => { + _onmessage?.(message, extra); + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + this._onresponse(message); + } else if (isJSONRPCRequest(message)) { + this._onrequest(message, extra); + } else if (isJSONRPCNotification(message)) { + this._onnotification(message); + } else { + this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); + } + }; + await this._transport.start(); + } + _onclose() { + const responseHandlers = this._responseHandlers; + this._responseHandlers = /* @__PURE__ */ new Map(); + this._progressHandlers.clear(); + this._taskProgressTokens.clear(); + this._pendingDebouncedNotifications.clear(); + for (const info of this._timeoutInfo.values()) { + clearTimeout(info.timeoutId); + } + this._timeoutInfo.clear(); + for (const controller of this._requestHandlerAbortControllers.values()) { + controller.abort(); + } + this._requestHandlerAbortControllers.clear(); + const error2 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed"); + this._transport = void 0; + this.onclose?.(); + for (const handler of responseHandlers.values()) { + handler(error2); + } + } + _onerror(error2) { + this.onerror?.(error2); + } + _onnotification(notification) { + const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler; + if (handler === void 0) { + return; + } + Promise.resolve().then(() => handler(notification)).catch((error2) => this._onerror(new Error(`Uncaught error in notification handler: ${error2}`))); + } + _onrequest(request, extra) { + const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; + const capturedTransport = this._transport; + const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId; + if (handler === void 0) { + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: ErrorCode.MethodNotFound, + message: "Method not found" + } + }; + if (relatedTaskId && this._taskMessageQueue) { + this._enqueueTaskMessage(relatedTaskId, { + type: "error", + message: errorResponse, + timestamp: Date.now() + }, capturedTransport?.sessionId).catch((error2) => this._onerror(new Error(`Failed to enqueue error response: ${error2}`))); + } else { + capturedTransport?.send(errorResponse).catch((error2) => this._onerror(new Error(`Failed to send an error response: ${error2}`))); + } + return; + } + const abortController = new AbortController(); + this._requestHandlerAbortControllers.set(request.id, abortController); + const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0; + const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : void 0; + const fullExtra = { + signal: abortController.signal, + sessionId: capturedTransport?.sessionId, + _meta: request.params?._meta, + sendNotification: async (notification) => { + if (abortController.signal.aborted) + return; + const notificationOptions = { relatedRequestId: request.id }; + if (relatedTaskId) { + notificationOptions.relatedTask = { taskId: relatedTaskId }; + } + await this.notification(notification, notificationOptions); + }, + sendRequest: async (r, resultSchema, options) => { + if (abortController.signal.aborted) { + throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled"); + } + const requestOptions = { ...options, relatedRequestId: request.id }; + if (relatedTaskId && !requestOptions.relatedTask) { + requestOptions.relatedTask = { taskId: relatedTaskId }; + } + const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId; + if (effectiveTaskId && taskStore) { + await taskStore.updateTaskStatus(effectiveTaskId, "input_required"); + } + return await this.request(r, resultSchema, requestOptions); + }, + authInfo: extra?.authInfo, + requestId: request.id, + requestInfo: extra?.requestInfo, + taskId: relatedTaskId, + taskStore, + taskRequestedTtl: taskCreationParams?.ttl, + closeSSEStream: extra?.closeSSEStream, + closeStandaloneSSEStream: extra?.closeStandaloneSSEStream + }; + Promise.resolve().then(() => { + if (taskCreationParams) { + this.assertTaskHandlerCapability(request.method); + } + }).then(() => handler(request, fullExtra)).then(async (result) => { + if (abortController.signal.aborted) { + return; + } + const response = { + result, + jsonrpc: "2.0", + id: request.id + }; + if (relatedTaskId && this._taskMessageQueue) { + await this._enqueueTaskMessage(relatedTaskId, { + type: "response", + message: response, + timestamp: Date.now() + }, capturedTransport?.sessionId); + } else { + await capturedTransport?.send(response); + } + }, async (error2) => { + if (abortController.signal.aborted) { + return; + } + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: Number.isSafeInteger(error2["code"]) ? error2["code"] : ErrorCode.InternalError, + message: error2.message ?? "Internal error", + ...error2["data"] !== void 0 && { data: error2["data"] } + } + }; + if (relatedTaskId && this._taskMessageQueue) { + await this._enqueueTaskMessage(relatedTaskId, { + type: "error", + message: errorResponse, + timestamp: Date.now() + }, capturedTransport?.sessionId); + } else { + await capturedTransport?.send(errorResponse); + } + }).catch((error2) => this._onerror(new Error(`Failed to send response: ${error2}`))).finally(() => { + if (this._requestHandlerAbortControllers.get(request.id) === abortController) { + this._requestHandlerAbortControllers.delete(request.id); + } + }); + } + _onprogress(notification) { + const { progressToken, ...params } = notification.params; + const messageId = Number(progressToken); + const handler = this._progressHandlers.get(messageId); + if (!handler) { + this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); + return; + } + const responseHandler = this._responseHandlers.get(messageId); + const timeoutInfo = this._timeoutInfo.get(messageId); + if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { + try { + this._resetTimeout(messageId); + } catch (error2) { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + responseHandler(error2); + return; + } + } + handler(params); + } + _onresponse(response) { + const messageId = Number(response.id); + const resolver = this._requestResolvers.get(messageId); + if (resolver) { + this._requestResolvers.delete(messageId); + if (isJSONRPCResultResponse(response)) { + resolver(response); + } else { + const error2 = new McpError(response.error.code, response.error.message, response.error.data); + resolver(error2); + } + return; + } + const handler = this._responseHandlers.get(messageId); + if (handler === void 0) { + this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); + return; + } + this._responseHandlers.delete(messageId); + this._cleanupTimeout(messageId); + let isTaskResponse = false; + if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") { + const result = response.result; + if (result.task && typeof result.task === "object") { + const task = result.task; + if (typeof task.taskId === "string") { + isTaskResponse = true; + this._taskProgressTokens.set(task.taskId, messageId); + } + } + } + if (!isTaskResponse) { + this._progressHandlers.delete(messageId); + } + if (isJSONRPCResultResponse(response)) { + handler(response); + } else { + const error2 = McpError.fromError(response.error.code, response.error.message, response.error.data); + handler(error2); + } + } + get transport() { + return this._transport; + } /** - * The URI of this resource. + * Closes the connection. */ - uri: string2(), + async close() { + await this._transport?.close(); + } /** - * A description of what this resource represents. + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description: optional(string2()), - /** - * The MIME type of this resource, if known. - */ - mimeType: optional(string2()), - /** - * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. + * @example + * ```typescript + * const stream = protocol.requestStream(request, resultSchema, options); + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Task created:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Task status:', message.task.status); + * break; + * case 'result': + * console.log('Final result:', message.result); + * break; + * case 'error': + * console.error('Error:', message.error); + * break; + * } + * } + * ``` * - * This can be used by Hosts to display file sizes and estimate context window usage. - */ - size: optional(number2()), - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: optional(looseObject({})) -}); -var ResourceTemplateSchema = object2({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - /** - * A URI template (according to RFC 6570) that can be used to construct resource URIs. + * @experimental Use `client.experimental.tasks.requestStream()` to access this method. */ - uriTemplate: string2(), + async *requestStream(request, resultSchema, options) { + const { task } = options ?? {}; + if (!task) { + try { + const result = await this.request(request, resultSchema, options); + yield { type: "result", result }; + } catch (error2) { + yield { + type: "error", + error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2)) + }; + } + return; + } + let taskId; + try { + const createResult = await this.request(request, CreateTaskResultSchema, options); + if (createResult.task) { + taskId = createResult.task.taskId; + yield { type: "taskCreated", task: createResult.task }; + } else { + throw new McpError(ErrorCode.InternalError, "Task creation did not return a task"); + } + while (true) { + const task2 = await this.getTask({ taskId }, options); + yield { type: "taskStatus", task: task2 }; + if (isTerminal(task2.status)) { + if (task2.status === "completed") { + const result = await this.getTaskResult({ taskId }, resultSchema, options); + yield { type: "result", result }; + } else if (task2.status === "failed") { + yield { + type: "error", + error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`) + }; + } else if (task2.status === "cancelled") { + yield { + type: "error", + error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`) + }; + } + return; + } + if (task2.status === "input_required") { + const result = await this.getTaskResult({ taskId }, resultSchema, options); + yield { type: "result", result }; + return; + } + const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3; + await new Promise((resolve2) => setTimeout(resolve2, pollInterval)); + options?.signal?.throwIfAborted(); + } + } catch (error2) { + yield { + type: "error", + error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2)) + }; + } + } /** - * A description of what this template is for. + * Sends a request and waits for a response. * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description: optional(string2()), - /** - * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. - */ - mimeType: optional(string2()), - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. + * Do not use this method to emit notifications! Use notification() instead. */ - _meta: optional(looseObject({})) -}); -var ListResourcesRequestSchema = PaginatedRequestSchema.extend({ - method: literal("resources/list") -}); -var ListResourcesResultSchema = PaginatedResultSchema.extend({ - resources: array(ResourceSchema) -}); -var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ - method: literal("resources/templates/list") -}); -var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ - resourceTemplates: array(ResourceTemplateSchema) -}); -var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ + request(request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {}; + return new Promise((resolve2, reject) => { + const earlyReject = (error2) => { + reject(error2); + }; + if (!this._transport) { + earlyReject(new Error("Not connected")); + return; + } + if (this._options?.enforceStrictCapabilities === true) { + try { + this.assertCapabilityForMethod(request.method); + if (task) { + this.assertTaskCapability(request.method); + } + } catch (e3) { + earlyReject(e3); + return; + } + } + options?.signal?.throwIfAborted(); + const messageId = this._requestMessageId++; + const jsonrpcRequest = { + ...request, + jsonrpc: "2.0", + id: messageId + }; + if (options?.onprogress) { + this._progressHandlers.set(messageId, options.onprogress); + jsonrpcRequest.params = { + ...request.params, + _meta: { + ...request.params?._meta || {}, + progressToken: messageId + } + }; + } + if (task) { + jsonrpcRequest.params = { + ...jsonrpcRequest.params, + task + }; + } + if (relatedTask) { + jsonrpcRequest.params = { + ...jsonrpcRequest.params, + _meta: { + ...jsonrpcRequest.params?._meta || {}, + [RELATED_TASK_META_KEY]: relatedTask + } + }; + } + const cancel = (reason) => { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + this._transport?.send({ + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { + requestId: messageId, + reason: String(reason) + } + }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error3) => this._onerror(new Error(`Failed to send cancellation: ${error3}`))); + const error2 = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason)); + reject(error2); + }; + this._responseHandlers.set(messageId, (response) => { + if (options?.signal?.aborted) { + return; + } + if (response instanceof Error) { + return reject(response); + } + try { + const parseResult = safeParse2(resultSchema, response.result); + if (!parseResult.success) { + reject(parseResult.error); + } else { + resolve2(parseResult.data); + } + } catch (error2) { + reject(error2); + } + }); + options?.signal?.addEventListener("abort", () => { + cancel(options?.signal?.reason); + }); + const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; + const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout })); + this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); + const relatedTaskId = relatedTask?.taskId; + if (relatedTaskId) { + const responseResolver = (response) => { + const handler = this._responseHandlers.get(messageId); + if (handler) { + handler(response); + } else { + this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`)); + } + }; + this._requestResolvers.set(messageId, responseResolver); + this._enqueueTaskMessage(relatedTaskId, { + type: "request", + message: jsonrpcRequest, + timestamp: Date.now() + }).catch((error2) => { + this._cleanupTimeout(messageId); + reject(error2); + }); + } else { + this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => { + this._cleanupTimeout(messageId); + reject(error2); + }); + } + }); + } /** - * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. + * Gets the current status of a task. * - * @format uri - */ - uri: string2() -}); -var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; -var ReadResourceRequestSchema = RequestSchema.extend({ - method: literal("resources/read"), - params: ReadResourceRequestParamsSchema -}); -var ReadResourceResultSchema = ResultSchema.extend({ - contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema])) -}); -var ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema.optional() -}); -var SubscribeRequestParamsSchema = ResourceRequestParamsSchema; -var SubscribeRequestSchema = RequestSchema.extend({ - method: literal("resources/subscribe"), - params: SubscribeRequestParamsSchema -}); -var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; -var UnsubscribeRequestSchema = RequestSchema.extend({ - method: literal("resources/unsubscribe"), - params: UnsubscribeRequestParamsSchema -}); -var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. - */ - uri: string2() -}); -var ResourceUpdatedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema -}); -var PromptArgumentSchema = object2({ - /** - * The name of the argument. - */ - name: string2(), - /** - * A human-readable description of the argument. - */ - description: optional(string2()), - /** - * Whether this argument must be provided. - */ - required: optional(boolean2()) -}); -var PromptSchema = object2({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - /** - * An optional description of what this prompt provides - */ - description: optional(string2()), - /** - * A list of arguments to use for templating the prompt. - */ - arguments: optional(array(PromptArgumentSchema)), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. + * @experimental Use `client.experimental.tasks.getTask()` to access this method. */ - _meta: optional(looseObject({})) -}); -var ListPromptsRequestSchema = PaginatedRequestSchema.extend({ - method: literal("prompts/list") -}); -var ListPromptsResultSchema = PaginatedResultSchema.extend({ - prompts: array(PromptSchema) -}); -var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + async getTask(params, options) { + return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options); + } /** - * The name of the prompt or prompt template. + * Retrieves the result of a completed task. + * + * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method. */ - name: string2(), + async getTaskResult(params, resultSchema, options) { + return this.request({ method: "tasks/result", params }, resultSchema, options); + } /** - * Arguments to use for templating the prompt. + * Lists tasks, optionally starting from a pagination cursor. + * + * @experimental Use `client.experimental.tasks.listTasks()` to access this method. */ - arguments: record(string2(), string2()).optional() -}); -var GetPromptRequestSchema = RequestSchema.extend({ - method: literal("prompts/get"), - params: GetPromptRequestParamsSchema -}); -var TextContentSchema = object2({ - type: literal("text"), + async listTasks(params, options) { + return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options); + } /** - * The text content of the message. + * Cancels a specific task. + * + * @experimental Use `client.experimental.tasks.cancelTask()` to access this method. */ - text: string2(), + async cancelTask(params, options) { + return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options); + } /** - * Optional annotations for the client. + * Emits a notification, which is a one-way message that does not expect a response. */ - annotations: AnnotationsSchema.optional(), + async notification(notification, options) { + if (!this._transport) { + throw new Error("Not connected"); + } + this.assertNotificationCapability(notification.method); + const relatedTaskId = options?.relatedTask?.taskId; + if (relatedTaskId) { + const jsonrpcNotification2 = { + ...notification, + jsonrpc: "2.0", + params: { + ...notification.params, + _meta: { + ...notification.params?._meta || {}, + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + await this._enqueueTaskMessage(relatedTaskId, { + type: "notification", + message: jsonrpcNotification2, + timestamp: Date.now() + }); + return; + } + const debouncedMethods = this._options?.debouncedNotificationMethods ?? []; + const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask; + if (canDebounce) { + if (this._pendingDebouncedNotifications.has(notification.method)) { + return; + } + this._pendingDebouncedNotifications.add(notification.method); + Promise.resolve().then(() => { + this._pendingDebouncedNotifications.delete(notification.method); + if (!this._transport) { + return; + } + let jsonrpcNotification2 = { + ...notification, + jsonrpc: "2.0" + }; + if (options?.relatedTask) { + jsonrpcNotification2 = { + ...jsonrpcNotification2, + params: { + ...jsonrpcNotification2.params, + _meta: { + ...jsonrpcNotification2.params?._meta || {}, + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + } + this._transport?.send(jsonrpcNotification2, options).catch((error2) => this._onerror(error2)); + }); + return; + } + let jsonrpcNotification = { + ...notification, + jsonrpc: "2.0" + }; + if (options?.relatedTask) { + jsonrpcNotification = { + ...jsonrpcNotification, + params: { + ...jsonrpcNotification.params, + _meta: { + ...jsonrpcNotification.params?._meta || {}, + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + } + await this._transport.send(jsonrpcNotification, options); + } /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. + * Registers a handler to invoke when this protocol object receives a request with the given method. + * + * Note that this will replace any previous request handler for the same method. */ - _meta: record(string2(), unknown()).optional() -}); -var ImageContentSchema = object2({ - type: literal("image"), + setRequestHandler(requestSchema, handler) { + const method = getMethodLiteral(requestSchema); + this.assertRequestHandlerCapability(method); + this._requestHandlers.set(method, (request, extra) => { + const parsed = parseWithCompat(requestSchema, request); + return Promise.resolve(handler(parsed, extra)); + }); + } /** - * The base64-encoded image data. + * Removes the request handler for the given method. */ - data: Base64Schema, + removeRequestHandler(method) { + this._requestHandlers.delete(method); + } /** - * The MIME type of the image. Different providers may support different image types. + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. */ - mimeType: string2(), + assertCanSetRequestHandler(method) { + if (this._requestHandlers.has(method)) { + throw new Error(`A request handler for ${method} already exists, which would be overridden`); + } + } /** - * Optional annotations for the client. + * Registers a handler to invoke when this protocol object receives a notification with the given method. + * + * Note that this will replace any previous notification handler for the same method. */ - annotations: AnnotationsSchema.optional(), + setNotificationHandler(notificationSchema, handler) { + const method = getMethodLiteral(notificationSchema); + this._notificationHandlers.set(method, (notification) => { + const parsed = parseWithCompat(notificationSchema, notification); + return Promise.resolve(handler(parsed)); + }); + } /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. + * Removes the notification handler for the given method. */ - _meta: record(string2(), unknown()).optional() -}); -var AudioContentSchema = object2({ - type: literal("audio"), + removeNotificationHandler(method) { + this._notificationHandlers.delete(method); + } /** - * The base64-encoded audio data. + * Cleans up the progress handler associated with a task. + * This should be called when a task reaches a terminal status. */ - data: Base64Schema, + _cleanupTaskProgressHandler(taskId) { + const progressToken = this._taskProgressTokens.get(taskId); + if (progressToken !== void 0) { + this._progressHandlers.delete(progressToken); + this._taskProgressTokens.delete(taskId); + } + } /** - * The MIME type of the audio. Different providers may support different audio types. + * Enqueues a task-related message for side-channel delivery via tasks/result. + * @param taskId The task ID to associate the message with + * @param message The message to enqueue + * @param sessionId Optional session ID for binding the operation to a specific session + * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow) + * + * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle + * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer + * simply propagates the error. */ - mimeType: string2(), + async _enqueueTaskMessage(taskId, message, sessionId) { + if (!this._taskStore || !this._taskMessageQueue) { + throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured"); + } + const maxQueueSize = this._options?.maxTaskQueueSize; + await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize); + } /** - * Optional annotations for the client. + * Clears the message queue for a task and rejects any pending request resolvers. + * @param taskId The task ID whose queue should be cleared + * @param sessionId Optional session ID for binding the operation to a specific session */ - annotations: AnnotationsSchema.optional(), + async _clearTaskQueue(taskId, sessionId) { + if (this._taskMessageQueue) { + const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId); + for (const message of messages) { + if (message.type === "request" && isJSONRPCRequest(message.message)) { + const requestId = message.message.id; + const resolver = this._requestResolvers.get(requestId); + if (resolver) { + resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed")); + this._requestResolvers.delete(requestId); + } else { + this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`)); + } + } + } + } + } /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. + * Waits for a task update (new messages or status change) with abort signal support. + * Uses polling to check for updates at the task's configured poll interval. + * @param taskId The task ID to wait for + * @param signal Abort signal to cancel the wait + * @returns Promise that resolves when an update occurs or rejects if aborted */ - _meta: record(string2(), unknown()).optional() -}); -var ToolUseContentSchema = object2({ - type: literal("tool_use"), + async _waitForTaskUpdate(taskId, signal) { + let interval = this._options?.defaultTaskPollInterval ?? 1e3; + try { + const task = await this._taskStore?.getTask(taskId); + if (task?.pollInterval) { + interval = task.pollInterval; + } + } catch { + } + return new Promise((resolve2, reject) => { + if (signal.aborted) { + reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled")); + return; + } + const timeoutId = setTimeout(resolve2, interval); + signal.addEventListener("abort", () => { + clearTimeout(timeoutId); + reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled")); + }, { once: true }); + }); + } + requestTaskStore(request, sessionId) { + const taskStore = this._taskStore; + if (!taskStore) { + throw new Error("No task store configured"); + } + return { + createTask: async (taskParams) => { + if (!request) { + throw new Error("No request provided"); + } + return await taskStore.createTask(taskParams, request.id, { + method: request.method, + params: request.params + }, sessionId); + }, + getTask: async (taskId) => { + const task = await taskStore.getTask(taskId, sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found"); + } + return task; + }, + storeTaskResult: async (taskId, status, result) => { + await taskStore.storeTaskResult(taskId, status, result, sessionId); + const task = await taskStore.getTask(taskId, sessionId); + if (task) { + const notification = TaskStatusNotificationSchema.parse({ + method: "notifications/tasks/status", + params: task + }); + await this.notification(notification); + if (isTerminal(task.status)) { + this._cleanupTaskProgressHandler(taskId); + } + } + }, + getTaskResult: (taskId) => { + return taskStore.getTaskResult(taskId, sessionId); + }, + updateTaskStatus: async (taskId, status, statusMessage) => { + const task = await taskStore.getTask(taskId, sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`); + } + if (isTerminal(task.status)) { + throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`); + } + await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId); + const updatedTask = await taskStore.getTask(taskId, sessionId); + if (updatedTask) { + const notification = TaskStatusNotificationSchema.parse({ + method: "notifications/tasks/status", + params: updatedTask + }); + await this.notification(notification); + if (isTerminal(updatedTask.status)) { + this._cleanupTaskProgressHandler(taskId); + } + } + }, + listTasks: (cursor) => { + return taskStore.listTasks(cursor, sessionId); + } + }; + } +}; +function isPlainObject2(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function mergeCapabilities(base, additional) { + const result = { ...base }; + for (const key in additional) { + const k = key; + const addValue = additional[k]; + if (addValue === void 0) + continue; + const baseValue = result[k]; + if (isPlainObject2(baseValue) && isPlainObject2(addValue)) { + result[k] = { ...baseValue, ...addValue }; + } else { + result[k] = addValue; + } + } + return result; +} + +// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js +var import_ajv = __toESM(require_ajv(), 1); +var import_ajv_formats = __toESM(require_dist(), 1); +function createDefaultAjvInstance() { + const ajv2 = new import_ajv.default({ + strict: false, + validateFormats: true, + validateSchema: false, + allErrors: true + }); + const addFormats = import_ajv_formats.default; + addFormats(ajv2); + return ajv2; +} +var AjvJsonSchemaValidator = class { /** - * The name of the tool to invoke. - * Must match a tool name from the request's tools array. + * Create an AJV validator + * + * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. + * + * @example + * ```typescript + * // Use default configuration (recommended for most cases) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Or provide custom AJV instance for advanced configuration + * import { Ajv } from 'ajv'; + * import addFormats from 'ajv-formats'; + * + * const ajv = new Ajv({ validateFormats: true }); + * addFormats(ajv); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` */ - name: string2(), + constructor(ajv2) { + this._ajv = ajv2 ?? createDefaultAjvInstance(); + } /** - * Unique identifier for this tool call. - * Used to correlate with ToolResultContent in subsequent messages. + * Create a validator for the given JSON Schema + * + * The validator is compiled once and can be reused multiple times. + * If the schema has an $id, it will be cached by AJV automatically. + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data */ - id: string2(), + getValidator(schema2) { + const ajvValidator = "$id" in schema2 && typeof schema2.$id === "string" ? this._ajv.getSchema(schema2.$id) ?? this._ajv.compile(schema2) : this._ajv.compile(schema2); + return (input) => { + const valid = ajvValidator(input); + if (valid) { + return { + valid: true, + data: input, + errorMessage: void 0 + }; + } else { + return { + valid: false, + data: void 0, + errorMessage: this._ajv.errorsText(ajvValidator.errors) + }; + } + }; + } +}; + +// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js +var ExperimentalServerTasks = class { + constructor(_server) { + this._server = _server; + } /** - * Arguments to pass to the tool. - * Must conform to the tool's inputSchema. + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to request processing, allowing you to + * observe intermediate task status updates for task-augmented requests. + * + * @param request - The request to send + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental */ - input: record(string2(), unknown()), + requestStream(request, resultSchema, options) { + return this._server.requestStream(request, resultSchema, options); + } /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. + * Sends a sampling request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages + * before the final result. + * + * @example + * ```typescript + * const stream = server.experimental.tasks.createMessageStream({ + * messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }], + * maxTokens: 100 + * }, { + * onprogress: (progress) => { + * // Handle streaming tokens via progress notifications + * console.log('Progress:', progress.message); + * } + * }); + * + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Task created:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Task status:', message.task.status); + * break; + * case 'result': + * console.log('Final result:', message.result); + * break; + * case 'error': + * console.error('Error:', message.error); + * break; + * } + * } + * ``` + * + * @param params - The sampling request parameters + * @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental */ - _meta: record(string2(), unknown()).optional() -}); -var EmbeddedResourceSchema = object2({ - type: literal("resource"), - resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]), + createMessageStream(params, options) { + const clientCapabilities = this._server.getClientCapabilities(); + if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) { + throw new Error("Client does not support sampling tools capability."); + } + if (params.messages.length > 0) { + const lastMessage = params.messages[params.messages.length - 1]; + const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; + const hasToolResults = lastContent.some((c) => c.type === "tool_result"); + const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0; + const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; + const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); + if (hasToolResults) { + if (lastContent.some((c) => c.type !== "tool_result")) { + throw new Error("The last message must contain only tool_result content if any is present"); + } + if (!hasPreviousToolUse) { + throw new Error("tool_result blocks are not matching any tool_use from the previous message"); + } + } + if (hasPreviousToolUse) { + const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); + const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); + if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) { + throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match"); + } + } + } + return this.requestStream({ + method: "sampling/createMessage", + params + }, CreateMessageResultSchema, options); + } /** - * Optional annotations for the client. + * Sends an elicitation request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * For task-augmented requests (especially URL-based elicitation), yields 'taskCreated' + * and 'taskStatus' messages before the final result. + * + * @example + * ```typescript + * const stream = server.experimental.tasks.elicitInputStream({ + * mode: 'url', + * message: 'Please authenticate', + * elicitationId: 'auth-123', + * url: 'https://example.com/auth' + * }, { + * task: { ttl: 300000 } // Task-augmented for long-running auth flow + * }); + * + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Task created:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Task status:', message.task.status); + * break; + * case 'result': + * console.log('User action:', message.result.action); + * break; + * case 'error': + * console.error('Error:', message.error); + * break; + * } + * } + * ``` + * + * @param params - The elicitation request parameters + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental */ - annotations: AnnotationsSchema.optional(), + elicitInputStream(params, options) { + const clientCapabilities = this._server.getClientCapabilities(); + const mode2 = params.mode ?? "form"; + switch (mode2) { + case "url": { + if (!clientCapabilities?.elicitation?.url) { + throw new Error("Client does not support url elicitation."); + } + break; + } + case "form": { + if (!clientCapabilities?.elicitation?.form) { + throw new Error("Client does not support form elicitation."); + } + break; + } + } + const normalizedParams = mode2 === "form" && params.mode === void 0 ? { ...params, mode: "form" } : params; + return this.requestStream({ + method: "elicitation/create", + params: normalizedParams + }, ElicitResultSchema, options); + } /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * @returns The task status + * + * @experimental */ - _meta: record(string2(), unknown()).optional() -}); -var ResourceLinkSchema = ResourceSchema.extend({ - type: literal("resource_link") -}); -var ContentBlockSchema = union([ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ResourceLinkSchema, - EmbeddedResourceSchema -]); -var PromptMessageSchema = object2({ - role: RoleSchema, - content: ContentBlockSchema -}); -var GetPromptResultSchema = ResultSchema.extend({ + async getTask(taskId, options) { + return this._server.getTask({ taskId }, options); + } /** - * An optional description for the prompt. + * Retrieves the result of a completed task. + * + * @param taskId - The task identifier + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options + * @returns The task result + * + * @experimental */ - description: string2().optional(), - messages: array(PromptMessageSchema) -}); -var PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema.optional() -}); -var ToolAnnotationsSchema = object2({ + async getTaskResult(taskId, resultSchema, options) { + return this._server.getTaskResult({ taskId }, resultSchema, options); + } /** - * A human-readable title for the tool. + * Lists tasks with optional pagination. + * + * @param cursor - Optional pagination cursor + * @param options - Optional request options + * @returns List of tasks with optional next cursor + * + * @experimental */ - title: string2().optional(), + async listTasks(cursor, options) { + return this._server.listTasks(cursor ? { cursor } : void 0, options); + } /** - * If true, the tool does not modify its environment. + * Cancels a running task. * - * Default: false + * @param taskId - The task identifier + * @param options - Optional request options + * + * @experimental */ - readOnlyHint: boolean2().optional(), + async cancelTask(taskId, options) { + return this._server.cancelTask({ taskId }, options); + } +}; + +// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js +function assertToolsCallTaskCapability(requests, method, entityName) { + if (!requests) { + throw new Error(`${entityName} does not support task creation (required for ${method})`); + } + switch (method) { + case "tools/call": + if (!requests.tools?.call) { + throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`); + } + break; + default: + break; + } +} +function assertClientRequestTaskCapability(requests, method, entityName) { + if (!requests) { + throw new Error(`${entityName} does not support task creation (required for ${method})`); + } + switch (method) { + case "sampling/createMessage": + if (!requests.sampling?.createMessage) { + throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`); + } + break; + case "elicitation/create": + if (!requests.elicitation?.create) { + throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`); + } + break; + default: + break; + } +} + +// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js +var Server = class extends Protocol { /** - * If true, the tool may perform destructive updates to its environment. - * If false, the tool performs only additive updates. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: true + * Initializes this server with the given name and version information. */ - destructiveHint: boolean2().optional(), + constructor(_serverInfo, options) { + super(options); + this._serverInfo = _serverInfo; + this._loggingLevels = /* @__PURE__ */ new Map(); + this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index2) => [level, index2])); + this.isMessageIgnored = (level, sessionId) => { + const currentLevel = this._loggingLevels.get(sessionId); + return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; + }; + this._capabilities = options?.capabilities ?? {}; + this._instructions = options?.instructions; + this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); + this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request)); + this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.()); + if (this._capabilities.logging) { + this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => { + const transportSessionId = extra.sessionId || extra.requestInfo?.headers["mcp-session-id"] || void 0; + const { level } = request.params; + const parseResult = LoggingLevelSchema.safeParse(level); + if (parseResult.success) { + this._loggingLevels.set(transportSessionId, parseResult.data); + } + return {}; + }); + } + } /** - * If true, calling the tool repeatedly with the same arguments - * will have no additional effect on the its environment. - * - * (This property is meaningful only when `readOnlyHint == false`) + * Access experimental features. * - * Default: false - */ - idempotentHint: boolean2().optional(), - /** - * If true, this tool may interact with an "open world" of external - * entities. If false, the tool's domain of interaction is closed. - * For example, the world of a web search tool is open, whereas that - * of a memory tool is not. + * WARNING: These APIs are experimental and may change without notice. * - * Default: true + * @experimental */ - openWorldHint: boolean2().optional() -}); -var ToolExecutionSchema = object2({ + get experimental() { + if (!this._experimental) { + this._experimental = { + tasks: new ExperimentalServerTasks(this) + }; + } + return this._experimental; + } /** - * Indicates the tool's preference for task-augmented execution. - * - "required": Clients MUST invoke the tool as a task - * - "optional": Clients MAY invoke the tool as a task or normal request - * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task + * Registers new capabilities. This can only be called before connecting to a transport. * - * If not present, defaults to "forbidden". + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). */ - taskSupport: _enum(["required", "optional", "forbidden"]).optional() -}); -var ToolSchema = object2({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, + registerCapabilities(capabilities) { + if (this.transport) { + throw new Error("Cannot register capabilities after connecting to transport"); + } + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + } /** - * A human-readable description of the tool. + * Override request handler registration to enforce server-side validation for tools/call. */ - description: string2().optional(), + setRequestHandler(requestSchema, handler) { + const shape = getObjectShape(requestSchema); + const methodSchema = shape?.method; + if (!methodSchema) { + throw new Error("Schema is missing a method literal"); + } + let methodValue; + if (isZ4Schema(methodSchema)) { + const v4Schema = methodSchema; + const v4Def = v4Schema._zod?.def; + methodValue = v4Def?.value ?? v4Schema.value; + } else { + const v3Schema = methodSchema; + const legacyDef = v3Schema._def; + methodValue = legacyDef?.value ?? v3Schema.value; + } + if (typeof methodValue !== "string") { + throw new Error("Schema method literal must be a string"); + } + const method = methodValue; + if (method === "tools/call") { + const wrappedHandler = async (request, extra) => { + const validatedRequest = safeParse2(CallToolRequestSchema, request); + if (!validatedRequest.success) { + const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`); + } + const { params } = validatedRequest.data; + const result = await Promise.resolve(handler(request, extra)); + if (params.task) { + const taskValidationResult = safeParse2(CreateTaskResultSchema, result); + if (!taskValidationResult.success) { + const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); + } + return taskValidationResult.data; + } + const validationResult = safeParse2(CallToolResultSchema, result); + if (!validationResult.success) { + const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`); + } + return validationResult.data; + }; + return super.setRequestHandler(requestSchema, wrappedHandler); + } + return super.setRequestHandler(requestSchema, handler); + } + assertCapabilityForMethod(method) { + switch (method) { + case "sampling/createMessage": + if (!this._clientCapabilities?.sampling) { + throw new Error(`Client does not support sampling (required for ${method})`); + } + break; + case "elicitation/create": + if (!this._clientCapabilities?.elicitation) { + throw new Error(`Client does not support elicitation (required for ${method})`); + } + break; + case "roots/list": + if (!this._clientCapabilities?.roots) { + throw new Error(`Client does not support listing roots (required for ${method})`); + } + break; + case "ping": + break; + } + } + assertNotificationCapability(method) { + switch (method) { + case "notifications/message": + if (!this._capabilities.logging) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case "notifications/resources/updated": + case "notifications/resources/list_changed": + if (!this._capabilities.resources) { + throw new Error(`Server does not support notifying about resources (required for ${method})`); + } + break; + case "notifications/tools/list_changed": + if (!this._capabilities.tools) { + throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); + } + break; + case "notifications/prompts/list_changed": + if (!this._capabilities.prompts) { + throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); + } + break; + case "notifications/elicitation/complete": + if (!this._clientCapabilities?.elicitation?.url) { + throw new Error(`Client does not support URL elicitation (required for ${method})`); + } + break; + case "notifications/cancelled": + break; + case "notifications/progress": + break; + } + } + assertRequestHandlerCapability(method) { + if (!this._capabilities) { + return; + } + switch (method) { + case "completion/complete": + if (!this._capabilities.completions) { + throw new Error(`Server does not support completions (required for ${method})`); + } + break; + case "logging/setLevel": + if (!this._capabilities.logging) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case "prompts/get": + case "prompts/list": + if (!this._capabilities.prompts) { + throw new Error(`Server does not support prompts (required for ${method})`); + } + break; + case "resources/list": + case "resources/templates/list": + case "resources/read": + if (!this._capabilities.resources) { + throw new Error(`Server does not support resources (required for ${method})`); + } + break; + case "tools/call": + case "tools/list": + if (!this._capabilities.tools) { + throw new Error(`Server does not support tools (required for ${method})`); + } + break; + case "tasks/get": + case "tasks/list": + case "tasks/result": + case "tasks/cancel": + if (!this._capabilities.tasks) { + throw new Error(`Server does not support tasks capability (required for ${method})`); + } + break; + case "ping": + case "initialize": + break; + } + } + assertTaskCapability(method) { + assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, "Client"); + } + assertTaskHandlerCapability(method) { + if (!this._capabilities) { + return; + } + assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, "Server"); + } + async _oninitialize(request) { + const requestedVersion = request.params.protocolVersion; + this._clientCapabilities = request.params.capabilities; + this._clientVersion = request.params.clientInfo; + const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION; + return { + protocolVersion, + capabilities: this.getCapabilities(), + serverInfo: this._serverInfo, + ...this._instructions && { instructions: this._instructions } + }; + } /** - * A JSON Schema 2020-12 object defining the expected parameters for the tool. - * Must have type: 'object' at the root level per MCP spec. + * After initialization has completed, this will be populated with the client's reported capabilities. */ - inputSchema: object2({ - type: literal("object"), - properties: record(string2(), AssertObjectSchema).optional(), - required: array(string2()).optional() - }).catchall(unknown()), + getClientCapabilities() { + return this._clientCapabilities; + } /** - * An optional JSON Schema 2020-12 object defining the structure of the tool's output - * returned in the structuredContent field of a CallToolResult. - * Must have type: 'object' at the root level per MCP spec. + * After initialization has completed, this will be populated with information about the client's name and version. */ - outputSchema: object2({ - type: literal("object"), - properties: record(string2(), AssertObjectSchema).optional(), - required: array(string2()).optional() - }).catchall(unknown()).optional(), + getClientVersion() { + return this._clientVersion; + } + getCapabilities() { + return this._capabilities; + } + async ping() { + return this.request({ method: "ping" }, EmptyResultSchema); + } + // Implementation + async createMessage(params, options) { + if (params.tools || params.toolChoice) { + if (!this._clientCapabilities?.sampling?.tools) { + throw new Error("Client does not support sampling tools capability."); + } + } + if (params.messages.length > 0) { + const lastMessage = params.messages[params.messages.length - 1]; + const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; + const hasToolResults = lastContent.some((c) => c.type === "tool_result"); + const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0; + const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; + const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); + if (hasToolResults) { + if (lastContent.some((c) => c.type !== "tool_result")) { + throw new Error("The last message must contain only tool_result content if any is present"); + } + if (!hasPreviousToolUse) { + throw new Error("tool_result blocks are not matching any tool_use from the previous message"); + } + } + if (hasPreviousToolUse) { + const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); + const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); + if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) { + throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match"); + } + } + } + if (params.tools) { + return this.request({ method: "sampling/createMessage", params }, CreateMessageResultWithToolsSchema, options); + } + return this.request({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options); + } /** - * Optional additional tool information. + * Creates an elicitation request for the given parameters. + * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`. + * @param params The parameters for the elicitation request. + * @param options Optional request options. + * @returns The result of the elicitation request. */ - annotations: ToolAnnotationsSchema.optional(), + async elicitInput(params, options) { + const mode2 = params.mode ?? "form"; + switch (mode2) { + case "url": { + if (!this._clientCapabilities?.elicitation?.url) { + throw new Error("Client does not support url elicitation."); + } + const urlParams = params; + return this.request({ method: "elicitation/create", params: urlParams }, ElicitResultSchema, options); + } + case "form": { + if (!this._clientCapabilities?.elicitation?.form) { + throw new Error("Client does not support form elicitation."); + } + const formParams = params.mode === "form" ? params : { ...params, mode: "form" }; + const result = await this.request({ method: "elicitation/create", params: formParams }, ElicitResultSchema, options); + if (result.action === "accept" && result.content && formParams.requestedSchema) { + try { + const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema); + const validationResult = validator(result.content); + if (!validationResult.valid) { + throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); + } + } catch (error2) { + if (error2 instanceof McpError) { + throw error2; + } + throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error2 instanceof Error ? error2.message : String(error2)}`); + } + } + return result; + } + } + } /** - * Execution-related properties for this tool. + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. */ - execution: ToolExecutionSchema.optional(), + createElicitationCompletionNotifier(elicitationId, options) { + if (!this._clientCapabilities?.elicitation?.url) { + throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)"); + } + return () => this.notification({ + method: "notifications/elicitation/complete", + params: { + elicitationId + } + }, options); + } + async listRoots(params, options) { + return this.request({ method: "roots/list", params }, ListRootsResultSchema, options); + } /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility */ - _meta: record(string2(), unknown()).optional() -}); -var ListToolsRequestSchema = PaginatedRequestSchema.extend({ - method: literal("tools/list") -}); -var ListToolsResultSchema = PaginatedResultSchema.extend({ - tools: array(ToolSchema) -}); -var CallToolResultSchema = ResultSchema.extend({ + async sendLoggingMessage(params, sessionId) { + if (this._capabilities.logging) { + if (!this.isMessageIgnored(params.level, sessionId)) { + return this.notification({ method: "notifications/message", params }); + } + } + } + async sendResourceUpdated(params) { + return this.notification({ + method: "notifications/resources/updated", + params + }); + } + async sendResourceListChanged() { + return this.notification({ + method: "notifications/resources/list_changed" + }); + } + async sendToolListChanged() { + return this.notification({ method: "notifications/tools/list_changed" }); + } + async sendPromptListChanged() { + return this.notification({ method: "notifications/prompts/list_changed" }); + } +}; + +// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js +var COMPLETABLE_SYMBOL = /* @__PURE__ */ Symbol.for("mcp.completable"); +function isCompletable(schema2) { + return !!schema2 && typeof schema2 === "object" && COMPLETABLE_SYMBOL in schema2; +} +function getCompleter(schema2) { + const meta = schema2[COMPLETABLE_SYMBOL]; + return meta?.complete; +} +var McpZodTypeKind; +(function(McpZodTypeKind2) { + McpZodTypeKind2["Completable"] = "McpCompletable"; +})(McpZodTypeKind || (McpZodTypeKind = {})); + +// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js +var TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; +function validateToolName(name315) { + const warnings = []; + if (name315.length === 0) { + return { + isValid: false, + warnings: ["Tool name cannot be empty"] + }; + } + if (name315.length > 128) { + return { + isValid: false, + warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name315.length})`] + }; + } + if (name315.includes(" ")) { + warnings.push("Tool name contains spaces, which may cause parsing issues"); + } + if (name315.includes(",")) { + warnings.push("Tool name contains commas, which may cause parsing issues"); + } + if (name315.startsWith("-") || name315.endsWith("-")) { + warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"); + } + if (name315.startsWith(".") || name315.endsWith(".")) { + warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"); + } + if (!TOOL_NAME_REGEX.test(name315)) { + const invalidChars = name315.split("").filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index2, arr) => arr.indexOf(char) === index2); + warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"); + return { + isValid: false, + warnings + }; + } + return { + isValid: true, + warnings + }; +} +function issueToolNameWarning(name315, warnings) { + if (warnings.length > 0) { + console.warn(`Tool name validation warning for "${name315}":`); + for (const warning of warnings) { + console.warn(` - ${warning}`); + } + console.warn("Tool registration will proceed, but this may cause compatibility issues."); + console.warn("Consider updating the tool name to conform to the MCP tool naming standard."); + console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details."); + } +} +function validateAndWarnToolName(name315) { + const result = validateToolName(name315); + issueToolNameWarning(name315, result.warnings); + return result.isValid; +} + +// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js +var ExperimentalMcpServerTasks = class { + constructor(_mcpServer) { + this._mcpServer = _mcpServer; + } + registerToolTask(name315, config5, handler) { + const execution = { taskSupport: "required", ...config5.execution }; + if (execution.taskSupport === "forbidden") { + throw new Error(`Cannot register task-based tool '${name315}' with taskSupport 'forbidden'. Use registerTool() instead.`); + } + const mcpServerInternal = this._mcpServer; + return mcpServerInternal._createRegisteredTool(name315, config5.title, config5.description, config5.inputSchema, config5.outputSchema, config5.annotations, execution, config5._meta, handler); + } +}; + +// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js +var McpServer = class { + constructor(serverInfo, options) { + this._registeredResources = {}; + this._registeredResourceTemplates = {}; + this._registeredTools = {}; + this._registeredPrompts = {}; + this._toolHandlersInitialized = false; + this._completionHandlerInitialized = false; + this._resourceHandlersInitialized = false; + this._promptHandlersInitialized = false; + this.server = new Server(serverInfo, options); + } /** - * A list of content objects that represent the result of the tool call. + * Access experimental features. * - * If the Tool does not define an outputSchema, this field MUST be present in the result. - * For backwards compatibility, this field is always present, but it may be empty. - */ - content: array(ContentBlockSchema).default([]), - /** - * An object containing structured tool output. + * WARNING: These APIs are experimental and may change without notice. * - * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. + * @experimental */ - structuredContent: record(string2(), unknown()).optional(), + get experimental() { + if (!this._experimental) { + this._experimental = { + tasks: new ExperimentalMcpServerTasks(this) + }; + } + return this._experimental; + } /** - * Whether the tool call ended in an error. - * - * If not set, this is assumed to be false (the call was successful). - * - * Any errors that originate from the tool SHOULD be reported inside the result - * object, with `isError` set to true, _not_ as an MCP protocol-level error - * response. Otherwise, the LLM would not be able to see that an error occurred - * and self-correct. + * Attaches to the given transport, starts it, and starts listening for messages. * - * However, any errors in _finding_ the tool, an error indicating that the - * server does not support tool calls, or any other exceptional conditions, - * should be reported as an MCP error response. + * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. */ - isError: boolean2().optional() -}); -var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ - toolResult: unknown() -})); -var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + async connect(transport) { + return await this.server.connect(transport); + } /** - * The name of the tool to call. + * Closes the connection. */ - name: string2(), + async close() { + await this.server.close(); + } + setToolRequestHandlers() { + if (this._toolHandlersInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)); + this.server.registerCapabilities({ + tools: { + listChanged: true + } + }); + this.server.setRequestHandler(ListToolsRequestSchema, () => ({ + tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name315, tool]) => { + const toolDefinition = { + name: name315, + title: tool.title, + description: tool.description, + inputSchema: (() => { + const obj = normalizeObjectSchema(tool.inputSchema); + return obj ? toJsonSchemaCompat(obj, { + strictUnions: true, + pipeStrategy: "input" + }) : EMPTY_OBJECT_JSON_SCHEMA; + })(), + annotations: tool.annotations, + execution: tool.execution, + _meta: tool._meta + }; + if (tool.outputSchema) { + const obj = normalizeObjectSchema(tool.outputSchema); + if (obj) { + toolDefinition.outputSchema = toJsonSchemaCompat(obj, { + strictUnions: true, + pipeStrategy: "output" + }); + } + } + return toolDefinition; + }) + })); + this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { + try { + const tool = this._registeredTools[request.params.name]; + if (!tool) { + throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`); + } + if (!tool.enabled) { + throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); + } + const isTaskRequest = !!request.params.task; + const taskSupport = tool.execution?.taskSupport; + const isTaskHandler = "createTask" in tool.handler; + if ((taskSupport === "required" || taskSupport === "optional") && !isTaskHandler) { + throw new McpError(ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`); + } + if (taskSupport === "required" && !isTaskRequest) { + throw new McpError(ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`); + } + if (taskSupport === "optional" && !isTaskRequest && isTaskHandler) { + return await this.handleAutomaticTaskPolling(tool, request, extra); + } + const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); + const result = await this.executeToolHandler(tool, args, extra); + if (isTaskRequest) { + return result; + } + await this.validateToolOutput(tool, result, request.params.name); + return result; + } catch (error2) { + if (error2 instanceof McpError) { + if (error2.code === ErrorCode.UrlElicitationRequired) { + throw error2; + } + } + return this.createToolError(error2 instanceof Error ? error2.message : String(error2)); + } + }); + this._toolHandlersInitialized = true; + } /** - * Arguments to pass to the tool. + * Creates a tool error result. + * + * @param errorMessage - The error message. + * @returns The tool error result. */ - arguments: record(string2(), unknown()).optional() -}); -var CallToolRequestSchema = RequestSchema.extend({ - method: literal("tools/call"), - params: CallToolRequestParamsSchema -}); -var ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema.optional() -}); -var ListChangedOptionsBaseSchema = object2({ + createToolError(errorMessage) { + return { + content: [ + { + type: "text", + text: errorMessage + } + ], + isError: true + }; + } /** - * If true, the list will be refreshed automatically when a list changed notification is received. - * The callback will be called with the updated list. - * - * If false, the callback will be called with null items, allowing manual refresh. - * - * @default true + * Validates tool input arguments against the tool's input schema. */ - autoRefresh: boolean2().default(true), + async validateToolInput(tool, args, toolName) { + if (!tool.inputSchema) { + return void 0; + } + const inputObj = normalizeObjectSchema(tool.inputSchema); + const schemaToParse = inputObj ?? tool.inputSchema; + const parseResult = await safeParseAsync2(schemaToParse, args); + if (!parseResult.success) { + const error2 = "error" in parseResult ? parseResult.error : "Unknown error"; + const errorMessage = getParseErrorMessage(error2); + throw new McpError(ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`); + } + return parseResult.data; + } /** - * Debounce time in milliseconds for list changed notification processing. - * - * Multiple notifications received within this timeframe will only trigger one refresh. - * Set to 0 to disable debouncing. - * - * @default 300 + * Validates tool output against the tool's output schema. */ - debounceMs: number2().int().nonnegative().default(300) -}); -var LoggingLevelSchema = _enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]); -var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ + async validateToolOutput(tool, result, toolName) { + if (!tool.outputSchema) { + return; + } + if (!("content" in result)) { + return; + } + if (result.isError) { + return; + } + if (!result.structuredContent) { + throw new McpError(ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); + } + const outputObj = normalizeObjectSchema(tool.outputSchema); + const parseResult = await safeParseAsync2(outputObj, result.structuredContent); + if (!parseResult.success) { + const error2 = "error" in parseResult ? parseResult.error : "Unknown error"; + const errorMessage = getParseErrorMessage(error2); + throw new McpError(ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`); + } + } /** - * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. + * Executes a tool handler (either regular or task-based). */ - level: LoggingLevelSchema -}); -var SetLevelRequestSchema = RequestSchema.extend({ - method: literal("logging/setLevel"), - params: SetLevelRequestParamsSchema -}); -var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + async executeToolHandler(tool, args, extra) { + const handler = tool.handler; + const isTaskHandler = "createTask" in handler; + if (isTaskHandler) { + if (!extra.taskStore) { + throw new Error("No task store provided."); + } + const taskExtra = { ...extra, taskStore: extra.taskStore }; + if (tool.inputSchema) { + const typedHandler = handler; + return await Promise.resolve(typedHandler.createTask(args, taskExtra)); + } else { + const typedHandler = handler; + return await Promise.resolve(typedHandler.createTask(taskExtra)); + } + } + if (tool.inputSchema) { + const typedHandler = handler; + return await Promise.resolve(typedHandler(args, extra)); + } else { + const typedHandler = handler; + return await Promise.resolve(typedHandler(extra)); + } + } /** - * The severity of this log message. + * Handles automatic task polling for tools with taskSupport 'optional'. */ - level: LoggingLevelSchema, + async handleAutomaticTaskPolling(tool, request, extra) { + if (!extra.taskStore) { + throw new Error("No task store provided for task-capable tool."); + } + const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); + const handler = tool.handler; + const taskExtra = { ...extra, taskStore: extra.taskStore }; + const createTaskResult = args ? await Promise.resolve(handler.createTask(args, taskExtra)) : ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + await Promise.resolve(handler.createTask(taskExtra)) + ); + const taskId = createTaskResult.task.taskId; + let task = createTaskResult.task; + const pollInterval = task.pollInterval ?? 5e3; + while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") { + await new Promise((resolve2) => setTimeout(resolve2, pollInterval)); + const updatedTask = await extra.taskStore.getTask(taskId); + if (!updatedTask) { + throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`); + } + task = updatedTask; + } + return await extra.taskStore.getTaskResult(taskId); + } + setCompletionRequestHandler() { + if (this._completionHandlerInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)); + this.server.registerCapabilities({ + completions: {} + }); + this.server.setRequestHandler(CompleteRequestSchema, async (request) => { + switch (request.params.ref.type) { + case "ref/prompt": + assertCompleteRequestPrompt(request); + return this.handlePromptCompletion(request, request.params.ref); + case "ref/resource": + assertCompleteRequestResourceTemplate(request); + return this.handleResourceCompletion(request, request.params.ref); + default: + throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); + } + }); + this._completionHandlerInitialized = true; + } + async handlePromptCompletion(request, ref) { + const prompt = this._registeredPrompts[ref.name]; + if (!prompt) { + throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`); + } + if (!prompt.enabled) { + throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); + } + if (!prompt.argsSchema) { + return EMPTY_COMPLETION_RESULT; + } + const promptShape = getObjectShape(prompt.argsSchema); + const field = promptShape?.[request.params.argument.name]; + if (!isCompletable(field)) { + return EMPTY_COMPLETION_RESULT; + } + const completer = getCompleter(field); + if (!completer) { + return EMPTY_COMPLETION_RESULT; + } + const suggestions = await completer(request.params.argument.value, request.params.context); + return createCompletionResult(suggestions); + } + async handleResourceCompletion(request, ref) { + const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri); + if (!template) { + if (this._registeredResources[ref.uri]) { + return EMPTY_COMPLETION_RESULT; + } + throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); + } + const completer = template.resourceTemplate.completeCallback(request.params.argument.name); + if (!completer) { + return EMPTY_COMPLETION_RESULT; + } + const suggestions = await completer(request.params.argument.value, request.params.context); + return createCompletionResult(suggestions); + } + setResourceRequestHandlers() { + if (this._resourceHandlersInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)); + this.server.registerCapabilities({ + resources: { + listChanged: true + } + }); + this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => { + const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({ + uri, + name: resource.name, + ...resource.metadata + })); + const templateResources = []; + for (const template of Object.values(this._registeredResourceTemplates)) { + if (!template.resourceTemplate.listCallback) { + continue; + } + const result = await template.resourceTemplate.listCallback(extra); + for (const resource of result.resources) { + templateResources.push({ + ...template.metadata, + // the defined resource metadata should override the template metadata if present + ...resource + }); + } + } + return { resources: [...resources, ...templateResources] }; + }); + this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => { + const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name315, template]) => ({ + name: name315, + uriTemplate: template.resourceTemplate.uriTemplate.toString(), + ...template.metadata + })); + return { resourceTemplates }; + }); + this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => { + const uri = new URL(request.params.uri); + const resource = this._registeredResources[uri.toString()]; + if (resource) { + if (!resource.enabled) { + throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`); + } + return resource.readCallback(uri, extra); + } + for (const template of Object.values(this._registeredResourceTemplates)) { + const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); + if (variables) { + return template.readCallback(uri, variables, extra); + } + } + throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`); + }); + this._resourceHandlersInitialized = true; + } + setPromptRequestHandlers() { + if (this._promptHandlersInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)); + this.server.registerCapabilities({ + prompts: { + listChanged: true + } + }); + this.server.setRequestHandler(ListPromptsRequestSchema, () => ({ + prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name315, prompt]) => { + return { + name: name315, + title: prompt.title, + description: prompt.description, + arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : void 0 + }; + }) + })); + this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => { + const prompt = this._registeredPrompts[request.params.name]; + if (!prompt) { + throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); + } + if (!prompt.enabled) { + throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); + } + if (prompt.argsSchema) { + const argsObj = normalizeObjectSchema(prompt.argsSchema); + const parseResult = await safeParseAsync2(argsObj, request.params.arguments); + if (!parseResult.success) { + const error2 = "error" in parseResult ? parseResult.error : "Unknown error"; + const errorMessage = getParseErrorMessage(error2); + throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage}`); + } + const args = parseResult.data; + const cb = prompt.callback; + return await Promise.resolve(cb(args, extra)); + } else { + const cb = prompt.callback; + return await Promise.resolve(cb(extra)); + } + }); + this._promptHandlersInitialized = true; + } + resource(name315, uriOrTemplate, ...rest) { + let metadata; + if (typeof rest[0] === "object") { + metadata = rest.shift(); + } + const readCallback = rest[0]; + if (typeof uriOrTemplate === "string") { + if (this._registeredResources[uriOrTemplate]) { + throw new Error(`Resource ${uriOrTemplate} is already registered`); + } + const registeredResource = this._createRegisteredResource(name315, void 0, uriOrTemplate, metadata, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResource; + } else { + if (this._registeredResourceTemplates[name315]) { + throw new Error(`Resource template ${name315} is already registered`); + } + const registeredResourceTemplate = this._createRegisteredResourceTemplate(name315, void 0, uriOrTemplate, metadata, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResourceTemplate; + } + } + registerResource(name315, uriOrTemplate, config5, readCallback) { + if (typeof uriOrTemplate === "string") { + if (this._registeredResources[uriOrTemplate]) { + throw new Error(`Resource ${uriOrTemplate} is already registered`); + } + const registeredResource = this._createRegisteredResource(name315, config5.title, uriOrTemplate, config5, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResource; + } else { + if (this._registeredResourceTemplates[name315]) { + throw new Error(`Resource template ${name315} is already registered`); + } + const registeredResourceTemplate = this._createRegisteredResourceTemplate(name315, config5.title, uriOrTemplate, config5, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResourceTemplate; + } + } + _createRegisteredResource(name315, title, uri, metadata, readCallback) { + const registeredResource = { + name: name315, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResource.update({ enabled: false }), + enable: () => registeredResource.update({ enabled: true }), + remove: () => registeredResource.update({ uri: null }), + update: (updates) => { + if (typeof updates.uri !== "undefined" && updates.uri !== uri) { + delete this._registeredResources[uri]; + if (updates.uri) + this._registeredResources[updates.uri] = registeredResource; + } + if (typeof updates.name !== "undefined") + registeredResource.name = updates.name; + if (typeof updates.title !== "undefined") + registeredResource.title = updates.title; + if (typeof updates.metadata !== "undefined") + registeredResource.metadata = updates.metadata; + if (typeof updates.callback !== "undefined") + registeredResource.readCallback = updates.callback; + if (typeof updates.enabled !== "undefined") + registeredResource.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResources[uri] = registeredResource; + return registeredResource; + } + _createRegisteredResourceTemplate(name315, title, template, metadata, readCallback) { + const registeredResourceTemplate = { + resourceTemplate: template, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResourceTemplate.update({ enabled: false }), + enable: () => registeredResourceTemplate.update({ enabled: true }), + remove: () => registeredResourceTemplate.update({ name: null }), + update: (updates) => { + if (typeof updates.name !== "undefined" && updates.name !== name315) { + delete this._registeredResourceTemplates[name315]; + if (updates.name) + this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; + } + if (typeof updates.title !== "undefined") + registeredResourceTemplate.title = updates.title; + if (typeof updates.template !== "undefined") + registeredResourceTemplate.resourceTemplate = updates.template; + if (typeof updates.metadata !== "undefined") + registeredResourceTemplate.metadata = updates.metadata; + if (typeof updates.callback !== "undefined") + registeredResourceTemplate.readCallback = updates.callback; + if (typeof updates.enabled !== "undefined") + registeredResourceTemplate.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResourceTemplates[name315] = registeredResourceTemplate; + const variableNames = template.uriTemplate.variableNames; + const hasCompleter = Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v)); + if (hasCompleter) { + this.setCompletionRequestHandler(); + } + return registeredResourceTemplate; + } + _createRegisteredPrompt(name315, title, description, argsSchema, callback) { + const registeredPrompt = { + title, + description, + argsSchema: argsSchema === void 0 ? void 0 : objectFromShape(argsSchema), + callback, + enabled: true, + disable: () => registeredPrompt.update({ enabled: false }), + enable: () => registeredPrompt.update({ enabled: true }), + remove: () => registeredPrompt.update({ name: null }), + update: (updates) => { + if (typeof updates.name !== "undefined" && updates.name !== name315) { + delete this._registeredPrompts[name315]; + if (updates.name) + this._registeredPrompts[updates.name] = registeredPrompt; + } + if (typeof updates.title !== "undefined") + registeredPrompt.title = updates.title; + if (typeof updates.description !== "undefined") + registeredPrompt.description = updates.description; + if (typeof updates.argsSchema !== "undefined") + registeredPrompt.argsSchema = objectFromShape(updates.argsSchema); + if (typeof updates.callback !== "undefined") + registeredPrompt.callback = updates.callback; + if (typeof updates.enabled !== "undefined") + registeredPrompt.enabled = updates.enabled; + this.sendPromptListChanged(); + } + }; + this._registeredPrompts[name315] = registeredPrompt; + if (argsSchema) { + const hasCompletable = Object.values(argsSchema).some((field) => { + const inner = field instanceof ZodOptional ? field._def?.innerType : field; + return isCompletable(inner); + }); + if (hasCompletable) { + this.setCompletionRequestHandler(); + } + } + return registeredPrompt; + } + _createRegisteredTool(name315, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) { + validateAndWarnToolName(name315); + const registeredTool = { + title, + description, + inputSchema: getZodSchemaObject(inputSchema), + outputSchema: getZodSchemaObject(outputSchema), + annotations, + execution, + _meta, + handler, + enabled: true, + disable: () => registeredTool.update({ enabled: false }), + enable: () => registeredTool.update({ enabled: true }), + remove: () => registeredTool.update({ name: null }), + update: (updates) => { + if (typeof updates.name !== "undefined" && updates.name !== name315) { + if (typeof updates.name === "string") { + validateAndWarnToolName(updates.name); + } + delete this._registeredTools[name315]; + if (updates.name) + this._registeredTools[updates.name] = registeredTool; + } + if (typeof updates.title !== "undefined") + registeredTool.title = updates.title; + if (typeof updates.description !== "undefined") + registeredTool.description = updates.description; + if (typeof updates.paramsSchema !== "undefined") + registeredTool.inputSchema = objectFromShape(updates.paramsSchema); + if (typeof updates.outputSchema !== "undefined") + registeredTool.outputSchema = objectFromShape(updates.outputSchema); + if (typeof updates.callback !== "undefined") + registeredTool.handler = updates.callback; + if (typeof updates.annotations !== "undefined") + registeredTool.annotations = updates.annotations; + if (typeof updates._meta !== "undefined") + registeredTool._meta = updates._meta; + if (typeof updates.enabled !== "undefined") + registeredTool.enabled = updates.enabled; + this.sendToolListChanged(); + } + }; + this._registeredTools[name315] = registeredTool; + this.setToolRequestHandlers(); + this.sendToolListChanged(); + return registeredTool; + } /** - * An optional name of the logger issuing this message. + * tool() implementation. Parses arguments passed to overrides defined above. */ - logger: string2().optional(), + tool(name315, ...rest) { + if (this._registeredTools[name315]) { + throw new Error(`Tool ${name315} is already registered`); + } + let description; + let inputSchema; + let outputSchema; + let annotations; + if (typeof rest[0] === "string") { + description = rest.shift(); + } + if (rest.length > 1) { + const firstArg = rest[0]; + if (isZodRawShapeCompat(firstArg)) { + inputSchema = rest.shift(); + if (rest.length > 1 && typeof rest[0] === "object" && rest[0] !== null && !isZodRawShapeCompat(rest[0])) { + annotations = rest.shift(); + } + } else if (typeof firstArg === "object" && firstArg !== null) { + if (Object.values(firstArg).some((v) => typeof v === "object" && v !== null)) { + throw new Error(`Tool ${name315} expected a Zod schema or ToolAnnotations, but received an unrecognized object`); + } + annotations = rest.shift(); + } + } + const callback = rest[0]; + return this._createRegisteredTool(name315, void 0, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, void 0, callback); + } /** - * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + * Registers a tool with a config object and callback. */ - data: unknown() -}); -var LoggingMessageNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema -}); -var ModelHintSchema = object2({ + registerTool(name315, config5, cb) { + if (this._registeredTools[name315]) { + throw new Error(`Tool ${name315} is already registered`); + } + const { title, description, inputSchema, outputSchema, annotations, _meta } = config5; + return this._createRegisteredTool(name315, title, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, _meta, cb); + } + prompt(name315, ...rest) { + if (this._registeredPrompts[name315]) { + throw new Error(`Prompt ${name315} is already registered`); + } + let description; + if (typeof rest[0] === "string") { + description = rest.shift(); + } + let argsSchema; + if (rest.length > 1) { + argsSchema = rest.shift(); + } + const cb = rest[0]; + const registeredPrompt = this._createRegisteredPrompt(name315, void 0, description, argsSchema, cb); + this.setPromptRequestHandlers(); + this.sendPromptListChanged(); + return registeredPrompt; + } /** - * A hint for a model name. + * Registers a prompt with a config object and callback. */ - name: string2().optional() -}); -var ModelPreferencesSchema = object2({ + registerPrompt(name315, config5, cb) { + if (this._registeredPrompts[name315]) { + throw new Error(`Prompt ${name315} is already registered`); + } + const { title, description, argsSchema } = config5; + const registeredPrompt = this._createRegisteredPrompt(name315, title, description, argsSchema, cb); + this.setPromptRequestHandlers(); + this.sendPromptListChanged(); + return registeredPrompt; + } /** - * Optional hints to use for model selection. + * Checks if the server is connected to a transport. + * @returns True if the server is connected */ - hints: array(ModelHintSchema).optional(), + isConnected() { + return this.server.transport !== void 0; + } /** - * How much to prioritize cost when selecting a model. + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility */ - costPriority: number2().min(0).max(1).optional(), + async sendLoggingMessage(params, sessionId) { + return this.server.sendLoggingMessage(params, sessionId); + } /** - * How much to prioritize sampling speed (latency) when selecting a model. + * Sends a resource list changed event to the client, if connected. */ - speedPriority: number2().min(0).max(1).optional(), + sendResourceListChanged() { + if (this.isConnected()) { + this.server.sendResourceListChanged(); + } + } /** - * How much to prioritize intelligence and capabilities when selecting a model. + * Sends a tool list changed event to the client, if connected. */ - intelligencePriority: number2().min(0).max(1).optional() -}); -var ToolChoiceSchema = object2({ + sendToolListChanged() { + if (this.isConnected()) { + this.server.sendToolListChanged(); + } + } /** - * Controls when tools are used: - * - "auto": Model decides whether to use tools (default) - * - "required": Model MUST use at least one tool before completing - * - "none": Model MUST NOT use any tools + * Sends a prompt list changed event to the client, if connected. */ - mode: _enum(["auto", "required", "none"]).optional() -}); -var ToolResultContentSchema = object2({ - type: literal("tool_result"), - toolUseId: string2().describe("The unique identifier for the corresponding tool call."), - content: array(ContentBlockSchema).default([]), - structuredContent: object2({}).loose().optional(), - isError: boolean2().optional(), + sendPromptListChanged() { + if (this.isConnected()) { + this.server.sendPromptListChanged(); + } + } +}; +var EMPTY_OBJECT_JSON_SCHEMA = { + type: "object", + properties: {} +}; +function isZodTypeLike(value) { + return value !== null && typeof value === "object" && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function"; +} +function isZodSchemaInstance(obj) { + return "_def" in obj || "_zod" in obj || isZodTypeLike(obj); +} +function isZodRawShapeCompat(obj) { + if (typeof obj !== "object" || obj === null) { + return false; + } + if (isZodSchemaInstance(obj)) { + return false; + } + if (Object.keys(obj).length === 0) { + return true; + } + return Object.values(obj).some(isZodTypeLike); +} +function getZodSchemaObject(schema2) { + if (!schema2) { + return void 0; + } + if (isZodRawShapeCompat(schema2)) { + return objectFromShape(schema2); + } + if (!isZodSchemaInstance(schema2)) { + throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object"); + } + return schema2; +} +function promptArgumentsFromSchema(schema2) { + const shape = getObjectShape(schema2); + if (!shape) + return []; + return Object.entries(shape).map(([name315, field]) => { + const description = getSchemaDescription(field); + const isOptional = isSchemaOptional(field); + return { + name: name315, + description, + required: !isOptional + }; + }); +} +function getMethodValue(schema2) { + const shape = getObjectShape(schema2); + const methodSchema = shape?.method; + if (!methodSchema) { + throw new Error("Schema is missing a method literal"); + } + const value = getLiteralValue(methodSchema); + if (typeof value === "string") { + return value; + } + throw new Error("Schema method literal must be a string"); +} +function createCompletionResult(suggestions) { + return { + completion: { + values: suggestions.slice(0, 100), + total: suggestions.length, + hasMore: suggestions.length > 100 + } + }; +} +var EMPTY_COMPLETION_RESULT = { + completion: { + values: [], + hasMore: false + } +}; + +// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js +import process2 from "node:process"; + +// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js +var ReadBuffer = class { + append(chunk) { + this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; + } + readMessage() { + if (!this._buffer) { + return null; + } + const index2 = this._buffer.indexOf("\n"); + if (index2 === -1) { + return null; + } + const line = this._buffer.toString("utf8", 0, index2).replace(/\r$/, ""); + this._buffer = this._buffer.subarray(index2 + 1); + return deserializeMessage(line); + } + clear() { + this._buffer = void 0; + } +}; +function deserializeMessage(line) { + return JSONRPCMessageSchema.parse(JSON.parse(line)); +} +function serializeMessage(message) { + return JSON.stringify(message) + "\n"; +} + +// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js +var StdioServerTransport = class { + constructor(_stdin = process2.stdin, _stdout = process2.stdout) { + this._stdin = _stdin; + this._stdout = _stdout; + this._readBuffer = new ReadBuffer(); + this._started = false; + this._ondata = (chunk) => { + this._readBuffer.append(chunk); + this.processReadBuffer(); + }; + this._onerror = (error2) => { + this.onerror?.(error2); + }; + } /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. + * Starts listening for messages on stdin. */ - _meta: record(string2(), unknown()).optional() + async start() { + if (this._started) { + throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); + } + this._started = true; + this._stdin.on("data", this._ondata); + this._stdin.on("error", this._onerror); + } + processReadBuffer() { + while (true) { + try { + const message = this._readBuffer.readMessage(); + if (message === null) { + break; + } + this.onmessage?.(message); + } catch (error2) { + this.onerror?.(error2); + } + } + } + async close() { + this._stdin.off("data", this._ondata); + this._stdin.off("error", this._onerror); + const remainingDataListeners = this._stdin.listenerCount("data"); + if (remainingDataListeners === 0) { + this._stdin.pause(); + } + this._readBuffer.clear(); + this.onclose?.(); + } + send(message) { + return new Promise((resolve2) => { + const json2 = serializeMessage(message); + if (this._stdout.write(json2)) { + resolve2(); + } else { + this._stdout.once("drain", resolve2); + } + }); + } +}; + +// packages/mcp-server/dist/index.js +import { readFileSync as readFileSync4, existsSync as existsSync6 } from "node:fs"; +import { join as join9, dirname as dirname2 } from "node:path"; +import { fileURLToPath } from "node:url"; + +// packages/core/dist/domain/prd-context.js +var PRDContextSchema = external_exports.enum([ + "proposal", + "feature", + "bug", + "incident", + "poc", + "mvp", + "release", + "cicd" +]); +var PRD_CONTEXT_CONFIGS = { + proposal: { + displayName: "Proposal", + description: "High-level, stakeholder-facing PRD focused on business value and ROI", + clarificationRange: [5, 6], + ragMaxHops: 1, + expectedSectionCount: 7, + preferredStrategyTier: 2 + }, + feature: { + displayName: "Feature", + description: "Implementation-ready PRD with deep technical specifications", + clarificationRange: [8, 10], + ragMaxHops: 3, + expectedSectionCount: 11, + preferredStrategyTier: 1 + }, + bug: { + displayName: "Bug Fix", + description: "Root cause analysis PRD focused on targeted fix and regression prevention", + clarificationRange: [6, 8], + ragMaxHops: 3, + expectedSectionCount: 6, + preferredStrategyTier: 1 + }, + incident: { + displayName: "Incident", + description: "Forensic investigation PRD for urgent response and mitigation", + clarificationRange: [10, 12], + ragMaxHops: 4, + expectedSectionCount: 8, + preferredStrategyTier: 1 + }, + poc: { + displayName: "Proof of Concept", + description: "Technical feasibility validation PRD with minimal scope", + clarificationRange: [4, 5], + ragMaxHops: 2, + expectedSectionCount: 5, + preferredStrategyTier: 3 + }, + mvp: { + displayName: "MVP", + description: "Minimum viable product PRD focused on core value and fast delivery", + clarificationRange: [6, 7], + ragMaxHops: 2, + expectedSectionCount: 8, + preferredStrategyTier: 2 + }, + release: { + displayName: "Release", + description: "Production release PRD with full documentation and migration guides", + clarificationRange: [9, 11], + ragMaxHops: 3, + expectedSectionCount: 10, + preferredStrategyTier: 1 + }, + cicd: { + displayName: "CI/CD Pipeline", + description: "CI/CD pipeline PRD with automation stages, testing, and deployment flows", + clarificationRange: [7, 9], + ragMaxHops: 3, + expectedSectionCount: 9, + preferredStrategyTier: 1 + } +}; + +// packages/core/dist/domain/section-type.js +var SectionTypeSchema = external_exports.enum([ + "overview", + "goals", + "requirements", + "user_stories", + "technical_specification", + "acceptance_criteria", + "data_model", + "api_specification", + "security_considerations", + "performance_requirements", + "testing", + "deployment", + "risks", + "timeline", + "source_code", + "test_code", + "jira_tickets" +]); +var SECTION_DISPLAY_NAMES = { + overview: "Overview", + goals: "Goals & Objectives", + requirements: "Requirements", + user_stories: "User Stories", + technical_specification: "Technical Specification", + acceptance_criteria: "Acceptance Criteria", + data_model: "Data Model", + api_specification: "API Specification", + security_considerations: "Security Considerations", + performance_requirements: "Performance Requirements", + testing: "Testing Strategy", + deployment: "Deployment Plan", + risks: "Risks & Mitigation", + timeline: "Timeline & Milestones", + source_code: "Source Code", + test_code: "Test Code", + jira_tickets: "JIRA Tickets" +}; +var SECTION_ORDER = { + overview: 0, + goals: 1, + requirements: 2, + user_stories: 3, + technical_specification: 4, + acceptance_criteria: 5, + data_model: 6, + api_specification: 7, + security_considerations: 8, + performance_requirements: 9, + testing: 10, + deployment: 11, + risks: 12, + timeline: 13, + source_code: 14, + test_code: 15, + jira_tickets: 16 +}; + +// packages/core/dist/domain/hard-output-rule.js +var HardOutputRuleSchema = external_exports.enum([ + // Core PRD Rules (1-17+) + "sp_arithmetic", + "no_self_referencing_deps", + "ac_numbering", + "no_orphan_ddl", + "no_now_in_partial_indexes", + "no_any_codable", + "no_placeholder_tests", + "sp_not_in_fr_table", + "uneven_sp_distribution", + "metrics_disclaimer", + "fr_traceability", + "clean_architecture", + "post_generation_self_check", + "mandatory_codebase_analysis", + "honest_verification_verdicts", + "code_example_port_compliance", + "test_traceability_integrity", + "duplicate_requirement_ids", + "fr_to_ac_coverage", + "ac_to_test_coverage", + "fk_references_exist", + "fr_numbering_gaps", + "risk_mitigation_completeness", + "deployment_rollback_plan", + // Architecture & Code Quality (18-24) + "generic_over_specific", + "no_nested_types", + "single_responsibility", + "explicit_access_control", + "factory_based_injection", + "solid_compliance", + "code_reusability", + // Security (25-32) + "no_hardcoded_secrets", + "input_validation_required", + "output_encoding_injection_prevention", + "auth_on_every_endpoint", + "security_safe_error_handling", + "cryptographic_standards", + "rate_limiting_required", + "secure_communication", + // Data Protection & Compliance (33-38) + "data_classification_required", + "sensitive_data_protection", + "no_sensitive_data_in_logs", + "data_minimization", + "audit_trail_required", + "consent_and_erasure_support", + // Error Handling & Resilience (39-43) + "structured_error_handling", + "resilience_patterns", + "graceful_degradation", + "transaction_boundaries", + "consistent_error_format", + // Concurrency & State Management (44-46) + "concurrency_safety", + "immutability_by_default", + "atomic_operations", + // Senior Code Quality Standards (47-52) + "no_magic_numbers", + "defensive_coding", + "method_size_limits", + "consistent_naming", + "api_contract_documentation", + "deprecation_strategy", + // Comprehensive Testing (53-58) + "mandatory_test_coverage", + "security_testing_required", + "performance_testing_required", + "no_production_data_in_tests", + "edge_case_negative_tests", + "test_isolation", + // Observability & Monitoring (59-62) + "structured_logging", + "distributed_tracing", + "no_pii_in_observability", + "alerting_thresholds", + // Dependency & Supply Chain (63-64) + "dependency_vulnerability_scanning", + "minimal_dependency_principle" +]); +var NON_CRITICAL_RULES = /* @__PURE__ */ new Set([ + "uneven_sp_distribution", + "metrics_disclaimer", + "post_generation_self_check", + "mandatory_codebase_analysis", + "fr_numbering_gaps", + "risk_mitigation_completeness", + "deployment_rollback_plan", + "explicit_access_control", + "code_reusability", + "immutability_by_default", + "consistent_naming", + "deprecation_strategy", + "distributed_tracing", + "alerting_thresholds", + "minimal_dependency_principle" +]); +function isCriticalRule(rule) { + return !NON_CRITICAL_RULES.has(rule); +} +function scorePenalty(rule) { + return isCriticalRule(rule) ? 0.15 : 0.05; +} + +// packages/core/dist/domain/thinking-strategy.js +var ThinkingStrategySchema = external_exports.enum([ + // Core reasoning strategies + "chain_of_thought", + "tree_of_thoughts", + "graph_of_thoughts", + "react", + "reflexion", + "plan_and_solve", + "verified_reasoning", + "recursive_refinement", + "problem_analysis", + // Prompting strategies + "zero_shot", + "few_shot", + "self_consistency", + "generate_knowledge", + "prompt_chaining", + "multimodal_cot", + "meta_prompting" +]); +var STRATEGY_TIERS = { + 1: { + selectionWeight: 3, + strategies: [ + "recursive_refinement", + "verified_reasoning", + "self_consistency", + "graph_of_thoughts" + ] + }, + 2: { + selectionWeight: 2, + strategies: [ + "tree_of_thoughts", + "react", + "reflexion", + "problem_analysis" + ] + }, + 3: { + selectionWeight: 1, + strategies: [ + "few_shot", + "meta_prompting", + "plan_and_solve", + "generate_knowledge" + ] + }, + 4: { + selectionWeight: 0.3, + strategies: [ + "zero_shot", + "chain_of_thought", + "prompt_chaining", + "multimodal_cot" + ] + } +}; + +// packages/core/dist/domain/clarification.js +var ClarificationAnswerSchema = external_exports.object({ + questionId: external_exports.string(), + round: external_exports.number().int().min(1), + question: external_exports.string(), + answer: external_exports.string(), + category: external_exports.string(), + priority: external_exports.number().min(0).max(1), + source: external_exports.enum(["user_freeform", "user_selection", "codebase_inferred", "default"]) +}); +var ClarificationStateSchema = external_exports.object({ + answers: external_exports.array(ClarificationAnswerSchema), + currentRound: external_exports.number().int().min(0), + confidenceScore: external_exports.number().min(0).max(1), + isComplete: external_exports.boolean() }); -var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]); -var SamplingMessageContentBlockSchema = discriminatedUnion("type", [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ToolUseContentSchema, - ToolResultContentSchema + +// packages/core/dist/domain/verdict.js +var VerdictSchema = external_exports.enum([ + "PASS", + "SPEC-COMPLETE", + "NEEDS-RUNTIME", + "INCONCLUSIVE", + "FAIL" ]); -var SamplingMessageSchema = object2({ - role: RoleSchema, - content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: record(string2(), unknown()).optional() -}); -var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - messages: array(SamplingMessageSchema), - /** - * The server's preferences for which model to select. The client MAY modify or omit this request. - */ - modelPreferences: ModelPreferencesSchema.optional(), - /** - * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. - */ - systemPrompt: string2().optional(), - /** - * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. - * The client MAY ignore this request. - * - * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client - * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. - */ - includeContext: _enum(["none", "thisServer", "allServers"]).optional(), - temperature: number2().optional(), - /** - * The requested maximum number of tokens to sample (to prevent runaway completions). - * - * The client MAY choose to sample fewer tokens than the requested maximum. - */ - maxTokens: number2().int(), - stopSequences: array(string2()).optional(), - /** - * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. - */ - metadata: AssertObjectSchema.optional(), - /** - * Tools that the model may use during generation. - * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. - */ - tools: array(ToolSchema).optional(), - /** - * Controls how the model uses tools. - * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. - * Default is `{ mode: "auto" }`. - */ - toolChoice: ToolChoiceSchema.optional() + +// packages/core/dist/domain/capabilities.js +var CAPABILITIES = { + // source: matches allowedStrategies.length below. + maxStrategies: 16, + allowedStrategies: [ + "chain_of_thought", + "tree_of_thoughts", + "graph_of_thoughts", + "react", + "reflexion", + "plan_and_solve", + "verified_reasoning", + "recursive_refinement", + "problem_analysis", + "zero_shot", + "few_shot", + "self_consistency", + "generate_knowledge", + "prompt_chaining", + "multimodal_cot", + "meta_prompting" + ], + maxClarificationRounds: Infinity, + allowedContextTypes: [ + "proposal", + "feature", + "bug", + "incident", + "poc", + "mvp", + "release", + "cicd" + ], + maxSections: 11, + verificationLevel: "full" +}; + +// packages/core/dist/domain/prd-document.js +var PRDSectionSchema = external_exports.object({ + type: SectionTypeSchema, + title: external_exports.string(), + content: external_exports.string(), + order: external_exports.number().int().min(0), + metadata: external_exports.object({ + generatedAt: external_exports.string().datetime(), + wordCount: external_exports.number().int().min(0), + strategy: external_exports.string().optional(), + validationStatus: external_exports.enum(["pending", "passed", "failed"]), + violationCount: external_exports.number().int().min(0).default(0) + }) }); -var CreateMessageRequestSchema = RequestSchema.extend({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema +var PRDDocumentSchema = external_exports.object({ + id: external_exports.string().uuid(), + name: external_exports.string().min(1), + context: PRDContextSchema, + sections: external_exports.array(PRDSectionSchema), + clarificationAnswers: external_exports.array(ClarificationAnswerSchema), + createdAt: external_exports.string().datetime(), + updatedAt: external_exports.string().datetime() }); -var CreateMessageResultSchema = ResultSchema.extend({ - /** - * The name of the model that generated the message. - */ - model: string2(), - /** - * The reason why sampling stopped, if known. - * - * Standard values: - * - "endTurn": Natural end of the assistant's turn - * - "stopSequence": A stop sequence was encountered - * - "maxTokens": Maximum token limit was reached - * - * This field is an open string to allow for provider-specific stop reasons. - */ - stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens"]).or(string2())), - role: RoleSchema, - /** - * Response content. Single content block (text, image, or audio). - */ - content: SamplingContentSchema + +// packages/core/dist/domain/validation-result.js +var HardOutputRuleViolationSchema = external_exports.object({ + rule: HardOutputRuleSchema, + sectionType: SectionTypeSchema.nullable(), + message: external_exports.string(), + offendingContent: external_exports.string().nullable(), + location: external_exports.string().nullable(), + isCritical: external_exports.boolean(), + scorePenalty: external_exports.number().min(0).max(1) +}); +var ValidationReportSchema = external_exports.object({ + violations: external_exports.array(HardOutputRuleViolationSchema), + rulesChecked: external_exports.array(HardOutputRuleSchema), + rulesPassed: external_exports.array(HardOutputRuleSchema), + sectionType: SectionTypeSchema.nullable(), + hasCriticalViolations: external_exports.boolean(), + totalScore: external_exports.number().min(0).max(1), + checkedAt: external_exports.string().datetime() +}); +var CrossRefValidationResultSchema = external_exports.object({ + danglingReferences: external_exports.array(external_exports.object({ + id: external_exports.string(), + referencedIn: external_exports.string(), + type: external_exports.string() + })), + orphanNodes: external_exports.array(external_exports.object({ + id: external_exports.string(), + type: external_exports.string(), + reason: external_exports.string() + })), + cycles: external_exports.array(external_exports.array(external_exports.string())), + numberingGaps: external_exports.array(external_exports.object({ + prefix: external_exports.string(), + expected: external_exports.number(), + actual: external_exports.number() + })), + duplicateIds: external_exports.array(external_exports.string()), + isValid: external_exports.boolean() }); -var CreateMessageResultWithToolsSchema = ResultSchema.extend({ - /** - * The name of the model that generated the message. - */ - model: string2(), + +// packages/core/dist/domain/agent.js +var GeniusAgentSchema = external_exports.enum([ + "alexander", + "alkhwarizmi", + "altshuller", + "archimedes", + "arendt", + "aristotle", + "bateson", + "beer", + "borges", + "boyd", + "braudel", + "bruner", + "carnot", + "champollion", + "coase", + "cochrane", + "curie", + "darwin", + "deming", + "dijkstra", + "eco", + "einstein", + "ekman", + "engelbart", + "erdos", + "erlang", + "euler", + "feinstein", + "fermi", + "feynman", + "fisher", + "fleming", + "foucault", + "gadamer", + "galileo", + "geertz", + "ginzburg", + "godel", + "hamilton", + "hart", + "hopper", + "ibnalhaytham", + "ibnkhaldun", + "jobs", + "kahneman", + "kauffman", + "kay", + "kekule", + "knuth", + "lamport", + "laplace", + "lavoisier", + "leguin", + "lem", + "liskov", + "mandelbrot", + "margulis", + "maxwell", + "mcclintock", + "meadows", + "mendeleev", + "midgley", + "mill", + "nagarjuna", + "noether", + "ostrom", + "panini", + "pearl", + "peirce", + "poincare", + "polya", + "popper", + "propp", + "ramanujan", + "ranganathan", + "rawls", + "rejewski", + "rogerfisher", + "rogers", + "schelling", + "schon", + "semmelweis", + "shannon", + "simon", + "snow", + "strauss", + "taleb", + "thompson", + "toulmin", + "turing", + "varela", + "ventris", + "vonneumann", + "vygotsky", + "wittgenstein", + "wu", + "zhuangzi" +]); +var TeamAgentSchema = external_exports.enum([ + "architect", + "code-reviewer", + "data-scientist", + "dba", + "devops-engineer", + "engineer", + "experiment-runner", + "frontend-engineer", + "latex-engineer", + "mlops", + "orchestrator", + "paper-writer", + "professor", + "refactorer", + "research-scientist", + "reviewer-academic", + "security-auditor", + "test-engineer", + "ux-designer" +]); +var AgentIdentitySchema = external_exports.discriminatedUnion("kind", [ + external_exports.object({ kind: external_exports.literal("genius"), name: GeniusAgentSchema }), + external_exports.object({ kind: external_exports.literal("team"), name: TeamAgentSchema }) +]); +function agentSubagentType(identity2) { + return identity2.kind === "genius" ? `zetetic-team-subagents:genius:${identity2.name}` : `zetetic-team-subagents:${identity2.name}`; +} +var ExternalGroundingTypeSchema = external_exports.enum([ + "schema", + "math", + "code", + "spec" +]); +var ClaimSchema = external_exports.object({ + claim_id: external_exports.string().describe("Stable ID, e.g., FR-001, AC-005, NFR-LATENCY"), + claim_type: external_exports.enum([ + "architecture", + "performance", + "correctness", + "security", + "data_model", + "test_coverage", + "story_point_arithmetic", + "fr_traceability", + "risk", + "acceptance_criteria_completeness", + "cross_file_consistency" + ]), + text: external_exports.string().describe("The claim being verified, in plain language"), + evidence: external_exports.string().describe("Section content / surrounding context"), + source_section: external_exports.string().optional(), /** - * The reason why sampling stopped, if known. - * - * Standard values: - * - "endTurn": Natural end of the assistant's turn - * - "stopSequence": A stop sequence was encountered - * - "maxTokens": Maximum token limit was reached - * - "toolUse": The model wants to use one or more tools + * Optional oracle grounding. When present, the downstream oracle pipeline + * resolves the claim's ground truth deterministically instead of relying on + * judge consensus alone. * - * This field is an open string to allow for provider-specific stop reasons. - */ - stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())), - role: RoleSchema, - /** - * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse". + * Leaving this field undefined preserves the existing consensus-majority + * behaviour for that claim. */ - content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]) -}); -var BooleanSchemaSchema = object2({ - type: literal("boolean"), - title: string2().optional(), - description: string2().optional(), - default: boolean2().optional() -}); -var StringSchemaSchema = object2({ - type: literal("string"), - title: string2().optional(), - description: string2().optional(), - minLength: number2().optional(), - maxLength: number2().optional(), - format: _enum(["email", "uri", "date", "date-time"]).optional(), - default: string2().optional() -}); -var NumberSchemaSchema = object2({ - type: _enum(["number", "integer"]), - title: string2().optional(), - description: string2().optional(), - minimum: number2().optional(), - maximum: number2().optional(), - default: number2().optional() -}); -var UntitledSingleSelectEnumSchemaSchema = object2({ - type: literal("string"), - title: string2().optional(), - description: string2().optional(), - enum: array(string2()), - default: string2().optional() -}); -var TitledSingleSelectEnumSchemaSchema = object2({ - type: literal("string"), - title: string2().optional(), - description: string2().optional(), - oneOf: array(object2({ - const: string2(), - title: string2() - })), - default: string2().optional() + external_grounding: external_exports.object({ + type: ExternalGroundingTypeSchema, + payload: external_exports.unknown().describe("Oracle-specific payload; shape validated by the oracle implementation") + }).optional() }); -var LegacyTitledEnumSchemaSchema = object2({ - type: literal("string"), - title: string2().optional(), - description: string2().optional(), - enum: array(string2()), - enumNames: array(string2()).optional(), - default: string2().optional() +var JudgeVerdictSchema = external_exports.object({ + judge: AgentIdentitySchema, + claim_id: external_exports.string(), + verdict: VerdictSchema, + rationale: external_exports.string(), + caveats: external_exports.array(external_exports.string()).default([]), + confidence: external_exports.number().min(0).max(1) +}); +var JudgeRequestSchema = external_exports.object({ + judge: AgentIdentitySchema, + claim: ClaimSchema, + context: external_exports.object({ + prd_excerpt: external_exports.string().optional(), + codebase_excerpts: external_exports.array(external_exports.string()).default([]), + memory_excerpts: external_exports.array(external_exports.string()).default([]) + }).default({ prd_excerpt: void 0, codebase_excerpts: [], memory_excerpts: [] }) }); -var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); -var UntitledMultiSelectEnumSchemaSchema = object2({ - type: literal("array"), - title: string2().optional(), - description: string2().optional(), - minItems: number2().optional(), - maxItems: number2().optional(), - items: object2({ - type: literal("string"), - enum: array(string2()) - }), - default: array(string2()).optional() +var SubagentInvocationSchema = external_exports.object({ + agent: AgentIdentitySchema, + task_description: external_exports.string().describe("Short title for the task"), + prompt: external_exports.string().describe("Full self-contained prompt \u2014 agent has no prior context"), + expected_format: external_exports.enum(["freeform", "json", "markdown"]).default("freeform"), + isolation: external_exports.enum(["worktree", "none"]).default("none") }); -var TitledMultiSelectEnumSchemaSchema = object2({ - type: literal("array"), - title: string2().optional(), - description: string2().optional(), - minItems: number2().optional(), - maxItems: number2().optional(), - items: object2({ - anyOf: array(object2({ - const: string2(), - title: string2() - })) - }), - default: array(string2()).optional() +var SubagentResponseSchema = external_exports.object({ + agent: AgentIdentitySchema, + text: external_exports.string(), + duration_ms: external_exports.number().int().nonnegative().optional() }); -var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); -var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); -var PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); -var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + +// packages/core/dist/utils/json-extract.js +function extractJsonObject(text) { + const stripped = text.replace(/```(?:json)?\s*/gi, "").replace(/```/g, ""); + const start = stripped.indexOf("{"); + if (start === -1) + throw new Error("no JSON object found in response"); + let depth = 0; + let inString = false; + let escape3 = false; + for (let i2 = start; i2 < stripped.length; i2++) { + const ch = stripped[i2]; + if (escape3) { + escape3 = false; + continue; + } + if (ch === "\\") { + escape3 = true; + continue; + } + if (ch === '"') { + inString = !inString; + continue; + } + if (inString) + continue; + if (ch === "{") + depth++; + else if (ch === "}") { + depth--; + if (depth === 0) { + const candidate = stripped.slice(start, i2 + 1); + return JSON.parse(candidate); + } + } + } + throw new Error("unbalanced JSON object in response"); +} + +// packages/core/dist/persistence/evidence-repository.js +import { join } from "node:path"; +import { homedir } from "node:os"; +import { mkdirSync, existsSync } from "node:fs"; +var Database = null; +try { + Database = (await import("better-sqlite3")).default; +} catch { +} +var EvidenceRepository = class { + db; + constructor(dbPath) { + if (!Database) { + throw new Error("better-sqlite3 not available \u2014 install it with: pnpm add better-sqlite3"); + } + const resolvedPath = dbPath ?? this.defaultDbPath(); + const dir = resolvedPath.substring(0, resolvedPath.lastIndexOf("/")); + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true }); + } + this.db = new Database(resolvedPath); + this.db.pragma("journal_mode = WAL"); + this.db.pragma("foreign_keys = ON"); + this.migrate(); + } + defaultDbPath() { + return join(homedir(), ".prd-gen", "evidence.db"); + } + migrate() { + this.db.exec(` + CREATE TABLE IF NOT EXISTS strategy_executions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + session_id TEXT NOT NULL DEFAULT '', + strategy TEXT NOT NULL, + claim_characteristics TEXT NOT NULL, + complexity_tier TEXT NOT NULL, + expected_improvement REAL NOT NULL, + actual_confidence_gain REAL NOT NULL, + was_compliant INTEGER NOT NULL DEFAULT 1, + retry_count INTEGER NOT NULL DEFAULT 0, + prd_context TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (datetime('now')) + ); + + CREATE TABLE IF NOT EXISTS prd_quality_scores ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + prd_id TEXT NOT NULL, + prd_context TEXT NOT NULL, + rules_checked INTEGER NOT NULL, + rules_passed INTEGER NOT NULL, + critical_violations INTEGER NOT NULL, + total_score REAL NOT NULL, + audit_flags_raised INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL DEFAULT (datetime('now')) + ); + + CREATE TABLE IF NOT EXISTS adaptive_thresholds ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + metric_name TEXT NOT NULL UNIQUE, + current_value REAL NOT NULL, + sample_count INTEGER NOT NULL DEFAULT 0, + last_updated TEXT NOT NULL DEFAULT (datetime('now')) + ); + + CREATE INDEX IF NOT EXISTS idx_strategy_executions_strategy + ON strategy_executions(strategy); + CREATE INDEX IF NOT EXISTS idx_strategy_executions_context + ON strategy_executions(prd_context); + CREATE INDEX IF NOT EXISTS idx_prd_quality_scores_context + ON prd_quality_scores(prd_context); + CREATE INDEX IF NOT EXISTS idx_prd_quality_scores_prd_id + ON prd_quality_scores(prd_id); + `); + } + // ─── Strategy Executions ───────────────────────────────────────────────── + recordStrategyExecution(execution, sessionId) { + const stmt = this.db.prepare(` + INSERT INTO strategy_executions + (session_id, strategy, claim_characteristics, complexity_tier, + expected_improvement, actual_confidence_gain, was_compliant, + retry_count, prd_context) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + `); + stmt.run(sessionId ?? "", execution.strategy, JSON.stringify(execution.claimCharacteristics), execution.complexityTier, execution.expectedImprovement, execution.actualConfidenceGain, execution.wasCompliant ? 1 : 0, execution.retryCount, execution.prdContext); + } /** - * The elicitation mode. - * - * Optional for backward compatibility. Clients MUST treat missing mode as "form". + * Get performance summary per strategy — used to close the feedback loop. + * Returns historical adjustment factor for the selector. */ - mode: literal("form").optional(), + getStrategyPerformance(minExecutions = 10) { + const rows = this.db.prepare(` + SELECT + strategy, + COUNT(*) as execution_count, + AVG(expected_improvement) as avg_expected, + AVG(actual_confidence_gain) as avg_actual, + AVG(CAST(was_compliant AS REAL)) as compliance_rate + FROM strategy_executions + GROUP BY strategy + HAVING COUNT(*) >= ? + ORDER BY COUNT(*) DESC + `).all(minExecutions); + return rows.map((row2) => ({ + strategy: row2.strategy, + executionCount: row2.execution_count, + avgExpectedImprovement: row2.avg_expected, + avgActualGain: row2.avg_actual, + performanceDelta: row2.avg_actual - row2.avg_expected, + complianceRate: row2.compliance_rate + })); + } /** - * The message to present to the user describing what information is being requested. + * Compute historical adjustments for strategy selection. + * Bounded [-0.3, +0.3] — prevents runaway feedback. */ - message: string2(), + getHistoricalAdjustments(minExecutions = 10) { + const summaries = this.getStrategyPerformance(minExecutions); + const adjustments = /* @__PURE__ */ new Map(); + for (const summary of summaries) { + if (summary.avgExpectedImprovement === 0) + continue; + const rawAdjustment = summary.performanceDelta / summary.avgExpectedImprovement; + const clamped = Math.max(-0.3, Math.min(0.3, rawAdjustment)); + adjustments.set(summary.strategy, clamped); + } + return adjustments; + } + // ─── PRD Quality Scores ────────────────────────────────────────────────── + recordQualityScore(score) { + const stmt = this.db.prepare(` + INSERT INTO prd_quality_scores + (prd_id, prd_context, rules_checked, rules_passed, + critical_violations, total_score, audit_flags_raised) + VALUES (?, ?, ?, ?, ?, ?, ?) + `); + stmt.run(score.prdId, score.prdContext, score.rulesChecked, score.rulesPassed, score.criticalViolations, score.totalScore, score.auditFlagsRaised); + } + getQualityHistory(limit = 50) { + const rows = this.db.prepare(` + SELECT prd_id, prd_context, rules_checked, rules_passed, + critical_violations, total_score, audit_flags_raised + FROM prd_quality_scores + ORDER BY created_at DESC + LIMIT ? + `).all(limit); + return rows.map((row2) => ({ + prdId: row2.prd_id, + prdContext: row2.prd_context, + rulesChecked: row2.rules_checked, + rulesPassed: row2.rules_passed, + criticalViolations: row2.critical_violations, + totalScore: row2.total_score, + auditFlagsRaised: row2.audit_flags_raised + })); + } + // ─── Adaptive Thresholds ───────────────────────────────────────────────── + getThreshold(metricName) { + const row2 = this.db.prepare(`SELECT metric_name, current_value, sample_count, last_updated + FROM adaptive_thresholds WHERE metric_name = ?`).get(metricName); + if (!row2) + return void 0; + return { + metricName: row2.metric_name, + currentValue: row2.current_value, + sampleCount: row2.sample_count, + lastUpdated: row2.last_updated + }; + } /** - * A restricted subset of JSON Schema. - * Only top-level properties are allowed, without nesting. + * Recalculate adaptive thresholds from historical quality data. + * Uses percentiles: p25 = fail, p50 = needs-improvement, p75 = good. + * Only updates if sufficient data exists (minSamples). */ - requestedSchema: object2({ - type: literal("object"), - properties: record(string2(), PrimitiveSchemaDefinitionSchema), - required: array(string2()).optional() - }) + recalculateThresholds(minSamples = 20) { + const scores = this.db.prepare(`SELECT total_score FROM prd_quality_scores ORDER BY total_score ASC`).all(); + if (scores.length < minSamples) + return; + const values = scores.map((s) => s.total_score); + const p25 = values[Math.floor(values.length * 0.25)]; + const p50 = values[Math.floor(values.length * 0.5)]; + const p75 = values[Math.floor(values.length * 0.75)]; + const upsert = this.db.prepare(` + INSERT INTO adaptive_thresholds (metric_name, current_value, sample_count, last_updated) + VALUES (?, ?, ?, datetime('now')) + ON CONFLICT(metric_name) DO UPDATE SET + current_value = excluded.current_value, + sample_count = excluded.sample_count, + last_updated = datetime('now') + `); + const updateAll = this.db.transaction(() => { + upsert.run("quality_fail_threshold", p25, values.length); + upsert.run("quality_improvement_threshold", p50, values.length); + upsert.run("quality_good_threshold", p75, values.length); + }); + updateAll(); + } + // ─── Lifecycle ─────────────────────────────────────────────────────────── + close() { + this.db.close(); + } +}; +function tryCreateEvidenceRepository(dbPath) { + if (!Database) + return null; + try { + return new EvidenceRepository(dbPath); + } catch { + return null; + } +} + +// packages/core/dist/persistence/reliability-repository.js +var RELIABILITY_SCHEMA_VERSION = 2; +var DEFAULT_RELIABILITY_PRIOR = Object.freeze({ + alpha: 7, + beta: 3 }); -var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - /** - * The elicitation mode. - */ - mode: literal("url"), - /** - * The message to present to the user explaining why the interaction is needed. - */ - message: string2(), - /** - * The ID of the elicitation, which must be unique within the context of the server. - * The client MUST treat this ID as an opaque value. - */ - elicitationId: string2(), +var RELIABILITY_PRIOR_ESS = DEFAULT_RELIABILITY_PRIOR.alpha + DEFAULT_RELIABILITY_PRIOR.beta; + +// packages/core/dist/persistence/sqlite-reliability-repository.js +import { join as join2 } from "node:path"; +import { homedir as homedir2 } from "node:os"; +import { mkdirSync as mkdirSync2, existsSync as existsSync2 } from "node:fs"; +var Database2 = null; +try { + Database2 = (await import("better-sqlite3")).default; +} catch { +} +var SqliteReliabilityRepository = class { + db; + closed = false; + constructor(dbPath) { + if (!Database2) { + throw new Error("better-sqlite3 not available \u2014 install it with: pnpm add better-sqlite3"); + } + const resolvedPath = dbPath ?? defaultDbPath(); + const dir = resolvedPath.substring(0, resolvedPath.lastIndexOf("/")); + if (!existsSync2(dir)) { + mkdirSync2(dir, { recursive: true }); + } + this.db = new Database2(resolvedPath); + this.db.pragma("journal_mode = WAL"); + this.db.pragma("foreign_keys = ON"); + this.db.pragma("busy_timeout = 5000"); + this.migrate(); + this.verifySchemaVersion(); + } + // ─── Schema lifecycle ─────────────────────────────────────────────────── + migrate() { + this.db.exec(` + CREATE TABLE IF NOT EXISTS schema_meta ( + schema_version INTEGER NOT NULL + ); + + CREATE TABLE IF NOT EXISTS agent_reliability ( + agent_kind TEXT NOT NULL, + agent_name TEXT NOT NULL, + claim_type TEXT NOT NULL, + verdict_direction TEXT NOT NULL CHECK (verdict_direction IN ('sensitivity_arm', 'specificity_arm')), + alpha REAL NOT NULL, + beta REAL NOT NULL, + n_observations INTEGER NOT NULL DEFAULT 0, + last_updated TEXT NOT NULL DEFAULT (datetime('now')), + PRIMARY KEY (agent_kind, agent_name, claim_type, verdict_direction) + ); + + CREATE INDEX IF NOT EXISTS idx_ar_agent + ON agent_reliability (agent_kind, agent_name); + + CREATE INDEX IF NOT EXISTS idx_ar_claim_type + ON agent_reliability (claim_type); + `); + const existing = this.db.prepare("SELECT schema_version FROM schema_meta LIMIT 1").get(); + if (!existing) { + this.db.prepare("INSERT INTO schema_meta (schema_version) VALUES (?)").run(RELIABILITY_SCHEMA_VERSION); + } + } /** - * The URL that the user should navigate to. + * Read the persisted schema_version and refuse to continue if it does not + * match RELIABILITY_SCHEMA_VERSION. + * + * Auto-migration is out of scope for Wave B. A version mismatch means the DB + * was written by a different schema and must be migrated manually or deleted + * before this implementation can use it. + * + * source: Laplace L6 / docs/PHASE_4_PLAN.md §4.1 Persistence. */ - url: string2().url() -}); -var ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); -var ElicitRequestSchema = RequestSchema.extend({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema -}); -var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ + verifySchemaVersion() { + const row2 = this.db.prepare("SELECT schema_version FROM schema_meta LIMIT 1").get(); + if (!row2) { + throw new Error("SqliteReliabilityRepository: schema_meta table is empty after migration \u2014 this should not happen; the DB may be corrupt."); + } + if (row2.schema_version !== RELIABILITY_SCHEMA_VERSION) { + throw new Error(`SqliteReliabilityRepository: schema version mismatch \u2014 DB has version ${row2.schema_version}, implementation expects version ${RELIABILITY_SCHEMA_VERSION}. Delete the DB or run a manual migration before proceeding.`); + } + } + // ─── ReliabilityRepository port ───────────────────────────────────────── + getSchemaVersion() { + this.assertOpen(); + const row2 = this.db.prepare("SELECT schema_version FROM schema_meta LIMIT 1").get(); + return row2?.schema_version ?? RELIABILITY_SCHEMA_VERSION; + } + getReliability(judge, claimType, verdictDirection) { + this.assertOpen(); + const row2 = this.db.prepare(`SELECT agent_kind, agent_name, claim_type, verdict_direction, + alpha, beta, n_observations, last_updated + FROM agent_reliability + WHERE agent_kind = ? AND agent_name = ? AND claim_type = ? AND verdict_direction = ?`).get(judge.kind, judge.name, claimType, verdictDirection); + if (!row2) + return null; + return rowToRecord(row2); + } /** - * The ID of the elicitation that completed. + * Record one ground-truth-matched observation. + * + * Uses an UPSERT (INSERT ... ON CONFLICT DO UPDATE) so the first call for + * a new cell initialises from the Beta(7,3) prior, and subsequent calls + * accumulate. + * + * Concurrency: SQLite WAL + file lock serialises concurrent writes. + * Two callers racing on the same cell will execute their UPSERTs sequentially + * (last writer wins at the OS file lock level). Because each UPSERT is an + * atomic read-modify-write on the server side (no separate SELECT), the + * result matches sequential application — there is no lost-update anomaly. + * + * source: SQLite documentation — "WAL mode allows concurrent readers; + * writers serialise at the WAL lock" (https://www.sqlite.org/wal.html). + * source: docs/PHASE_4_PLAN.md §Persistence concurrency — "writes serialize + * at the SQLite file lock." */ - elicitationId: string2() -}); -var ElicitationCompleteNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/elicitation/complete"), - params: ElicitationCompleteNotificationParamsSchema + recordObservation(judge, claimType, observation) { + this.assertOpen(); + const verdictDirection = observation.groundTruthIsFail ? "sensitivity_arm" : "specificity_arm"; + const alphaDelta = observation.judgeWasCorrect ? 1 : 0; + const betaDelta = observation.judgeWasCorrect ? 0 : 1; + this.db.prepare(`INSERT INTO agent_reliability + (agent_kind, agent_name, claim_type, verdict_direction, + alpha, beta, n_observations, last_updated) + VALUES (?, ?, ?, ?, ?, ?, 1, datetime('now')) + ON CONFLICT(agent_kind, agent_name, claim_type, verdict_direction) DO UPDATE SET + alpha = alpha + ?, + beta = beta + ?, + n_observations = n_observations + 1, + last_updated = datetime('now')`).run( + judge.kind, + judge.name, + claimType, + verdictDirection, + // INSERT values (first-run cell): prior + this observation + // source: DEFAULT_RELIABILITY_PRIOR = Beta(7,3); docs/PHASE_4_PLAN.md §4.1 + DEFAULT_RELIABILITY_PRIOR.alpha + alphaDelta, + DEFAULT_RELIABILITY_PRIOR.beta + betaDelta, + // UPDATE deltas + alphaDelta, + betaDelta + ); + } + getAllRecords() { + this.assertOpen(); + const rows = this.db.prepare(`SELECT agent_kind, agent_name, claim_type, verdict_direction, + alpha, beta, n_observations, last_updated + FROM agent_reliability + ORDER BY agent_kind, agent_name, claim_type, verdict_direction`).all(); + return rows.map(rowToRecord); + } + close() { + if (!this.closed) { + this.db.close(); + this.closed = true; + } + } + assertOpen() { + if (this.closed) { + throw new Error("SqliteReliabilityRepository: cannot call methods after close()"); + } + } +}; +function defaultDbPath() { + return join2(homedir2(), ".prd-gen", "reliability.db"); +} +function rowToRecord(row2) { + return { + agentKind: row2.agent_kind, + agentName: row2.agent_name, + claimType: row2.claim_type, + verdictDirection: row2.verdict_direction, + alpha: row2.alpha, + beta: row2.beta, + nObservations: row2.n_observations, + lastUpdated: row2.last_updated, + schemaVersion: RELIABILITY_SCHEMA_VERSION + }; +} +function tryCreateReliabilityRepository(dbPath) { + if (!Database2) + return null; + try { + return new SqliteReliabilityRepository(dbPath); + } catch { + return null; + } +} + +// packages/validation/dist/hard-output-rules/rule-mapping.js +var SECTION_RULES = { + requirements: [ + "sp_not_in_fr_table", + "fr_traceability", + "no_self_referencing_deps", + "duplicate_requirement_ids", + "fr_numbering_gaps" + ], + user_stories: ["no_self_referencing_deps"], + technical_specification: [ + // Architecture & Code Quality (18-24) + "clean_architecture", + "no_any_codable", + "code_example_port_compliance", + "generic_over_specific", + "no_nested_types", + "single_responsibility", + "explicit_access_control", + "factory_based_injection", + "solid_compliance", + "code_reusability", + // Security (25-32) + "no_hardcoded_secrets", + "input_validation_required", + "output_encoding_injection_prevention", + "auth_on_every_endpoint", + "security_safe_error_handling", + "cryptographic_standards", + "rate_limiting_required", + "secure_communication", + // Data Protection (33-38) + "data_classification_required", + "sensitive_data_protection", + "no_sensitive_data_in_logs", + "data_minimization", + "audit_trail_required", + "consent_and_erasure_support", + // Error Handling & Resilience (39-43) + "structured_error_handling", + "resilience_patterns", + "graceful_degradation", + "transaction_boundaries", + "consistent_error_format", + // Concurrency (44-46) + "concurrency_safety", + "immutability_by_default", + "atomic_operations", + // Senior Code Quality (47-52) + "no_magic_numbers", + "defensive_coding", + "method_size_limits", + "consistent_naming", + "api_contract_documentation", + "deprecation_strategy", + // Observability (59-62) + "structured_logging", + "distributed_tracing", + "no_pii_in_observability", + "alerting_thresholds", + // Dependencies (63-64) + "dependency_vulnerability_scanning", + "minimal_dependency_principle" + ], + data_model: [ + "no_orphan_ddl", + "no_now_in_partial_indexes", + "no_any_codable", + "fk_references_exist", + "data_classification_required", + "sensitive_data_protection", + "consent_and_erasure_support" + ], + api_specification: [ + "no_any_codable", + "auth_on_every_endpoint", + "rate_limiting_required", + "consistent_error_format", + "api_contract_documentation", + "deprecation_strategy" + ], + security_considerations: [ + "no_hardcoded_secrets", + "input_validation_required", + "output_encoding_injection_prevention", + "auth_on_every_endpoint", + "security_safe_error_handling", + "cryptographic_standards", + "rate_limiting_required", + "secure_communication", + "data_classification_required", + "sensitive_data_protection", + "no_sensitive_data_in_logs", + "data_minimization", + "audit_trail_required", + "consent_and_erasure_support" + ], + testing: [ + "no_placeholder_tests", + "test_traceability_integrity", + "mandatory_test_coverage", + "security_testing_required", + "performance_testing_required", + "no_production_data_in_tests", + "edge_case_negative_tests", + "test_isolation" + ], + timeline: [ + "sp_arithmetic", + "uneven_sp_distribution", + "no_self_referencing_deps" + ], + deployment: [ + "sp_arithmetic", + "ac_numbering", + "deployment_rollback_plan", + "structured_logging", + "distributed_tracing", + "no_pii_in_observability", + "alerting_thresholds" + ], + acceptance_criteria: ["ac_numbering"], + performance_requirements: ["honest_verification_verdicts"], + risks: ["risk_mitigation_completeness"], + overview: [], + goals: [], + source_code: [], + test_code: [], + // jira_tickets is a synthetic bucket emitted by jira-generation; its + // rules apply to the source sections (requirements / acceptance_criteria), + // not to the JIRA markdown itself. + jira_tickets: [] +}; +function rulesForSection(sectionType) { + return [...SECTION_RULES[sectionType]]; +} + +// packages/validation/dist/hard-output-rules/rules/helpers.js +function findPatternViolations(pattern, content, rule, sectionType, message) { + const matches = content.match(pattern); + if (!matches) + return []; + return matches.map((match) => ({ + rule, + sectionType, + message, + offendingContent: match.length > 0 ? match.substring(0, 120) : null, + location: null, + isCritical: isCriticalRule(rule), + scorePenalty: scorePenalty(rule) + })); +} +function findAbsenceViolation(content, signals, threshold, rule, sectionType, message) { + const lowered = content.toLowerCase(); + const signalCount = signals.filter((s) => lowered.includes(s)).length; + if (signalCount < threshold) { + return [ + { + rule, + sectionType, + message, + offendingContent: null, + location: null, + isCritical: isCriticalRule(rule), + scorePenalty: scorePenalty(rule) + } + ]; + } + return []; +} +function makeViolation(rule, sectionType, message, offendingContent = null) { + return { + rule, + sectionType, + message, + offendingContent, + location: null, + isCritical: isCriticalRule(rule), + scorePenalty: scorePenalty(rule) + }; +} +function extractCodeBlocks(content) { + const pattern = /```(?:\w+)?\s*\n([\s\S]*?)```/g; + const blocks = []; + let match; + while ((match = pattern.exec(content)) !== null) { + blocks.push(match[1]); + } + return blocks; +} +var OPT_OUT_WINDOW = 240; +var OPT_OUT_MARKERS = [ + "n/a", + "not applicable", + "by construction", + "no network", + "no database", + "no endpoint", + "no public surface", + "no public interface", + "no http", + "no rest", + "no graphql", + "no grpc", + "no users", + "no caller", + "no remote", + "no service", + "no api", + "absent surface", + "no attack surface", + "out of scope" +]; +function hasExplicitOptOut(content, topicSignals) { + if (topicSignals.length === 0) + return false; + const lowered = content.toLowerCase(); + for (const topic of topicSignals) { + const t = topic.toLowerCase(); + let idx = lowered.indexOf(t); + while (idx !== -1) { + const start = Math.max(0, idx - OPT_OUT_WINDOW); + const end = Math.min(lowered.length, idx + t.length + OPT_OUT_WINDOW); + const window = lowered.substring(start, end); + for (const marker of OPT_OUT_MARKERS) { + if (window.includes(marker)) + return true; + } + idx = lowered.indexOf(t, idx + t.length); + } + } + return false; +} +function extractTypeName(line) { + const typeKeywords = [ + "struct", + "class", + "enum", + "interface", + "object", + "record" + ]; + const words = line.split(/\s+/).filter((w) => w.length > 0); + for (let i2 = 0; i2 < words.length; i2++) { + const clean = words[i2].toLowerCase().replace(/[^\w]/g, ""); + if (typeKeywords.includes(clean) && i2 + 1 < words.length) { + return words[i2 + 1].replace(/[^\w]/g, ""); + } + } + return "Unknown"; +} + +// packages/validation/dist/hard-output-rules/rules/sp-rules.js +function checkSPNotInFRTable(content, sectionType) { + return findPatternViolations(/^\s*\|(?:[^|]*\|)*[^|]*(?:Story\s*Points?)[^|]*\|/gim, content, "sp_not_in_fr_table", sectionType, "FR table contains Story Points column \u2014 SP belongs only in Implementation Roadmap"); +} +function checkUnevenSPDistribution(content, sectionType) { + const sprintPattern = /(?:sprint|iteration)\s*\d+[^|]*?\|\s*(\d+)\s*(?:SP|story\s*points?)/gim; + const spValues = []; + let match; + while ((match = sprintPattern.exec(content)) !== null) { + const val = parseInt(match[1], 10); + if (!isNaN(val)) + spValues.push(val); + } + if (spValues.length < 3) + return []; + const allSame = new Set(spValues).size === 1; + if (allSame) { + return [ + makeViolation("uneven_sp_distribution", sectionType, `All ${spValues.length} sprints have identical SP (${spValues[0]}) \u2014 real projects have uneven complexity`, `Sprint SP values: ${spValues.join(", ")}`) + ]; + } + return []; +} +function checkSPArithmetic(content, sectionType) { + const totalRowPattern = /^\s*\|\s*(?:\*{0,2})(?:Total|Sum|Grand\s+Total)(?:\*{0,2})\s*\|(.+)\|/gim; + const numberPattern = /(\d+)/g; + const dataRowPattern = /^\s*\|\s*(?!\s*(?:-|(?:\*{0,2})(?:Total|Sum|Grand\s+Total)))([^|]+)\|(.+)\|/gim; + const individualSPs = []; + let dataMatch; + while ((dataMatch = dataRowPattern.exec(content)) !== null) { + const cellsText = dataMatch[2]; + const numbers = []; + let numMatch; + const numRegex = /(\d+)/g; + while ((numMatch = numRegex.exec(cellsText)) !== null) { + numbers.push(parseInt(numMatch[1], 10)); + } + if (numbers.length > 0) { + individualSPs.push(numbers[numbers.length - 1]); + } + } + const violations = []; + let totalMatch; + while ((totalMatch = totalRowPattern.exec(content)) !== null) { + const cellsText = totalMatch[1]; + const numbers = []; + let numMatch; + const numRegex = /(\d+)/g; + while ((numMatch = numRegex.exec(cellsText)) !== null) { + numbers.push(parseInt(numMatch[1], 10)); + } + if (numbers.length === 0) + continue; + const totalValue = numbers[numbers.length - 1]; + const computedSum = individualSPs.reduce((sum3, v) => sum3 + v, 0); + if (computedSum > 0 && computedSum !== totalValue) { + violations.push(makeViolation("sp_arithmetic", sectionType, `SP total row shows ${totalValue} but individual rows sum to ${computedSum}`, `Total: ${totalValue}, Computed: ${computedSum}`)); + } + } + return violations; +} +function checkDocumentSPArithmetic(sections) { + const spSections = sections.filter((s) => s.type === "timeline" || s.type === "deployment" || s.type === "requirements"); + if (spSections.length === 0) + return []; + const combinedContent = spSections.map((s) => s.content).join("\n\n"); + return checkSPArithmetic(combinedContent, "timeline"); +} + +// packages/validation/dist/hard-output-rules/rules/quality-rules.js +function checkNoSelfReferencingDeps(content, sectionType) { + const violations = []; + const pattern = /((?:STORY|US|EPIC|FR)-\d+)[^|\n]{0,200}?(?:depends\s+on|blocked\s+by|requires)[^|\n]{0,200}?\1/gi; + let match; + while ((match = pattern.exec(content)) !== null) { + const storyId = match[1]; + const matchText = match[0].substring(0, 120); + violations.push(makeViolation("no_self_referencing_deps", sectionType, `${storyId} references itself in dependencies`, matchText)); + } + const tablePattern = /^\s*\|\s*((?:STORY|US|EPIC|FR)-\d+)\s*\|(?:[^|\n]*\|)*[^|\n]*\1[^|\n]*\|/gm; + while ((match = tablePattern.exec(content)) !== null) { + const storyId = match[1]; + const alreadyReported = violations.some((v) => v.offendingContent?.includes(storyId) === true); + if (!alreadyReported) { + violations.push(makeViolation("no_self_referencing_deps", sectionType, `${storyId} appears to reference itself in table row`, storyId)); + } + } + return violations; +} +function checkMetricsDisclaimer(content, sectionType) { + const lowered = content.toLowerCase(); + const hasMetrics = lowered.includes("reasoning") && lowered.includes("metric"); + if (!hasMetrics) + return []; + const hasDisclaimer = lowered.includes("model-projected") || lowered.includes("projected") || lowered.includes("not independent") || lowered.includes("disclaimer"); + if (!hasDisclaimer) { + return [ + makeViolation("metrics_disclaimer", sectionType, "Verification metrics found without 'model-projected' disclaimer") + ]; + } + return []; +} +function checkHonestVerificationVerdicts(content, sectionType) { + const nfrPattern = /NFR-\d+|(?:p95|p99|latency|throughput|response\s+time)\s*[:<≤<=]\s*\d+/gi; + if (!nfrPattern.test(content)) + return []; + const verdictPattern = /\b(?:PASS|SPEC-COMPLETE|NEEDS-RUNTIME|INCONCLUSIVE|FAIL)\b/gi; + const verdicts = []; + let match; + while ((match = verdictPattern.exec(content)) !== null) { + verdicts.push(match[0].toUpperCase()); + } + if (verdicts.length === 0) + return []; + const hasOnlyPass = verdicts.every((v) => v === "PASS"); + if (hasOnlyPass && verdicts.length >= 2) { + return [ + makeViolation("honest_verification_verdicts", sectionType, `All ${verdicts.length} verdicts are PASS despite NFR performance claims that require runtime measurement \u2014 use SPEC-COMPLETE or NEEDS-RUNTIME for unverified metrics`, `Verdicts: ${verdicts.length}x PASS, 0x SPEC-COMPLETE/NEEDS-RUNTIME`) + ]; + } + return []; +} +function checkDocumentVerificationVerdicts(sections) { + const perfSections = sections.filter((s) => s.type === "performance_requirements"); + const testSections = sections.filter((s) => s.type === "testing"); + if (perfSections.length === 0) + return []; + const perfContent = perfSections.map((s) => s.content).join("\n\n"); + const testContent = testSections.map((s) => s.content).join("\n\n"); + const combinedContent = perfContent + "\n\n" + testContent; + return checkHonestVerificationVerdicts(combinedContent, "performance_requirements"); +} +function checkRiskMitigationCompleteness(content, sectionType) { + const headerPattern = /^\s*\|[^\n]*(?:Risk|Threat)[^\n]*(?:Mitigation|Response|Action)[^\n]*\|/gim; + if (!headerPattern.test(content)) + return []; + const rowPattern = /^\s*\|(?!\s*[-:]+\s*\|)(.+)\|/gm; + const violations = []; + const emptyMitigationPattern = /^\s*(?:-|N\/?A|TBD|TODO|None)?\s*$/i; + let index2 = 0; + let match; + while ((match = rowPattern.exec(content)) !== null) { + index2++; + if (index2 === 1) + continue; + const rowText = match[1]; + const cells = rowText.split("|").map((c) => c.trim()); + const isSeparator = cells.every((cell) => [...cell].every((ch) => ch === "-" || ch === ":" || ch === " ")); + if (isSeparator) + continue; + const lastCell = cells[cells.length - 1]; + if (lastCell === void 0) + continue; + if (emptyMitigationPattern.test(lastCell)) { + const riskDescription = cells[0] ?? "Unknown"; + violations.push(makeViolation("risk_mitigation_completeness", sectionType, `Risk '${riskDescription.substring(0, 60)}' has empty or placeholder mitigation`, `Mitigation: ${lastCell.length === 0 ? "(empty)" : lastCell}`)); + } + } + return violations; +} +function checkDeploymentRollbackPlan(content, sectionType) { + const lowered = content.toLowerCase(); + const rollbackKeywords = [ + "rollback", + "roll back", + "undo", + "revert", + "restore", + "fallback" + ]; + const hasRollbackPlan = rollbackKeywords.some((k) => lowered.includes(k)); + if (!hasRollbackPlan) { + return [ + makeViolation("deployment_rollback_plan", sectionType, "Deployment section lacks a rollback/restore strategy \u2014 every deployment must have a recovery plan") + ]; + } + return []; +} + +// packages/validation/dist/hard-output-rules/rules/numbering-rules.js +function checkACNumbering(content, sectionType) { + const acPattern = /AC-(\d+)/g; + const acNumbers = []; + let match; + while ((match = acPattern.exec(content)) !== null) { + acNumbers.push(parseInt(match[1], 10)); + } + if (acNumbers.length === 0) + return []; + const sorted = [...new Set(acNumbers)].sort((a, b) => a - b); + const first = sorted[0]; + const last = sorted[sorted.length - 1]; + const gaps = []; + for (let n = first; n <= last; n++) { + if (!sorted.includes(n)) + gaps.push(n); + } + if (gaps.length > 0) { + return [ + makeViolation("ac_numbering", sectionType, `AC numbering has gaps: missing AC-${gaps.join(", AC-")}`, `Found: AC-${sorted.join(", AC-")}`) + ]; + } + return []; +} +function checkFRTraceability(content, sectionType) { + const tableHeaderPattern = /^\s*\|[^\n]*\bID\b[^\n]*(?:Requirement|Description)[^\n]*\|/gim; + if (!tableHeaderPattern.test(content)) + return []; + const sourcePattern = /^\s*\|[^\n]*\bID\b[^\n]*\bSource\b[^\n]*\|/gim; + if (!sourcePattern.test(content)) { + return [ + makeViolation("fr_traceability", sectionType, "FR table exists but lacks a Source/Traceability column \u2014 every FR must trace to its origin") + ]; + } + return []; +} +function checkDuplicateRequirementIds(content, sectionType) { + const idPattern = /^\s*\|\s*((FR|NFR)-\d+)\s*\|/gm; + const seenIds = /* @__PURE__ */ new Map(); + let match; + while ((match = idPattern.exec(content)) !== null) { + const id = match[1]; + seenIds.set(id, (seenIds.get(id) ?? 0) + 1); + } + const violations = []; + for (const [id, count2] of seenIds) { + if (count2 > 1) { + violations.push(makeViolation("duplicate_requirement_ids", sectionType, `Requirement ID '${id}' appears ${count2} times \u2014 each ID must be unique`, id)); + } + } + return violations; +} +function checkFRNumberingGaps(content, sectionType) { + return [ + ...checkIdNumberingGaps(content, "FR", "fr_numbering_gaps", sectionType), + ...checkIdNumberingGaps(content, "NFR", "fr_numbering_gaps", sectionType) + ]; +} +function checkIdNumberingGaps(content, prefix, rule, sectionType) { + const pattern = new RegExp(`${prefix}-(\\d+)`, "g"); + const numbers = []; + let match; + while ((match = pattern.exec(content)) !== null) { + numbers.push(parseInt(match[1], 10)); + } + if (numbers.length === 0) + return []; + const sorted = [...new Set(numbers)].sort((a, b) => a - b); + const first = sorted[0]; + const last = sorted[sorted.length - 1]; + const gaps = []; + for (let n = first; n <= last; n++) { + if (!sorted.includes(n)) + gaps.push(n); + } + if (gaps.length > 0) { + return [ + makeViolation(rule, sectionType, `${prefix} numbering has gaps: missing ${prefix}-${gaps.join(`, ${prefix}-`)}`, `Found: ${prefix}-${sorted.join(`, ${prefix}-`)}`) + ]; + } + return []; +} +function checkDocumentACConsistency(content) { + const acPattern = /AC-(\d+)/g; + const acNumbers = []; + let match; + while ((match = acPattern.exec(content)) !== null) { + acNumbers.push(parseInt(match[1], 10)); + } + if (acNumbers.length <= 1) + return []; + const sorted = [...new Set(acNumbers)].sort((a, b) => a - b); + const first = sorted[0]; + const last = sorted[sorted.length - 1]; + const gaps = []; + for (let n = first; n <= last; n++) { + if (!sorted.includes(n)) + gaps.push(n); + } + if (gaps.length > 0) { + return [ + makeViolation("ac_numbering", null, `Document-level AC numbering has gaps: missing AC-${gaps.join(", AC-")}`, `Found across document: AC-${sorted.join(", AC-")}`) + ]; + } + return []; +} + +// packages/validation/dist/hard-output-rules/rules/database-rules.js +function checkNoAnyCodable(content, sectionType) { + return findPatternViolations(/\bAny(?:Codable|Encodable|Decodable|JSON)\b/g, content, "no_any_codable", sectionType, "Found prohibited AnyCodable/AnyEncodable/AnyDecodable/AnyJSON type"); +} +function checkNoNowInPartialIndexes(content, sectionType) { + return findPatternViolations(/CREATE\s+INDEX\b[^;]*WHERE\b[^;]*\b(?:NOW\s*\(\)|CURRENT_TIMESTAMP)/gi, content, "no_now_in_partial_indexes", sectionType, "NOW()/CURRENT_TIMESTAMP in partial index WHERE clause \u2014 evaluated once at creation, not at query time"); +} +function checkNoOrphanDDL(content, sectionType) { + const typePattern = /CREATE\s+(?:TYPE|ENUM)\s+(\w+)/gi; + const violations = []; + let match; + while ((match = typePattern.exec(content)) !== null) { + const typeName = match[1]; + const escapedName = typeName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const refPattern = new RegExp(`\\b${escapedName}\\b`, "gi"); + const refMatches = content.match(refPattern); + const refCount = refMatches ? refMatches.length : 0; + if (refCount <= 1) { + violations.push(makeViolation("no_orphan_ddl", sectionType, `Type '${typeName}' is defined but never referenced by any table or column`, `CREATE TYPE/ENUM ${typeName}`)); + } + } + return violations; +} +function checkFKReferencesExist(content, sectionType) { + const createPattern = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(\w+)/gi; + const tableNames = /* @__PURE__ */ new Set(); + let match; + while ((match = createPattern.exec(content)) !== null) { + tableNames.add(match[1].toLowerCase()); + } + if (tableNames.size === 0) + return []; + const refPattern = /REFERENCES\s+(\w+)/gi; + const violations = []; + while ((match = refPattern.exec(content)) !== null) { + const refTarget = match[1]; + if (!tableNames.has(refTarget.toLowerCase())) { + violations.push(makeViolation("fk_references_exist", sectionType, `Foreign key references table '${refTarget}' which has no CREATE TABLE in the data model`, `REFERENCES ${refTarget}`)); + } + } + return violations; +} + +// packages/validation/dist/hard-output-rules/rules/test-rules.js +function checkNoPlaceholderTests(content, sectionType) { + const patterns = [ + /func\s+test\w+\s*\([^)]*\)\s*(?:throws\s+)?(?:async\s+)?(?:throws\s+)?\{[^}]*\/\/\s*(?:TODO|FIXME|PLACEHOLDER)[^}]*\}/g, + /func\s+test\w+\s*\([^)]*\)\s*(?:throws\s+)?(?:async\s+)?(?:throws\s+)?\{\s*\}/g, + /^\s*\|\s*test\w+\s*\|[^|]*\|\s*`?\s*\/\/\s*(?:TODO|Setup)/gm + ]; + const violations = []; + for (const pattern of patterns) { + violations.push(...findPatternViolations(pattern, content, "no_placeholder_tests", sectionType, "Found placeholder test with empty or TODO-only body")); + } + return violations; +} +function checkTestTraceabilityIntegrity(content, sectionType) { + const matrixRowPattern = /^\s*\|\s*(test\w+)\s*\|/gm; + const matrixTestNames = []; + let match; + while ((match = matrixRowPattern.exec(content)) !== null) { + matrixTestNames.push(match[1]); + } + if (matrixTestNames.length === 0) + return []; + const testFuncPattern = /func\s+(test\w+)\s*\(/g; + const definedTestNames = /* @__PURE__ */ new Set(); + while ((match = testFuncPattern.exec(content)) !== null) { + definedTestNames.add(match[1]); + } + const violations = []; + for (const matrixName of matrixTestNames) { + if (!definedTestNames.has(matrixName)) { + violations.push(makeViolation("test_traceability_integrity", sectionType, `Test '${matrixName}' listed in traceability matrix but no matching func ${matrixName}() found in test code`, matrixName)); + } + } + return violations; +} +function checkDocumentTestTraceability(sections) { + const testSections = sections.filter((s) => s.type === "testing"); + if (testSections.length === 0) + return []; + const combinedTestContent = testSections.map((s) => s.content).join("\n\n"); + return checkTestTraceabilityIntegrity(combinedTestContent, "testing"); +} + +// packages/validation/dist/hard-output-rules/rules/architecture-rules.js +function checkCleanArchitecture(content, sectionType) { + const lowered = content.toLowerCase(); + const hasPortAdapter = lowered.includes("port") && lowered.includes("adapter"); + const hasHexagonal = lowered.includes("hexagonal"); + const hasCleanArch = lowered.includes("clean architecture"); + const hasDomainLayer = lowered.includes("domain layer") || lowered.includes("domain model"); + const hasCompositionRoot = lowered.includes("composition root") || lowered.includes("composition layer"); + const hasArchPattern = hasPortAdapter || hasHexagonal || hasCleanArch; + const hasLayerSeparation = hasDomainLayer || hasCompositionRoot; + if (!hasArchPattern && !hasLayerSeparation) { + return [ + makeViolation("clean_architecture", sectionType, "Technical spec lacks ports/adapters architecture \u2014 must show domain layer with ports, adapter layer, and composition root") + ]; + } + return []; +} +function checkCodeExamplePortCompliance(content, sectionType) { + const codeBlocks = extractCodeBlocks(content); + if (codeBlocks.length === 0) + return []; + const portViolations = [ + { pattern: /\bDate\(\)/, message: "Date() \u2014 inject a Clock port instead" }, + { + pattern: /\bUUID\(\)/, + message: "UUID() \u2014 inject a UUIDGenerator port instead" + }, + { + pattern: /\bFileManager\b/, + message: "FileManager \u2014 inject a FileSystem port instead" + }, + { + pattern: /\bURLSession\b/, + message: "URLSession \u2014 inject an HTTPClient port instead" + }, + { + pattern: /\bUserDefaults\b/, + message: "UserDefaults \u2014 inject a KeyValueStore port instead" + } + ]; + const foundViolations = []; + for (const codeBlock of codeBlocks) { + if (!isDomainLayerCode(codeBlock)) + continue; + for (const { pattern, message } of portViolations) { + const globalPattern = new RegExp(pattern.source, "g"); + let match; + while ((match = globalPattern.exec(codeBlock)) !== null) { + foundViolations.push(makeViolation("code_example_port_compliance", sectionType, `Domain-layer code example uses framework type: ${message}`, match[0])); + } + } + } + return foundViolations; +} +function checkGenericOverSpecific(content, sectionType) { + const lowered = content.toLowerCase(); + const paramSignals = [ + "parameter", + "configurable", + "configuration", + "default value", + "sensible default", + "optional", + "override", + "customizable" + ]; + const extensibilitySignals = [ + "extensible", + "reusable", + "composable", + "generic", + "abstraction", + "centralized", + "single source of truth", + "shared component", + "common module" + ]; + const patternSignals = [ + "strategy pattern", + "builder pattern", + "factory", + "protocol", + "interface", + "contract", + "dependency injection", + "inversion of control", + "plugin", + "middleware", + "decorator" + ]; + let categoriesPresent = 0; + if (paramSignals.some((s) => lowered.includes(s))) + categoriesPresent++; + if (extensibilitySignals.some((s) => lowered.includes(s))) + categoriesPresent++; + if (patternSignals.some((s) => lowered.includes(s))) + categoriesPresent++; + if (categoriesPresent < 2) { + return [ + makeViolation("generic_over_specific", sectionType, "Technical spec lacks scalable design \u2014 must demonstrate parameterization (configurable values, defaults) AND extensibility (reusable abstractions, centralized components, design patterns). A solution that requires repeating the same fix across many files is not scalable.") + ]; + } + return []; +} +function isDomainLayerCode(code) { + const lowered = code.toLowerCase(); + const hasDomainSignals = lowered.includes("protocol ") || lowered.includes("entity") || lowered.includes("use case") || lowered.includes("usecase") || lowered.includes("domain") || lowered.includes("port") || lowered.includes("repository"); + const hasAdapterSignals = lowered.includes("import uikit") || lowered.includes("import swiftui") || lowered.includes("import foundation") || lowered.includes("adapter") || lowered.includes("controller") || lowered.includes("viewmodel") || lowered.includes("@main") || lowered.includes("@objc"); + return hasDomainSignals && !hasAdapterSignals; +} + +// packages/validation/dist/hard-output-rules/rules/code-quality-rules.js +function checkNoNestedTypes(content, sectionType) { + const codeBlocks = extractCodeBlocks(content); + if (codeBlocks.length === 0) + return []; + const typeKeywordPattern = /(?:^|\n)\s*(?:public\s+|private\s+|internal\s+|protected\s+|open\s+|fileprivate\s+|final\s+|abstract\s+|sealed\s+|data\s+)*(?:struct|class|enum|interface|object|record)\s+\w+/; + const violations = []; + for (const codeBlock of codeBlocks) { + const lines = codeBlock.split("\n"); + let braceDepth = 0; + for (const line of lines) { + if (typeKeywordPattern.test(line)) { + if (braceDepth > 0) { + const typeName = extractTypeName(line.trim()); + violations.push(makeViolation("no_nested_types", sectionType, `Nested type declaration detected \u2014 extract '${typeName}' to its own top-level definition. Nested types reduce readability and reusability.`, line.trim())); + } + } + braceDepth += (line.match(/\{/g) || []).length; + braceDepth -= (line.match(/\}/g) || []).length; + braceDepth = Math.max(0, braceDepth); + } + } + return violations; +} +function checkSingleResponsibility(content, sectionType) { + const violations = []; + const lowered = content.toLowerCase(); + const srpSignals = [ + "single responsibility", + "separation of concern", + "one reason to change", + "focused class", + "small class", + "cohesion", + "cohesive", + "do one thing", + "bounded context" + ]; + if (!srpSignals.some((s) => lowered.includes(s))) { + violations.push(makeViolation("single_responsibility", sectionType, "Technical spec must establish single responsibility constraints \u2014 classes should have one reason to change, with clear separation of concerns.")); + } + const codeBlocks = extractCodeBlocks(content); + const typeStartPattern = /(?:public\s+|private\s+|internal\s+|protected\s+|open\s+|final\s+|abstract\s+|sealed\s+|data\s+)*(?:struct|class|enum|interface|object)\s+(\w+)/; + for (const codeBlock of codeBlocks) { + const lines = codeBlock.split("\n"); + let currentTypeName = null; + let typeStartLine = 0; + let braceDepth = 0; + for (let index2 = 0; index2 < lines.length; index2++) { + const line = lines[index2]; + if (braceDepth === 0) { + const match = line.match(typeStartPattern); + if (match) { + currentTypeName = match[1] ?? extractTypeName(line.trim()); + typeStartLine = index2; + } + } + braceDepth += (line.match(/\{/g) || []).length; + braceDepth -= (line.match(/\}/g) || []).length; + if (braceDepth <= 0 && currentTypeName !== null) { + const typeLineCount = index2 - typeStartLine + 1; + if (typeLineCount > 50) { + violations.push(makeViolation("single_responsibility", sectionType, `Code example shows '${currentTypeName}' spanning ${typeLineCount} lines \u2014 split into smaller, focused types. A single class/struct should not exceed ~50 lines in a PRD example.`, currentTypeName)); + } + currentTypeName = null; + braceDepth = 0; + } + } + } + return violations; +} +function checkExplicitAccessControl(content, sectionType) { + return findAbsenceViolation(content, [ + "access control", + "visibility", + "scope", + "public", + "private", + "internal", + "protected", + "encapsulation", + "information hiding", + "expose only", + "minimal api surface", + "least privilege", + "api boundary" + ], 2, "explicit_access_control", sectionType, "Technical spec should establish access control guidelines \u2014 define what is public vs private, enforce encapsulation, and minimize exposed API surface."); +} +function checkFactoryBasedInjection(content, sectionType) { + return findAbsenceViolation(content, [ + "dependency injection", + "inject", + "factory", + "container", + "composition root", + "wire", + "provider", + "resolver", + "assembler", + "inversion of control", + "ioc" + ], 2, "factory_based_injection", sectionType, "Technical spec must mandate dependency injection through factories or DI containers \u2014 concrete types should not be instantiated directly in business logic. Specify how dependencies are wired."); +} +function checkSolidCompliance(content, sectionType) { + const lowered = content.toLowerCase(); + const solidCategories = [ + { + principle: "Single Responsibility", + signals: [ + "single responsibility", + "one reason to change", + "separation of concern", + "focused", + "cohesive" + ] + }, + { + principle: "Open/Closed", + signals: [ + "open/closed", + "open for extension", + "closed for modification", + "extensible", + "plugin", + "strategy", + "decorator" + ] + }, + { + principle: "Dependency Inversion", + signals: [ + "dependency inversion", + "depend on abstraction", + "protocol", + "interface", + "port", + "contract", + "injection", + "inversion of control" + ] + } + ]; + let categoriesMet = 0; + for (const { signals } of solidCategories) { + if (signals.some((s) => lowered.includes(s))) { + categoriesMet++; + } + } + if (categoriesMet < 2) { + return [ + makeViolation("solid_compliance", sectionType, "Technical spec must demonstrate SOLID principles \u2014 at minimum: single responsibility (focused classes), open/closed (extensible without modification), and dependency inversion (depend on abstractions, not concretions).") + ]; + } + return []; +} +function checkCodeReusability(content, sectionType) { + const lowered = content.toLowerCase(); + const reusabilitySignals = [ + "reusable", + "reuse", + "shared", + "common", + "utility", + "helper", + "library", + "module", + "component", + "centralized" + ]; + const readabilitySignals = [ + "readable", + "readability", + "naming convention", + "self-documenting", + "clean code", + "maintainable", + "clear", + "descriptive", + "consistent" + ]; + const hasReusability = reusabilitySignals.some((s) => lowered.includes(s)); + const hasReadability = readabilitySignals.some((s) => lowered.includes(s)); + if (!hasReusability && !hasReadability) { + return [ + makeViolation("code_reusability", sectionType, "Technical spec should establish code quality standards \u2014 specify that code must be reusable (shared components, centralized utilities) and readable (clear naming, self-documenting, consistent patterns).") + ]; + } + return []; +} + +// packages/validation/dist/hard-output-rules/rules/coverage-rules.js +function checkDocumentFRToACCoverage(sections) { + const reqSections = sections.filter((s) => s.type === "requirements"); + const acSections = sections.filter((s) => s.type === "acceptance_criteria"); + if (reqSections.length === 0) + return []; + const reqContent = reqSections.map((s) => s.content).join("\n\n"); + const frPattern = /^\s*\|\s*(FR-\d+)\s*\|/gm; + const definedFRs = /* @__PURE__ */ new Set(); + let match; + while ((match = frPattern.exec(reqContent)) !== null) { + definedFRs.add(match[1]); + } + if (definedFRs.size === 0) + return []; + const acContent = acSections.map((s) => s.content).join("\n\n"); + const frRefPattern = /(FR-\d+)/g; + const referencedFRs = /* @__PURE__ */ new Set(); + while ((match = frRefPattern.exec(acContent)) !== null) { + referencedFRs.add(match[1]); + } + const uncoveredFRs = [...definedFRs].filter((fr) => !referencedFRs.has(fr)).sort(); + if (uncoveredFRs.length > 0) { + return [ + makeViolation("fr_to_ac_coverage", null, `${uncoveredFRs.length} FR(s) have no acceptance criteria: ${uncoveredFRs.join(", ")}`, `Uncovered: ${uncoveredFRs.join(", ")}`) + ]; + } + return []; +} +function checkDocumentACToTestCoverage(sections) { + const acSections = sections.filter((s) => s.type === "acceptance_criteria"); + const testSections = sections.filter((s) => s.type === "testing"); + if (acSections.length === 0) + return []; + const acContent = acSections.map((s) => s.content).join("\n\n"); + const acPattern = /(AC-\d+)/g; + const definedACs = /* @__PURE__ */ new Set(); + let match; + while ((match = acPattern.exec(acContent)) !== null) { + definedACs.add(match[1]); + } + if (definedACs.size === 0) + return []; + const testContent = testSections.map((s) => s.content).join("\n\n"); + const acRefPattern = /(AC-\d+)/g; + const referencedACs = /* @__PURE__ */ new Set(); + while ((match = acRefPattern.exec(testContent)) !== null) { + referencedACs.add(match[1]); + } + const uncoveredACs = [...definedACs].filter((ac) => !referencedACs.has(ac)).sort(); + if (uncoveredACs.length > 0) { + return [ + makeViolation("ac_to_test_coverage", null, `${uncoveredACs.length} AC(s) have no test coverage: ${uncoveredACs.join(", ")}`, `Uncovered: ${uncoveredACs.join(", ")}`) + ]; + } + return []; +} + +// packages/validation/dist/hard-output-rules/rules/security-rules.js +function checkNoHardcodedSecrets(content, sectionType) { + const violations = []; + const codeBlocks = extractCodeBlocks(content); + const secretPatterns = [ + { + pattern: /(?:password|passwd|pwd)\s*[:=]\s*["'][^"']{3,}/i, + description: "hardcoded password" + }, + { + pattern: /(?:api[_-]?key|apikey)\s*[:=]\s*["'][^"']{8,}/i, + description: "hardcoded API key" + }, + { + pattern: /(?:secret|token|auth)\s*[:=]\s*["'][A-Za-z0-9+/=]{16,}/i, + description: "hardcoded secret/token" + }, + { + pattern: /(?:Bearer|Basic)\s+[A-Za-z0-9+/=]{20,}/i, + description: "hardcoded auth token" + }, + { + pattern: /(?:jdbc|mongodb|postgres|mysql|redis):\/\/[^\s"']+:[^\s"']+@/i, + description: "hardcoded connection string with credentials" + }, + { + pattern: /-----BEGIN (?:RSA |EC )?PRIVATE KEY-----/, + description: "embedded private key" + } + ]; + for (const codeBlock of codeBlocks) { + for (const { pattern, description } of secretPatterns) { + if (pattern.test(codeBlock)) { + violations.push(makeViolation("no_hardcoded_secrets", sectionType, `Code example contains ${description} \u2014 use environment variables, secret managers, or configuration injection instead.`, description)); + } + } + } + const lowered = content.toLowerCase(); + const dangerousPhrases = [ + "hardcode the password", + "hardcode the key", + "embed the secret", + "paste your api key", + "put your token directly" + ]; + for (const phrase of dangerousPhrases) { + if (lowered.includes(phrase)) { + violations.push(makeViolation("no_hardcoded_secrets", sectionType, "Spec instructs hardcoding secrets \u2014 must use secure configuration (env vars, vault, secret manager).", phrase)); + } + } + return violations; +} +function checkInputValidationRequired(content, sectionType) { + return findAbsenceViolation(content, [ + "input validation", + "validate input", + "sanitize", + "sanitization", + "whitelist", + "allowlist", + "blocklist", + "reject invalid", + "schema validation", + "request validation", + "payload validation", + "type check", + "bounds check", + "length check", + "format validation", + "validate request", + "input filter", + "data validation" + ], 2, "input_validation_required", sectionType, "Technical spec must specify input validation strategy \u2014 every external input (API, user, file, webhook) needs validation and sanitization rules at system boundaries."); +} +function checkOutputEncodingInjectionPrevention(content, sectionType) { + const lowered = content.toLowerCase(); + const injectionSignals = [ + "injection prevention", + "sql injection", + "xss", + "cross-site scripting", + "command injection", + "output encoding", + "escape", + "parameterized quer", + "prepared statement", + "orm", + "html encoding", + "content security policy", + "csp", + "sanitize output", + "template escaping", + "injection attack" + ]; + const signalCount = injectionSignals.filter((s) => lowered.includes(s)).length; + if (signalCount < 2) { + return [ + makeViolation("output_encoding_injection_prevention", sectionType, "Technical spec must address injection prevention \u2014 specify parameterized queries (SQL injection), output encoding (XSS), and input sanitization strategies.") + ]; + } + const violations = []; + const codeBlocks = extractCodeBlocks(content); + const unsafeQueryPatterns = [ + { + pattern: /(?:SELECT|INSERT|UPDATE|DELETE).*\+\s*(?:user|input|param|req)/i, + description: "string concatenation in SQL query" + }, + { + pattern: /(?:SELECT|INSERT|UPDATE|DELETE).*\$\{.*\}/i, + description: "string interpolation in SQL query" + }, + { + pattern: /exec\s*\(.*\+.*\)/i, + description: "string concatenation in exec/eval" + } + ]; + for (const codeBlock of codeBlocks) { + for (const { pattern, description } of unsafeQueryPatterns) { + if (pattern.test(codeBlock)) { + violations.push(makeViolation("output_encoding_injection_prevention", sectionType, `Code example shows ${description} \u2014 use parameterized queries or prepared statements instead.`, description)); + } + } + } + return violations; +} +function checkAuthOnEveryEndpoint(content, sectionType) { + if (hasExplicitOptOut(content, [ + "authentication", + "authorization", + "endpoint", + "auth strategy", + "caller identity" + ])) { + return []; + } + const lowered = content.toLowerCase(); + const authNSignals = [ + "authentication", + "authenticate", + "login", + "sign in", + "jwt", + "oauth", + "api key", + "bearer token", + "session", + "identity", + "credential", + "mfa", + "multi-factor", + "sso" + ]; + const authZSignals = [ + "authorization", + "authorize", + "permission", + "role", + "rbac", + "abac", + "access control", + "privilege", + "scope", + "claim", + "policy", + "grant" + ]; + const hasAuthN = authNSignals.some((s) => lowered.includes(s)); + const hasAuthZ = authZSignals.some((s) => lowered.includes(s)); + if (!hasAuthN || !hasAuthZ) { + const missing = []; + if (!hasAuthN) + missing.push("authentication"); + if (!hasAuthZ) + missing.push("authorization"); + return [ + makeViolation("auth_on_every_endpoint", sectionType, `Technical spec must specify ${missing.join(" and ")} strategy \u2014 every endpoint/operation needs auth method, roles, and permission checks.`) + ]; + } + return []; +} +function checkSecuritySafeErrorHandling(content, sectionType) { + const lowered = content.toLowerCase(); + const safeErrorSignals = [ + "no stack trace", + "hide internal", + "generic error", + "error message sanitiz", + "no implementation detail", + "user-facing error", + "error boundary", + "safe error", + "don't leak", + "do not expose", + "error abstraction", + "error mapping", + "client-safe", + "production error" + ]; + const signalCount = safeErrorSignals.filter((s) => lowered.includes(s)).length; + if (signalCount < 1) { + const hasErrorSecurity = lowered.includes("error") && (lowered.includes("secur") || lowered.includes("sensitive")); + if (!hasErrorSecurity) { + return [ + makeViolation("security_safe_error_handling", sectionType, "Technical spec must ensure errors don't leak implementation details \u2014 no stack traces, internal paths, DB schemas, or server versions in error responses to clients.") + ]; + } + } + return []; +} +function checkCryptographicStandards(content, sectionType) { + const lowered = content.toLowerCase(); + const violations = []; + const cryptoSignals = [ + "encrypt", + "encryption", + "aes", + "rsa", + "tls", + "hash", + "bcrypt", + "argon2", + "scrypt", + "pbkdf2", + "hmac", + "sha-256", + "sha-384", + "sha-512", + "key management", + "key rotation", + "certificate" + ]; + const signalCount = cryptoSignals.filter((s) => lowered.includes(s)).length; + if (signalCount < 2) { + violations.push(makeViolation("cryptographic_standards", sectionType, "Technical spec must specify cryptographic standards \u2014 define encryption algorithms, hashing for passwords (bcrypt/argon2), minimum key sizes, and key management strategy.")); + } + const codeBlocks = extractCodeBlocks(content); + const weakPatterns = [ + { pattern: /\bMD5\b/, description: "MD5 (cryptographically broken)" }, + { pattern: /\bSHA-?1\b/, description: "SHA-1 (deprecated for security)" }, + { pattern: /\bDES\b/, description: "DES (obsolete, use AES)" }, + { pattern: /\bRC4\b/, description: "RC4 (broken)" } + ]; + for (const codeBlock of codeBlocks) { + for (const { pattern, description } of weakPatterns) { + if (pattern.test(codeBlock)) { + violations.push(makeViolation("cryptographic_standards", sectionType, `Code example uses weak cryptographic algorithm: ${description}. Use AES-256, SHA-256+, bcrypt/argon2 for passwords.`, description)); + } + } + } + return violations; +} +function checkRateLimitingRequired(content, sectionType) { + if (hasExplicitOptOut(content, [ + "rate limit", + "rate limiting", + "throttl", + "endpoint", + "abuse prevention" + ])) { + return []; + } + return findAbsenceViolation(content, [ + "rate limit", + "rate-limit", + "throttl", + "request limit", + "quota", + "burst limit", + "sliding window", + "token bucket", + "leaky bucket", + "ddos", + "abuse prevention", + "requests per", + "calls per" + ], 1, "rate_limiting_required", sectionType, "Technical spec must specify rate limiting strategy \u2014 define request limits per user/IP, throttling behavior, and abuse prevention for public-facing endpoints."); +} +function checkSecureCommunication(content, sectionType) { + if (hasExplicitOptOut(content, [ + "tls", + "https", + "network i/o", + "network", + "secure communication", + "transport", + "encrypted channel" + ])) { + return []; + } + return findAbsenceViolation(content, [ + "tls", + "https", + "ssl", + "transport layer security", + "encrypt in transit", + "encryption in transit", + "certificate", + "cert pinning", + "certificate pinning", + "mutual tls", + "mtls", + "secure channel", + "encrypted connection" + ], 1, "secure_communication", sectionType, "Technical spec must specify secure communication \u2014 TLS requirements, certificate validation, no mixed content, encrypted channels for all data in transit."); +} + +// packages/validation/dist/hard-output-rules/rules/data-protection-rules.js +function checkDataClassificationRequired(content, sectionType) { + if (hasExplicitOptOut(content, [ + "data classification", + "sensitivity", + "pii", + "personal data", + "sensitive data" + ])) { + return []; + } + return findAbsenceViolation(content, [ + "data classification", + "classify", + "classification level", + "public data", + "internal data", + "confidential", + "restricted", + "sensitivity level", + "sensitivity class", + "data tier", + "data category", + "personal data", + "non-personal", + "pii", + "phi", + "pci", + "sensitive data" + ], 2, "data_classification_required", sectionType, "Technical spec must classify all data entities \u2014 define sensitivity levels (public/internal/confidential/restricted) with handling rules per classification."); +} +function checkSensitiveDataProtection(content, sectionType) { + if (hasExplicitOptOut(content, [ + "sensitive data", + "sensitive data protection", + "pii", + "personal data", + "credentials", + "secrets" + ])) { + return []; + } + const lowered = content.toLowerCase(); + const encryptionSignals = [ + "encrypt at rest", + "encryption at rest", + "field-level encryption", + "column encryption", + "database encryption", + "aes" + ]; + const maskingSignals = [ + "mask", + "anonymiz", + "pseudonymiz", + "redact", + "obfuscat", + "tokeniz", + "de-identif", + "data scrub" + ]; + const accessSignals = [ + "row-level security", + "rls", + "column-level", + "field-level access", + "data access control", + "need-to-know", + "least privilege" + ]; + let categoriesMet = 0; + if (encryptionSignals.some((s) => lowered.includes(s))) + categoriesMet++; + if (maskingSignals.some((s) => lowered.includes(s))) + categoriesMet++; + if (accessSignals.some((s) => lowered.includes(s))) + categoriesMet++; + if (categoriesMet < 2) { + return [ + makeViolation("sensitive_data_protection", sectionType, "Technical spec must specify sensitive data protection strategy \u2014 address at least 2 of: encryption at rest, masking/anonymization, and access restrictions for PII and sensitive fields.") + ]; + } + return []; +} +function checkNoSensitiveDataInLogs(content, sectionType) { + if (hasExplicitOptOut(content, [ + "sensitive data", + "pii", + "personal data", + "log", + "credentials", + "tokens" + ])) { + return []; + } + const lowered = content.toLowerCase(); + const noLogPIISignals = [ + "no pii in log", + "mask in log", + "redact in log", + "filter sensitive", + "log sanitiz", + "scrub log", + "no sensitive data in log", + "log masking", + "exclude pii", + "strip pii", + "no personal data in log", + "structured log", + "safe logging" + ]; + const hasLogProtection = noLogPIISignals.some((s) => lowered.includes(s)); + const broaderSignals = lowered.includes("sensitive") && lowered.includes("log") && (lowered.includes("never") || lowered.includes("must not") || lowered.includes("exclude") || lowered.includes("prevent")); + if (!hasLogProtection && !broaderSignals) { + return [ + makeViolation("no_sensitive_data_in_logs", sectionType, "Technical spec must explicitly prevent sensitive data (PII, credentials, tokens) from appearing in logs, error messages, URLs, or query parameters.") + ]; + } + return []; +} +function checkDataMinimization(content, sectionType) { + if (hasExplicitOptOut(content, [ + "data minimization", + "personal data", + "pii", + "user data", + "data collected" + ])) { + return []; + } + return findAbsenceViolation(content, [ + "data minimization", + "minimal data", + "minimise", + "collect only", + "store only", + "need-to-know", + "purpose limitation", + "data purpose", + "justified", + "necessary data", + "required fields only", + "no unnecessary", + "reduce data footprint" + ], 1, "data_minimization", sectionType, "Technical spec must address data minimization \u2014 collect and store only what's necessary, justify every sensitive field, define purpose limitation."); +} +function checkAuditTrailRequired(content, sectionType) { + if (hasExplicitOptOut(content, [ + "audit", + "audit trail", + "compliance", + "authentication events", + "data access" + ])) { + return []; + } + return findAbsenceViolation(content, [ + "audit trail", + "audit log", + "audit event", + "who did what", + "who/what/when", + "accountability", + "compliance log", + "activity log", + "change log", + "access log", + "security log", + "event sourcing", + "tamper-proof log", + "immutable log" + ], 1, "audit_trail_required", sectionType, "Technical spec must require audit trails for sensitive operations \u2014 log who/what/when for authentication events, data access, configuration changes, and admin actions."); +} +function checkConsentAndErasureSupport(content, sectionType) { + if (hasExplicitOptOut(content, [ + "consent", + "erasure", + "personal data", + "gdpr", + "privacy compliance", + "user data" + ])) { + return []; + } + const lowered = content.toLowerCase(); + const consentSignals = [ + "consent", + "opt-in", + "opt-out", + "user agreement", + "privacy preference", + "data subject", + "lawful basis" + ]; + const erasureSignals = [ + "right to erasure", + "right to deletion", + "right to be forgotten", + "gdpr erasure", + "data deletion", + "cascade delete", + "soft delete", + "hard delete", + "purge", + "anonymize on delete", + "account deletion", + "data removal" + ]; + const hasConsent = consentSignals.some((s) => lowered.includes(s)); + const hasErasure = erasureSignals.some((s) => lowered.includes(s)); + if (!hasConsent && !hasErasure) { + return [ + makeViolation("consent_and_erasure_support", sectionType, "Technical spec must support consent management and data erasure \u2014 specify how user consent is tracked, how deletion cascades through the data model, and GDPR/privacy compliance.") + ]; + } + return []; +} + +// packages/validation/dist/hard-output-rules/rules/resilience-rules.js +function checkStructuredErrorHandling(content, sectionType) { + if (hasExplicitOptOut(content, [ + "error", + "exception", + "error handling", + "error propagation", + "swallowed exception" + ])) { + return []; + } + const lowered = content.toLowerCase(); + const domainErrorSignals = [ + "domain error", + "error type", + "error enum", + "error class", + "custom exception", + "business exception", + "typed error", + "error hierarchy", + "error code", + "error catalog" + ]; + const propagationSignals = [ + "error propagation", + "error boundary", + "error handling strategy", + "catch and rethrow", + "error translation", + "error mapping", + "exception filter", + "global error handler", + "error middleware", + "no swallow", + "never swallow", + "always propagate" + ]; + const hasDomainErrors = domainErrorSignals.some((s) => lowered.includes(s)); + const hasPropagation = propagationSignals.some((s) => lowered.includes(s)); + if (!hasDomainErrors && !hasPropagation) { + return [ + makeViolation("structured_error_handling", sectionType, "Technical spec must define structured error handling \u2014 domain-specific error types, no swallowed exceptions, no generic catch-all, and explicit error propagation strategy.") + ]; + } + return []; +} +function checkResiliencePatterns(content, sectionType) { + if (hasExplicitOptOut(content, [ + "resilience", + "circuit breaker", + "retry", + "external dependency", + "remote call", + "transient" + ])) { + return []; + } + return findAbsenceViolation(content, [ + "circuit breaker", + "retry", + "exponential backoff", + "timeout", + "bulkhead", + "rate limit", + "failure isolation", + "fault tolerance", + "resilience", + "health check", + "dead letter", + "fallback", + "backpressure", + "load shedding" + ], 2, "resilience_patterns", sectionType, "Technical spec must specify resilience patterns \u2014 circuit breaker for external dependencies, retry with exponential backoff, and timeout on every external call."); +} +function checkGracefulDegradation(content, sectionType) { + if (hasExplicitOptOut(content, [ + "graceful degradation", + "degradation", + "fallback", + "dependency failure", + "cascading failure" + ])) { + return []; + } + return findAbsenceViolation(content, [ + "graceful degradation", + "degrade gracefully", + "fallback", + "fail gracefully", + "partial failure", + "degraded mode", + "offline mode", + "cache fallback", + "default response", + "service unavailable", + "cascading failure", + "blast radius" + ], 1, "graceful_degradation", sectionType, "Technical spec must define graceful degradation \u2014 specify fallback behavior when dependencies fail, prevent cascading failures, and define degraded operation modes."); +} +function checkTransactionBoundaries(content, sectionType) { + if (hasExplicitOptOut(content, [ + "transaction", + "rollback", + "atomic", + "multi-step", + "read-only", + "no writes", + "database" + ])) { + return []; + } + return findAbsenceViolation(content, [ + "transaction", + "transactional", + "atomicity", + "atomic operation", + "isolation level", + "rollback", + "commit", + "saga", + "compensating transaction", + "eventual consistency", + "two-phase commit", + "optimistic lock", + "pessimistic lock", + "idempoten", + "exactly-once", + "at-least-once" + ], 2, "transaction_boundaries", sectionType, "Technical spec must define transaction boundaries \u2014 specify transaction scope, isolation level, rollback strategy, and idempotency for multi-step operations."); +} +function checkConsistentErrorFormat(content, sectionType) { + if (hasExplicitOptOut(content, [ + "error format", + "error response", + "error envelope", + "error code", + "error catalog" + ])) { + return []; + } + return findAbsenceViolation(content, [ + "error format", + "error response format", + "error schema", + "error contract", + "rfc 7807", + "problem detail", + "error code", + "error_code", + "error response structure", + "standardized error", + "consistent error", + "error envelope", + "error body", + "machine-readable error" + ], 1, "consistent_error_format", sectionType, "Technical spec must define a consistent error response format \u2014 standardized structure with error codes, human-readable messages, and machine-readable details (e.g., RFC 7807)."); +} + +// packages/validation/dist/hard-output-rules/rules/concurrency-rules.js +function checkConcurrencySafety(content, sectionType) { + return findAbsenceViolation(content, [ + "thread safe", + "thread-safe", + "concurren", + "race condition", + "mutex", + "semaphore", + "lock", + "synchronized", + "atomic", + "volatile", + "actor", + "serial queue", + "dispatch queue", + "async/await", + "coroutine", + "channel", + "deadlock", + "livelock", + "starvation", + "shared state", + "mutable state", + "concurrent access" + ], 2, "concurrency_safety", sectionType, "Technical spec must address concurrency safety \u2014 specify how shared mutable state is protected, thread safety guarantees, race condition prevention, and deadlock avoidance strategies."); +} +function checkImmutabilityByDefault(content, sectionType) { + return findAbsenceViolation(content, [ + "immutable", + "immutability", + "value type", + "value object", + "val ", + "let ", + "const ", + "readonly", + "read-only", + "frozen", + "unmodifiable", + "persistent data structure", + "copy-on-write", + "defensive copy", + "final field" + ], 1, "immutability_by_default", sectionType, "Technical spec should prefer immutable data structures \u2014 use value types, const/let/val by default, and justify any mutable state explicitly."); +} +function checkAtomicOperations(content, sectionType) { + return findAbsenceViolation(content, [ + "atomic", + "atomicity", + "compare-and-swap", + "cas ", + "transaction isolation", + "serializable", + "read committed", + "repeatable read", + "snapshot isolation", + "optimistic concurrency", + "version check", + "etag", + "if-match", + "conditional update" + ], 1, "atomic_operations", sectionType, "Technical spec must specify atomicity for multi-step state changes \u2014 define transaction isolation levels, optimistic concurrency control, and atomic operation boundaries."); +} + +// packages/validation/dist/hard-output-rules/rules/senior-quality-rules.js +function checkNoMagicNumbers(content, sectionType) { + const violations = []; + const codeBlocks = extractCodeBlocks(content); + const magicNumberPattern = /(?:(?:timeout|delay|limit|max|min|size|count|threshold|retry|interval|duration|width|height|margin|padding)\s*[:=]\s*)\d{2,}/gi; + for (const codeBlock of codeBlocks) { + const matches = codeBlock.match(magicNumberPattern); + if (matches && matches.length >= 3) { + violations.push(makeViolation("no_magic_numbers", sectionType, "Code examples contain multiple raw numeric literals \u2014 extract to named constants (e.g., MAX_RETRY_COUNT, DEFAULT_TIMEOUT_MS) for maintainability.", `Found ${matches.length} magic numbers in code block`)); + } + } + const lowered = content.toLowerCase(); + const constantSignals = [ + "named constant", + "named variable", + "const ", + "static let", + "static final", + "companion object", + "no magic number", + "extract constant", + "configuration value" + ]; + const hasConstantGuidance = constantSignals.some((s) => lowered.includes(s)); + if (!hasConstantGuidance && codeBlocks.length > 0) { + violations.push(makeViolation("no_magic_numbers", sectionType, "Technical spec should mandate named constants \u2014 all configuration values, thresholds, and limits must be extracted to named constants, not raw literals.")); + } + return violations; +} +function checkDefensiveCoding(content, sectionType) { + return findAbsenceViolation(content, [ + "guard", + "precondition", + "require", + "assert", + "null safe", + "null check", + "nil check", + "optional", + "non-null", + "nonnull", + "notnull", + "bounds check", + "range check", + "defensive", + "fail fast", + "early return", + "validation", + "contract", + "invariant" + ], 2, "defensive_coding", sectionType, "Technical spec must enforce defensive coding \u2014 guard clauses, preconditions, null safety, bounds checking at all entry points. Fail fast on invalid state."); +} +function checkMethodSizeLimits(content, sectionType) { + const violations = []; + const codeBlocks = extractCodeBlocks(content); + const funcPattern = /(?:func |function |def |fn |fun |public |private |protected |internal |static )*(?:func|function|def|fn|fun|method)\s+(\w+)/; + for (const codeBlock of codeBlocks) { + const lines = codeBlock.split("\n"); + let currentFuncName = null; + let funcStartLine = 0; + let braceDepth = 0; + let inFunction = false; + for (let index2 = 0; index2 < lines.length; index2++) { + const line = lines[index2]; + if (!inFunction) { + const match = line.match(funcPattern); + if (match) { + currentFuncName = match[1] ?? "anonymous"; + funcStartLine = index2; + inFunction = true; + braceDepth = 0; + } + } + if (inFunction) { + braceDepth += (line.match(/\{/g) || []).length; + braceDepth -= (line.match(/\}/g) || []).length; + if (braceDepth <= 0 && line.includes("}")) { + const funcLineCount = index2 - funcStartLine + 1; + if (funcLineCount > 30) { + violations.push(makeViolation("method_size_limits", sectionType, `Code example shows function '${currentFuncName}' spanning ${funcLineCount} lines \u2014 extract logic into smaller functions. Methods should be ~30 lines max in PRD examples.`, currentFuncName)); + } + inFunction = false; + currentFuncName = null; + } + } + } + } + return violations; +} +function checkConsistentNaming(content, sectionType) { + return findAbsenceViolation(content, [ + "naming convention", + "naming standard", + "naming rule", + "camelcase", + "camel case", + "snake_case", + "snake case", + "pascalcase", + "pascal case", + "kebab-case", + "descriptive name", + "self-documenting", + "meaningful name", + "no abbreviation", + "full word", + "consistent naming" + ], 1, "consistent_naming", sectionType, "Technical spec should establish naming conventions \u2014 specify casing style, use descriptive names, avoid abbreviations in public APIs, and enforce consistent patterns."); +} +function checkAPIContractDocumentation(content, sectionType) { + return findAbsenceViolation(content, [ + "request schema", + "response schema", + "api contract", + "openapi", + "swagger", + "api spec", + "endpoint spec", + "request body", + "response body", + "status code", + "content-type", + "accept header", + "api documentation", + "typed request", + "typed response" + ], 2, "api_contract_documentation", sectionType, "Technical spec must document API contracts \u2014 every endpoint needs typed request/response schemas, status codes, error responses, and content-type specifications."); +} +function checkDeprecationStrategy(content, sectionType) { + return findAbsenceViolation(content, [ + "deprecat", + "sunset", + "breaking change", + "migration path", + "backward compat", + "backwards compat", + "version", + "api version", + "v1", + "v2", + "changelog", + "upgrade guide", + "migration guide" + ], 1, "deprecation_strategy", sectionType, "Technical spec should define deprecation strategy \u2014 specify migration paths for breaking changes, sunset timelines, and versioning approach."); +} + +// packages/validation/dist/hard-output-rules/rules/testing-rules.js +function checkMandatoryTestCoverage(content, sectionType) { + const lowered = content.toLowerCase(); + const unitSignals = [ + "unit test", + "ut-", + "unit coverage", + "function test", + "method test", + "class test", + "module test" + ]; + const integrationSignals = [ + "integration test", + "it-", + "api test", + "contract test", + "component test", + "service test", + "end-to-end", + "e2e" + ]; + const coverageSignals = [ + "test coverage", + "code coverage", + "coverage target", + "coverage threshold", + "coverage report", + "line coverage", + "branch coverage", + "100% coverage", + "minimum coverage" + ]; + const hasUnit = unitSignals.some((s) => lowered.includes(s)); + const hasIntegration = integrationSignals.some((s) => lowered.includes(s)); + const hasCoverage = coverageSignals.some((s) => lowered.includes(s)); + const violations = []; + if (!hasUnit || !hasIntegration) { + violations.push(makeViolation("mandatory_test_coverage", sectionType, "Test spec must include both unit tests and integration tests \u2014 every public method/endpoint needs corresponding test specifications.")); + } + if (!hasCoverage) { + violations.push(makeViolation("mandatory_test_coverage", sectionType, "Test spec must define coverage targets \u2014 specify minimum code coverage thresholds for unit, integration, and overall coverage.")); + } + return violations; +} +function checkSecurityTestingRequired(content, sectionType) { + return findAbsenceViolation(content, [ + "security test", + "penetration test", + "pen test", + "sast", + "dast", + "static analysis", + "dynamic analysis", + "vulnerability scan", + "dependency scan", + "snyk", + "owasp", + "security audit", + "threat model", + "fuzz", + "injection test", + "auth test", + "access control test", + "privilege escalation" + ], 2, "security_testing_required", sectionType, "Test spec must include security testing \u2014 SAST/DAST, dependency vulnerability scanning, penetration test plan, and OWASP-based test cases."); +} +function checkPerformanceTestingRequired(content, sectionType) { + return findAbsenceViolation(content, [ + "performance test", + "load test", + "stress test", + "benchmark", + "throughput test", + "latency test", + "spike test", + "soak test", + "capacity test", + "response time", + "p95", + "p99", + "percentile", + "concurrent user", + "requests per second", + "rps" + ], 2, "performance_testing_required", sectionType, "Test spec must include performance testing \u2014 load test scenarios, stress thresholds, baseline comparisons, and latency percentile targets."); +} +function checkNoProductionDataInTests(content, sectionType) { + return findAbsenceViolation(content, [ + "synthetic data", + "anonymized", + "anonymised", + "test fixture", + "mock data", + "fake data", + "factory", + "faker", + "seed data", + "generated data", + "no production data", + "no real data", + "test data", + "sample data", + "fixture" + ], 1, "no_production_data_in_tests", sectionType, "Test spec must mandate synthetic test data \u2014 no real PII, no production data dumps, use factories/fakers/fixtures for all test data."); +} +function checkEdgeCaseNegativeTests(content, sectionType) { + const lowered = content.toLowerCase(); + const negativeSignals = [ + "negative test", + "failure case", + "error case", + "unhappy path", + "sad path", + "invalid input", + "reject", + "unauthorized", + "forbidden", + "not found", + "timeout", + "failure scenario" + ]; + const edgeCaseSignals = [ + "edge case", + "boundary", + "corner case", + "empty", + "null", + "zero", + "overflow", + "maximum", + "minimum", + "limit", + "concurrent", + "race condition", + "duplicate", + "idempoten" + ]; + const hasNegative = negativeSignals.some((s) => lowered.includes(s)); + const hasEdgeCases = edgeCaseSignals.some((s) => lowered.includes(s)); + if (!hasNegative || !hasEdgeCases) { + return [ + makeViolation("edge_case_negative_tests", sectionType, "Test spec must include both negative tests (failure scenarios, invalid inputs, unauthorized access) and edge cases (boundary values, empty states, concurrent operations).") + ]; + } + return []; +} +function checkTestIsolation(content, sectionType) { + return findAbsenceViolation(content, [ + "test isolation", + "isolated test", + "independent test", + "no shared state", + "setup and teardown", + "setup/teardown", + "before each", + "after each", + "beforeeach", + "aftereach", + "fresh instance", + "clean state", + "reset", + "test container", + "in-memory database", + "mock" + ], 2, "test_isolation", sectionType, "Test spec must ensure test isolation \u2014 no shared mutable state between tests, proper setup/teardown, each test independent and repeatable in any order."); +} + +// packages/validation/dist/hard-output-rules/rules/observability-rules.js +function checkStructuredLogging(content, sectionType) { + const lowered = content.toLowerCase(); + const formatSignals = [ + "structured log", + "json log", + "log format", + "log schema", + "log standard", + "log framework" + ]; + const levelSignals = [ + "log level", + "debug", + "info", + "warn", + "error", + "trace", + "fatal", + "severity", + "verbosity" + ]; + const hasFormat = formatSignals.some((s) => lowered.includes(s)); + const hasLevels = levelSignals.filter((s) => lowered.includes(s)).length >= 2; + if (!hasFormat && !hasLevels) { + return [ + makeViolation("structured_logging", sectionType, "Technical spec must define structured logging \u2014 specify log format (JSON/structured), log levels (DEBUG/INFO/WARN/ERROR), and what to log at each level.") + ]; + } + return []; +} +function checkDistributedTracing(content, sectionType) { + if (hasExplicitOptOut(content, [ + "distributed tracing", + "tracing", + "correlation id", + "single-process", + "single process", + "cross-service", + "second hop" + ])) { + return []; + } + return findAbsenceViolation(content, [ + "correlation id", + "trace id", + "request id", + "distributed trac", + "opentelemetry", + "jaeger", + "zipkin", + "trace context", + "span", + "trace propagat", + "x-request-id", + "x-correlation-id", + "end-to-end trac", + "cross-service trac" + ], 1, "distributed_tracing", sectionType, "Technical spec should specify distributed tracing \u2014 correlation IDs for cross-service request tracking, trace context propagation, and observability integration."); +} +function checkNoPIIInObservability(content, sectionType) { + if (hasExplicitOptOut(content, [ + "pii", + "observability", + "personal data", + "logs", + "metrics", + "traces", + "dashboards" + ])) { + return []; + } + const lowered = content.toLowerCase(); + const piiProtectionSignals = [ + "no pii in log", + "no pii in metric", + "no pii in trace", + "mask sensitive", + "redact", + "scrub", + "sanitize log", + "filter pii", + "exclude sensitive", + "log safe", + "safe to log", + "no personal data in" + ]; + const hasProtection = piiProtectionSignals.some((s) => lowered.includes(s)); + const hasBroader = (lowered.includes("pii") || lowered.includes("sensitive") || lowered.includes("personal data")) && (lowered.includes("log") || lowered.includes("metric") || lowered.includes("trace") || lowered.includes("monitor")) && (lowered.includes("never") || lowered.includes("must not") || lowered.includes("exclude") || lowered.includes("prevent") || lowered.includes("mask") || lowered.includes("redact")); + if (!hasProtection && !hasBroader) { + return [ + makeViolation("no_pii_in_observability", sectionType, "Technical spec must ensure no PII in observability \u2014 logs, metrics, traces, and dashboards must not contain sensitive personal data. Specify masking/redaction strategy.") + ]; + } + return []; +} +function checkAlertingThresholds(content, sectionType) { + return findAbsenceViolation(content, [ + "alert", + "alerting", + "threshold", + "alarm", + "escalat", + "on-call", + "pagerduty", + "opsgenie", + "notification", + "sla breach", + "slo", + "warning threshold", + "critical threshold", + "runbook", + "incident response" + ], 2, "alerting_thresholds", sectionType, "Technical spec should define alerting thresholds \u2014 specify what triggers alerts, severity levels, escalation paths, and on-call routing."); +} + +// packages/validation/dist/hard-output-rules/rules/dependency-rules.js +function checkDependencyVulnerabilityScanning(content, sectionType) { + return findAbsenceViolation(content, [ + "dependency scan", + "vulnerability scan", + "cve", + "snyk", + "dependabot", + "renovate", + "trivy", + "software composition analysis", + "sca", + "supply chain", + "sbom", + "software bill of materials", + "known vulnerabilit", + "security advisory", + "dependency audit", + "npm audit", + "pip audit" + ], 1, "dependency_vulnerability_scanning", sectionType, "Technical spec must require dependency vulnerability scanning \u2014 specify SCA tooling, CVE monitoring, and automated scanning in CI/CD pipeline."); +} +function checkMinimalDependencyPrinciple(content, sectionType) { + return findAbsenceViolation(content, [ + "minimal dependenc", + "minimize dependenc", + "reduce dependenc", + "standard library", + "built-in", + "native", + "justify dependenc", + "dependency rationale", + "license compliance", + "license audit", + "license check", + "dependency review", + "approved dependenc" + ], 1, "minimal_dependency_principle", sectionType, "Technical spec should apply minimal dependency principle \u2014 justify new dependencies, prefer standard library, and verify license compliance."); +} + +// packages/validation/dist/hard-output-rules/index.js +function checkRule(rule, content, sectionType) { + switch (rule) { + // Core PRD Rules + case "sp_arithmetic": + return checkSPArithmetic(content, sectionType); + case "no_self_referencing_deps": + return checkNoSelfReferencingDeps(content, sectionType); + case "ac_numbering": + return checkACNumbering(content, sectionType); + case "no_orphan_ddl": + return checkNoOrphanDDL(content, sectionType); + case "no_now_in_partial_indexes": + return checkNoNowInPartialIndexes(content, sectionType); + case "no_any_codable": + return checkNoAnyCodable(content, sectionType); + case "no_placeholder_tests": + return checkNoPlaceholderTests(content, sectionType); + case "sp_not_in_fr_table": + return checkSPNotInFRTable(content, sectionType); + case "uneven_sp_distribution": + return checkUnevenSPDistribution(content, sectionType); + case "metrics_disclaimer": + return checkMetricsDisclaimer(content, sectionType); + case "fr_traceability": + return checkFRTraceability(content, sectionType); + case "clean_architecture": + return checkCleanArchitecture(content, sectionType); + case "honest_verification_verdicts": + return checkHonestVerificationVerdicts(content, sectionType); + case "code_example_port_compliance": + return checkCodeExamplePortCompliance(content, sectionType); + case "test_traceability_integrity": + return checkTestTraceabilityIntegrity(content, sectionType); + case "duplicate_requirement_ids": + return checkDuplicateRequirementIds(content, sectionType); + case "fk_references_exist": + return checkFKReferencesExist(content, sectionType); + case "fr_numbering_gaps": + return checkFRNumberingGaps(content, sectionType); + case "risk_mitigation_completeness": + return checkRiskMitigationCompleteness(content, sectionType); + case "deployment_rollback_plan": + return checkDeploymentRollbackPlan(content, sectionType); + // Architecture & Code Quality (18-24) + case "generic_over_specific": + return checkGenericOverSpecific(content, sectionType); + case "no_nested_types": + return checkNoNestedTypes(content, sectionType); + case "single_responsibility": + return checkSingleResponsibility(content, sectionType); + case "explicit_access_control": + return checkExplicitAccessControl(content, sectionType); + case "factory_based_injection": + return checkFactoryBasedInjection(content, sectionType); + case "solid_compliance": + return checkSolidCompliance(content, sectionType); + case "code_reusability": + return checkCodeReusability(content, sectionType); + // Security (25-32) + case "no_hardcoded_secrets": + return checkNoHardcodedSecrets(content, sectionType); + case "input_validation_required": + return checkInputValidationRequired(content, sectionType); + case "output_encoding_injection_prevention": + return checkOutputEncodingInjectionPrevention(content, sectionType); + case "auth_on_every_endpoint": + return checkAuthOnEveryEndpoint(content, sectionType); + case "security_safe_error_handling": + return checkSecuritySafeErrorHandling(content, sectionType); + case "cryptographic_standards": + return checkCryptographicStandards(content, sectionType); + case "rate_limiting_required": + return checkRateLimitingRequired(content, sectionType); + case "secure_communication": + return checkSecureCommunication(content, sectionType); + // Data Protection (33-38) + case "data_classification_required": + return checkDataClassificationRequired(content, sectionType); + case "sensitive_data_protection": + return checkSensitiveDataProtection(content, sectionType); + case "no_sensitive_data_in_logs": + return checkNoSensitiveDataInLogs(content, sectionType); + case "data_minimization": + return checkDataMinimization(content, sectionType); + case "audit_trail_required": + return checkAuditTrailRequired(content, sectionType); + case "consent_and_erasure_support": + return checkConsentAndErasureSupport(content, sectionType); + // Error Handling & Resilience (39-43) + case "structured_error_handling": + return checkStructuredErrorHandling(content, sectionType); + case "resilience_patterns": + return checkResiliencePatterns(content, sectionType); + case "graceful_degradation": + return checkGracefulDegradation(content, sectionType); + case "transaction_boundaries": + return checkTransactionBoundaries(content, sectionType); + case "consistent_error_format": + return checkConsistentErrorFormat(content, sectionType); + // Concurrency (44-46) + case "concurrency_safety": + return checkConcurrencySafety(content, sectionType); + case "immutability_by_default": + return checkImmutabilityByDefault(content, sectionType); + case "atomic_operations": + return checkAtomicOperations(content, sectionType); + // Senior Quality (47-52) + case "no_magic_numbers": + return checkNoMagicNumbers(content, sectionType); + case "defensive_coding": + return checkDefensiveCoding(content, sectionType); + case "method_size_limits": + return checkMethodSizeLimits(content, sectionType); + case "consistent_naming": + return checkConsistentNaming(content, sectionType); + case "api_contract_documentation": + return checkAPIContractDocumentation(content, sectionType); + case "deprecation_strategy": + return checkDeprecationStrategy(content, sectionType); + // Testing (53-58) + case "mandatory_test_coverage": + return checkMandatoryTestCoverage(content, sectionType); + case "security_testing_required": + return checkSecurityTestingRequired(content, sectionType); + case "performance_testing_required": + return checkPerformanceTestingRequired(content, sectionType); + case "no_production_data_in_tests": + return checkNoProductionDataInTests(content, sectionType); + case "edge_case_negative_tests": + return checkEdgeCaseNegativeTests(content, sectionType); + case "test_isolation": + return checkTestIsolation(content, sectionType); + // Observability (59-62) + case "structured_logging": + return checkStructuredLogging(content, sectionType); + case "distributed_tracing": + return checkDistributedTracing(content, sectionType); + case "no_pii_in_observability": + return checkNoPIIInObservability(content, sectionType); + case "alerting_thresholds": + return checkAlertingThresholds(content, sectionType); + // Dependencies (63-64) + case "dependency_vulnerability_scanning": + return checkDependencyVulnerabilityScanning(content, sectionType); + case "minimal_dependency_principle": + return checkMinimalDependencyPrinciple(content, sectionType); + // Document-level / process-level rules — checked in validateDocument() + case "fr_to_ac_coverage": + case "ac_to_test_coverage": + case "post_generation_self_check": + case "mandatory_codebase_analysis": + return []; + } +} +function validateSection(content, sectionType) { + const applicableRules = rulesForSection(sectionType); + const violations = []; + const rulesPassed = []; + for (const rule of applicableRules) { + const ruleViolations = checkRule(rule, content, sectionType); + if (ruleViolations.length === 0) { + rulesPassed.push(rule); + } else { + violations.push(...ruleViolations); + } + } + const hasCriticalViolations = violations.some((v) => v.isCritical); + const totalPenalty = violations.reduce((sum3, v) => sum3 + v.scorePenalty, 0); + const totalScore = Math.max(0, 1 - totalPenalty); + return { + violations, + rulesChecked: applicableRules, + rulesPassed, + sectionType, + hasCriticalViolations, + totalScore, + checkedAt: (/* @__PURE__ */ new Date()).toISOString() + }; +} +function validateDocument(sections) { + const allViolations = []; + const allRulesChecked = /* @__PURE__ */ new Set(); + const allRulesPassed = /* @__PURE__ */ new Set(); + for (const section of sections) { + const report = validateSection(section.content, section.type); + allViolations.push(...report.violations); + for (const r of report.rulesChecked) + allRulesChecked.add(r); + for (const r of report.rulesPassed) + allRulesPassed.add(r); + } + const combinedContent = sections.map((s) => s.content).join("\n\n"); + const addDocCheck = (rule, violations) => { + allRulesChecked.add(rule); + if (violations.length === 0) { + allRulesPassed.add(rule); + } else { + allRulesPassed.delete(rule); + allViolations.push(...violations); + } + }; + addDocCheck("sp_arithmetic", checkDocumentSPArithmetic(sections)); + addDocCheck("ac_numbering", checkDocumentACConsistency(combinedContent)); + addDocCheck("honest_verification_verdicts", checkDocumentVerificationVerdicts(sections)); + addDocCheck("test_traceability_integrity", checkDocumentTestTraceability(sections)); + addDocCheck("fr_to_ac_coverage", checkDocumentFRToACCoverage(sections)); + addDocCheck("ac_to_test_coverage", checkDocumentACToTestCoverage(sections)); + const violatedRules = new Set(allViolations.map((v) => v.rule)); + for (const rule of violatedRules) { + allRulesPassed.delete(rule); + } + const hasCriticalViolations = allViolations.some((v) => v.isCritical); + const totalPenalty = allViolations.reduce((sum3, v) => sum3 + v.scorePenalty, 0); + const totalScore = Math.max(0, 1 - totalPenalty); + return { + violations: allViolations, + rulesChecked: [...allRulesChecked].sort(), + rulesPassed: [...allRulesPassed].sort(), + sectionType: null, + hasCriticalViolations, + totalScore, + checkedAt: (/* @__PURE__ */ new Date()).toISOString() + }; +} + +// packages/validation/dist/cross-ref-validator.js +var ID_PATTERNS = { + FR: /\bFR-(\d+)\b/g, + AC: /\bAC-(\d+)\b/g, + US: /\bUS-(\d+)\b/g, + STORY: /\bSTORY-(\d+)\b/g, + TEST: /\bTEST-(\d+)\b/g, + OQ: /\bOQ-(\d+)\b/g, + RISK: /\bRISK-(\d+)\b/g, + NFR: /\bNFR-(\d+)\b/g +}; +function extractIds(content, sectionName) { + const occurrences = []; + for (const [type2, pattern] of Object.entries(ID_PATTERNS)) { + const regex = new RegExp(pattern.source, pattern.flags); + let match; + while ((match = regex.exec(content)) !== null) { + const id = match[0]; + const lineStart = content.lastIndexOf("\n", match.index) + 1; + const linePrefix = content.slice(lineStart, match.index).trim(); + const isDefinition = linePrefix === "" || linePrefix === "|" || linePrefix.startsWith("#"); + occurrences.push({ id, type: type2, section: sectionName, isDefinition }); + } + } + return occurrences; +} +function detectCycles(adjacency) { + const cycles = []; + const visited = /* @__PURE__ */ new Set(); + const inStack = /* @__PURE__ */ new Set(); + function dfs(node, path) { + if (inStack.has(node)) { + const cycleStart2 = path.indexOf(node); + if (cycleStart2 >= 0) { + cycles.push(path.slice(cycleStart2)); + } + return; + } + if (visited.has(node)) + return; + visited.add(node); + inStack.add(node); + path.push(node); + for (const neighbor of adjacency.get(node) ?? []) { + dfs(neighbor, [...path]); + } + inStack.delete(node); + } + for (const node of adjacency.keys()) { + if (!visited.has(node)) { + dfs(node, []); + } + } + return cycles; +} +function checkNumberingContinuity(ids, prefix) { + const gaps = []; + const numbers = ids.filter((id) => id.startsWith(`${prefix}-`)).map((id) => parseInt(id.split("-")[1], 10)).filter((n) => !isNaN(n)).sort((a, b) => a - b); + for (let i2 = 1; i2 < numbers.length; i2++) { + if (numbers[i2] !== numbers[i2 - 1] + 1) { + gaps.push({ + prefix, + expected: numbers[i2 - 1] + 1, + actual: numbers[i2] + }); + } + } + return gaps; +} +function validateCrossReferences(sections) { + const allOccurrences = []; + for (const section of sections) { + allOccurrences.push(...extractIds(section.content, section.name)); + } + const definitions = /* @__PURE__ */ new Set(); + const references = /* @__PURE__ */ new Map(); + for (const occ of allOccurrences) { + if (occ.isDefinition) { + definitions.add(occ.id); + } + const refs = references.get(occ.id) ?? []; + refs.push(occ.section); + references.set(occ.id, refs); + } + const danglingReferences = [...references.entries()].filter(([id]) => !definitions.has(id)).map(([id, sections2]) => ({ + id, + referencedIn: sections2.join(", "), + type: id.split("-")[0] + })); + const orphanNodes = [...definitions].filter((id) => { + const refs = references.get(id) ?? []; + return new Set(refs).size <= 1; + }).map((id) => ({ + id, + type: id.split("-")[0], + reason: "Defined but not referenced in other sections" + })); + const dependsOnPattern = /Depends\s*(?:On|on)[:\s]*([^\n|]+)/g; + const adjacency = /* @__PURE__ */ new Map(); + for (const section of sections) { + let match; + const regex = new RegExp(dependsOnPattern.source, dependsOnPattern.flags); + while ((match = regex.exec(section.content)) !== null) { + const depList = match[1]; + const ids = depList.match(/(?:FR|US|STORY|AC)-\d+/g) ?? []; + const lineStart = section.content.lastIndexOf("\n", match.index); + const lineBefore = section.content.slice(Math.max(0, lineStart - 200), match.index); + const ownerMatch = lineBefore.match(/(?:FR|US|STORY|AC)-\d+/g); + const owner = ownerMatch?.[ownerMatch.length - 1]; + if (owner) { + if (!adjacency.has(owner)) + adjacency.set(owner, /* @__PURE__ */ new Set()); + for (const dep of ids) { + adjacency.get(owner).add(dep); + } + } + } + } + const cycles = detectCycles(adjacency); + const allDefinedIds = [...definitions]; + const numberingGaps = [ + ...checkNumberingContinuity(allDefinedIds, "FR"), + ...checkNumberingContinuity(allDefinedIds, "AC"), + ...checkNumberingContinuity(allDefinedIds, "US"), + ...checkNumberingContinuity(allDefinedIds, "NFR") + ]; + const idCounts = /* @__PURE__ */ new Map(); + for (const occ of allOccurrences.filter((o) => o.isDefinition)) { + idCounts.set(occ.id, (idCounts.get(occ.id) ?? 0) + 1); + } + const duplicateIds = [...idCounts.entries()].filter(([, count2]) => count2 > 1).map(([id]) => id); + const isValid2 = danglingReferences.length === 0 && cycles.length === 0 && duplicateIds.length === 0; + return { + danglingReferences, + orphanNodes, + cycles, + numberingGaps, + duplicateIds, + isValid: isValid2 + }; +} + +// node_modules/.pnpm/js-yaml@4.1.1/node_modules/js-yaml/dist/js-yaml.mjs +function isNothing(subject) { + return typeof subject === "undefined" || subject === null; +} +function isObject2(subject) { + return typeof subject === "object" && subject !== null; +} +function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; + return [sequence]; +} +function extend2(target, source) { + var index2, length, key, sourceKeys; + if (source) { + sourceKeys = Object.keys(source); + for (index2 = 0, length = sourceKeys.length; index2 < length; index2 += 1) { + key = sourceKeys[index2]; + target[key] = source[key]; + } + } + return target; +} +function repeat(string4, count2) { + var result = "", cycle; + for (cycle = 0; cycle < count2; cycle += 1) { + result += string4; + } + return result; +} +function isNegativeZero(number4) { + return number4 === 0 && Number.NEGATIVE_INFINITY === 1 / number4; +} +var isNothing_1 = isNothing; +var isObject_1 = isObject2; +var toArray_1 = toArray; +var repeat_1 = repeat; +var isNegativeZero_1 = isNegativeZero; +var extend_1 = extend2; +var common = { + isNothing: isNothing_1, + isObject: isObject_1, + toArray: toArray_1, + repeat: repeat_1, + isNegativeZero: isNegativeZero_1, + extend: extend_1 +}; +function formatError2(exception2, compact) { + var where = "", message = exception2.reason || "(unknown reason)"; + if (!exception2.mark) return message; + if (exception2.mark.name) { + where += 'in "' + exception2.mark.name + '" '; + } + where += "(" + (exception2.mark.line + 1) + ":" + (exception2.mark.column + 1) + ")"; + if (!compact && exception2.mark.snippet) { + where += "\n\n" + exception2.mark.snippet; + } + return message + " " + where; +} +function YAMLException$1(reason, mark) { + Error.call(this); + this.name = "YAMLException"; + this.reason = reason; + this.mark = mark; + this.message = formatError2(this, false); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } else { + this.stack = new Error().stack || ""; + } +} +YAMLException$1.prototype = Object.create(Error.prototype); +YAMLException$1.prototype.constructor = YAMLException$1; +YAMLException$1.prototype.toString = function toString(compact) { + return this.name + ": " + formatError2(this, compact); +}; +var exception = YAMLException$1; +function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { + var head = ""; + var tail = ""; + var maxHalfLength = Math.floor(maxLineLength / 2) - 1; + if (position - lineStart > maxHalfLength) { + head = " ... "; + lineStart = position - maxHalfLength + head.length; + } + if (lineEnd - position > maxHalfLength) { + tail = " ..."; + lineEnd = position + maxHalfLength - tail.length; + } + return { + str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail, + pos: position - lineStart + head.length + // relative position + }; +} +function padStart(string4, max3) { + return common.repeat(" ", max3 - string4.length) + string4; +} +function makeSnippet(mark, options) { + options = Object.create(options || null); + if (!mark.buffer) return null; + if (!options.maxLength) options.maxLength = 79; + if (typeof options.indent !== "number") options.indent = 1; + if (typeof options.linesBefore !== "number") options.linesBefore = 3; + if (typeof options.linesAfter !== "number") options.linesAfter = 2; + var re2 = /\r?\n|\r|\0/g; + var lineStarts = [0]; + var lineEnds = []; + var match; + var foundLineNo = -1; + while (match = re2.exec(mark.buffer)) { + lineEnds.push(match.index); + lineStarts.push(match.index + match[0].length); + if (mark.position <= match.index && foundLineNo < 0) { + foundLineNo = lineStarts.length - 2; + } + } + if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; + var result = "", i2, line; + var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; + var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); + for (i2 = 1; i2 <= options.linesBefore; i2++) { + if (foundLineNo - i2 < 0) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo - i2], + lineEnds[foundLineNo - i2], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i2]), + maxLineLength + ); + result = common.repeat(" ", options.indent) + padStart((mark.line - i2 + 1).toString(), lineNoLength) + " | " + line.str + "\n" + result; + } + line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); + result += common.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\n"; + result += common.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\n"; + for (i2 = 1; i2 <= options.linesAfter; i2++) { + if (foundLineNo + i2 >= lineEnds.length) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo + i2], + lineEnds[foundLineNo + i2], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i2]), + maxLineLength + ); + result += common.repeat(" ", options.indent) + padStart((mark.line + i2 + 1).toString(), lineNoLength) + " | " + line.str + "\n"; + } + return result.replace(/\n$/, ""); +} +var snippet = makeSnippet; +var TYPE_CONSTRUCTOR_OPTIONS = [ + "kind", + "multi", + "resolve", + "construct", + "instanceOf", + "predicate", + "represent", + "representName", + "defaultStyle", + "styleAliases" +]; +var YAML_NODE_KINDS = [ + "scalar", + "sequence", + "mapping" +]; +function compileStyleAliases(map4) { + var result = {}; + if (map4 !== null) { + Object.keys(map4).forEach(function(style) { + map4[style].forEach(function(alias) { + result[String(alias)] = style; + }); + }); + } + return result; +} +function Type$1(tag2, options) { + options = options || {}; + Object.keys(options).forEach(function(name315) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name315) === -1) { + throw new exception('Unknown option "' + name315 + '" is met in definition of "' + tag2 + '" YAML type.'); + } + }); + this.options = options; + this.tag = tag2; + this.kind = options["kind"] || null; + this.resolve = options["resolve"] || function() { + return true; + }; + this.construct = options["construct"] || function(data) { + return data; + }; + this.instanceOf = options["instanceOf"] || null; + this.predicate = options["predicate"] || null; + this.represent = options["represent"] || null; + this.representName = options["representName"] || null; + this.defaultStyle = options["defaultStyle"] || null; + this.multi = options["multi"] || false; + this.styleAliases = compileStyleAliases(options["styleAliases"] || null); + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag2 + '" YAML type.'); + } +} +var type = Type$1; +function compileList(schema2, name315) { + var result = []; + schema2[name315].forEach(function(currentType) { + var newIndex = result.length; + result.forEach(function(previousType, previousIndex) { + if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) { + newIndex = previousIndex; + } + }); + result[newIndex] = currentType; + }); + return result; +} +function compileMap() { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {}, + multi: { + scalar: [], + sequence: [], + mapping: [], + fallback: [] + } + }, index2, length; + function collectType(type2) { + if (type2.multi) { + result.multi[type2.kind].push(type2); + result.multi["fallback"].push(type2); + } else { + result[type2.kind][type2.tag] = result["fallback"][type2.tag] = type2; + } + } + for (index2 = 0, length = arguments.length; index2 < length; index2 += 1) { + arguments[index2].forEach(collectType); + } + return result; +} +function Schema$1(definition) { + return this.extend(definition); +} +Schema$1.prototype.extend = function extend3(definition) { + var implicit = []; + var explicit = []; + if (definition instanceof type) { + explicit.push(definition); + } else if (Array.isArray(definition)) { + explicit = explicit.concat(definition); + } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { + if (definition.implicit) implicit = implicit.concat(definition.implicit); + if (definition.explicit) explicit = explicit.concat(definition.explicit); + } else { + throw new exception("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })"); + } + implicit.forEach(function(type$1) { + if (!(type$1 instanceof type)) { + throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object."); + } + if (type$1.loadKind && type$1.loadKind !== "scalar") { + throw new exception("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported."); + } + if (type$1.multi) { + throw new exception("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit."); + } + }); + explicit.forEach(function(type$1) { + if (!(type$1 instanceof type)) { + throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object."); + } + }); + var result = Object.create(Schema$1.prototype); + result.implicit = (this.implicit || []).concat(implicit); + result.explicit = (this.explicit || []).concat(explicit); + result.compiledImplicit = compileList(result, "implicit"); + result.compiledExplicit = compileList(result, "explicit"); + result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); + return result; +}; +var schema = Schema$1; +var str = new type("tag:yaml.org,2002:str", { + kind: "scalar", + construct: function(data) { + return data !== null ? data : ""; + } }); -var ElicitResultSchema = ResultSchema.extend({ - /** - * The user action in response to the elicitation. - * - "accept": User submitted the form/confirmed the action - * - "decline": User explicitly decline the action - * - "cancel": User dismissed without making an explicit choice - */ - action: _enum(["accept", "decline", "cancel"]), - /** - * The submitted form data, only present when action is "accept". - * Contains values matching the requested schema. - * Per MCP spec, content is "typically omitted" for decline/cancel actions. - * We normalize null to undefined for leniency while maintaining type compatibility. - */ - content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional()) +var seq = new type("tag:yaml.org,2002:seq", { + kind: "sequence", + construct: function(data) { + return data !== null ? data : []; + } }); -var ResourceTemplateReferenceSchema = object2({ - type: literal("ref/resource"), - /** - * The URI or URI template of the resource. - */ - uri: string2() +var map = new type("tag:yaml.org,2002:map", { + kind: "mapping", + construct: function(data) { + return data !== null ? data : {}; + } }); -var PromptReferenceSchema = object2({ - type: literal("ref/prompt"), - /** - * The name of the prompt or prompt template - */ - name: string2() +var failsafe = new schema({ + explicit: [ + str, + seq, + map + ] }); -var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ - ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), - /** - * The argument's information - */ - argument: object2({ - /** - * The name of the argument - */ - name: string2(), - /** - * The value of the argument to use for completion matching. - */ - value: string2() - }), - context: object2({ - /** - * Previously-resolved variables in a URI template or prompt. - */ - arguments: record(string2(), string2()).optional() - }).optional() +function resolveYamlNull(data) { + if (data === null) return true; + var max3 = data.length; + return max3 === 1 && data === "~" || max3 === 4 && (data === "null" || data === "Null" || data === "NULL"); +} +function constructYamlNull() { + return null; +} +function isNull(object3) { + return object3 === null; +} +var _null4 = new type("tag:yaml.org,2002:null", { + kind: "scalar", + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function() { + return "~"; + }, + lowercase: function() { + return "null"; + }, + uppercase: function() { + return "NULL"; + }, + camelcase: function() { + return "Null"; + }, + empty: function() { + return ""; + } + }, + defaultStyle: "lowercase" }); -var CompleteRequestSchema = RequestSchema.extend({ - method: literal("completion/complete"), - params: CompleteRequestParamsSchema +function resolveYamlBoolean(data) { + if (data === null) return false; + var max3 = data.length; + return max3 === 4 && (data === "true" || data === "True" || data === "TRUE") || max3 === 5 && (data === "false" || data === "False" || data === "FALSE"); +} +function constructYamlBoolean(data) { + return data === "true" || data === "True" || data === "TRUE"; +} +function isBoolean(object3) { + return Object.prototype.toString.call(object3) === "[object Boolean]"; +} +var bool = new type("tag:yaml.org,2002:bool", { + kind: "scalar", + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function(object3) { + return object3 ? "true" : "false"; + }, + uppercase: function(object3) { + return object3 ? "TRUE" : "FALSE"; + }, + camelcase: function(object3) { + return object3 ? "True" : "False"; + } + }, + defaultStyle: "lowercase" }); -function assertCompleteRequestPrompt(request) { - if (request.params.ref.type !== "ref/prompt") { - throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); +function isHexCode(c) { + return 48 <= c && c <= 57 || 65 <= c && c <= 70 || 97 <= c && c <= 102; +} +function isOctCode(c) { + return 48 <= c && c <= 55; +} +function isDecCode(c) { + return 48 <= c && c <= 57; +} +function resolveYamlInteger(data) { + if (data === null) return false; + var max3 = data.length, index2 = 0, hasDigits = false, ch; + if (!max3) return false; + ch = data[index2]; + if (ch === "-" || ch === "+") { + ch = data[++index2]; } - void request; + if (ch === "0") { + if (index2 + 1 === max3) return true; + ch = data[++index2]; + if (ch === "b") { + index2++; + for (; index2 < max3; index2++) { + ch = data[index2]; + if (ch === "_") continue; + if (ch !== "0" && ch !== "1") return false; + hasDigits = true; + } + return hasDigits && ch !== "_"; + } + if (ch === "x") { + index2++; + for (; index2 < max3; index2++) { + ch = data[index2]; + if (ch === "_") continue; + if (!isHexCode(data.charCodeAt(index2))) return false; + hasDigits = true; + } + return hasDigits && ch !== "_"; + } + if (ch === "o") { + index2++; + for (; index2 < max3; index2++) { + ch = data[index2]; + if (ch === "_") continue; + if (!isOctCode(data.charCodeAt(index2))) return false; + hasDigits = true; + } + return hasDigits && ch !== "_"; + } + } + if (ch === "_") return false; + for (; index2 < max3; index2++) { + ch = data[index2]; + if (ch === "_") continue; + if (!isDecCode(data.charCodeAt(index2))) { + return false; + } + hasDigits = true; + } + if (!hasDigits || ch === "_") return false; + return true; } -function assertCompleteRequestResourceTemplate(request) { - if (request.params.ref.type !== "ref/resource") { - throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); +function constructYamlInteger(data) { + var value = data, sign4 = 1, ch; + if (value.indexOf("_") !== -1) { + value = value.replace(/_/g, ""); } - void request; + ch = value[0]; + if (ch === "-" || ch === "+") { + if (ch === "-") sign4 = -1; + value = value.slice(1); + ch = value[0]; + } + if (value === "0") return 0; + if (ch === "0") { + if (value[1] === "b") return sign4 * parseInt(value.slice(2), 2); + if (value[1] === "x") return sign4 * parseInt(value.slice(2), 16); + if (value[1] === "o") return sign4 * parseInt(value.slice(2), 8); + } + return sign4 * parseInt(value, 10); } -var CompleteResultSchema = ResultSchema.extend({ - completion: looseObject({ - /** - * An array of completion values. Must not exceed 100 items. - */ - values: array(string2()).max(100), - /** - * The total number of completion options available. This can exceed the number of values actually sent in the response. - */ - total: optional(number2().int()), - /** - * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. - */ - hasMore: optional(boolean2()) - }) -}); -var RootSchema = object2({ - /** - * The URI identifying the root. This *must* start with file:// for now. - */ - uri: string2().startsWith("file://"), - /** - * An optional name for the root. - */ - name: string2().optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: record(string2(), unknown()).optional() -}); -var ListRootsRequestSchema = RequestSchema.extend({ - method: literal("roots/list"), - params: BaseRequestParamsSchema.optional() +function isInteger(object3) { + return Object.prototype.toString.call(object3) === "[object Number]" && (object3 % 1 === 0 && !common.isNegativeZero(object3)); +} +var int2 = new type("tag:yaml.org,2002:int", { + kind: "scalar", + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function(obj) { + return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1); + }, + octal: function(obj) { + return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1); + }, + decimal: function(obj) { + return obj.toString(10); + }, + /* eslint-disable max-len */ + hexadecimal: function(obj) { + return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1); + } + }, + defaultStyle: "decimal", + styleAliases: { + binary: [2, "bin"], + octal: [8, "oct"], + decimal: [10, "dec"], + hexadecimal: [16, "hex"] + } }); -var ListRootsResultSchema = ResultSchema.extend({ - roots: array(RootSchema) +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + "^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$" +); +function resolveYamlFloat(data) { + if (data === null) return false; + if (!YAML_FLOAT_PATTERN.test(data) || // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === "_") { + return false; + } + return true; +} +function constructYamlFloat(data) { + var value, sign4; + value = data.replace(/_/g, "").toLowerCase(); + sign4 = value[0] === "-" ? -1 : 1; + if ("+-".indexOf(value[0]) >= 0) { + value = value.slice(1); + } + if (value === ".inf") { + return sign4 === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + } else if (value === ".nan") { + return NaN; + } + return sign4 * parseFloat(value, 10); +} +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; +function representYamlFloat(object3, style) { + var res; + if (isNaN(object3)) { + switch (style) { + case "lowercase": + return ".nan"; + case "uppercase": + return ".NAN"; + case "camelcase": + return ".NaN"; + } + } else if (Number.POSITIVE_INFINITY === object3) { + switch (style) { + case "lowercase": + return ".inf"; + case "uppercase": + return ".INF"; + case "camelcase": + return ".Inf"; + } + } else if (Number.NEGATIVE_INFINITY === object3) { + switch (style) { + case "lowercase": + return "-.inf"; + case "uppercase": + return "-.INF"; + case "camelcase": + return "-.Inf"; + } + } else if (common.isNegativeZero(object3)) { + return "-0.0"; + } + res = object3.toString(10); + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res; +} +function isFloat(object3) { + return Object.prototype.toString.call(object3) === "[object Number]" && (object3 % 1 !== 0 || common.isNegativeZero(object3)); +} +var float = new type("tag:yaml.org,2002:float", { + kind: "scalar", + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: "lowercase" +}); +var json = failsafe.extend({ + implicit: [ + _null4, + bool, + int2, + float + ] +}); +var core = json; +var YAML_DATE_REGEXP = new RegExp( + "^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$" +); +var YAML_TIMESTAMP_REGEXP = new RegExp( + "^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$" +); +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction2 = 0, delta = null, tz_hour, tz_minute, date3; + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + if (match === null) throw new Error("Date resolve error"); + year = +match[1]; + month = +match[2] - 1; + day = +match[3]; + if (!match[4]) { + return new Date(Date.UTC(year, month, day)); + } + hour = +match[4]; + minute = +match[5]; + second = +match[6]; + if (match[7]) { + fraction2 = match[7].slice(0, 3); + while (fraction2.length < 3) { + fraction2 += "0"; + } + fraction2 = +fraction2; + } + if (match[9]) { + tz_hour = +match[10]; + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 6e4; + if (match[9] === "-") delta = -delta; + } + date3 = new Date(Date.UTC(year, month, day, hour, minute, second, fraction2)); + if (delta) date3.setTime(date3.getTime() - delta); + return date3; +} +function representYamlTimestamp(object3) { + return object3.toISOString(); +} +var timestamp = new type("tag:yaml.org,2002:timestamp", { + kind: "scalar", + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp }); -var RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/roots/list_changed"), - params: NotificationsParamsSchema.optional() +function resolveYamlMerge(data) { + return data === "<<" || data === null; +} +var merge2 = new type("tag:yaml.org,2002:merge", { + kind: "scalar", + resolve: resolveYamlMerge }); -var ClientRequestSchema = union([ - PingRequestSchema, - InitializeRequestSchema, - CompleteRequestSchema, - SetLevelRequestSchema, - GetPromptRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema, - CallToolRequestSchema, - ListToolsRequestSchema, - GetTaskRequestSchema, - GetTaskPayloadRequestSchema, - ListTasksRequestSchema, - CancelTaskRequestSchema -]); -var ClientNotificationSchema = union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - InitializedNotificationSchema, - RootsListChangedNotificationSchema, - TaskStatusNotificationSchema -]); -var ClientResultSchema = union([ - EmptyResultSchema, - CreateMessageResultSchema, - CreateMessageResultWithToolsSchema, - ElicitResultSchema, - ListRootsResultSchema, - GetTaskResultSchema, - ListTasksResultSchema, - CreateTaskResultSchema -]); -var ServerRequestSchema = union([ - PingRequestSchema, - CreateMessageRequestSchema, - ElicitRequestSchema, - ListRootsRequestSchema, - GetTaskRequestSchema, - GetTaskPayloadRequestSchema, - ListTasksRequestSchema, - CancelTaskRequestSchema -]); -var ServerNotificationSchema = union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - LoggingMessageNotificationSchema, - ResourceUpdatedNotificationSchema, - ResourceListChangedNotificationSchema, - ToolListChangedNotificationSchema, - PromptListChangedNotificationSchema, - TaskStatusNotificationSchema, - ElicitationCompleteNotificationSchema -]); -var ServerResultSchema = union([ - EmptyResultSchema, - InitializeResultSchema, - CompleteResultSchema, - GetPromptResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ReadResourceResultSchema, - CallToolResultSchema, - ListToolsResultSchema, - GetTaskResultSchema, - ListTasksResultSchema, - CreateTaskResultSchema -]); -var McpError = class _McpError extends Error { - constructor(code, message, data) { - super(`MCP error ${code}: ${message}`); - this.code = code; - this.data = data; - this.name = "McpError"; +var BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r"; +function resolveYamlBinary(data) { + if (data === null) return false; + var code, idx, bitlen = 0, max3 = data.length, map4 = BASE64_MAP; + for (idx = 0; idx < max3; idx++) { + code = map4.indexOf(data.charAt(idx)); + if (code > 64) continue; + if (code < 0) return false; + bitlen += 6; + } + return bitlen % 8 === 0; +} +function constructYamlBinary(data) { + var idx, tailbits, input = data.replace(/[\r\n=]/g, ""), max3 = input.length, map4 = BASE64_MAP, bits = 0, result = []; + for (idx = 0; idx < max3; idx++) { + if (idx % 4 === 0 && idx) { + result.push(bits >> 16 & 255); + result.push(bits >> 8 & 255); + result.push(bits & 255); + } + bits = bits << 6 | map4.indexOf(input.charAt(idx)); + } + tailbits = max3 % 4 * 6; + if (tailbits === 0) { + result.push(bits >> 16 & 255); + result.push(bits >> 8 & 255); + result.push(bits & 255); + } else if (tailbits === 18) { + result.push(bits >> 10 & 255); + result.push(bits >> 2 & 255); + } else if (tailbits === 12) { + result.push(bits >> 4 & 255); + } + return new Uint8Array(result); +} +function representYamlBinary(object3) { + var result = "", bits = 0, idx, tail, max3 = object3.length, map4 = BASE64_MAP; + for (idx = 0; idx < max3; idx++) { + if (idx % 3 === 0 && idx) { + result += map4[bits >> 18 & 63]; + result += map4[bits >> 12 & 63]; + result += map4[bits >> 6 & 63]; + result += map4[bits & 63]; + } + bits = (bits << 8) + object3[idx]; + } + tail = max3 % 3; + if (tail === 0) { + result += map4[bits >> 18 & 63]; + result += map4[bits >> 12 & 63]; + result += map4[bits >> 6 & 63]; + result += map4[bits & 63]; + } else if (tail === 2) { + result += map4[bits >> 10 & 63]; + result += map4[bits >> 4 & 63]; + result += map4[bits << 2 & 63]; + result += map4[64]; + } else if (tail === 1) { + result += map4[bits >> 2 & 63]; + result += map4[bits << 4 & 63]; + result += map4[64]; + result += map4[64]; } - /** - * Factory method to create the appropriate error type based on the error code and data - */ - static fromError(code, message, data) { - if (code === ErrorCode.UrlElicitationRequired && data) { - const errorData = data; - if (errorData.elicitations) { - return new UrlElicitationRequiredError(errorData.elicitations, message); + return result; +} +function isBinary(obj) { + return Object.prototype.toString.call(obj) === "[object Uint8Array]"; +} +var binary = new type("tag:yaml.org,2002:binary", { + kind: "scalar", + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); +var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; +var _toString$2 = Object.prototype.toString; +function resolveYamlOmap(data) { + if (data === null) return true; + var objectKeys = [], index2, length, pair, pairKey, pairHasKey, object3 = data; + for (index2 = 0, length = object3.length; index2 < length; index2 += 1) { + pair = object3[index2]; + pairHasKey = false; + if (_toString$2.call(pair) !== "[object Object]") return false; + for (pairKey in pair) { + if (_hasOwnProperty$3.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; } } - return new _McpError(code, message, data); + if (!pairHasKey) return false; + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; } -}; -var UrlElicitationRequiredError = class extends McpError { - constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { - super(ErrorCode.UrlElicitationRequired, message, { - elicitations - }); + return true; +} +function constructYamlOmap(data) { + return data !== null ? data : []; +} +var omap = new type("tag:yaml.org,2002:omap", { + kind: "sequence", + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); +var _toString$1 = Object.prototype.toString; +function resolveYamlPairs(data) { + if (data === null) return true; + var index2, length, pair, keys, result, object3 = data; + result = new Array(object3.length); + for (index2 = 0, length = object3.length; index2 < length; index2 += 1) { + pair = object3[index2]; + if (_toString$1.call(pair) !== "[object Object]") return false; + keys = Object.keys(pair); + if (keys.length !== 1) return false; + result[index2] = [keys[0], pair[keys[0]]]; } - get elicitations() { - return this.data?.elicitations ?? []; + return true; +} +function constructYamlPairs(data) { + if (data === null) return []; + var index2, length, pair, keys, result, object3 = data; + result = new Array(object3.length); + for (index2 = 0, length = object3.length; index2 < length; index2 += 1) { + pair = object3[index2]; + keys = Object.keys(pair); + result[index2] = [keys[0], pair[keys[0]]]; } -}; - -// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js -function isTerminal(status) { - return status === "completed" || status === "failed" || status === "cancelled"; + return result; } - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/Options.js -var ignoreOverride = /* @__PURE__ */ Symbol("Let zodToJsonSchema decide on which parser to use"); -var defaultOptions = { - name: void 0, - $refStrategy: "root", - basePath: ["#"], - effectStrategy: "input", - pipeStrategy: "all", - dateStrategy: "format:date-time", - mapStrategy: "entries", - removeAdditionalStrategy: "passthrough", - allowedAdditionalProperties: true, - rejectedAdditionalProperties: false, - definitionPath: "definitions", - target: "jsonSchema7", - strictUnions: false, - definitions: {}, - errorMessages: false, - markdownDescription: false, - patternStrategy: "escape", - applyRegexFlags: false, - emailStrategy: "format:email", - base64Strategy: "contentEncoding:base64", - nameStrategy: "ref", - openAiAnyTypeName: "OpenAiAnyType" -}; -var getDefaultOptions = (options) => typeof options === "string" ? { - ...defaultOptions, - name: options -} : { - ...defaultOptions, - ...options -}; - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/Refs.js -var getRefs = (options) => { - const _options = getDefaultOptions(options); - const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; - return { - ..._options, - flags: { hasReferencedOpenAiAnyType: false }, - currentPath, - propertyPath: void 0, - seen: new Map(Object.entries(_options.definitions).map(([name315, def]) => [ - def._def, - { - def: def._def, - path: [..._options.basePath, _options.definitionPath, name315], - // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. - jsonSchema: void 0 - } - ])) - }; -}; - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/errorMessages.js -function addErrorMessage(res, key, errorMessage, refs) { - if (!refs?.errorMessages) - return; - if (errorMessage) { - res.errorMessage = { - ...res.errorMessage, - [key]: errorMessage - }; +var pairs = new type("tag:yaml.org,2002:pairs", { + kind: "sequence", + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); +var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; +function resolveYamlSet(data) { + if (data === null) return true; + var key, object3 = data; + for (key in object3) { + if (_hasOwnProperty$2.call(object3, key)) { + if (object3[key] !== null) return false; + } } + return true; } -function setResponseValueAndErrors(res, key, value, errorMessage, refs) { - res[key] = value; - addErrorMessage(res, key, errorMessage, refs); +function constructYamlSet(data) { + return data !== null ? data : {}; } - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js -var getRelativePath = (pathA, pathB) => { - let i2 = 0; - for (; i2 < pathA.length && i2 < pathB.length; i2++) { - if (pathA[i2] !== pathB[i2]) - break; +var set = new type("tag:yaml.org,2002:set", { + kind: "mapping", + resolve: resolveYamlSet, + construct: constructYamlSet +}); +var _default2 = core.extend({ + implicit: [ + timestamp, + merge2 + ], + explicit: [ + binary, + omap, + pairs, + set + ] +}); +var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; +function _class(obj) { + return Object.prototype.toString.call(obj); +} +function is_EOL(c) { + return c === 10 || c === 13; +} +function is_WHITE_SPACE(c) { + return c === 9 || c === 32; +} +function is_WS_OR_EOL(c) { + return c === 9 || c === 32 || c === 10 || c === 13; +} +function is_FLOW_INDICATOR(c) { + return c === 44 || c === 91 || c === 93 || c === 123 || c === 125; +} +function fromHexCode(c) { + var lc; + if (48 <= c && c <= 57) { + return c - 48; } - return [(pathA.length - i2).toString(), ...pathB.slice(i2)].join("/"); -}; - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/any.js -function parseAnyDef(refs) { - if (refs.target !== "openAi") { - return {}; + lc = c | 32; + if (97 <= lc && lc <= 102) { + return lc - 97 + 10; } - const anyDefinitionPath = [ - ...refs.basePath, - refs.definitionPath, - refs.openAiAnyTypeName - ]; - refs.flags.hasReferencedOpenAiAnyType = true; - return { - $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/") - }; + return -1; } - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/array.js -function parseArrayDef(def, refs) { - const res = { - type: "array" - }; - if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) { - res.items = parseDef(def.type._def, { - ...refs, - currentPath: [...refs.currentPath, "items"] - }); +function escapedHexLen(c) { + if (c === 120) { + return 2; } - if (def.minLength) { - setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); + if (c === 117) { + return 4; } - if (def.maxLength) { - setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); + if (c === 85) { + return 8; } - if (def.exactLength) { - setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); - setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); + return 0; +} +function fromDecimalCode(c) { + if (48 <= c && c <= 57) { + return c - 48; } - return res; + return -1; } - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js -function parseBigintDef(def, refs) { - const res = { - type: "integer", - format: "int64" +function simpleEscapeSequence(c) { + return c === 48 ? "\0" : c === 97 ? "\x07" : c === 98 ? "\b" : c === 116 ? " " : c === 9 ? " " : c === 110 ? "\n" : c === 118 ? "\v" : c === 102 ? "\f" : c === 114 ? "\r" : c === 101 ? "\x1B" : c === 32 ? " " : c === 34 ? '"' : c === 47 ? "/" : c === 92 ? "\\" : c === 78 ? "\x85" : c === 95 ? "\xA0" : c === 76 ? "\u2028" : c === 80 ? "\u2029" : ""; +} +function charFromCodepoint(c) { + if (c <= 65535) { + return String.fromCharCode(c); + } + return String.fromCharCode( + (c - 65536 >> 10) + 55296, + (c - 65536 & 1023) + 56320 + ); +} +function setProperty(object3, key, value) { + if (key === "__proto__") { + Object.defineProperty(object3, key, { + configurable: true, + enumerable: true, + writable: true, + value + }); + } else { + object3[key] = value; + } +} +var simpleEscapeCheck = new Array(256); +var simpleEscapeMap = new Array(256); +for (i2 = 0; i2 < 256; i2++) { + simpleEscapeCheck[i2] = simpleEscapeSequence(i2) ? 1 : 0; + simpleEscapeMap[i2] = simpleEscapeSequence(i2); +} +var i2; +function State$1(input, options) { + this.input = input; + this.filename = options["filename"] || null; + this.schema = options["schema"] || _default2; + this.onWarning = options["onWarning"] || null; + this.legacy = options["legacy"] || false; + this.json = options["json"] || false; + this.listener = options["listener"] || null; + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + this.firstTabInLine = -1; + this.documents = []; +} +function generateError(state, message) { + var mark = { + name: state.filename, + buffer: state.input.slice(0, -1), + // omit trailing \0 + position: state.position, + line: state.line, + column: state.position - state.lineStart }; - if (!def.checks) - return res; - for (const check2 of def.checks) { - switch (check2.kind) { - case "min": - if (refs.target === "jsonSchema7") { - if (check2.inclusive) { - setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); - } else { - setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs); - } - } else { - if (!check2.inclusive) { - res.exclusiveMinimum = true; - } - setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); - } - break; - case "max": - if (refs.target === "jsonSchema7") { - if (check2.inclusive) { - setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); - } else { - setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs); - } - } else { - if (!check2.inclusive) { - res.exclusiveMaximum = true; - } - setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); + mark.snippet = snippet(mark); + return new exception(message, mark); +} +function throwError(state, message) { + throw generateError(state, message); +} +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} +var directiveHandlers = { + YAML: function handleYamlDirective(state, name315, args) { + var match, major, minor; + if (state.version !== null) { + throwError(state, "duplication of %YAML directive"); + } + if (args.length !== 1) { + throwError(state, "YAML directive accepts exactly one argument"); + } + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + if (match === null) { + throwError(state, "ill-formed argument of the YAML directive"); + } + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + if (major !== 1) { + throwError(state, "unacceptable YAML version of the document"); + } + state.version = args[0]; + state.checkLineBreaks = minor < 2; + if (minor !== 1 && minor !== 2) { + throwWarning(state, "unsupported YAML version of the document"); + } + }, + TAG: function handleTagDirective(state, name315, args) { + var handle, prefix; + if (args.length !== 2) { + throwError(state, "TAG directive accepts exactly two arguments"); + } + handle = args[0]; + prefix = args[1]; + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, "ill-formed tag handle (first argument) of the TAG directive"); + } + if (_hasOwnProperty$1.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, "ill-formed tag prefix (second argument) of the TAG directive"); + } + try { + prefix = decodeURIComponent(prefix); + } catch (err) { + throwError(state, "tag prefix is malformed: " + prefix); + } + state.tagMap[handle] = prefix; + } +}; +function captureSegment(state, start, end, checkJson) { + var _position, _length2, _character, _result; + if (start < end) { + _result = state.input.slice(start, end); + if (checkJson) { + for (_position = 0, _length2 = _result.length; _position < _length2; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 9 || 32 <= _character && _character <= 1114111)) { + throwError(state, "expected valid JSON character"); } - break; - case "multipleOf": - setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs); - break; + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, "the stream contains non-printable characters"); } + state.result += _result; } - return res; } - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js -function parseBooleanDef() { - return { - type: "boolean" - }; +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index2, quantity; + if (!common.isObject(source)) { + throwError(state, "cannot merge mappings; the provided source object is unacceptable"); + } + sourceKeys = Object.keys(source); + for (index2 = 0, quantity = sourceKeys.length; index2 < quantity; index2 += 1) { + key = sourceKeys[index2]; + if (!_hasOwnProperty$1.call(destination, key)) { + setProperty(destination, key, source[key]); + overridableKeys[key] = true; + } + } } - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js -function parseBrandedDef(_def, refs) { - return parseDef(_def.type._def, refs); +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) { + var index2, quantity; + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + for (index2 = 0, quantity = keyNode.length; index2 < quantity; index2 += 1) { + if (Array.isArray(keyNode[index2])) { + throwError(state, "nested arrays are not supported inside keys"); + } + if (typeof keyNode === "object" && _class(keyNode[index2]) === "[object Object]") { + keyNode[index2] = "[object Object]"; + } + } + } + if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") { + keyNode = "[object Object]"; + } + keyNode = String(keyNode); + if (_result === null) { + _result = {}; + } + if (keyTag === "tag:yaml.org,2002:merge") { + if (Array.isArray(valueNode)) { + for (index2 = 0, quantity = valueNode.length; index2 < quantity; index2 += 1) { + mergeMappings(state, _result, valueNode[index2], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && !_hasOwnProperty$1.call(overridableKeys, keyNode) && _hasOwnProperty$1.call(_result, keyNode)) { + state.line = startLine || state.line; + state.lineStart = startLineStart || state.lineStart; + state.position = startPos || state.position; + throwError(state, "duplicated mapping key"); + } + setProperty(_result, keyNode, valueNode); + delete overridableKeys[keyNode]; + } + return _result; } - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js -var parseCatchDef = (def, refs) => { - return parseDef(def.innerType._def, refs); -}; - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/date.js -function parseDateDef(def, refs, overrideDateStrategy) { - const strategy = overrideDateStrategy ?? refs.dateStrategy; - if (Array.isArray(strategy)) { - return { - anyOf: strategy.map((item, i2) => parseDateDef(def, refs, item)) - }; +function readLineBreak(state) { + var ch; + ch = state.input.charCodeAt(state.position); + if (ch === 10) { + state.position++; + } else if (ch === 13) { + state.position++; + if (state.input.charCodeAt(state.position) === 10) { + state.position++; + } + } else { + throwError(state, "a line break is expected"); } - switch (strategy) { - case "string": - case "format:date-time": - return { - type: "string", - format: "date-time" - }; - case "format:date": - return { - type: "string", - format: "date" - }; - case "integer": - return integerDateParser(def, refs); + state.line += 1; + state.lineStart = state.position; + state.firstTabInLine = -1; +} +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, ch = state.input.charCodeAt(state.position); + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + if (ch === 9 && state.firstTabInLine === -1) { + state.firstTabInLine = state.position; + } + ch = state.input.charCodeAt(++state.position); + } + if (allowComments && ch === 35) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 10 && ch !== 13 && ch !== 0); + } + if (is_EOL(ch)) { + readLineBreak(state); + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + while (ch === 32) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, "deficient indentation"); + } + return lineBreaks; +} +function testDocumentSeparator(state) { + var _position = state.position, ch; + ch = state.input.charCodeAt(_position); + if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) { + _position += 3; + ch = state.input.charCodeAt(_position); + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } } + return false; } -var integerDateParser = (def, refs) => { - const res = { - type: "integer", - format: "unix-time" - }; - if (refs.target === "openApi3") { - return res; +function writeFoldedLines(state, count2) { + if (count2 === 1) { + state.result += " "; + } else if (count2 > 1) { + state.result += common.repeat("\n", count2 - 1); } - for (const check2 of def.checks) { - switch (check2.kind) { - case "min": - setResponseValueAndErrors( - res, - "minimum", - check2.value, - // This is in milliseconds - check2.message, - refs - ); +} +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch; + ch = state.input.charCodeAt(state.position); + if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) { + return false; + } + if (ch === 63 || ch === 45) { + following = state.input.charCodeAt(state.position + 1); + if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + state.kind = "scalar"; + state.result = ""; + captureStart = captureEnd = state.position; + hasPendingContent = false; + while (ch !== 0) { + if (ch === 58) { + following = state.input.charCodeAt(state.position + 1); + if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) { break; - case "max": - setResponseValueAndErrors( - res, - "maximum", - check2.value, - // This is in milliseconds - check2.message, - refs - ); + } + } else if (ch === 35) { + preceding = state.input.charCodeAt(state.position - 1); + if (is_WS_OR_EOL(preceding)) { + break; + } + } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; break; + } + } + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; } + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + ch = state.input.charCodeAt(++state.position); } - return res; -}; - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/default.js -function parseDefaultDef(_def, refs) { - return { - ...parseDef(_def.innerType._def, refs), - default: _def.defaultValue() - }; -} - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js -function parseEffectsDef(_def, refs) { - return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs); -} - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js -function parseEnumDef(def) { - return { - type: "string", - enum: Array.from(def.values) - }; + captureSegment(state, captureStart, captureEnd, false); + if (state.result) { + return true; + } + state.kind = _kind; + state.result = _result; + return false; } - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js -var isJsonSchema7AllOfType = (type2) => { - if ("type" in type2 && type2.type === "string") +function readSingleQuotedScalar(state, nodeIndent) { + var ch, captureStart, captureEnd; + ch = state.input.charCodeAt(state.position); + if (ch !== 39) { return false; - return "allOf" in type2; -}; -function parseIntersectionDef(def, refs) { - const allOf = [ - parseDef(def.left._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", "0"] - }), - parseDef(def.right._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", "1"] - }) - ].filter((x) => !!x); - let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0; - const mergedAllOf = []; - allOf.forEach((schema2) => { - if (isJsonSchema7AllOfType(schema2)) { - mergedAllOf.push(...schema2.allOf); - if (schema2.unevaluatedProperties === void 0) { - unevaluatedProperties = void 0; + } + state.kind = "scalar"; + state.result = ""; + state.position++; + captureStart = captureEnd = state.position; + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 39) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + if (ch === 39) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; } + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, "unexpected end of the document within a single quoted scalar"); } else { - let nestedSchema = schema2; - if ("additionalProperties" in schema2 && schema2.additionalProperties === false) { - const { additionalProperties, ...rest } = schema2; - nestedSchema = rest; + state.position++; + captureEnd = state.position; + } + } + throwError(state, "unexpected end of the stream within a single quoted scalar"); +} +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, captureEnd, hexLength, hexResult, tmp, ch; + ch = state.input.charCodeAt(state.position); + if (ch !== 34) { + return false; + } + state.kind = "scalar"; + state.result = ""; + state.position++; + captureStart = captureEnd = state.position; + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 34) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + } else if (ch === 92) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + } else { + throwError(state, "expected hexadecimal character"); + } + } + state.result += charFromCodepoint(hexResult); + state.position++; } else { - unevaluatedProperties = void 0; + throwError(state, "unknown escape sequence"); } - mergedAllOf.push(nestedSchema); + captureStart = captureEnd = state.position; + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, "unexpected end of the document within a double quoted scalar"); + } else { + state.position++; + captureEnd = state.position; } - }); - return mergedAllOf.length ? { - allOf: mergedAllOf, - ...unevaluatedProperties - } : void 0; + } + throwError(state, "unexpected end of the stream within a double quoted scalar"); } - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js -function parseLiteralDef(def, refs) { - const parsedType2 = typeof def.value; - if (parsedType2 !== "bigint" && parsedType2 !== "number" && parsedType2 !== "boolean" && parsedType2 !== "string") { - return { - type: Array.isArray(def.value) ? "array" : "object" - }; +function readFlowCollection(state, nodeIndent) { + var readNext = true, _line, _lineStart, _pos, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = /* @__PURE__ */ Object.create(null), keyNode, keyTag, valueNode, ch; + ch = state.input.charCodeAt(state.position); + if (ch === 91) { + terminator = 93; + isMapping = false; + _result = []; + } else if (ch === 123) { + terminator = 125; + isMapping = true; + _result = {}; + } else { + return false; } - if (refs.target === "openApi3") { - return { - type: parsedType2 === "bigint" ? "integer" : parsedType2, - enum: [def.value] - }; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; } - return { - type: parsedType2 === "bigint" ? "integer" : parsedType2, - const: def.value - }; -} - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/string.js -var emojiRegex2 = void 0; -var zodPatterns = { - /** - * `c` was changed to `[cC]` to replicate /i flag - */ - cuid: /^[cC][^\s-]{8,}$/, - cuid2: /^[0-9a-z]+$/, - ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, - /** - * `a-z` was added to replicate /i flag - */ - email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, - /** - * Constructed a valid Unicode RegExp - * - * Lazily instantiate since this type of regex isn't supported - * in all envs (e.g. React Native). - * - * See: - * https://github.com/colinhacks/zod/issues/2433 - * Fix in Zod: - * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b - */ - emoji: () => { - if (emojiRegex2 === void 0) { - emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); + ch = state.input.charCodeAt(++state.position); + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + ch = state.input.charCodeAt(state.position); + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? "mapping" : "sequence"; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, "missed comma between flow collection entries"); + } else if (ch === 44) { + throwError(state, "expected the node content, but found ','"); } - return emojiRegex2; - }, - /** - * Unused - */ - uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, - /** - * Unused - */ - 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])$/, - ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, - /** - * Unused - */ - ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, - ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, - base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, - base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, - nanoid: /^[a-zA-Z0-9_-]{21}$/, - jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ -}; -function parseStringDef(def, refs) { - const res = { - type: "string" - }; - if (def.checks) { - for (const check2 of def.checks) { - switch (check2.kind) { - case "min": - setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs); - break; - case "max": - setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs); - break; - case "email": - switch (refs.emailStrategy) { - case "format:email": - addFormat(res, "email", check2.message, refs); - break; - case "format:idn-email": - addFormat(res, "idn-email", check2.message, refs); - break; - case "pattern:zod": - addPattern(res, zodPatterns.email, check2.message, refs); - break; - } - break; - case "url": - addFormat(res, "uri", check2.message, refs); - break; - case "uuid": - addFormat(res, "uuid", check2.message, refs); - break; - case "regex": - addPattern(res, check2.regex, check2.message, refs); - break; - case "cuid": - addPattern(res, zodPatterns.cuid, check2.message, refs); - break; - case "cuid2": - addPattern(res, zodPatterns.cuid2, check2.message, refs); - break; - case "startsWith": - addPattern(res, RegExp(`^${escapeLiteralCheckValue(check2.value, refs)}`), check2.message, refs); - break; - case "endsWith": - addPattern(res, RegExp(`${escapeLiteralCheckValue(check2.value, refs)}$`), check2.message, refs); - break; - case "datetime": - addFormat(res, "date-time", check2.message, refs); - break; - case "date": - addFormat(res, "date", check2.message, refs); - break; - case "time": - addFormat(res, "time", check2.message, refs); - break; - case "duration": - addFormat(res, "duration", check2.message, refs); - break; - case "length": - setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check2.value) : check2.value, check2.message, refs); - setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check2.value) : check2.value, check2.message, refs); - break; - case "includes": { - addPattern(res, RegExp(escapeLiteralCheckValue(check2.value, refs)), check2.message, refs); - break; - } - case "ip": { - if (check2.version !== "v6") { - addFormat(res, "ipv4", check2.message, refs); - } - if (check2.version !== "v4") { - addFormat(res, "ipv6", check2.message, refs); - } - break; - } - case "base64url": - addPattern(res, zodPatterns.base64url, check2.message, refs); - break; - case "jwt": - addPattern(res, zodPatterns.jwt, check2.message, refs); - break; - case "cidr": { - if (check2.version !== "v6") { - addPattern(res, zodPatterns.ipv4Cidr, check2.message, refs); - } - if (check2.version !== "v4") { - addPattern(res, zodPatterns.ipv6Cidr, check2.message, refs); - } - break; - } - case "emoji": - addPattern(res, zodPatterns.emoji(), check2.message, refs); - break; - case "ulid": { - addPattern(res, zodPatterns.ulid, check2.message, refs); - break; - } - case "base64": { - switch (refs.base64Strategy) { - case "format:binary": { - addFormat(res, "binary", check2.message, refs); - break; - } - case "contentEncoding:base64": { - setResponseValueAndErrors(res, "contentEncoding", "base64", check2.message, refs); - break; - } - case "pattern:zod": { - addPattern(res, zodPatterns.base64, check2.message, refs); - break; - } - } - break; - } - case "nanoid": { - addPattern(res, zodPatterns.nanoid, check2.message, refs); - } - case "toLowerCase": - case "toUpperCase": - case "trim": - break; - default: - /* @__PURE__ */ ((_) => { - })(check2); + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + if (ch === 63) { + following = state.input.charCodeAt(state.position + 1); + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + _line = state.line; + _lineStart = state.lineStart; + _pos = state.position; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + ch = state.input.charCodeAt(state.position); + if ((isExplicitPair || state.line === _line) && ch === 58) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); + } else { + _result.push(keyNode); + } + skipSeparationSpace(state, true, nodeIndent); + ch = state.input.charCodeAt(state.position); + if (ch === 44) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + throwError(state, "unexpected end of the stream within a flow collection"); +} +function readBlockScalar(state, nodeIndent) { + var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch; + ch = state.input.charCodeAt(state.position); + if (ch === 124) { + folding = false; + } else if (ch === 62) { + folding = true; + } else { + return false; + } + state.kind = "scalar"; + state.result = ""; + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + if (ch === 43 || ch === 45) { + if (CHOMPING_CLIP === chomping) { + chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, "repeat of a chomping mode identifier"); + } + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one"); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, "repeat of an indentation width identifier"); } + } else { + break; } } - return res; -} -function escapeLiteralCheckValue(literal2, refs) { - return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal2) : literal2; -} -var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); -function escapeNonAlphaNumeric(source) { - let result = ""; - for (let i2 = 0; i2 < source.length; i2++) { - if (!ALPHA_NUMERIC.has(source[i2])) { - result += "\\"; + if (is_WHITE_SPACE(ch)) { + do { + ch = state.input.charCodeAt(++state.position); + } while (is_WHITE_SPACE(ch)); + if (ch === 35) { + do { + ch = state.input.charCodeAt(++state.position); + } while (!is_EOL(ch) && ch !== 0); } - result += source[i2]; } - return result; -} -function addFormat(schema2, value, message, refs) { - if (schema2.format || schema2.anyOf?.some((x) => x.format)) { - if (!schema2.anyOf) { - schema2.anyOf = []; + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + ch = state.input.charCodeAt(state.position); + while ((!detectedIndent || state.lineIndent < textIndent) && ch === 32) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); } - if (schema2.format) { - schema2.anyOf.push({ - format: schema2.format, - ...schema2.errorMessage && refs.errorMessages && { - errorMessage: { format: schema2.errorMessage.format } - } - }); - delete schema2.format; - if (schema2.errorMessage) { - delete schema2.errorMessage.format; - if (Object.keys(schema2.errorMessage).length === 0) { - delete schema2.errorMessage; - } - } + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; } - schema2.anyOf.push({ - format: value, - ...message && refs.errorMessages && { errorMessage: { format: message } } - }); - } else { - setResponseValueAndErrors(schema2, "format", value, message, refs); - } -} -function addPattern(schema2, regex, message, refs) { - if (schema2.pattern || schema2.allOf?.some((x) => x.pattern)) { - if (!schema2.allOf) { - schema2.allOf = []; + if (is_EOL(ch)) { + emptyLines++; + continue; } - if (schema2.pattern) { - schema2.allOf.push({ - pattern: schema2.pattern, - ...schema2.errorMessage && refs.errorMessages && { - errorMessage: { pattern: schema2.errorMessage.pattern } + if (state.lineIndent < textIndent) { + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { + state.result += "\n"; } - }); - delete schema2.pattern; - if (schema2.errorMessage) { - delete schema2.errorMessage.pattern; - if (Object.keys(schema2.errorMessage).length === 0) { - delete schema2.errorMessage; + } + break; + } + if (folding) { + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat("\n", emptyLines + 1); + } else if (emptyLines === 0) { + if (didReadContent) { + state.result += " "; } + } else { + state.result += common.repeat("\n", emptyLines); } + } else { + state.result += common.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines); } - schema2.allOf.push({ - pattern: stringifyRegExpWithFlags(regex, refs), - ...message && refs.errorMessages && { errorMessage: { pattern: message } } - }); - } else { - setResponseValueAndErrors(schema2, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + while (!is_EOL(ch) && ch !== 0) { + ch = state.input.charCodeAt(++state.position); + } + captureSegment(state, captureStart, state.position, false); } + return true; } -function stringifyRegExpWithFlags(regex, refs) { - if (!refs.applyRegexFlags || !regex.flags) { - return regex.source; +function readBlockSequence(state, nodeIndent) { + var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch; + if (state.firstTabInLine !== -1) return false; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; } - const flags = { - i: regex.flags.includes("i"), - m: regex.flags.includes("m"), - s: regex.flags.includes("s") - // `.` matches newlines - }; - const source = flags.i ? regex.source.toLowerCase() : regex.source; - let pattern = ""; - let isEscaped = false; - let inCharGroup = false; - let inCharRange = false; - for (let i2 = 0; i2 < source.length; i2++) { - if (isEscaped) { - pattern += source[i2]; - isEscaped = false; - continue; + ch = state.input.charCodeAt(state.position); + while (ch !== 0) { + if (state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, "tab characters must not be used in indentation"); } - if (flags.i) { - if (inCharGroup) { - if (source[i2].match(/[a-z]/)) { - if (inCharRange) { - pattern += source[i2]; - pattern += `${source[i2 - 2]}-${source[i2]}`.toUpperCase(); - inCharRange = false; - } else if (source[i2 + 1] === "-" && source[i2 + 2]?.match(/[a-z]/)) { - pattern += source[i2]; - inCharRange = true; - } else { - pattern += `${source[i2]}${source[i2].toUpperCase()}`; - } - continue; - } - } else if (source[i2].match(/[a-z]/)) { - pattern += `[${source[i2]}${source[i2].toUpperCase()}]`; - continue; - } + if (ch !== 45) { + break; } - if (flags.m) { - if (source[i2] === "^") { - pattern += `(^|(?<=[\r -]))`; - continue; - } else if (source[i2] === "$") { - pattern += `($|(?=[\r -]))`; + following = state.input.charCodeAt(state.position + 1); + if (!is_WS_OR_EOL(following)) { + break; + } + detected = true; + state.position++; + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); continue; } } - if (flags.s && source[i2] === ".") { - pattern += inCharGroup ? `${source[i2]}\r -` : `[${source[i2]}\r -]`; - continue; - } - pattern += source[i2]; - if (source[i2] === "\\") { - isEscaped = true; - } else if (inCharGroup && source[i2] === "]") { - inCharGroup = false; - } else if (!inCharGroup && source[i2] === "[") { - inCharGroup = true; + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) { + throwError(state, "bad indentation of a sequence entry"); + } else if (state.lineIndent < nodeIndent) { + break; } } - try { - new RegExp(pattern); - } catch { - console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); - return regex.source; - } - return pattern; -} - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/record.js -function parseRecordDef(def, refs) { - if (refs.target === "openAi") { - console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); - } - if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { - return { - type: "object", - required: def.keyType._def.values, - properties: def.keyType._def.values.reduce((acc, key) => ({ - ...acc, - [key]: parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "properties", key] - }) ?? parseAnyDef(refs) - }), {}), - additionalProperties: refs.rejectedAdditionalProperties - }; - } - const schema2 = { - type: "object", - additionalProperties: parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalProperties"] - }) ?? refs.allowedAdditionalProperties - }; - if (refs.target === "openApi3") { - return schema2; - } - if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { - const { type: type2, ...keyType } = parseStringDef(def.keyType._def, refs); - return { - ...schema2, - propertyNames: keyType - }; - } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { - return { - ...schema2, - propertyNames: { - enum: def.keyType._def.values - } - }; - } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) { - const { type: type2, ...keyType } = parseBrandedDef(def.keyType._def, refs); - return { - ...schema2, - propertyNames: keyType - }; + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = "sequence"; + state.result = _result; + return true; } - return schema2; + return false; } - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/map.js -function parseMapDef(def, refs) { - if (refs.mapStrategy === "record") { - return parseRecordDef(def, refs); +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, allowCompact, _line, _keyLine, _keyLineStart, _keyPos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = /* @__PURE__ */ Object.create(null), keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch; + if (state.firstTabInLine !== -1) return false; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; } - const keys = parseDef(def.keyType._def, { - ...refs, - currentPath: [...refs.currentPath, "items", "items", "0"] - }) || parseAnyDef(refs); - const values = parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "items", "items", "1"] - }) || parseAnyDef(refs); - return { - type: "array", - maxItems: 125, - items: { - type: "array", - items: [keys, values], - minItems: 2, - maxItems: 2 + ch = state.input.charCodeAt(state.position); + while (ch !== 0) { + if (!atExplicitKey && state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, "tab characters must not be used in indentation"); } - }; -} - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js -function parseNativeEnumDef(def) { - const object3 = def.values; - const actualKeys = Object.keys(def.values).filter((key) => { - return typeof object3[object3[key]] !== "number"; - }); - const actualValues = actualKeys.map((key) => object3[key]); - const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); - return { - type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], - enum: actualValues - }; -} - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/never.js -function parseNeverDef(refs) { - return refs.target === "openAi" ? void 0 : { - not: parseAnyDef({ - ...refs, - currentPath: [...refs.currentPath, "not"] - }) - }; -} - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/null.js -function parseNullDef(refs) { - return refs.target === "openApi3" ? { - enum: ["null"], - nullable: true - } : { - type: "null" - }; -} - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/union.js -var primitiveMappings = { - ZodString: "string", - ZodNumber: "number", - ZodBigInt: "integer", - ZodBoolean: "boolean", - ZodNull: "null" -}; -function parseUnionDef(def, refs) { - if (refs.target === "openApi3") - return asAnyOf(def, refs); - const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; - if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) { - const types = options.reduce((types2, x) => { - const type2 = primitiveMappings[x._def.typeName]; - return type2 && !types2.includes(type2) ? [...types2, type2] : types2; - }, []); - return { - type: types.length > 1 ? types : types[0] - }; - } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { - const types = options.reduce((acc, x) => { - const type2 = typeof x._def.value; - switch (type2) { - case "string": - case "number": - case "boolean": - return [...acc, type2]; - case "bigint": - return [...acc, "integer"]; - case "object": - if (x._def.value === null) - return [...acc, "null"]; - case "symbol": - case "undefined": - case "function": - default: - return acc; + following = state.input.charCodeAt(state.position + 1); + _line = state.line; + if ((ch === 63 || ch === 58) && is_WS_OR_EOL(following)) { + if (ch === 63) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + detected = true; + atExplicitKey = true; + allowCompact = true; + } else if (atExplicitKey) { + atExplicitKey = false; + allowCompact = true; + } else { + throwError(state, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"); } - }, []); - if (types.length === options.length) { - const uniqueTypes = types.filter((x, i2, a) => a.indexOf(x) === i2); - return { - type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], - enum: options.reduce((acc, x) => { - return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; - }, []) - }; - } - } else if (options.every((x) => x._def.typeName === "ZodEnum")) { - return { - type: "string", - enum: options.reduce((acc, x) => [ - ...acc, - ...x._def.values.filter((x2) => !acc.includes(x2)) - ], []) - }; - } - return asAnyOf(def, refs); -} -var asAnyOf = (def, refs) => { - const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i2) => parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, "anyOf", `${i2}`] - })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)); - return anyOf.length ? { anyOf } : void 0; -}; - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js -function parseNullableDef(def, refs) { - if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { - if (refs.target === "openApi3") { - return { - type: primitiveMappings[def.innerType._def.typeName], - nullable: true - }; - } - return { - type: [ - primitiveMappings[def.innerType._def.typeName], - "null" - ] - }; - } - if (refs.target === "openApi3") { - const base2 = parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath] - }); - if (base2 && "$ref" in base2) - return { allOf: [base2], nullable: true }; - return base2 && { ...base2, nullable: true }; - } - const base = parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath, "anyOf", "0"] - }); - return base && { anyOf: [base, { type: "null" }] }; -} - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/number.js -function parseNumberDef(def, refs) { - const res = { - type: "number" - }; - if (!def.checks) - return res; - for (const check2 of def.checks) { - switch (check2.kind) { - case "int": - res.type = "integer"; - addErrorMessage(res, "type", check2.message, refs); + state.position += 1; + ch = following; + } else { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { break; - case "min": - if (refs.target === "jsonSchema7") { - if (check2.inclusive) { - setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); - } else { - setResponseValueAndErrors(res, "exclusiveMinimum", check2.value, check2.message, refs); + } + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + if (ch === 58) { + ch = state.input.charCodeAt(++state.position); + if (!is_WS_OR_EOL(ch)) { + throwError(state, "a whitespace character is expected after the key-value separator within a block mapping"); + } + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; } + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + } else if (detected) { + throwError(state, "can not read an implicit mapping pair; a colon is missed"); } else { - if (!check2.inclusive) { - res.exclusiveMinimum = true; - } - setResponseValueAndErrors(res, "minimum", check2.value, check2.message, refs); + state.tag = _tag; + state.anchor = _anchor; + return true; } - break; - case "max": - if (refs.target === "jsonSchema7") { - if (check2.inclusive) { - setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); - } else { - setResponseValueAndErrors(res, "exclusiveMaximum", check2.value, check2.message, refs); - } + } else if (detected) { + throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key"); + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; + } + } + if (state.line === _line || state.lineIndent > nodeIndent) { + if (atExplicitKey) { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + } + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; } else { - if (!check2.inclusive) { - res.exclusiveMaximum = true; - } - setResponseValueAndErrors(res, "maximum", check2.value, check2.message, refs); + valueNode = state.result; } - break; - case "multipleOf": - setResponseValueAndErrors(res, "multipleOf", check2.value, check2.message, refs); - break; + } + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) { + throwError(state, "bad indentation of a mapping entry"); + } else if (state.lineIndent < nodeIndent) { + break; } } - return res; + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + } + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = "mapping"; + state.result = _result; + } + return detected; } - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/object.js -function parseObjectDef(def, refs) { - const forceOptionalIntoNullable = refs.target === "openAi"; - const result = { - type: "object", - properties: {} - }; - const required2 = []; - const shape = def.shape(); - for (const propName in shape) { - let propDef = shape[propName]; - if (propDef === void 0 || propDef._def === void 0) { - continue; +function readTagProperty(state) { + var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch; + ch = state.input.charCodeAt(state.position); + if (ch !== 33) return false; + if (state.tag !== null) { + throwError(state, "duplication of a tag property"); + } + ch = state.input.charCodeAt(++state.position); + if (ch === 60) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + } else if (ch === 33) { + isNamed = true; + tagHandle = "!!"; + ch = state.input.charCodeAt(++state.position); + } else { + tagHandle = "!"; + } + _position = state.position; + if (isVerbatim) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0 && ch !== 62); + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, "unexpected end of the stream within a verbatim tag"); } - let propOptional = safeIsOptional(propDef); - if (propOptional && forceOptionalIntoNullable) { - if (propDef._def.typeName === "ZodOptional") { - propDef = propDef._def.innerType; - } - if (!propDef.isNullable()) { - propDef = propDef.nullable(); + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + if (ch === 33) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, "named tag handle cannot contain such characters"); + } + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, "tag suffix cannot contain exclamation marks"); + } } - propOptional = false; - } - const parsedDef = parseDef(propDef._def, { - ...refs, - currentPath: [...refs.currentPath, "properties", propName], - propertyPath: [...refs.currentPath, "properties", propName] - }); - if (parsedDef === void 0) { - continue; + ch = state.input.charCodeAt(++state.position); } - result.properties[propName] = parsedDef; - if (!propOptional) { - required2.push(propName); + tagName = state.input.slice(_position, state.position); + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, "tag suffix cannot contain flow indicator characters"); } } - if (required2.length) { - result.required = required2; + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, "tag name cannot contain such characters: " + tagName); } - const additionalProperties = decideAdditionalProperties(def, refs); - if (additionalProperties !== void 0) { - result.additionalProperties = additionalProperties; + try { + tagName = decodeURIComponent(tagName); + } catch (err) { + throwError(state, "tag name is malformed: " + tagName); } - return result; + if (isVerbatim) { + state.tag = tagName; + } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + } else if (tagHandle === "!") { + state.tag = "!" + tagName; + } else if (tagHandle === "!!") { + state.tag = "tag:yaml.org,2002:" + tagName; + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + return true; } -function decideAdditionalProperties(def, refs) { - if (def.catchall._def.typeName !== "ZodNever") { - return parseDef(def.catchall._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalProperties"] - }); +function readAnchorProperty(state) { + var _position, ch; + ch = state.input.charCodeAt(state.position); + if (ch !== 38) return false; + if (state.anchor !== null) { + throwError(state, "duplication of an anchor property"); } - switch (def.unknownKeys) { - case "passthrough": - return refs.allowedAdditionalProperties; - case "strict": - return refs.rejectedAdditionalProperties; - case "strip": - return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); } -} -function safeIsOptional(schema2) { - try { - return schema2.isOptional(); - } catch { - return true; + if (state.position === _position) { + throwError(state, "name of an anchor node must contain at least one character"); } + state.anchor = state.input.slice(_position, state.position); + return true; } - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js -var parseOptionalDef = (def, refs) => { - if (refs.currentPath.toString() === refs.propertyPath?.toString()) { - return parseDef(def.innerType._def, refs); +function readAlias(state) { + var _position, alias, ch; + ch = state.input.charCodeAt(state.position); + if (ch !== 42) return false; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); } - const innerSchema = parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath, "anyOf", "1"] - }); - return innerSchema ? { - anyOf: [ - { - not: parseAnyDef(refs) - }, - innerSchema - ] - } : parseAnyDef(refs); -}; - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js -var parsePipelineDef = (def, refs) => { - if (refs.pipeStrategy === "input") { - return parseDef(def.in._def, refs); - } else if (refs.pipeStrategy === "output") { - return parseDef(def.out._def, refs); + if (state.position === _position) { + throwError(state, "name of an alias node must contain at least one character"); } - const a = parseDef(def.in._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", "0"] - }); - const b = parseDef(def.out._def, { - ...refs, - currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"] - }); - return { - allOf: [a, b].filter((x) => x !== void 0) - }; -}; - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js -function parsePromiseDef(def, refs) { - return parseDef(def.type._def, refs); + alias = state.input.slice(_position, state.position); + if (!_hasOwnProperty$1.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; } - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/set.js -function parseSetDef(def, refs) { - const items = parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "items"] - }); - const schema2 = { - type: "array", - uniqueItems: true, - items - }; - if (def.minSize) { - setResponseValueAndErrors(schema2, "minItems", def.minSize.value, def.minSize.message, refs); +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, typeIndex, typeQuantity, typeList, type2, flowIndent, blockIndent; + if (state.listener !== null) { + state.listener("open", state); } - if (def.maxSize) { - setResponseValueAndErrors(schema2, "maxItems", def.maxSize.value, def.maxSize.message, refs); + state.tag = null; + state.anchor = null; + state.kind = null; + state.result = null; + allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext; + if (allowToSeek) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } } - return schema2; -} - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js -function parseTupleDef(def, refs) { - if (def.rest) { - return { - type: "array", - minItems: def.items.length, - items: def.items.map((x, i2) => parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, "items", `${i2}`] - })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []), - additionalItems: parseDef(def.rest._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalItems"] - }) - }; - } else { - return { - type: "array", - minItems: def.items.length, - maxItems: def.items.length, - items: def.items.map((x, i2) => parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, "items", `${i2}`] - })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []) - }; + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } } -} - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js -function parseUndefinedDef(refs) { - return { - not: parseAnyDef(refs) - }; -} - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js -function parseUnknownDef(refs) { - return parseAnyDef(refs); -} - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js -var parseReadonlyDef = (def, refs) => { - return parseDef(def.innerType._def, refs); -}; - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/selectParser.js -var selectParser = (def, typeName, refs) => { - switch (typeName) { - case ZodFirstPartyTypeKind.ZodString: - return parseStringDef(def, refs); - case ZodFirstPartyTypeKind.ZodNumber: - return parseNumberDef(def, refs); - case ZodFirstPartyTypeKind.ZodObject: - return parseObjectDef(def, refs); - case ZodFirstPartyTypeKind.ZodBigInt: - return parseBigintDef(def, refs); - case ZodFirstPartyTypeKind.ZodBoolean: - return parseBooleanDef(); - case ZodFirstPartyTypeKind.ZodDate: - return parseDateDef(def, refs); - case ZodFirstPartyTypeKind.ZodUndefined: - return parseUndefinedDef(refs); - case ZodFirstPartyTypeKind.ZodNull: - return parseNullDef(refs); - case ZodFirstPartyTypeKind.ZodArray: - return parseArrayDef(def, refs); - case ZodFirstPartyTypeKind.ZodUnion: - case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: - return parseUnionDef(def, refs); - case ZodFirstPartyTypeKind.ZodIntersection: - return parseIntersectionDef(def, refs); - case ZodFirstPartyTypeKind.ZodTuple: - return parseTupleDef(def, refs); - case ZodFirstPartyTypeKind.ZodRecord: - return parseRecordDef(def, refs); - case ZodFirstPartyTypeKind.ZodLiteral: - return parseLiteralDef(def, refs); - case ZodFirstPartyTypeKind.ZodEnum: - return parseEnumDef(def); - case ZodFirstPartyTypeKind.ZodNativeEnum: - return parseNativeEnumDef(def); - case ZodFirstPartyTypeKind.ZodNullable: - return parseNullableDef(def, refs); - case ZodFirstPartyTypeKind.ZodOptional: - return parseOptionalDef(def, refs); - case ZodFirstPartyTypeKind.ZodMap: - return parseMapDef(def, refs); - case ZodFirstPartyTypeKind.ZodSet: - return parseSetDef(def, refs); - case ZodFirstPartyTypeKind.ZodLazy: - return () => def.getter()._def; - case ZodFirstPartyTypeKind.ZodPromise: - return parsePromiseDef(def, refs); - case ZodFirstPartyTypeKind.ZodNaN: - case ZodFirstPartyTypeKind.ZodNever: - return parseNeverDef(refs); - case ZodFirstPartyTypeKind.ZodEffects: - return parseEffectsDef(def, refs); - case ZodFirstPartyTypeKind.ZodAny: - return parseAnyDef(refs); - case ZodFirstPartyTypeKind.ZodUnknown: - return parseUnknownDef(refs); - case ZodFirstPartyTypeKind.ZodDefault: - return parseDefaultDef(def, refs); - case ZodFirstPartyTypeKind.ZodBranded: - return parseBrandedDef(def, refs); - case ZodFirstPartyTypeKind.ZodReadonly: - return parseReadonlyDef(def, refs); - case ZodFirstPartyTypeKind.ZodCatch: - return parseCatchDef(def, refs); - case ZodFirstPartyTypeKind.ZodPipeline: - return parsePipelineDef(def, refs); - case ZodFirstPartyTypeKind.ZodFunction: - case ZodFirstPartyTypeKind.ZodVoid: - case ZodFirstPartyTypeKind.ZodSymbol: - return void 0; - default: - return /* @__PURE__ */ ((_) => void 0)(typeName); + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; } -}; - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/parseDef.js -function parseDef(def, refs, forceResolution = false) { - const seenItem = refs.seen.get(def); - if (refs.override) { - const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); - if (overrideResult !== ignoreOverride) { - return overrideResult; + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + blockIndent = state.position - state.lineStart; + if (indentStatus === 1) { + if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + } else if (readAlias(state)) { + hasContent = true; + if (state.tag !== null || state.anchor !== null) { + throwError(state, "alias node should not have any properties"); + } + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + if (state.tag === null) { + state.tag = "?"; + } + } + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); } } - if (seenItem && !forceResolution) { - const seenSchema = get$ref(seenItem, refs); - if (seenSchema !== void 0) { - return seenSchema; + if (state.tag === null) { + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } else if (state.tag === "?") { + if (state.result !== null && state.kind !== "scalar") { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type2 = state.implicitTypes[typeIndex]; + if (type2.resolve(state.result)) { + state.result = type2.construct(state.result); + state.tag = type2.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (state.tag !== "!") { + if (_hasOwnProperty$1.call(state.typeMap[state.kind || "fallback"], state.tag)) { + type2 = state.typeMap[state.kind || "fallback"][state.tag]; + } else { + type2 = null; + typeList = state.typeMap.multi[state.kind || "fallback"]; + for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { + if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { + type2 = typeList[typeIndex]; + break; + } + } + } + if (!type2) { + throwError(state, "unknown tag !<" + state.tag + ">"); + } + if (state.result !== null && type2.kind !== state.kind) { + throwError(state, "unacceptable node kind for !<" + state.tag + '> tag; it should be "' + type2.kind + '", not "' + state.kind + '"'); + } + if (!type2.resolve(state.result, state.tag)) { + throwError(state, "cannot resolve a node with !<" + state.tag + "> explicit tag"); + } else { + state.result = type2.construct(state.result, state.tag); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } } } - const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; - refs.seen.set(def, newItem); - const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); - const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; - if (jsonSchema) { - addMeta(def, refs, jsonSchema); - } - if (refs.postProcess) { - const postProcessResult = refs.postProcess(jsonSchema, def, refs); - newItem.jsonSchema = jsonSchema; - return postProcessResult; + if (state.listener !== null) { + state.listener("close", state); } - newItem.jsonSchema = jsonSchema; - return jsonSchema; + return state.tag !== null || state.anchor !== null || hasContent; } -var get$ref = (item, refs) => { - switch (refs.$refStrategy) { - case "root": - return { $ref: item.path.join("/") }; - case "relative": - return { $ref: getRelativePath(refs.currentPath, item.path) }; - case "none": - case "seen": { - if (item.path.length < refs.currentPath.length && item.path.every((value, index2) => refs.currentPath[index2] === value)) { - console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); - return parseAnyDef(refs); +function readDocument(state) { + var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch; + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = /* @__PURE__ */ Object.create(null); + state.anchorMap = /* @__PURE__ */ Object.create(null); + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + if (state.lineIndent > 0 || ch !== 37) { + break; + } + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + if (directiveName.length < 1) { + throwError(state, "directive name must not be less than one character in length"); + } + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); } - return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0; + if (ch === 35) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0 && !is_EOL(ch)); + break; + } + if (is_EOL(ch)) break; + _position = state.position; + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + directiveArgs.push(state.input.slice(_position, state.position)); + } + if (ch !== 0) readLineBreak(state); + if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); } } -}; -var addMeta = (def, refs, jsonSchema) => { - if (def.description) { - jsonSchema.description = def.description; - if (refs.markdownDescription) { - jsonSchema.markdownDescription = def.description; + skipSeparationSpace(state, true, -1); + if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } else if (hasDirectives) { + throwError(state, "directives end mark is expected"); + } + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, "non-ASCII line breaks are interpreted as content"); + } + state.documents.push(state.result); + if (state.position === state.lineStart && testDocumentSeparator(state)) { + if (state.input.charCodeAt(state.position) === 46) { + state.position += 3; + skipSeparationSpace(state, true, -1); } + return; } - return jsonSchema; -}; - -// node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@3.25.76/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js -var zodToJsonSchema = (schema2, options) => { - const refs = getRefs(options); - let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name316, schema3]) => ({ - ...acc, - [name316]: parseDef(schema3._def, { - ...refs, - currentPath: [...refs.basePath, refs.definitionPath, name316] - }, true) ?? parseAnyDef(refs) - }), {}) : void 0; - const name315 = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name; - const main4 = parseDef(schema2._def, name315 === void 0 ? refs : { - ...refs, - currentPath: [...refs.basePath, refs.definitionPath, name315] - }, false) ?? parseAnyDef(refs); - const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; - if (title !== void 0) { - main4.title = title; + if (state.position < state.length - 1) { + throwError(state, "end of the stream or a document separator is expected"); + } else { + return; } - if (refs.flags.hasReferencedOpenAiAnyType) { - if (!definitions) { - definitions = {}; +} +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + if (input.length !== 0) { + if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) { + input += "\n"; } - if (!definitions[refs.openAiAnyTypeName]) { - definitions[refs.openAiAnyTypeName] = { - // Skipping "object" as no properties can be defined and additionalProperties must be "false" - type: ["string", "number", "integer", "boolean", "array", "null"], - items: { - $ref: refs.$refStrategy === "relative" ? "1" : [ - ...refs.basePath, - refs.definitionPath, - refs.openAiAnyTypeName - ].join("/") - } - }; + if (input.charCodeAt(0) === 65279) { + input = input.slice(1); } } - const combined = name315 === void 0 ? definitions ? { - ...main4, - [refs.definitionPath]: definitions - } : main4 : { - $ref: [ - ...refs.$refStrategy === "relative" ? [] : refs.basePath, - refs.definitionPath, - name315 - ].join("/"), - [refs.definitionPath]: { - ...definitions, - [name315]: main4 - } - }; - if (refs.target === "jsonSchema7") { - combined.$schema = "http://json-schema.org/draft-07/schema#"; - } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { - combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; + var state = new State$1(input, options); + var nullpos = input.indexOf("\0"); + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, "null byte is not allowed in input"); } - if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) { - console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); + state.input += "\0"; + while (state.input.charCodeAt(state.position) === 32) { + state.lineIndent += 1; + state.position += 1; } - return combined; + while (state.position < state.length - 1) { + readDocument(state); + } + return state.documents; +} +function loadAll$1(input, iterator, options) { + if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") { + options = iterator; + iterator = null; + } + var documents = loadDocuments(input, options); + if (typeof iterator !== "function") { + return documents; + } + for (var index2 = 0, length = documents.length; index2 < length; index2 += 1) { + iterator(documents[index2]); + } +} +function load$1(input, options) { + var documents = loadDocuments(input, options); + if (documents.length === 0) { + return void 0; + } else if (documents.length === 1) { + return documents[0]; + } + throw new exception("expected a single document in the stream, but found more"); +} +var loadAll_1 = loadAll$1; +var load_1 = load$1; +var loader = { + loadAll: loadAll_1, + load: load_1 }; - -// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js -function mapMiniTarget(t) { - if (!t) - return "draft-7"; - if (t === "jsonSchema7" || t === "draft-7") - return "draft-7"; - if (t === "jsonSchema2019-09" || t === "draft-2020-12") - return "draft-2020-12"; - return "draft-7"; +var _toString = Object.prototype.toString; +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var CHAR_BOM = 65279; +var CHAR_TAB = 9; +var CHAR_LINE_FEED = 10; +var CHAR_CARRIAGE_RETURN = 13; +var CHAR_SPACE = 32; +var CHAR_EXCLAMATION = 33; +var CHAR_DOUBLE_QUOTE = 34; +var CHAR_SHARP = 35; +var CHAR_PERCENT = 37; +var CHAR_AMPERSAND = 38; +var CHAR_SINGLE_QUOTE = 39; +var CHAR_ASTERISK = 42; +var CHAR_COMMA = 44; +var CHAR_MINUS = 45; +var CHAR_COLON = 58; +var CHAR_EQUALS = 61; +var CHAR_GREATER_THAN = 62; +var CHAR_QUESTION = 63; +var CHAR_COMMERCIAL_AT = 64; +var CHAR_LEFT_SQUARE_BRACKET = 91; +var CHAR_RIGHT_SQUARE_BRACKET = 93; +var CHAR_GRAVE_ACCENT = 96; +var CHAR_LEFT_CURLY_BRACKET = 123; +var CHAR_VERTICAL_LINE = 124; +var CHAR_RIGHT_CURLY_BRACKET = 125; +var ESCAPE_SEQUENCES = {}; +ESCAPE_SEQUENCES[0] = "\\0"; +ESCAPE_SEQUENCES[7] = "\\a"; +ESCAPE_SEQUENCES[8] = "\\b"; +ESCAPE_SEQUENCES[9] = "\\t"; +ESCAPE_SEQUENCES[10] = "\\n"; +ESCAPE_SEQUENCES[11] = "\\v"; +ESCAPE_SEQUENCES[12] = "\\f"; +ESCAPE_SEQUENCES[13] = "\\r"; +ESCAPE_SEQUENCES[27] = "\\e"; +ESCAPE_SEQUENCES[34] = '\\"'; +ESCAPE_SEQUENCES[92] = "\\\\"; +ESCAPE_SEQUENCES[133] = "\\N"; +ESCAPE_SEQUENCES[160] = "\\_"; +ESCAPE_SEQUENCES[8232] = "\\L"; +ESCAPE_SEQUENCES[8233] = "\\P"; +var DEPRECATED_BOOLEANS_SYNTAX = [ + "y", + "Y", + "yes", + "Yes", + "YES", + "on", + "On", + "ON", + "n", + "N", + "no", + "No", + "NO", + "off", + "Off", + "OFF" +]; +var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; +function compileStyleMap(schema2, map4) { + var result, keys, index2, length, tag2, style, type2; + if (map4 === null) return {}; + result = {}; + keys = Object.keys(map4); + for (index2 = 0, length = keys.length; index2 < length; index2 += 1) { + tag2 = keys[index2]; + style = String(map4[tag2]); + if (tag2.slice(0, 2) === "!!") { + tag2 = "tag:yaml.org,2002:" + tag2.slice(2); + } + type2 = schema2.compiledTypeMap["fallback"][tag2]; + if (type2 && _hasOwnProperty.call(type2.styleAliases, style)) { + style = type2.styleAliases[style]; + } + result[tag2] = style; + } + return result; } -function toJsonSchemaCompat(schema2, opts) { - if (isZ4Schema(schema2)) { - return toJSONSchema(schema2, { - target: mapMiniTarget(opts?.target), - io: opts?.pipeStrategy ?? "input" - }); +function encodeHex(character) { + var string4, handle, length; + string4 = character.toString(16).toUpperCase(); + if (character <= 255) { + handle = "x"; + length = 2; + } else if (character <= 65535) { + handle = "u"; + length = 4; + } else if (character <= 4294967295) { + handle = "U"; + length = 8; + } else { + throw new exception("code point within a string may not be greater than 0xFFFFFFFF"); } - return zodToJsonSchema(schema2, { - strictUnions: opts?.strictUnions ?? true, - pipeStrategy: opts?.pipeStrategy ?? "input" - }); + return "\\" + handle + common.repeat("0", length - string4.length) + string4; } -function getMethodLiteral(schema2) { - const shape = getObjectShape(schema2); - const methodSchema = shape?.method; - if (!methodSchema) { - throw new Error("Schema is missing a method literal"); +var QUOTING_TYPE_SINGLE = 1; +var QUOTING_TYPE_DOUBLE = 2; +function State(options) { + this.schema = options["schema"] || _default2; + this.indent = Math.max(1, options["indent"] || 2); + this.noArrayIndent = options["noArrayIndent"] || false; + this.skipInvalid = options["skipInvalid"] || false; + this.flowLevel = common.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"]; + this.styleMap = compileStyleMap(this.schema, options["styles"] || null); + this.sortKeys = options["sortKeys"] || false; + this.lineWidth = options["lineWidth"] || 80; + this.noRefs = options["noRefs"] || false; + this.noCompatMode = options["noCompatMode"] || false; + this.condenseFlow = options["condenseFlow"] || false; + this.quotingType = options["quotingType"] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; + this.forceQuotes = options["forceQuotes"] || false; + this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null; + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + this.tag = null; + this.result = ""; + this.duplicates = []; + this.usedDuplicates = null; +} +function indentString(string4, spaces) { + var ind = common.repeat(" ", spaces), position = 0, next = -1, result = "", line, length = string4.length; + while (position < length) { + next = string4.indexOf("\n", position); + if (next === -1) { + line = string4.slice(position); + position = length; + } else { + line = string4.slice(position, next + 1); + position = next + 1; + } + if (line.length && line !== "\n") result += ind; + result += line; } - const value = getLiteralValue(methodSchema); - if (typeof value !== "string") { - throw new Error("Schema method literal must be a string"); + return result; +} +function generateNextLine(state, level) { + return "\n" + common.repeat(" ", state.indent * level); +} +function testImplicitResolving(state, str2) { + var index2, length, type2; + for (index2 = 0, length = state.implicitTypes.length; index2 < length; index2 += 1) { + type2 = state.implicitTypes[index2]; + if (type2.resolve(str2)) { + return true; + } } - return value; + return false; } -function parseWithCompat(schema2, data) { - const result = safeParse2(schema2, data); - if (!result.success) { - throw result.error; +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} +function isPrintable(c) { + return 32 <= c && c <= 126 || 161 <= c && c <= 55295 && c !== 8232 && c !== 8233 || 57344 <= c && c <= 65533 && c !== CHAR_BOM || 65536 <= c && c <= 1114111; +} +function isNsCharOrWhitespace(c) { + return isPrintable(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED; +} +function isPlainSafe(c, prev, inblock) { + var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); + var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); + return ( + // ns-plain-safe + (inblock ? ( + // c = flow-in + cIsNsCharOrWhitespace + ) : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar + ); +} +function isPlainSafeFirst(c) { + return isPrintable(c) && c !== CHAR_BOM && !isWhitespace(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT; +} +function isPlainSafeLast(c) { + return !isWhitespace(c) && c !== CHAR_COLON; +} +function codePointAt(string4, pos) { + var first = string4.charCodeAt(pos), second; + if (first >= 55296 && first <= 56319 && pos + 1 < string4.length) { + second = string4.charCodeAt(pos + 1); + if (second >= 56320 && second <= 57343) { + return (first - 55296) * 1024 + second - 56320 + 65536; + } } - return result.data; + return first; } - -// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js -var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; -var Protocol = class { - constructor(_options) { - this._options = _options; - this._requestMessageId = 0; - this._requestHandlers = /* @__PURE__ */ new Map(); - this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); - this._notificationHandlers = /* @__PURE__ */ new Map(); - this._responseHandlers = /* @__PURE__ */ new Map(); - this._progressHandlers = /* @__PURE__ */ new Map(); - this._timeoutInfo = /* @__PURE__ */ new Map(); - this._pendingDebouncedNotifications = /* @__PURE__ */ new Set(); - this._taskProgressTokens = /* @__PURE__ */ new Map(); - this._requestResolvers = /* @__PURE__ */ new Map(); - this.setNotificationHandler(CancelledNotificationSchema, (notification) => { - this._oncancel(notification); - }); - this.setNotificationHandler(ProgressNotificationSchema, (notification) => { - this._onprogress(notification); - }); - this.setRequestHandler( - PingRequestSchema, - // Automatic pong by default. - (_request) => ({}) - ); - this._taskStore = _options?.taskStore; - this._taskMessageQueue = _options?.taskMessageQueue; - if (this._taskStore) { - this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => { - const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); - if (!task) { - throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found"); - } - return { - ...task - }; - }); - this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => { - const handleTaskResult = async () => { - const taskId = request.params.taskId; - if (this._taskMessageQueue) { - let queuedMessage; - while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) { - if (queuedMessage.type === "response" || queuedMessage.type === "error") { - const message = queuedMessage.message; - const requestId = message.id; - const resolver = this._requestResolvers.get(requestId); - if (resolver) { - this._requestResolvers.delete(requestId); - if (queuedMessage.type === "response") { - resolver(message); - } else { - const errorMessage = message; - const error2 = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data); - resolver(error2); - } - } else { - const messageType = queuedMessage.type === "response" ? "Response" : "Error"; - this._onerror(new Error(`${messageType} handler missing for request ${requestId}`)); - } - continue; - } - await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId }); - } - } - const task = await this._taskStore.getTask(taskId, extra.sessionId); - if (!task) { - throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`); - } - if (!isTerminal(task.status)) { - await this._waitForTaskUpdate(taskId, extra.signal); - return await handleTaskResult(); - } - if (isTerminal(task.status)) { - const result = await this._taskStore.getTaskResult(taskId, extra.sessionId); - this._clearTaskQueue(taskId); - return { - ...result, - _meta: { - ...result._meta, - [RELATED_TASK_META_KEY]: { - taskId - } - } - }; - } - return await handleTaskResult(); - }; - return await handleTaskResult(); - }); - this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => { - try { - const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId); - return { - tasks, - nextCursor, - _meta: {} - }; - } catch (error2) { - throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error2 instanceof Error ? error2.message : String(error2)}`); - } - }); - this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => { - try { - const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); - if (!task) { - throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`); - } - if (isTerminal(task.status)) { - throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`); - } - await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId); - this._clearTaskQueue(request.params.taskId); - const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId); - if (!cancelledTask) { - throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`); - } - return { - _meta: {}, - ...cancelledTask - }; - } catch (error2) { - if (error2 instanceof McpError) { - throw error2; - } - throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error2 instanceof Error ? error2.message : String(error2)}`); +function needIndentIndicator(string4) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string4); +} +var STYLE_PLAIN = 1; +var STYLE_SINGLE = 2; +var STYLE_LITERAL = 3; +var STYLE_FOLDED = 4; +var STYLE_DOUBLE = 5; +function chooseScalarStyle(string4, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) { + var i2; + var char = 0; + var prevChar = null; + var hasLineBreak = false; + var hasFoldableLine = false; + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; + var plain = isPlainSafeFirst(codePointAt(string4, 0)) && isPlainSafeLast(codePointAt(string4, string4.length - 1)); + if (singleLineOnly || forceQuotes) { + for (i2 = 0; i2 < string4.length; char >= 65536 ? i2 += 2 : i2++) { + char = codePointAt(string4, i2); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + } else { + for (i2 = 0; i2 < string4.length; char >= 65536 ? i2 += 2 : i2++) { + char = codePointAt(string4, i2); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || // Foldable line = too long, and not more-indented. + i2 - previousLineBreak - 1 > lineWidth && string4[previousLineBreak + 1] !== " "; + previousLineBreak = i2; } - }); + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; } + hasFoldableLine = hasFoldableLine || shouldTrackWidth && (i2 - previousLineBreak - 1 > lineWidth && string4[previousLineBreak + 1] !== " "); } - async _oncancel(notification) { - if (!notification.params.requestId) { - return; + if (!hasLineBreak && !hasFoldableLine) { + if (plain && !forceQuotes && !testAmbiguousType(string4)) { + return STYLE_PLAIN; } - const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); - controller?.abort(notification.params.reason); - } - _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { - this._timeoutInfo.set(messageId, { - timeoutId: setTimeout(onTimeout, timeout), - startTime: Date.now(), - timeout, - maxTotalTimeout, - resetTimeoutOnProgress, - onTimeout - }); + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } - _resetTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (!info) - return false; - const totalElapsed = Date.now() - info.startTime; - if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { - this._timeoutInfo.delete(messageId); - throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", { - maxTotalTimeout: info.maxTotalTimeout, - totalElapsed - }); - } - clearTimeout(info.timeoutId); - info.timeoutId = setTimeout(info.onTimeout, info.timeout); - return true; + if (indentPerLevel > 9 && needIndentIndicator(string4)) { + return STYLE_DOUBLE; } - _cleanupTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (info) { - clearTimeout(info.timeoutId); - this._timeoutInfo.delete(messageId); - } + if (!forceQuotes) { + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. - */ - async connect(transport) { - if (this._transport) { - throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection."); + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; +} +function writeScalar(state, string4, level, iskey, inblock) { + state.dump = (function() { + if (string4.length === 0) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; } - this._transport = transport; - const _onclose = this.transport?.onclose; - this._transport.onclose = () => { - _onclose?.(); - this._onclose(); - }; - const _onerror = this.transport?.onerror; - this._transport.onerror = (error2) => { - _onerror?.(error2); - this._onerror(error2); - }; - const _onmessage = this._transport?.onmessage; - this._transport.onmessage = (message, extra) => { - _onmessage?.(message, extra); - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - this._onresponse(message); - } else if (isJSONRPCRequest(message)) { - this._onrequest(message, extra); - } else if (isJSONRPCNotification(message)) { - this._onnotification(message); - } else { - this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); + if (!state.noCompatMode) { + if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string4) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string4)) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? '"' + string4 + '"' : "'" + string4 + "'"; } - }; - await this._transport.start(); - } - _onclose() { - const responseHandlers = this._responseHandlers; - this._responseHandlers = /* @__PURE__ */ new Map(); - this._progressHandlers.clear(); - this._taskProgressTokens.clear(); - this._pendingDebouncedNotifications.clear(); - for (const info of this._timeoutInfo.values()) { - clearTimeout(info.timeoutId); } - this._timeoutInfo.clear(); - for (const controller of this._requestHandlerAbortControllers.values()) { - controller.abort(); + var indent = state.indent * Math.max(1, level); + var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + var singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel; + function testAmbiguity(string5) { + return testImplicitResolving(state, string5); } - this._requestHandlerAbortControllers.clear(); - const error2 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed"); - this._transport = void 0; - this.onclose?.(); - for (const handler of responseHandlers.values()) { - handler(error2); + switch (chooseScalarStyle( + string4, + singleLineOnly, + state.indent, + lineWidth, + testAmbiguity, + state.quotingType, + state.forceQuotes && !iskey, + inblock + )) { + case STYLE_PLAIN: + return string4; + case STYLE_SINGLE: + return "'" + string4.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return "|" + blockHeader(string4, state.indent) + dropEndingNewline(indentString(string4, indent)); + case STYLE_FOLDED: + return ">" + blockHeader(string4, state.indent) + dropEndingNewline(indentString(foldString(string4, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string4) + '"'; + default: + throw new exception("impossible error: invalid scalar style"); } + })(); +} +function blockHeader(string4, indentPerLevel) { + var indentIndicator = needIndentIndicator(string4) ? String(indentPerLevel) : ""; + var clip = string4[string4.length - 1] === "\n"; + var keep = clip && (string4[string4.length - 2] === "\n" || string4 === "\n"); + var chomp = keep ? "+" : clip ? "" : "-"; + return indentIndicator + chomp + "\n"; +} +function dropEndingNewline(string4) { + return string4[string4.length - 1] === "\n" ? string4.slice(0, -1) : string4; +} +function foldString(string4, width) { + var lineRe = /(\n+)([^\n]*)/g; + var result = (function() { + var nextLF = string4.indexOf("\n"); + nextLF = nextLF !== -1 ? nextLF : string4.length; + lineRe.lastIndex = nextLF; + return foldLine(string4.slice(0, nextLF), width); + })(); + var prevMoreIndented = string4[0] === "\n" || string4[0] === " "; + var moreIndented; + var match; + while (match = lineRe.exec(string4)) { + var prefix = match[1], line = match[2]; + moreIndented = line[0] === " "; + result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width); + prevMoreIndented = moreIndented; } - _onerror(error2) { - this.onerror?.(error2); - } - _onnotification(notification) { - const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler; - if (handler === void 0) { - return; + return result; +} +function foldLine(line, width) { + if (line === "" || line[0] === " ") return line; + var breakRe = / [^ ]/g; + var match; + var start = 0, end, curr = 0, next = 0; + var result = ""; + while (match = breakRe.exec(line)) { + next = match.index; + if (next - start > width) { + end = curr > start ? curr : next; + result += "\n" + line.slice(start, end); + start = end + 1; } - Promise.resolve().then(() => handler(notification)).catch((error2) => this._onerror(new Error(`Uncaught error in notification handler: ${error2}`))); + curr = next; } - _onrequest(request, extra) { - const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; - const capturedTransport = this._transport; - const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId; - if (handler === void 0) { - const errorResponse = { - jsonrpc: "2.0", - id: request.id, - error: { - code: ErrorCode.MethodNotFound, - message: "Method not found" - } - }; - if (relatedTaskId && this._taskMessageQueue) { - this._enqueueTaskMessage(relatedTaskId, { - type: "error", - message: errorResponse, - timestamp: Date.now() - }, capturedTransport?.sessionId).catch((error2) => this._onerror(new Error(`Failed to enqueue error response: ${error2}`))); - } else { - capturedTransport?.send(errorResponse).catch((error2) => this._onerror(new Error(`Failed to send an error response: ${error2}`))); - } - return; + result += "\n"; + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + "\n" + line.slice(curr + 1); + } else { + result += line.slice(start); + } + return result.slice(1); +} +function escapeString(string4) { + var result = ""; + var char = 0; + var escapeSeq; + for (var i2 = 0; i2 < string4.length; char >= 65536 ? i2 += 2 : i2++) { + char = codePointAt(string4, i2); + escapeSeq = ESCAPE_SEQUENCES[char]; + if (!escapeSeq && isPrintable(char)) { + result += string4[i2]; + if (char >= 65536) result += string4[i2 + 1]; + } else { + result += escapeSeq || encodeHex(char); } - const abortController = new AbortController(); - this._requestHandlerAbortControllers.set(request.id, abortController); - const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0; - const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : void 0; - const fullExtra = { - signal: abortController.signal, - sessionId: capturedTransport?.sessionId, - _meta: request.params?._meta, - sendNotification: async (notification) => { - if (abortController.signal.aborted) - return; - const notificationOptions = { relatedRequestId: request.id }; - if (relatedTaskId) { - notificationOptions.relatedTask = { taskId: relatedTaskId }; - } - await this.notification(notification, notificationOptions); - }, - sendRequest: async (r, resultSchema, options) => { - if (abortController.signal.aborted) { - throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled"); - } - const requestOptions = { ...options, relatedRequestId: request.id }; - if (relatedTaskId && !requestOptions.relatedTask) { - requestOptions.relatedTask = { taskId: relatedTaskId }; - } - const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId; - if (effectiveTaskId && taskStore) { - await taskStore.updateTaskStatus(effectiveTaskId, "input_required"); - } - return await this.request(r, resultSchema, requestOptions); - }, - authInfo: extra?.authInfo, - requestId: request.id, - requestInfo: extra?.requestInfo, - taskId: relatedTaskId, - taskStore, - taskRequestedTtl: taskCreationParams?.ttl, - closeSSEStream: extra?.closeSSEStream, - closeStandaloneSSEStream: extra?.closeStandaloneSSEStream - }; - Promise.resolve().then(() => { - if (taskCreationParams) { - this.assertTaskHandlerCapability(request.method); - } - }).then(() => handler(request, fullExtra)).then(async (result) => { - if (abortController.signal.aborted) { - return; - } - const response = { - result, - jsonrpc: "2.0", - id: request.id - }; - if (relatedTaskId && this._taskMessageQueue) { - await this._enqueueTaskMessage(relatedTaskId, { - type: "response", - message: response, - timestamp: Date.now() - }, capturedTransport?.sessionId); - } else { - await capturedTransport?.send(response); - } - }, async (error2) => { - if (abortController.signal.aborted) { - return; - } - const errorResponse = { - jsonrpc: "2.0", - id: request.id, - error: { - code: Number.isSafeInteger(error2["code"]) ? error2["code"] : ErrorCode.InternalError, - message: error2.message ?? "Internal error", - ...error2["data"] !== void 0 && { data: error2["data"] } - } - }; - if (relatedTaskId && this._taskMessageQueue) { - await this._enqueueTaskMessage(relatedTaskId, { - type: "error", - message: errorResponse, - timestamp: Date.now() - }, capturedTransport?.sessionId); - } else { - await capturedTransport?.send(errorResponse); - } - }).catch((error2) => this._onerror(new Error(`Failed to send response: ${error2}`))).finally(() => { - if (this._requestHandlerAbortControllers.get(request.id) === abortController) { - this._requestHandlerAbortControllers.delete(request.id); - } - }); } - _onprogress(notification) { - const { progressToken, ...params } = notification.params; - const messageId = Number(progressToken); - const handler = this._progressHandlers.get(messageId); - if (!handler) { - this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); - return; + return result; +} +function writeFlowSequence(state, level, object3) { + var _result = "", _tag = state.tag, index2, length, value; + for (index2 = 0, length = object3.length; index2 < length; index2 += 1) { + value = object3[index2]; + if (state.replacer) { + value = state.replacer.call(object3, String(index2), value); } - const responseHandler = this._responseHandlers.get(messageId); - const timeoutInfo = this._timeoutInfo.get(messageId); - if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { - try { - this._resetTimeout(messageId); - } catch (error2) { - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - responseHandler(error2); - return; - } + if (writeNode(state, level, value, false, false) || typeof value === "undefined" && writeNode(state, level, null, false, false)) { + if (_result !== "") _result += "," + (!state.condenseFlow ? " " : ""); + _result += state.dump; } - handler(params); } - _onresponse(response) { - const messageId = Number(response.id); - const resolver = this._requestResolvers.get(messageId); - if (resolver) { - this._requestResolvers.delete(messageId); - if (isJSONRPCResultResponse(response)) { - resolver(response); + state.tag = _tag; + state.dump = "[" + _result + "]"; +} +function writeBlockSequence(state, level, object3, compact) { + var _result = "", _tag = state.tag, index2, length, value; + for (index2 = 0, length = object3.length; index2 < length; index2 += 1) { + value = object3[index2]; + if (state.replacer) { + value = state.replacer.call(object3, String(index2), value); + } + if (writeNode(state, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode(state, level + 1, null, true, true, false, true)) { + if (!compact || _result !== "") { + _result += generateNextLine(state, level); + } + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += "-"; } else { - const error2 = new McpError(response.error.code, response.error.message, response.error.data); - resolver(error2); + _result += "- "; } - return; - } - const handler = this._responseHandlers.get(messageId); - if (handler === void 0) { - this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); - return; + _result += state.dump; } - this._responseHandlers.delete(messageId); - this._cleanupTimeout(messageId); - let isTaskResponse = false; - if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") { - const result = response.result; - if (result.task && typeof result.task === "object") { - const task = result.task; - if (typeof task.taskId === "string") { - isTaskResponse = true; - this._taskProgressTokens.set(task.taskId, messageId); - } - } + } + state.tag = _tag; + state.dump = _result || "[]"; +} +function writeFlowMapping(state, level, object3) { + var _result = "", _tag = state.tag, objectKeyList = Object.keys(object3), index2, length, objectKey, objectValue, pairBuffer; + for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) { + pairBuffer = ""; + if (_result !== "") pairBuffer += ", "; + if (state.condenseFlow) pairBuffer += '"'; + objectKey = objectKeyList[index2]; + objectValue = object3[objectKey]; + if (state.replacer) { + objectValue = state.replacer.call(object3, objectKey, objectValue); } - if (!isTaskResponse) { - this._progressHandlers.delete(messageId); + if (!writeNode(state, level, objectKey, false, false)) { + continue; } - if (isJSONRPCResultResponse(response)) { - handler(response); - } else { - const error2 = McpError.fromError(response.error.code, response.error.message, response.error.data); - handler(error2); + if (state.dump.length > 1024) pairBuffer += "? "; + pairBuffer += state.dump + (state.condenseFlow ? '"' : "") + ":" + (state.condenseFlow ? "" : " "); + if (!writeNode(state, level, objectValue, false, false)) { + continue; } + pairBuffer += state.dump; + _result += pairBuffer; } - get transport() { - return this._transport; - } - /** - * Closes the connection. - */ - async close() { - await this._transport?.close(); + state.tag = _tag; + state.dump = "{" + _result + "}"; +} +function writeBlockMapping(state, level, object3, compact) { + var _result = "", _tag = state.tag, objectKeyList = Object.keys(object3), index2, length, objectKey, objectValue, explicitPair, pairBuffer; + if (state.sortKeys === true) { + objectKeyList.sort(); + } else if (typeof state.sortKeys === "function") { + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + throw new exception("sortKeys must be a boolean or a function"); } - /** - * Sends a request and returns an AsyncGenerator that yields response messages. - * The generator is guaranteed to end with either a 'result' or 'error' message. - * - * @example - * ```typescript - * const stream = protocol.requestStream(request, resultSchema, options); - * for await (const message of stream) { - * switch (message.type) { - * case 'taskCreated': - * console.log('Task created:', message.task.taskId); - * break; - * case 'taskStatus': - * console.log('Task status:', message.task.status); - * break; - * case 'result': - * console.log('Final result:', message.result); - * break; - * case 'error': - * console.error('Error:', message.error); - * break; - * } - * } - * ``` - * - * @experimental Use `client.experimental.tasks.requestStream()` to access this method. - */ - async *requestStream(request, resultSchema, options) { - const { task } = options ?? {}; - if (!task) { - try { - const result = await this.request(request, resultSchema, options); - yield { type: "result", result }; - } catch (error2) { - yield { - type: "error", - error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2)) - }; + for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) { + pairBuffer = ""; + if (!compact || _result !== "") { + pairBuffer += generateNextLine(state, level); + } + objectKey = objectKeyList[index2]; + objectValue = object3[objectKey]; + if (state.replacer) { + objectValue = state.replacer.call(object3, objectKey, objectValue); + } + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; + } + explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024; + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += "?"; + } else { + pairBuffer += "? "; } - return; } - let taskId; - try { - const createResult = await this.request(request, CreateTaskResultSchema, options); - if (createResult.task) { - taskId = createResult.task.taskId; - yield { type: "taskCreated", task: createResult.task }; + pairBuffer += state.dump; + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; + } + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ":"; + } else { + pairBuffer += ": "; + } + pairBuffer += state.dump; + _result += pairBuffer; + } + state.tag = _tag; + state.dump = _result || "{}"; +} +function detectType(state, object3, explicit) { + var _result, typeList, index2, length, type2, style; + typeList = explicit ? state.explicitTypes : state.implicitTypes; + for (index2 = 0, length = typeList.length; index2 < length; index2 += 1) { + type2 = typeList[index2]; + if ((type2.instanceOf || type2.predicate) && (!type2.instanceOf || typeof object3 === "object" && object3 instanceof type2.instanceOf) && (!type2.predicate || type2.predicate(object3))) { + if (explicit) { + if (type2.multi && type2.representName) { + state.tag = type2.representName(object3); + } else { + state.tag = type2.tag; + } } else { - throw new McpError(ErrorCode.InternalError, "Task creation did not return a task"); + state.tag = "?"; } - while (true) { - const task2 = await this.getTask({ taskId }, options); - yield { type: "taskStatus", task: task2 }; - if (isTerminal(task2.status)) { - if (task2.status === "completed") { - const result = await this.getTaskResult({ taskId }, resultSchema, options); - yield { type: "result", result }; - } else if (task2.status === "failed") { - yield { - type: "error", - error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`) - }; - } else if (task2.status === "cancelled") { - yield { - type: "error", - error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`) - }; - } - return; - } - if (task2.status === "input_required") { - const result = await this.getTaskResult({ taskId }, resultSchema, options); - yield { type: "result", result }; - return; + if (type2.represent) { + style = state.styleMap[type2.tag] || type2.defaultStyle; + if (_toString.call(type2.represent) === "[object Function]") { + _result = type2.represent(object3, style); + } else if (_hasOwnProperty.call(type2.represent, style)) { + _result = type2.represent[style](object3, style); + } else { + throw new exception("!<" + type2.tag + '> tag resolver accepts not "' + style + '" style'); } - const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3; - await new Promise((resolve3) => setTimeout(resolve3, pollInterval)); - options?.signal?.throwIfAborted(); + state.dump = _result; } - } catch (error2) { - yield { - type: "error", - error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2)) - }; + return true; } } - /** - * Sends a request and waits for a response. - * - * Do not use this method to emit notifications! Use notification() instead. - */ - request(request, resultSchema, options) { - const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {}; - return new Promise((resolve3, reject) => { - const earlyReject = (error2) => { - reject(error2); - }; - if (!this._transport) { - earlyReject(new Error("Not connected")); - return; + return false; +} +function writeNode(state, level, object3, block, compact, iskey, isblockseq) { + state.tag = null; + state.dump = object3; + if (!detectType(state, object3, false)) { + detectType(state, object3, true); + } + var type2 = _toString.call(state.dump); + var inblock = block; + var tagStr; + if (block) { + block = state.flowLevel < 0 || state.flowLevel > level; + } + var objectOrArray = type2 === "[object Object]" || type2 === "[object Array]", duplicateIndex, duplicate; + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object3); + duplicate = duplicateIndex !== -1; + } + if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) { + compact = false; + } + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = "*ref_" + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type2 === "[object Object]") { + if (block && Object.keys(state.dump).length !== 0) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = "&ref_" + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = "&ref_" + duplicateIndex + " " + state.dump; + } } - if (this._options?.enforceStrictCapabilities === true) { - try { - this.assertCapabilityForMethod(request.method); - if (task) { - this.assertTaskCapability(request.method); - } - } catch (e3) { - earlyReject(e3); - return; + } else if (type2 === "[object Array]") { + if (block && state.dump.length !== 0) { + if (state.noArrayIndent && !isblockseq && level > 0) { + writeBlockSequence(state, level - 1, state.dump, compact); + } else { + writeBlockSequence(state, level, state.dump, compact); + } + if (duplicate) { + state.dump = "&ref_" + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, level, state.dump); + if (duplicate) { + state.dump = "&ref_" + duplicateIndex + " " + state.dump; } } - options?.signal?.throwIfAborted(); - const messageId = this._requestMessageId++; - const jsonrpcRequest = { - ...request, - jsonrpc: "2.0", - id: messageId - }; - if (options?.onprogress) { - this._progressHandlers.set(messageId, options.onprogress); - jsonrpcRequest.params = { - ...request.params, - _meta: { - ...request.params?._meta || {}, - progressToken: messageId - } - }; + } else if (type2 === "[object String]") { + if (state.tag !== "?") { + writeScalar(state, state.dump, level, iskey, inblock); } - if (task) { - jsonrpcRequest.params = { - ...jsonrpcRequest.params, - task - }; + } else if (type2 === "[object Undefined]") { + return false; + } else { + if (state.skipInvalid) return false; + throw new exception("unacceptable kind of an object to dump " + type2); + } + if (state.tag !== null && state.tag !== "?") { + tagStr = encodeURI( + state.tag[0] === "!" ? state.tag.slice(1) : state.tag + ).replace(/!/g, "%21"); + if (state.tag[0] === "!") { + tagStr = "!" + tagStr; + } else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") { + tagStr = "!!" + tagStr.slice(18); + } else { + tagStr = "!<" + tagStr + ">"; } - if (relatedTask) { - jsonrpcRequest.params = { - ...jsonrpcRequest.params, - _meta: { - ...jsonrpcRequest.params?._meta || {}, - [RELATED_TASK_META_KEY]: relatedTask - } - }; + state.dump = tagStr + " " + state.dump; + } + } + return true; +} +function getDuplicateReferences(object3, state) { + var objects = [], duplicatesIndexes = [], index2, length; + inspectNode(object3, objects, duplicatesIndexes); + for (index2 = 0, length = duplicatesIndexes.length; index2 < length; index2 += 1) { + state.duplicates.push(objects[duplicatesIndexes[index2]]); + } + state.usedDuplicates = new Array(length); +} +function inspectNode(object3, objects, duplicatesIndexes) { + var objectKeyList, index2, length; + if (object3 !== null && typeof object3 === "object") { + index2 = objects.indexOf(object3); + if (index2 !== -1) { + if (duplicatesIndexes.indexOf(index2) === -1) { + duplicatesIndexes.push(index2); } - const cancel = (reason) => { - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - this._transport?.send({ - jsonrpc: "2.0", - method: "notifications/cancelled", - params: { - requestId: messageId, - reason: String(reason) - } - }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error3) => this._onerror(new Error(`Failed to send cancellation: ${error3}`))); - const error2 = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason)); - reject(error2); - }; - this._responseHandlers.set(messageId, (response) => { - if (options?.signal?.aborted) { - return; - } - if (response instanceof Error) { - return reject(response); - } - try { - const parseResult = safeParse2(resultSchema, response.result); - if (!parseResult.success) { - reject(parseResult.error); - } else { - resolve3(parseResult.data); - } - } catch (error2) { - reject(error2); + } else { + objects.push(object3); + if (Array.isArray(object3)) { + for (index2 = 0, length = object3.length; index2 < length; index2 += 1) { + inspectNode(object3[index2], objects, duplicatesIndexes); } - }); - options?.signal?.addEventListener("abort", () => { - cancel(options?.signal?.reason); - }); - const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; - const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout })); - this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); - const relatedTaskId = relatedTask?.taskId; - if (relatedTaskId) { - const responseResolver = (response) => { - const handler = this._responseHandlers.get(messageId); - if (handler) { - handler(response); - } else { - this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`)); - } - }; - this._requestResolvers.set(messageId, responseResolver); - this._enqueueTaskMessage(relatedTaskId, { - type: "request", - message: jsonrpcRequest, - timestamp: Date.now() - }).catch((error2) => { - this._cleanupTimeout(messageId); - reject(error2); - }); } else { - this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => { - this._cleanupTimeout(messageId); - reject(error2); - }); + objectKeyList = Object.keys(object3); + for (index2 = 0, length = objectKeyList.length; index2 < length; index2 += 1) { + inspectNode(object3[objectKeyList[index2]], objects, duplicatesIndexes); + } } - }); + } } - /** - * Gets the current status of a task. - * - * @experimental Use `client.experimental.tasks.getTask()` to access this method. - */ - async getTask(params, options) { - return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options); +} +function dump$1(input, options) { + options = options || {}; + var state = new State(options); + if (!state.noRefs) getDuplicateReferences(input, state); + var value = input; + if (state.replacer) { + value = state.replacer.call({ "": value }, "", value); } - /** - * Retrieves the result of a completed task. - * - * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method. - */ - async getTaskResult(params, resultSchema, options) { - return this.request({ method: "tasks/result", params }, resultSchema, options); + if (writeNode(state, 0, value, true, true)) return state.dump + "\n"; + return ""; +} +var dump_1 = dump$1; +var dumper = { + dump: dump_1 +}; +function renamed(from, to2) { + return function() { + throw new Error("Function yaml." + from + " is removed in js-yaml 4. Use yaml." + to2 + " instead, which is now safe by default."); + }; +} +var load = loader.load; +var loadAll = loader.loadAll; +var dump = dumper.dump; +var safeLoad = renamed("safeLoad", "load"); +var safeLoadAll = renamed("safeLoadAll", "loadAll"); +var safeDump = renamed("safeDump", "dump"); + +// packages/strategy/dist/research-evidence-database.js +var TIER_1_EVIDENCE = [ + { + strategy: "recursive_refinement", + tier: 1, + improvementPercent: 0.32, + claimCharacteristics: [ + "mathematical_reasoning", + "multi_step_logic", + "complex_technical", + "iterative_refinement", + "high_precision" + ], + source: "DeepSeek (2025) \u2014 DeepSeek-R1: Incentivizing Reasoning Capability in LLMs", + citation: "arXiv:2501.12948" + }, + { + strategy: "recursive_refinement", + tier: 1, + improvementPercent: 0.74, + claimCharacteristics: [ + "mathematical_reasoning", + "multi_step_logic", + "self_correction", + "high_precision" + ], + source: "OpenAI (2024) \u2014 Learning to Reason with LLMs", + citation: "OpenAI technical report (non-peer-reviewed)" + }, + { + strategy: "verified_reasoning", + tier: 1, + improvementPercent: 0.18, + claimCharacteristics: [ + "accuracy_critical", + "fact_verification", + "consistency_check", + "high_precision" + ], + source: "Stanford/Anthropic (2024) \u2014 Chain-of-Verification Reduces Hallucination in LLMs", + citation: "Stanford/Anthropic 2024" + }, + { + strategy: "graph_of_thoughts", + tier: 1, + improvementPercent: 0.62, + claimCharacteristics: [ + "dependency_analysis", + "cross_reference", + "structural_reasoning", + "complex_technical" + ], + source: "ETH Zurich (2024) \u2014 Graph of Thoughts: Solving Elaborate Problems with LLMs", + citation: "arXiv:2308.09687" + }, + { + strategy: "self_consistency", + tier: 1, + improvementPercent: 0.179, + claimCharacteristics: [ + "mathematical_reasoning", + "multiple_approaches", + "consistency_check", + "uncertainty_handling" + ], + source: "Google Research (2023) \u2014 Self-Consistency Improves Chain of Thought Reasoning", + citation: "arXiv:2203.11171" + }, + { + strategy: "reflexion", + tier: 1, + improvementPercent: 0.21, + claimCharacteristics: [ + "iterative_refinement", + "self_correction", + "quality_improvement", + "code_generation" + ], + source: "MIT/Northeastern (2023) \u2014 Reflexion: Language Agents with Verbal Reinforcement Learning", + citation: "arXiv:2303.11366" + }, + { + strategy: "problem_analysis", + tier: 1, + improvementPercent: 0.24, + claimCharacteristics: [ + "complex_technical", + "multi_dimensional", + "structural_reasoning", + "risk_analysis" + ], + source: "Harvard/MIT (2024) \u2014 Structured Decomposition Outperforms Linear Reasoning", + citation: "Harvard/MIT 2024" } - /** - * Lists tasks, optionally starting from a pagination cursor. - * - * @experimental Use `client.experimental.tasks.listTasks()` to access this method. - */ - async listTasks(params, options) { - return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options); +]; +var TIER_2_EVIDENCE = [ + { + strategy: "tree_of_thoughts", + tier: 2, + improvementPercent: 0.74, + claimCharacteristics: [ + "exploratory_reasoning", + "multiple_approaches", + "creative_problems", + "branch_exploration" + ], + source: "Princeton/Google DeepMind (2024) \u2014 Tree of Thoughts: Deliberate Problem Solving with LLMs", + citation: "arXiv:2305.10601" + }, + { + strategy: "react", + tier: 2, + improvementPercent: 0.27, + claimCharacteristics: [ + "codebase_integration", + "tool_use", + "external_knowledge", + "cross_reference" + ], + source: "Princeton/Google (2023) \u2014 ReAct: Synergizing Reasoning and Acting in Language Models", + citation: "arXiv:2210.03629" + }, + { + strategy: "meta_prompting", + tier: 2, + improvementPercent: 0.171, + claimCharacteristics: [ + "complex_technical", + "multi_step_logic", + "role_based_reasoning", + "expert_orchestration" + ], + source: "Stanford (2024) \u2014 Meta-Prompting: Enhancing Language Models with Task-Agnostic Scaffolding", + citation: "Stanford 2024" + }, + { + strategy: "plan_and_solve", + tier: 2, + improvementPercent: 0.058, + claimCharacteristics: [ + "multi_step_logic", + "sequential_planning", + "structural_reasoning" + ], + source: "NUS (2023) \u2014 Plan-and-Solve Prompting: Improving Zero-Shot CoT", + citation: "arXiv:2305.04091" } - /** - * Cancels a specific task. - * - * @experimental Use `client.experimental.tasks.cancelTask()` to access this method. - */ - async cancelTask(params, options) { - return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options); +]; +var TIER_3_EVIDENCE = [ + { + strategy: "few_shot", + tier: 3, + improvementPercent: 0.25, + claimCharacteristics: [ + "pattern_matching", + "domain_specific", + "example_based" + ], + source: "OpenAI (2020) \u2014 Language Models are Few-Shot Learners", + citation: "arXiv:2005.14165" + }, + { + strategy: "generate_knowledge", + tier: 3, + improvementPercent: 0.15, + claimCharacteristics: [ + "domain_knowledge", + "fact_generation", + "commonsense_reasoning" + ], + source: "AI2 (2022) \u2014 Generated Knowledge Prompting for Commonsense Reasoning", + citation: "arXiv:2110.08387" + }, + { + strategy: "multimodal_cot", + tier: 3, + improvementPercent: 0.16, + claimCharacteristics: [ + "visual_reasoning", + "multimodal", + "diagram_analysis" + ], + source: "Amazon/UCLA (2023) \u2014 Multimodal Chain-of-Thought Reasoning", + citation: "arXiv:2302.00923" } - /** - * Emits a notification, which is a one-way message that does not expect a response. - */ - async notification(notification, options) { - if (!this._transport) { - throw new Error("Not connected"); - } - this.assertNotificationCapability(notification.method); - const relatedTaskId = options?.relatedTask?.taskId; - if (relatedTaskId) { - const jsonrpcNotification2 = { - ...notification, - jsonrpc: "2.0", - params: { - ...notification.params, - _meta: { - ...notification.params?._meta || {}, - [RELATED_TASK_META_KEY]: options.relatedTask - } - } - }; - await this._enqueueTaskMessage(relatedTaskId, { - type: "notification", - message: jsonrpcNotification2, - timestamp: Date.now() - }); - return; - } - const debouncedMethods = this._options?.debouncedNotificationMethods ?? []; - const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask; - if (canDebounce) { - if (this._pendingDebouncedNotifications.has(notification.method)) { - return; +]; +var TIER_4_EVIDENCE = [ + { + strategy: "chain_of_thought", + tier: 4, + improvementPercent: 0, + claimCharacteristics: ["basic_reasoning"], + source: "Google/DeepMind (2024) \u2014 Chain-of-Thought Reasoning Without Prompting", + citation: "arXiv:2402.10200" + }, + { + strategy: "zero_shot", + tier: 4, + improvementPercent: 0, + claimCharacteristics: [], + source: "Various (2023) \u2014 Baseline comparison meta-analysis", + citation: "Various 2023" + } +]; +var ALL_EVIDENCE = [ + ...TIER_1_EVIDENCE, + ...TIER_2_EVIDENCE, + ...TIER_3_EVIDENCE, + ...TIER_4_EVIDENCE +]; +var ResearchEvidenceDatabase = class { + evidence = ALL_EVIDENCE; + getEvidence(strategy) { + return this.evidence.filter((e3) => e3.strategy === strategy); + } + getBestEvidence(strategy) { + return this.getEvidence(strategy).sort((a, b) => b.improvementPercent - a.improvementPercent)[0]; + } + getTier(strategy) { + const first = this.evidence.find((e3) => e3.strategy === strategy); + return first?.tier; + } + getStrategiesInTier(tier) { + const seen = /* @__PURE__ */ new Set(); + for (const e3 of this.evidence) { + if (e3.tier === tier) + seen.add(e3.strategy); + } + return [...seen]; + } + getMatchingStrategies(characteristics) { + const charSet = new Set(characteristics); + return this.evidence.filter((e3) => e3.claimCharacteristics.some((c) => charSet.has(c))).sort((a, b) => { + if (a.tier !== b.tier) + return a.tier - b.tier; + return b.improvementPercent - a.improvementPercent; + }); + } + calculateScore(strategy, characteristics) { + const matching = this.getEvidence(strategy); + if (matching.length === 0) + return 0; + let totalScore = 0; + for (const ev of matching) { + const evChars = new Set(ev.claimCharacteristics); + let overlap = 0; + for (const c of characteristics) { + if (evChars.has(c)) + overlap++; } - this._pendingDebouncedNotifications.add(notification.method); - Promise.resolve().then(() => { - this._pendingDebouncedNotifications.delete(notification.method); - if (!this._transport) { - return; - } - let jsonrpcNotification2 = { - ...notification, - jsonrpc: "2.0" - }; - if (options?.relatedTask) { - jsonrpcNotification2 = { - ...jsonrpcNotification2, - params: { - ...jsonrpcNotification2.params, - _meta: { - ...jsonrpcNotification2.params?._meta || {}, - [RELATED_TASK_META_KEY]: options.relatedTask - } - } - }; - } - this._transport?.send(jsonrpcNotification2, options).catch((error2) => this._onerror(error2)); - }); - return; + const overlapRatio = overlap / Math.max(1, ev.claimCharacteristics.length); + const tierWeight = STRATEGY_TIERS[ev.tier].selectionWeight; + totalScore += ev.improvementPercent * tierWeight * (0.5 + 0.5 * overlapRatio); } - let jsonrpcNotification = { - ...notification, - jsonrpc: "2.0" - }; - if (options?.relatedTask) { - jsonrpcNotification = { - ...jsonrpcNotification, - params: { - ...jsonrpcNotification.params, - _meta: { - ...jsonrpcNotification.params?._meta || {}, - [RELATED_TASK_META_KEY]: options.relatedTask - } - } - }; + return totalScore / matching.length; + } + getCitations(strategy) { + return this.getEvidence(strategy).map((e3) => e3.citation); + } + getAllStrategies() { + const seen = /* @__PURE__ */ new Set(); + for (const e3 of this.evidence) { + seen.add(e3.strategy); } - await this._transport.send(jsonrpcNotification, options); + return [...seen]; + } + getAllEvidence() { + return this.evidence; + } +}; + +// packages/strategy/dist/claim-analyzer.js +var ClaimAnalysisResultSchema = external_exports.object({ + claim: external_exports.string(), + characteristics: external_exports.array(external_exports.string()), + complexityScore: external_exports.number(), + complexityTier: external_exports.enum(["simple", "moderate", "complex"]), + analysisNotes: external_exports.array(external_exports.string()) +}); +function containsAny(text, patterns) { + return patterns.some((p) => text.includes(p)); +} +function detectReasoningComplexity(text) { + const characteristics = /* @__PURE__ */ new Set(); + const notes = []; + if (containsAny(text, ["calculate", "compute", "formula", "equation", "math"])) { + characteristics.add("mathematical_reasoning"); + notes.push("Mathematical reasoning detected"); + } + if (containsAny(text, ["step", "sequence", "then", "after", "before", "process"])) { + characteristics.add("multi_step_logic"); + characteristics.add("sequential_planning"); + } + if (containsAny(text, ["technical", "architecture", "system", "implementation", "api", "database"])) { + characteristics.add("complex_technical"); + notes.push("Technical domain content"); + } + if (containsAny(text, ["precise", "exact", "accurate", "critical", "must", "shall"])) { + characteristics.add("high_precision"); + characteristics.add("accuracy_critical"); + } + return { characteristics, notes }; +} +function detectStructurePatterns(text) { + const characteristics = /* @__PURE__ */ new Set(); + if (containsAny(text, ["depend", "relationship", "connect", "link", "reference"])) { + characteristics.add("dependency_analysis"); + characteristics.add("cross_reference"); + } + if (containsAny(text, ["structure", "hierarchy", "organize", "component", "module"])) { + characteristics.add("structural_reasoning"); + } + return characteristics; +} +function detectExplorationPatterns(text) { + const characteristics = /* @__PURE__ */ new Set(); + const notes = []; + if (containsAny(text, ["explore", "alternative", "option", "approach", "possibility"])) { + characteristics.add("exploratory_reasoning"); + characteristics.add("multiple_approaches"); + characteristics.add("branch_exploration"); + } + if (containsAny(text, ["creative", "innovative", "novel", "design"])) { + characteristics.add("creative_problems"); + } + if (containsAny(text, ["uncertain", "unclear", "ambiguous", "complex", "difficult"])) { + characteristics.add("uncertainty_handling"); + notes.push("High uncertainty detected"); } - /** - * Registers a handler to invoke when this protocol object receives a request with the given method. - * - * Note that this will replace any previous request handler for the same method. - */ - setRequestHandler(requestSchema, handler) { - const method = getMethodLiteral(requestSchema); - this.assertRequestHandlerCapability(method); - this._requestHandlers.set(method, (request, extra) => { - const parsed = parseWithCompat(requestSchema, request); - return Promise.resolve(handler(parsed, extra)); - }); + return { characteristics, notes }; +} +function detectVerificationNeeds(text) { + const characteristics = /* @__PURE__ */ new Set(); + if (containsAny(text, ["verify", "validate", "check", "ensure", "confirm"])) { + characteristics.add("fact_verification"); + characteristics.add("consistency_check"); } - /** - * Removes the request handler for the given method. - */ - removeRequestHandler(method) { - this._requestHandlers.delete(method); + if (containsAny(text, ["risk", "threat", "vulnerability", "issue", "problem"])) { + characteristics.add("risk_analysis"); } - /** - * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. - */ - assertCanSetRequestHandler(method) { - if (this._requestHandlers.has(method)) { - throw new Error(`A request handler for ${method} already exists, which would be overridden`); - } + return characteristics; +} +function detectDomainPatterns(text) { + const characteristics = /* @__PURE__ */ new Set(); + const notes = []; + if (containsAny(text, ["codebase", "repository", "existing code", "current system"])) { + characteristics.add("codebase_integration"); + characteristics.add("tool_use"); + notes.push("Codebase integration required"); } - /** - * Registers a handler to invoke when this protocol object receives a notification with the given method. - * - * Note that this will replace any previous notification handler for the same method. - */ - setNotificationHandler(notificationSchema, handler) { - const method = getMethodLiteral(notificationSchema); - this._notificationHandlers.set(method, (notification) => { - const parsed = parseWithCompat(notificationSchema, notification); - return Promise.resolve(handler(parsed)); - }); + if (containsAny(text, ["example", "sample", "template", "pattern"])) { + characteristics.add("pattern_matching"); + characteristics.add("example_based"); } - /** - * Removes the notification handler for the given method. - */ - removeNotificationHandler(method) { - this._notificationHandlers.delete(method); + if (containsAny(text, ["code", "function", "class", "method", "implement"])) { + characteristics.add("code_generation"); } - /** - * Cleans up the progress handler associated with a task. - * This should be called when a task reaches a terminal status. - */ - _cleanupTaskProgressHandler(taskId) { - const progressToken = this._taskProgressTokens.get(taskId); - if (progressToken !== void 0) { - this._progressHandlers.delete(progressToken); - this._taskProgressTokens.delete(taskId); - } + return { characteristics, notes }; +} +function detectIterativePatterns(text) { + const characteristics = /* @__PURE__ */ new Set(); + if (containsAny(text, ["refine", "improve", "iterate", "enhance", "optimize"])) { + characteristics.add("iterative_refinement"); + characteristics.add("quality_improvement"); } - /** - * Enqueues a task-related message for side-channel delivery via tasks/result. - * @param taskId The task ID to associate the message with - * @param message The message to enqueue - * @param sessionId Optional session ID for binding the operation to a specific session - * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow) - * - * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle - * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer - * simply propagates the error. - */ - async _enqueueTaskMessage(taskId, message, sessionId) { - if (!this._taskStore || !this._taskMessageQueue) { - throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured"); + if (containsAny(text, ["correct", "fix", "revise", "update"])) { + characteristics.add("self_correction"); + } + return characteristics; +} +function detectExternalDependencies(text) { + const characteristics = /* @__PURE__ */ new Set(); + if (containsAny(text, ["search", "find", "lookup", "retrieve", "fetch"])) { + characteristics.add("external_knowledge"); + characteristics.add("tool_use"); + } + return characteristics; +} +function detectSpecialModes(text) { + const characteristics = /* @__PURE__ */ new Set(); + const notes = []; + if (containsAny(text, ["image", "visual", "diagram", "mockup", "screenshot", "ui"])) { + characteristics.add("visual_reasoning"); + characteristics.add("multimodal"); + characteristics.add("diagram_analysis"); + notes.push("Visual content processing needed"); + } + if (containsAny(text, ["perspective", "role", "stakeholder", "expert"])) { + characteristics.add("role_based_reasoning"); + characteristics.add("expert_orchestration"); + } + return { characteristics, notes }; +} +var HIGH_COMPLEXITY_CHARS = /* @__PURE__ */ new Set([ + "mathematical_reasoning", + "complex_technical", + "dependency_analysis", + "multi_dimensional", + "accuracy_critical", + "risk_analysis", + "codebase_integration", + "iterative_refinement" +]); +var MEDIUM_COMPLEXITY_CHARS = /* @__PURE__ */ new Set([ + "multi_step_logic", + "cross_reference", + "structural_reasoning", + "exploratory_reasoning", + "multiple_approaches", + "uncertainty_handling", + "fact_verification", + "self_correction" +]); +function calculateComplexityScore(characteristics, text) { + let score = characteristics.size * 0.05; + for (const c of characteristics) { + if (HIGH_COMPLEXITY_CHARS.has(c)) { + score += 0.12; + } else if (MEDIUM_COMPLEXITY_CHARS.has(c)) { + score += 0.08; + } else { + score += 0.04; } - const maxQueueSize = this._options?.maxTaskQueueSize; - await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize); } - /** - * Clears the message queue for a task and rejects any pending request resolvers. - * @param taskId The task ID whose queue should be cleared - * @param sessionId Optional session ID for binding the operation to a specific session - */ - async _clearTaskQueue(taskId, sessionId) { - if (this._taskMessageQueue) { - const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId); - for (const message of messages) { - if (message.type === "request" && isJSONRPCRequest(message.message)) { - const requestId = message.message.id; - const resolver = this._requestResolvers.get(requestId); - if (resolver) { - resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed")); - this._requestResolvers.delete(requestId); - } else { - this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`)); - } - } + const wordCount = text.split(/\s+/).length; + score += Math.min(0.15, wordCount / 500); + return Math.min(1, score); +} +function complexityTierFromScore(score) { + if (score >= 0.6) + return "complex"; + if (score >= 0.3) + return "moderate"; + return "simple"; +} +function analyzeClaim(claim, context) { + const text = (claim + " " + (context ?? "")).toLowerCase(); + const reasoning = detectReasoningComplexity(text); + const structure = detectStructurePatterns(text); + const exploration = detectExplorationPatterns(text); + const verification = detectVerificationNeeds(text); + const domain = detectDomainPatterns(text); + const iterative = detectIterativePatterns(text); + const external2 = detectExternalDependencies(text); + const special = detectSpecialModes(text); + const characteristics = /* @__PURE__ */ new Set(); + for (const set2 of [ + reasoning.characteristics, + structure, + exploration.characteristics, + verification, + domain.characteristics, + iterative, + external2, + special.characteristics + ]) { + for (const c of set2) + characteristics.add(c); + } + if (characteristics.size === 0) { + characteristics.add("basic_reasoning"); + } + const notes = [ + ...reasoning.notes, + ...exploration.notes, + ...domain.notes, + ...special.notes + ]; + const complexityScore = calculateComplexityScore(characteristics, text); + return { + claim, + // Persisted as a deduplicated array. Set semantics recovered via + // `characteristicSet(...)` or `characteristics.includes(...)` at use sites. + characteristics: [...characteristics], + complexityScore, + complexityTier: complexityTierFromScore(complexityScore), + analysisNotes: notes + }; +} + +// packages/strategy/dist/selector.js +var StrategyAssignmentSchema = external_exports.object({ + required: external_exports.array(ThinkingStrategySchema), + optional: external_exports.array(ThinkingStrategySchema), + forbidden: external_exports.array(ThinkingStrategySchema), + expectedImprovement: external_exports.number(), + assignmentConfidence: external_exports.number(), + claimAnalysis: ClaimAnalysisResultSchema, + researchCitations: external_exports.array(external_exports.string()) +}); +var db = new ResearchEvidenceDatabase(); +function scoreStrategies(characteristics, historicalAdjustments, overlapWeight, minimumThreshold) { + const allStrategies = db.getAllStrategies(); + const scored = []; + for (const strategy of allStrategies) { + const tier = db.getTier(strategy); + if (tier === void 0) + continue; + const evidence = db.getEvidence(strategy); + if (evidence.length === 0) + continue; + let totalOverlap = 0; + let weightedImprovement = 0; + for (const ev of evidence) { + const evChars = new Set(ev.claimCharacteristics); + let overlap = 0; + for (const c of characteristics) { + if (evChars.has(c)) + overlap++; } + totalOverlap += overlap; + const overlapRatio = overlap / Math.max(1, ev.claimCharacteristics.length); + weightedImprovement += ev.improvementPercent * (overlapWeight * overlapRatio + (1 - overlapWeight)); } + const avgImprovement = weightedImprovement / evidence.length; + if (avgImprovement < minimumThreshold && tier !== 1) + continue; + const overlapFactor = 1 + totalOverlap / Math.max(1, characteristics.size); + let score = STRATEGY_TIERS[tier].selectionWeight * avgImprovement * overlapFactor; + const adjustment = historicalAdjustments.get(strategy) ?? 0; + const clampedAdjustment = Math.max(-0.3, Math.min(0.3, adjustment)); + score = score * (1 + clampedAdjustment); + scored.push({ strategy, score, tier, improvement: avgImprovement, overlapCount: totalOverlap }); } - /** - * Waits for a task update (new messages or status change) with abort signal support. - * Uses polling to check for updates at the task's configured poll interval. - * @param taskId The task ID to wait for - * @param signal Abort signal to cancel the wait - * @returns Promise that resolves when an update occurs or rejects if aborted - */ - async _waitForTaskUpdate(taskId, signal) { - let interval = this._options?.defaultTaskPollInterval ?? 1e3; - try { - const task = await this._taskStore?.getTask(taskId); - if (task?.pollInterval) { - interval = task.pollInterval; - } - } catch { + return scored.sort((a, b) => { + if (a.tier !== b.tier) + return a.tier - b.tier; + return b.score - a.score; + }); +} +function applyComplexityConstraints(strategies, complexityTier) { + const maxAllowedTier = complexityTier === "complex" ? 2 : complexityTier === "moderate" ? 3 : 4; + return strategies.filter((s) => s.tier <= maxAllowedTier); +} +function selectRequired(strategies, analysis, maxRequired) { + const required2 = []; + if (analysis.complexityTier === "complex") { + const tier1 = strategies.find((s) => s.tier === 1); + if (tier1) + required2.push(tier1.strategy); + } + const best = strategies[0]; + if (best && !required2.includes(best.strategy)) { + required2.push(best.strategy); + } + if (analysis.characteristics.includes("accuracy_critical") || analysis.characteristics.includes("high_precision")) { + if (!required2.includes("verified_reasoning")) { + required2.push("verified_reasoning"); } - return new Promise((resolve3, reject) => { - if (signal.aborted) { - reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled")); - return; - } - const timeoutId = setTimeout(resolve3, interval); - signal.addEventListener("abort", () => { - clearTimeout(timeoutId); - reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled")); - }, { once: true }); - }); } - requestTaskStore(request, sessionId) { - const taskStore = this._taskStore; - if (!taskStore) { - throw new Error("No task store configured"); + if (analysis.characteristics.includes("codebase_integration")) { + if (!required2.includes("react") && !required2.includes("verified_reasoning")) { + required2.push("react"); } - return { - createTask: async (taskParams) => { - if (!request) { - throw new Error("No request provided"); - } - return await taskStore.createTask(taskParams, request.id, { - method: request.method, - params: request.params - }, sessionId); - }, - getTask: async (taskId) => { - const task = await taskStore.getTask(taskId, sessionId); - if (!task) { - throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found"); - } - return task; - }, - storeTaskResult: async (taskId, status, result) => { - await taskStore.storeTaskResult(taskId, status, result, sessionId); - const task = await taskStore.getTask(taskId, sessionId); - if (task) { - const notification = TaskStatusNotificationSchema.parse({ - method: "notifications/tasks/status", - params: task - }); - await this.notification(notification); - if (isTerminal(task.status)) { - this._cleanupTaskProgressHandler(taskId); - } - } - }, - getTaskResult: (taskId) => { - return taskStore.getTaskResult(taskId, sessionId); - }, - updateTaskStatus: async (taskId, status, statusMessage) => { - const task = await taskStore.getTask(taskId, sessionId); - if (!task) { - throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`); - } - if (isTerminal(task.status)) { - throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`); - } - await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId); - const updatedTask = await taskStore.getTask(taskId, sessionId); - if (updatedTask) { - const notification = TaskStatusNotificationSchema.parse({ - method: "notifications/tasks/status", - params: updatedTask - }); - await this.notification(notification); - if (isTerminal(updatedTask.status)) { - this._cleanupTaskProgressHandler(taskId); - } - } - }, - listTasks: (cursor) => { - return taskStore.listTasks(cursor, sessionId); - } - }; } -}; -function isPlainObject2(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); + return required2.slice(0, maxRequired); } -function mergeCapabilities(base, additional) { - const result = { ...base }; - for (const key in additional) { - const k = key; - const addValue = additional[k]; - if (addValue === void 0) - continue; - const baseValue = result[k]; - if (isPlainObject2(baseValue) && isPlainObject2(addValue)) { - result[k] = { ...baseValue, ...addValue }; - } else { - result[k] = addValue; +function selectOptional(strategies, required2) { + const reqSet = new Set(required2); + return strategies.filter((s) => !reqSet.has(s.strategy) && s.tier <= 3).slice(0, 3).map((s) => s.strategy); +} +function selectForbidden(complexityTier) { + switch (complexityTier) { + case "complex": + return ["zero_shot", "chain_of_thought"]; + case "moderate": + return ["zero_shot"]; + case "simple": + return []; + } +} +function buildCitations(strategies) { + const citations = []; + for (const strategy of strategies) { + const evidence = db.getEvidence(strategy); + for (const ev of evidence.slice(0, 2)) { + citations.push(ev.citation); } } - return result; + return citations; } - -// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js -var import_ajv = __toESM(require_ajv(), 1); -var import_ajv_formats = __toESM(require_dist(), 1); -function createDefaultAjvInstance() { - const ajv2 = new import_ajv.default({ - strict: false, - validateFormats: true, - validateSchema: false, - allErrors: true - }); - const addFormats = import_ajv_formats.default; - addFormats(ajv2); - return ajv2; +function calculateExpectedImprovement(strategies, characteristics) { + if (strategies.length === 0) + return 0; + const improvements = strategies.map((s) => db.calculateScore(s, characteristics)); + return Math.max(...improvements); } -var AjvJsonSchemaValidator = class { - /** - * Create an AJV validator - * - * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. - * - * @example - * ```typescript - * // Use default configuration (recommended for most cases) - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // Or provide custom AJV instance for advanced configuration - * import { Ajv } from 'ajv'; - * import addFormats from 'ajv-formats'; - * - * const ajv = new Ajv({ validateFormats: true }); - * addFormats(ajv); - * const validator = new AjvJsonSchemaValidator(ajv); - * ``` - */ - constructor(ajv2) { - this._ajv = ajv2 ?? createDefaultAjvInstance(); +function calculateAssignmentConfidence(strategies, characteristics, complexityTier) { + let confidence = 0.5; + if (complexityTier === "complex") { + const hasTier1 = strategies.some((s) => db.getTier(s) === 1); + if (hasTier1) + confidence += 0.3; } - /** - * Create a validator for the given JSON Schema - * - * The validator is compiled once and can be reused multiple times. - * If the schema has an $id, it will be cached by AJV automatically. - * - * @param schema - Standard JSON Schema object - * @returns A validator function that validates input data - */ - getValidator(schema2) { - const ajvValidator = "$id" in schema2 && typeof schema2.$id === "string" ? this._ajv.getSchema(schema2.$id) ?? this._ajv.compile(schema2) : this._ajv.compile(schema2); - return (input) => { - const valid = ajvValidator(input); - if (valid) { - return { - valid: true, - data: input, - errorMessage: void 0 - }; - } else { - return { - valid: false, - data: void 0, - errorMessage: this._ajv.errorsText(ajvValidator.errors) - }; + let totalOverlap = 0; + for (const strategy of strategies) { + for (const ev of db.getEvidence(strategy)) { + const evChars = new Set(ev.claimCharacteristics); + for (const c of characteristics) { + if (evChars.has(c)) + totalOverlap++; } + } + } + confidence += Math.min(0.2, totalOverlap * 0.02); + return Math.min(1, confidence); +} +function selectStrategy(options) { + const { + claim, + context, + hasCodebase = false, + hasMockups = false, + evidenceRepository, + // source: chosen heuristically — overlap dominates over raw expectedImprovement + // because matched claim characteristics correlate more strongly with success + // than abstract improvement claims. Tune from execution history. + overlapWeight = 0.6, + // source: chosen heuristically — strategies whose marginal improvement falls + // below 5 percentage points are filtered as not worth the cost overhead. + // Calibrate against (cost, accuracy_delta) pairs in evidence repository. + minimumImprovementThreshold = 0.05, + maxRequiredStrategies = 3 + } = options; + const analysis = analyzeClaim(claim, context); + const characteristics = new Set(analysis.characteristics); + if (hasCodebase) { + characteristics.add("codebase_integration"); + characteristics.add("tool_use"); + } + if (hasMockups) { + characteristics.add("visual_reasoning"); + characteristics.add("multimodal"); + } + let historicalAdjustments = /* @__PURE__ */ new Map(); + if (evidenceRepository) { + historicalAdjustments = evidenceRepository.getHistoricalAdjustments(); + } + const scored = scoreStrategies(characteristics, historicalAdjustments, overlapWeight, minimumImprovementThreshold); + const allowed = new Set(CAPABILITIES.allowedStrategies); + const allowedScored = scored.filter((s) => allowed.has(s.strategy)); + const constrained = applyComplexityConstraints(allowedScored, analysis.complexityTier); + const enrichedAnalysis = { + ...analysis, + characteristics: [...characteristics] + }; + const required2 = selectRequired(constrained, enrichedAnalysis, maxRequiredStrategies); + const optional2 = selectOptional(constrained, required2); + const forbidden = selectForbidden(analysis.complexityTier); + const allSelected = [...required2, ...optional2]; + const researchCitations = buildCitations(allSelected); + const expectedImprovement = calculateExpectedImprovement(required2, characteristics); + const assignmentConfidence = calculateAssignmentConfidence(required2, characteristics, analysis.complexityTier); + return { + required: required2, + optional: optional2, + forbidden, + expectedImprovement, + assignmentConfidence, + claimAnalysis: enrichedAnalysis, + researchCitations + }; +} + +// packages/strategy/dist/effectiveness-tracker.js +var ExecutionResultSchema = external_exports.object({ + strategy: ThinkingStrategySchema, + assignment: StrategyAssignmentSchema, + actualConfidenceGain: external_exports.number(), + wasCompliant: external_exports.boolean(), + retryCount: external_exports.number().int().nonnegative(), + prdContext: PRDContextSchema, + sessionId: external_exports.string().optional() +}); +var EffectivenessTracker = class { + repository; + constructor(repository) { + this.repository = repository; + } + recordExecution(result) { + const execution = { + strategy: result.strategy, + claimCharacteristics: [...result.assignment.claimAnalysis.characteristics], + complexityTier: result.assignment.claimAnalysis.complexityTier, + expectedImprovement: result.assignment.expectedImprovement, + actualConfidenceGain: result.actualConfidenceGain, + wasCompliant: result.wasCompliant, + retryCount: result.retryCount, + prdContext: result.prdContext + }; + this.repository.recordStrategyExecution(execution, result.sessionId); + } + generateReport(minExecutions = 5) { + const summaries = this.repository.getStrategyPerformance(minExecutions); + const totalMeasurements = summaries.reduce((s, r) => s + r.executionCount, 0); + const averageConfidenceGain = totalMeasurements === 0 ? 0 : summaries.reduce((s, r) => s + r.avgActualGain * r.executionCount, 0) / totalMeasurements; + const overallComplianceRate = totalMeasurements === 0 ? 0 : summaries.reduce((s, r) => s + r.complianceRate * r.executionCount, 0) / totalMeasurements; + const underperforming = summaries.filter((s) => s.performanceDelta < -0.2 * Math.abs(s.avgExpectedImprovement)).map((s) => s.strategy); + const overperforming = summaries.filter((s) => s.performanceDelta > 0.2 * Math.abs(s.avgExpectedImprovement)).map((s) => s.strategy); + return { + totalMeasurements, + averageConfidenceGain, + overallComplianceRate, + underperformingStrategies: underperforming, + overperformingStrategies: overperforming }; } }; -// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js -var ExperimentalServerTasks = class { - constructor(_server) { - this._server = _server; - } +// packages/orchestration/dist/types/state.js +var PipelineStepSchema = external_exports.enum([ + "banner", + "preflight", + "context_detection", + "input_analysis", + "feasibility_gate", + "clarification", + "budget", + "section_generation", + "jira_generation", + "file_export", + "self_check", + "complete" +]); +var SectionStatusSchema = external_exports.object({ + section_type: SectionTypeSchema, + status: external_exports.enum([ + "pending", + "retrieving", + "generating", + "passed", + "failed" + ]), + attempt: external_exports.number().int().nonnegative(), + violation_count: external_exports.number().int().nonnegative(), + last_violations: external_exports.array(external_exports.string()).default([]), + /** Markdown content of the section — populated after generation passes validation */ + content: external_exports.string().optional(), /** - * Sends a request and returns an AsyncGenerator that yields response messages. - * The generator is guaranteed to end with either a 'result' or 'error' message. - * - * This method provides streaming access to request processing, allowing you to - * observe intermediate task status updates for task-augmented requests. - * - * @param request - The request to send - * @param resultSchema - Zod schema for validating the result - * @param options - Optional request options (timeout, signal, task creation params, etc.) - * @returns AsyncGenerator that yields ResponseMessage objects + * Strategy assignment chosen by `@prd-gen/strategy.selectStrategy` at the + * pending → retrieving transition. Persisted on the section so retries + * use the SAME strategies (not re-selecting per attempt) and so + * `EffectivenessTracker.recordExecution` has the assignment to attribute + * the outcome to. * - * @experimental + * source: Phase 4 strategy-wiring (2026-04). Optional because the + * selection is gated by the orchestration layer; legacy state snapshots + * predating the wiring may be absent. */ - requestStream(request, resultSchema, options) { - return this._server.requestStream(request, resultSchema, options); - } + strategy_assignment: StrategyAssignmentSchema.optional(), /** - * Sends a sampling request and returns an AsyncGenerator that yields response messages. - * The generator is guaranteed to end with either a 'result' or 'error' message. + * Per-attempt observation log. One entry per draft attempt, recording + * exactly which violations were fed into the prompt for that attempt. * - * For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages - * before the final result. - * - * @example - * ```typescript - * const stream = server.experimental.tasks.createMessageStream({ - * messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }], - * maxTokens: 100 - * }, { - * onprogress: (progress) => { - * // Handle streaming tokens via progress notifications - * console.log('Progress:', progress.message); - * } - * }); + * Invariant: attempt_log.length === section.attempt at any stable point + * (after each validateAndAdvance call). The log is written BEFORE the + * next draft action is emitted, so the benchmark extraction reads it + * synchronously rather than inferring from terminal state only. * - * for await (const message of stream) { - * switch (message.type) { - * case 'taskCreated': - * console.log('Task created:', message.task.taskId); - * break; - * case 'taskStatus': - * console.log('Task status:', message.task.status); - * break; - * case 'result': - * console.log('Final result:', message.result); - * break; - * case 'error': - * console.error('Error:', message.error); - * break; - * } - * } - * ``` + * Field semantics: + * attempt — 1-indexed attempt number. + * violations_fed — the violation strings actually passed to the + * engineer subagent prompt for this attempt. + * Empty ([]) on attempt 1 (no prior violations exist). + * For attempt k≥2: the last_violations from the + * previous attempt — OR [] if the run is in the + * without_prior_violations ablation arm (D1.C). + * `violations_fed` is the OBSERVED value, not inferred + * from the arm; this closes the Curie A2 observability + * gap flagged in retry-observations.ts TODO(C1). * - * @param params - The sampling request parameters - * @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.) - * @returns AsyncGenerator that yields ResponseMessage objects + * Defaults to [] for backward compatibility with state snapshots predating + * Wave D1.B. * - * @experimental + * source: Phase 4.2 ablation design (PHASE_4_PLAN.md §4.2) — per-attempt + * precision required for Schoenfeld N≈2,070 analysis (curie cross-audit + * A2: instrumentation must observe behavior, not infer it). */ - createMessageStream(params, options) { - const clientCapabilities = this._server.getClientCapabilities(); - if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) { - throw new Error("Client does not support sampling tools capability."); - } - if (params.messages.length > 0) { - const lastMessage = params.messages[params.messages.length - 1]; - const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; - const hasToolResults = lastContent.some((c) => c.type === "tool_result"); - const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0; - const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; - const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); - if (hasToolResults) { - if (lastContent.some((c) => c.type !== "tool_result")) { - throw new Error("The last message must contain only tool_result content if any is present"); - } - if (!hasPreviousToolUse) { - throw new Error("tool_result blocks are not matching any tool_use from the previous message"); - } - } - if (hasPreviousToolUse) { - const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); - const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); - if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) { - throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match"); - } - } - } - return this.requestStream({ - method: "sampling/createMessage", - params - }, CreateMessageResultSchema, options); - } + attempt_log: external_exports.array(external_exports.object({ + attempt: external_exports.number().int().positive(), + violations_fed: external_exports.array(external_exports.string()).readonly() + })).readonly().default([]) +}); +var ClarificationTurnSchema = external_exports.object({ + round: external_exports.number().int().min(1), + question: external_exports.string(), + answer: external_exports.string().optional(), + asked_at: external_exports.string(), + answered_at: external_exports.string().optional() +}); +var VerificationPlanSnapshotSchema = external_exports.object({ + batch_id: external_exports.string(), + /** Claim IDs in dispatch order — index = invocation slot. */ + claim_ids: external_exports.array(external_exports.string()), + /** Judge identities, parallel to claim_ids by index. */ + judges: external_exports.array(AgentIdentitySchema) +}).refine((s) => s.claim_ids.length === s.judges.length, { + message: "VerificationPlanSnapshot: claim_ids and judges must have the same length (positional invariant \u2014 see self-check.ts:parseVerdictsFromSnapshot).", + path: ["judges"] +}); +var PipelineStateSchema = external_exports.object({ + run_id: external_exports.string(), + current_step: PipelineStepSchema, + prd_context: PRDContextSchema.nullable(), + feature_description: external_exports.string(), + codebase_path: external_exports.string().nullable(), /** - * Sends an elicitation request and returns an AsyncGenerator that yields response messages. - * The generator is guaranteed to end with either a 'result' or 'error' message. + * Filesystem path returned by automatised-pipeline `index_codebase` + * (response field `graph_path`). Subsequent graph-query tools (query_graph, + * get_symbol, etc.) use this as their `graph_path` argument. + */ + codebase_graph_path: external_exports.string().nullable(), + /** Output directory passed to `index_codebase` so retries are idempotent. */ + codebase_output_dir: external_exports.string().nullable(), + codebase_indexed: external_exports.boolean(), + /** + * Preflight gate state — `null` while preflight has not been attempted + * yet, `"ok"` once Cortex (and ai-architect, when a codebase is given) + * passed their liveness checks. Treated as a precondition: the runner + * may not enter section_generation while preflight is unset. * - * For task-augmented requests (especially URL-based elicitation), yields 'taskCreated' - * and 'taskStatus' messages before the final result. + * source: missing-Cortex bug found 2026-04-26 — silent per-section + * recall failures should surface as ONE clear startup error, not as + * degraded generation across every section. + */ + preflight_status: external_exports.enum(["ok", "skipped"]).nullable().default(null), + sections: external_exports.array(SectionStatusSchema).default([]), + clarifications: external_exports.array(ClarificationTurnSchema).default([]), + /** + * Set when the user types "proceed" or clarification reaches max rounds. + * Read by handleBudget to sanity-check that clarification finished cleanly + * before generation starts. + */ + proceed_signal: external_exports.boolean().default(false), + started_at: external_exports.string(), + updated_at: external_exports.string(), + /** Genuine error messages only. NOT a progress log. */ + errors: external_exports.array(external_exports.string()).default([]), + /** + * Parallel to `errors[]` (same length, same order). Tags each error as + * one of three kinds. pipeline-kpis.ts:structural_error_count reads + * `"structural"` count DIRECTLY rather than deriving it by subtraction. * - * @example - * ```typescript - * const stream = server.experimental.tasks.elicitInputStream({ - * mode: 'url', - * message: 'Please authenticate', - * elicitationId: 'auth-123', - * url: 'https://example.com/auth' - * }, { - * task: { ttl: 300000 } // Task-augmented for long-running auth flow - * }); + * "section_failure" — section validator failed after MAX_ATTEMPTS. + * 1-per-failed-section by convention. Section- + * level retries are not counted; only the final + * fail-out increments. KPI: section_fail_count. * - * for await (const message of stream) { - * switch (message.type) { - * case 'taskCreated': - * console.log('Task created:', message.task.taskId); - * break; - * case 'taskStatus': - * console.log('Task status:', message.task.status); - * break; - * case 'result': - * console.log('User action:', message.result.action); - * break; - * case 'error': - * console.error('Error:', message.error); - * break; - * } - * } - * ``` + * "structural" — handler bug, runner protocol violation, + * schema mismatch, uncaught exception. The KPI + * gate `structural_error_count_max=0` blocks + * any run with a structural defect. * - * @param params - The elicitation request parameters - * @param options - Optional request options (timeout, signal, task creation params, etc.) - * @returns AsyncGenerator that yields ResponseMessage objects + * "upstream_failure" — recoverable failure in an external service + * the pipeline tolerates (jira-generation + * subagent fails → continue without JIRA; + * index_codebase tool fails → fail input_analysis + * but do not blame the handler). Counted + * separately so the structural gate does not + * fire spuriously on real-LLM runs where + * upstream services have realistic flake rates + * (cross-audit curie H1, Phase 3+4 follow-up, + * 2026-04). * - * @experimental + * source: curie cross-audit H-2 (Phase 3+4, 2026-04) for the introduction + * of the parallel array; curie H1 (Phase 3+4 follow-up, 2026-04) for the + * upstream_failure split. */ - elicitInputStream(params, options) { - const clientCapabilities = this._server.getClientCapabilities(); - const mode2 = params.mode ?? "form"; - switch (mode2) { - case "url": { - if (!clientCapabilities?.elicitation?.url) { - throw new Error("Client does not support url elicitation."); - } - break; - } - case "form": { - if (!clientCapabilities?.elicitation?.form) { - throw new Error("Client does not support form elicitation."); - } - break; - } - } - const normalizedParams = mode2 === "form" && params.mode === void 0 ? { ...params, mode: "form" } : params; - return this.requestStream({ - method: "elicitation/create", - params: normalizedParams - }, ElicitResultSchema, options); - } + error_kinds: external_exports.array(external_exports.enum(["section_failure", "structural", "upstream_failure"])).default([]), + /** Paths of files successfully written during file_export. Append-only. */ + written_files: external_exports.array(external_exports.string()).default([]), /** - * Gets the current status of a task. + * Count of Cortex `recall` tool invocations that returned zero hits. + * A non-zero count indicates sections were generated without memory context, + * which degrades output quality. KPI gate: pipeline-kpis.ts reads this field + * directly to surface the metric without post-hoc regex parsing. * - * @param taskId - The task identifier - * @param options - Optional request options - * @returns The task status + * Incremented in section-generation.ts at the retrieving→generating + * transition when summarizeRecall returns an empty string (data.results is + * absent, empty, or all entries have no content). * - * @experimental + * source: shannon S-6 (Phase 3+4 cross-audit, 2026-04) — load-bearing + * quantity needed for recall-efficacy analysis. */ - async getTask(taskId, options) { - return this._server.getTask({ taskId }, options); - } + cortex_recall_empty_count: external_exports.number().int().nonnegative().default(0), /** - * Retrieves the result of a completed task. - * - * @param taskId - The task identifier - * @param resultSchema - Zod schema for validating the result - * @param options - Optional request options - * @returns The task result - * - * @experimental + * Verification plan dispatched in self-check Phase A. Set during Phase A; + * read in Phase B to attribute verdicts. Null until Phase A runs. */ - async getTaskResult(taskId, resultSchema, options) { - return this._server.getTaskResult({ taskId }, resultSchema, options); - } + verification_plan: VerificationPlanSnapshotSchema.nullable().default(null), /** - * Lists tasks with optional pagination. + * Append-only queue of strategy execution results, populated when a + * section transitions to a terminal status (passed/failed). The + * composition root (mcp-server) drains this queue after each step and + * forwards entries to `EffectivenessTracker.recordExecution` so the + * closed feedback loop populates `EvidenceRepository`. * - * @param cursor - Optional pagination cursor - * @param options - Optional request options - * @returns List of tasks with optional next cursor + * Decouples orchestration (pure reducer) from infrastructure (SQLite + * persistence) per §2.2: the reducer emits data; the composition + * root is the only layer that performs I/O. * - * @experimental + * source: Phase 4 strategy-wiring (2026-04). */ - async listTasks(cursor, options) { - return this._server.listTasks(cursor ? { cursor } : void 0, options); - } + strategy_executions: external_exports.array(ExecutionResultSchema).default([]), /** - * Cancels a running task. + * Per-run retry policy injected by the composition root (mcp-server) before + * handing the state to the reducer. The reducer reads this field only — + * it never calls `getRetryArmForRun` or `getMaxAttemptsForRun` directly, + * preserving layer purity (§1.5 DIP / §2.2 layer rule: orchestration must + * not import from benchmark). * - * @param taskId - The task identifier - * @param options - Optional request options + * Fields: + * maxAttempts — effective max attempts for this run (may differ from the + * baseline MAX_ATTEMPTS for calibration treatment runs). + * arm — ablation arm: "with_prior_violations" feeds last_violations + * to the retry prompt; "without_prior_violations" feeds []. * - * @experimental + * Defaults to null (= use MAX_ATTEMPTS baseline, with_prior_violations arm) + * for backward compatibility. Wave D2 wires the composition root to populate + * this field using getRetryArmForRun + getMaxAttemptsForRun from the + * benchmark layer before starting the run. + * + * ADR (Wave D1.C, 2026-04-27): the seam is on the state object, not on a + * separate config argument, so that the runner's pure reducer signature + * (state → action) does not acquire a new parameter. State is the single + * authority for all reducer inputs. The composition root is the only site + * that calls benchmark-layer seams (§5.2 composition root pattern). + * + * source: Phase 4.2 ablation design (PHASE_4_PLAN.md §4.2). + * source: §1.5 DIP — high-level modules must not depend on low-level modules. + * source: §5.2 factory / composition root pattern. */ - async cancelTask(taskId, options) { - return this._server.cancelTask({ taskId }, options); - } -}; - -// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js -function assertToolsCallTaskCapability(requests, method, entityName) { - if (!requests) { - throw new Error(`${entityName} does not support task creation (required for ${method})`); - } - switch (method) { - case "tools/call": - if (!requests.tools?.call) { - throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`); - } - break; - default: - break; - } + // B9 — RetryPolicy is colocated with PipelineState rather than in a standalone + // retry-policy.ts file because it is structurally dependent on the state shape: + // the Zod schema here is an inline object (not a named Schema reference) so + // it participates in PipelineStateSchema's refinement chain and Zod inference + // without a separate parse boundary. The D1.C spec referenced a standalone + // file; this was intentionally inlined during Wave D1 implementation to keep + // the type adjacent to its only consumer (PipelineState). Any future caller + // that needs the RetryPolicy type standalone can do: + // type RetryPolicy = NonNullable + // source: Wave D B9 ADR (2026-04-27). + retry_policy: external_exports.object({ + maxAttempts: external_exports.number().int().positive(), + arm: external_exports.enum(["with_prior_violations", "without_prior_violations"]) + }).nullable().default(null) +}).refine((s) => s.errors.length === s.error_kinds.length, { + message: "PipelineState: errors[] and error_kinds[] must have the same length (lockstep invariant \u2014 use appendError() to append, never spread directly).", + path: ["error_kinds"] +}); +function newPipelineState(input) { + const now = (/* @__PURE__ */ new Date()).toISOString(); + return PipelineStateSchema.parse({ + run_id: input.run_id, + current_step: "banner", + prd_context: null, + feature_description: input.feature_description, + codebase_path: input.codebase_path ?? null, + codebase_graph_path: null, + codebase_output_dir: null, + codebase_indexed: false, + preflight_status: input.skip_preflight ? "skipped" : null, + sections: [], + clarifications: [], + proceed_signal: false, + started_at: now, + updated_at: now, + errors: [], + written_files: [], + verification_plan: null, + strategy_executions: [] + }); } -function assertClientRequestTaskCapability(requests, method, entityName) { - if (!requests) { - throw new Error(`${entityName} does not support task creation (required for ${method})`); - } - switch (method) { - case "sampling/createMessage": - if (!requests.sampling?.createMessage) { - throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`); - } - break; - case "elicitation/create": - if (!requests.elicitation?.create) { - throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`); - } - break; - default: - break; - } +function touch(state) { + return { ...state, updated_at: (/* @__PURE__ */ new Date()).toISOString() }; +} +function appendError(state, message, kind) { + return { + ...state, + errors: [...state.errors, message], + error_kinds: [...state.error_kinds, kind] + }; } -// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js -var Server = class extends Protocol { - /** - * Initializes this server with the given name and version information. - */ - constructor(_serverInfo, options) { - super(options); - this._serverInfo = _serverInfo; - this._loggingLevels = /* @__PURE__ */ new Map(); - this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index2) => [level, index2])); - this.isMessageIgnored = (level, sessionId) => { - const currentLevel = this._loggingLevels.get(sessionId); - return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; - }; - this._capabilities = options?.capabilities ?? {}; - this._instructions = options?.instructions; - this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); - this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request)); - this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.()); - if (this._capabilities.logging) { - this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => { - const transportSessionId = extra.sessionId || extra.requestInfo?.headers["mcp-session-id"] || void 0; - const { level } = request.params; - const parseResult = LoggingLevelSchema.safeParse(level); - if (parseResult.success) { - this._loggingLevels.set(transportSessionId, parseResult.data); - } - return {}; - }); - } - } - /** - * Access experimental features. - * - * WARNING: These APIs are experimental and may change without notice. - * - * @experimental - */ - get experimental() { - if (!this._experimental) { - this._experimental = { - tasks: new ExperimentalServerTasks(this) - }; - } - return this._experimental; - } +// packages/orchestration/dist/types/actions.js +var AskUserActionSchema = external_exports.object({ + kind: external_exports.literal("ask_user"), + /** Identifies the question so the host can map answer → state */ + question_id: external_exports.string(), + header: external_exports.string().describe("Short prompt header for AskUserQuestion tool"), + description: external_exports.string().describe("Body explaining what we need from the user"), + options: external_exports.array(external_exports.object({ + label: external_exports.string(), + description: external_exports.string().optional() + })).min(2).max(4).nullable().describe("Structured options for AskUserQuestion. Null = freeform answer."), + multi_select: external_exports.boolean().default(false) +}); +var CallPipelineToolActionSchema = external_exports.object({ + kind: external_exports.literal("call_pipeline_tool"), + tool_name: external_exports.string().describe("automatised-pipeline MCP tool name"), + arguments: external_exports.record(external_exports.string(), external_exports.unknown()), + /** Opaque routing token — host echoes it back unchanged on the corresponding tool_result. */ + correlation_id: external_exports.string() +}); +var CallCortexToolActionSchema = external_exports.object({ + kind: external_exports.literal("call_cortex_tool"), + tool_name: external_exports.string().describe("Cortex MCP tool name"), + arguments: external_exports.record(external_exports.string(), external_exports.unknown()), + /** Opaque routing token — host echoes it back unchanged on the corresponding tool_result. */ + correlation_id: external_exports.string() +}); +var SpawnSubagentsActionSchema = external_exports.object({ + kind: external_exports.literal("spawn_subagents"), + /** Multiple invocations to run IN PARALLEL — host MUST issue them in one message */ + invocations: external_exports.array(external_exports.object({ + invocation_id: external_exports.string(), + subagent_type: external_exports.string(), + description: external_exports.string(), + prompt: external_exports.string(), + isolation: external_exports.enum(["worktree", "none"]).default("none") + })), + /** Identifies the batch so the runner can route the batch result on submission. */ + batch_id: external_exports.string(), /** - * Registers new capabilities. This can only be called before connecting to a transport. - * - * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + * Observability label only — host dispatch logic MUST NOT branch on this + * field. It exists so logs and telemetry can attribute batches to a high- + * level intent (judging vs drafting vs reviewing). */ - registerCapabilities(capabilities) { - if (this.transport) { - throw new Error("Cannot register capabilities after connecting to transport"); - } - this._capabilities = mergeCapabilities(this._capabilities, capabilities); - } + purpose: external_exports.enum(["judge", "draft", "review"]) +}); +var WriteFileActionSchema = external_exports.object({ + kind: external_exports.literal("write_file"), + path: external_exports.string(), + content: external_exports.string() +}); +var EmitMessageActionSchema = external_exports.object({ + kind: external_exports.literal("emit_message"), + message: external_exports.string(), + level: external_exports.enum(["info", "warn", "error"]).default("info") +}); +var VerificationSummarySchema = external_exports.object({ + claims_evaluated: external_exports.number().int().nonnegative(), + distribution: external_exports.record(VerdictSchema, external_exports.number().int().nonnegative()), + distribution_suspicious: external_exports.boolean() +}); +var DoneActionSchema = external_exports.object({ + kind: external_exports.literal("done"), + summary: external_exports.string(), + artifacts: external_exports.array(external_exports.string()).default([]), /** - * Override request handler registration to enforce server-side validation for tools/call. + * Typed verification summary. Optional only because not every `done` + * emission has run the judge phase (zero-claim short-circuit, malformed + * input, etc.). When present, KPI extractors and tests MUST read this + * field — never regex-parse `summary`. */ - setRequestHandler(requestSchema, handler) { - const shape = getObjectShape(requestSchema); - const methodSchema = shape?.method; - if (!methodSchema) { - throw new Error("Schema is missing a method literal"); - } - let methodValue; - if (isZ4Schema(methodSchema)) { - const v4Schema = methodSchema; - const v4Def = v4Schema._zod?.def; - methodValue = v4Def?.value ?? v4Schema.value; - } else { - const v3Schema = methodSchema; - const legacyDef = v3Schema._def; - methodValue = legacyDef?.value ?? v3Schema.value; - } - if (typeof methodValue !== "string") { - throw new Error("Schema method literal must be a string"); - } - const method = methodValue; - if (method === "tools/call") { - const wrappedHandler = async (request, extra) => { - const validatedRequest = safeParse2(CallToolRequestSchema, request); - if (!validatedRequest.success) { - const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); - throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`); - } - const { params } = validatedRequest.data; - const result = await Promise.resolve(handler(request, extra)); - if (params.task) { - const taskValidationResult = safeParse2(CreateTaskResultSchema, result); - if (!taskValidationResult.success) { - const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error); - throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`); - } - return taskValidationResult.data; - } - const validationResult = safeParse2(CallToolResultSchema, result); - if (!validationResult.success) { - const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); - throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`); - } - return validationResult.data; - }; - return super.setRequestHandler(requestSchema, wrappedHandler); - } - return super.setRequestHandler(requestSchema, handler); - } - assertCapabilityForMethod(method) { - switch (method) { - case "sampling/createMessage": - if (!this._clientCapabilities?.sampling) { - throw new Error(`Client does not support sampling (required for ${method})`); - } - break; - case "elicitation/create": - if (!this._clientCapabilities?.elicitation) { - throw new Error(`Client does not support elicitation (required for ${method})`); - } - break; - case "roots/list": - if (!this._clientCapabilities?.roots) { - throw new Error(`Client does not support listing roots (required for ${method})`); - } - break; - case "ping": - break; + verification: VerificationSummarySchema.optional() +}); +var FailedActionSchema = external_exports.object({ + kind: external_exports.literal("failed"), + reason: external_exports.string(), + step: external_exports.string() +}); +var HandlerActionSchema = external_exports.discriminatedUnion("kind", [ + AskUserActionSchema, + CallPipelineToolActionSchema, + CallCortexToolActionSchema, + SpawnSubagentsActionSchema, + WriteFileActionSchema, + EmitMessageActionSchema, + DoneActionSchema, + FailedActionSchema +]); +var NextActionSchema = external_exports.discriminatedUnion("kind", [ + AskUserActionSchema, + CallPipelineToolActionSchema, + CallCortexToolActionSchema, + SpawnSubagentsActionSchema, + WriteFileActionSchema, + DoneActionSchema, + FailedActionSchema +]); +var UserAnswerSchema = external_exports.object({ + kind: external_exports.literal("user_answer"), + question_id: external_exports.string(), + selected: external_exports.array(external_exports.string()).default([]), + freeform: external_exports.string().optional() +}); +var ToolResultSchema = external_exports.object({ + kind: external_exports.literal("tool_result"), + correlation_id: external_exports.string(), + success: external_exports.boolean(), + data: external_exports.unknown(), + error: external_exports.string().optional() +}); +var SubagentBatchResultSchema = external_exports.object({ + kind: external_exports.literal("subagent_batch_result"), + batch_id: external_exports.string(), + responses: external_exports.array(external_exports.object({ + invocation_id: external_exports.string(), + raw_text: external_exports.string().optional(), + error: external_exports.string().optional() + })) +}); +var FileWrittenSchema = external_exports.object({ + kind: external_exports.literal("file_written"), + path: external_exports.string(), + bytes: external_exports.number().int().nonnegative() +}); +var ActionResultSchema = external_exports.discriminatedUnion("kind", [ + UserAnswerSchema, + ToolResultSchema, + SubagentBatchResultSchema, + FileWrittenSchema +]); + +// packages/orchestration/dist/section-plan.js +var SECTIONS_BY_CONTEXT = { + proposal: [ + "overview", + "goals", + "requirements", + "user_stories", + "acceptance_criteria", + "timeline", + "risks" + ], + feature: [ + "overview", + "goals", + "requirements", + "user_stories", + "technical_specification", + "acceptance_criteria", + "data_model", + "api_specification", + "security_considerations", + "performance_requirements", + "testing" + ], + bug: [ + "overview", + "requirements", + "technical_specification", + "acceptance_criteria", + "testing", + "deployment" + ], + incident: [ + "overview", + "requirements", + "technical_specification", + "acceptance_criteria", + "security_considerations", + "testing", + "deployment", + "risks" + ], + poc: [ + "overview", + "goals", + "requirements", + "technical_specification", + "acceptance_criteria" + ], + mvp: [ + "overview", + "goals", + "requirements", + "user_stories", + "technical_specification", + "acceptance_criteria", + "testing", + "timeline" + ], + release: [ + "overview", + "goals", + "requirements", + "technical_specification", + "acceptance_criteria", + "security_considerations", + "performance_requirements", + "testing", + "deployment", + "timeline" + ], + cicd: [ + "overview", + "goals", + "requirements", + "technical_specification", + "acceptance_criteria", + "security_considerations", + "testing", + "deployment", + "timeline" + ] +}; +var SECTION_RECALL_TEMPLATES = { + overview: "high-level architecture domain context for {feature}", + goals: "business goals success metrics KPIs for {feature}", + requirements: "public API surfaces exports interfaces contracts for {feature}", + user_stories: "user flows personas use cases for {feature}", + technical_specification: "architecture patterns module structure dependencies for {feature}", + acceptance_criteria: "test scenarios validation rules edge cases for {feature}", + data_model: "database schema tables relationships data types for {feature}", + api_specification: "REST GraphQL endpoints routes handlers middleware for {feature}", + security_considerations: "authentication authorization encryption validation secrets for {feature}", + performance_requirements: "latency throughput caching scalability targets for {feature}", + testing: "test patterns fixtures assertions coverage for {feature}", + deployment: "deployment configuration infrastructure CI/CD environments for {feature}", + risks: "error handling edge cases failure modes risks for {feature}", + timeline: "milestones phases release schedule for {feature}", + source_code: "implementation source code patterns for {feature}", + test_code: "test code patterns assertions for {feature}", + // jira_tickets is generated from the PRD itself, not from a Cortex query. + jira_tickets: "" +}; + +// packages/orchestration/dist/handlers/banner.js +var handleBanner = ({ state }) => { + const message = [ + "PRD Spec Generator", + `Run ID: ${state.run_id}`, + `Allowed strategies: ${CAPABILITIES.allowedStrategies.length}`, + `Allowed PRD contexts: ${CAPABILITIES.allowedContextTypes.length}`, + "", + `Feature: ${state.feature_description}`, + state.codebase_path ? `Codebase: ${state.codebase_path}` : "Codebase: (none provided)" + ].join("\n"); + return { + state: { ...state, current_step: "preflight" }, + action: { + kind: "emit_message", + message, + level: "info" } + }; +}; + +// packages/orchestration/dist/handlers/preflight.js +var CORTEX_PROBE_CORRELATION = "preflight_cortex_probe"; +var AI_ARCHITECT_PROBE_CORRELATION = "preflight_ai_architect_probe"; +function adviseCortexInstall() { + return [ + "Cortex MCP not reachable.", + "", + "The pipeline relies on Cortex for per-section memory recall during", + "section generation. Without it, every section is drafted without", + "prior-decision context \u2014 generation quality degrades silently.", + "", + "To install:", + " /plugin marketplace add cdeust/cortex", + " /plugin install cortex@cortex-plugins", + " /reload-plugins", + "", + "If you genuinely want to run without Cortex, re-invoke", + "start_pipeline with skip_preflight: true (degraded mode)." + ].join("\n"); +} +function adviseAiArchitectInstall() { + return [ + "automatised-pipeline (ai-architect) MCP not reachable.", + "", + "A codebase_path was supplied, which requires the automatised-pipeline", + "MCP for index_codebase + downstream graph queries.", + "", + "To install:", + " /plugin marketplace add cdeust/automatised-pipeline", + " /plugin install automatised-pipeline@automatised-pipeline-marketplace", + " /reload-plugins", + "", + "If you only need PRD generation without codebase analysis, omit", + "codebase_path on the next start_pipeline call." + ].join("\n"); +} +var handlePreflight = ({ state, result }) => { + if (state.preflight_status === "skipped") { + return { + state: { ...state, current_step: "context_detection" }, + action: { + kind: "emit_message", + message: "Preflight skipped (skip_preflight=true). Section generation will proceed without Cortex recall context if Cortex is unavailable.", + level: "warn" + } + }; } - assertNotificationCapability(method) { - switch (method) { - case "notifications/message": - if (!this._capabilities.logging) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - case "notifications/resources/updated": - case "notifications/resources/list_changed": - if (!this._capabilities.resources) { - throw new Error(`Server does not support notifying about resources (required for ${method})`); - } - break; - case "notifications/tools/list_changed": - if (!this._capabilities.tools) { - throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); - } - break; - case "notifications/prompts/list_changed": - if (!this._capabilities.prompts) { - throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); - } - break; - case "notifications/elicitation/complete": - if (!this._clientCapabilities?.elicitation?.url) { - throw new Error(`Client does not support URL elicitation (required for ${method})`); - } - break; - case "notifications/cancelled": - break; - case "notifications/progress": - break; - } + if (state.preflight_status === "ok") { + return { + state: { ...state, current_step: "context_detection" }, + action: { + kind: "emit_message", + message: "Preflight already passed. Proceeding to context detection." + } + }; } - assertRequestHandlerCapability(method) { - if (!this._capabilities) { - return; - } - switch (method) { - case "completion/complete": - if (!this._capabilities.completions) { - throw new Error(`Server does not support completions (required for ${method})`); - } - break; - case "logging/setLevel": - if (!this._capabilities.logging) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - case "prompts/get": - case "prompts/list": - if (!this._capabilities.prompts) { - throw new Error(`Server does not support prompts (required for ${method})`); - } - break; - case "resources/list": - case "resources/templates/list": - case "resources/read": - if (!this._capabilities.resources) { - throw new Error(`Server does not support resources (required for ${method})`); - } - break; - case "tools/call": - case "tools/list": - if (!this._capabilities.tools) { - throw new Error(`Server does not support tools (required for ${method})`); + if (result?.kind === "tool_result" && result.correlation_id === CORTEX_PROBE_CORRELATION) { + if (!result.success) { + return { + state: appendError(state, `preflight: cortex unreachable (${result.error ?? "unknown error"})`, "upstream_failure"), + action: { + kind: "failed", + reason: adviseCortexInstall(), + step: "preflight" } - break; - case "tasks/get": - case "tasks/list": - case "tasks/result": - case "tasks/cancel": - if (!this._capabilities.tasks) { - throw new Error(`Server does not support tasks capability (required for ${method})`); + }; + } + if (state.codebase_path) { + return { + state, + action: { + kind: "call_pipeline_tool", + tool_name: "health_check", + arguments: {}, + correlation_id: AI_ARCHITECT_PROBE_CORRELATION } - break; - case "ping": - case "initialize": - break; + }; } + return { + state: { + ...state, + preflight_status: "ok", + current_step: "context_detection" + }, + action: { + kind: "emit_message", + message: "Preflight passed: Cortex reachable. (no codebase \u2192 ai-architect probe skipped)" + } + }; } - assertTaskCapability(method) { - assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, "Client"); + if (result?.kind === "tool_result" && result.correlation_id === AI_ARCHITECT_PROBE_CORRELATION) { + if (!result.success) { + return { + state: appendError(state, `preflight: ai-architect unreachable (${result.error ?? "unknown error"})`, "upstream_failure"), + action: { + kind: "failed", + reason: adviseAiArchitectInstall(), + step: "preflight" + } + }; + } + return { + state: { + ...state, + preflight_status: "ok", + current_step: "context_detection" + }, + action: { + kind: "emit_message", + message: "Preflight passed: Cortex + ai-architect reachable." + } + }; } - assertTaskHandlerCapability(method) { - if (!this._capabilities) { - return; + return { + state, + action: { + kind: "call_cortex_tool", + tool_name: "memory_stats", + arguments: {}, + correlation_id: CORTEX_PROBE_CORRELATION } - assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, "Server"); + }; +}; + +// packages/orchestration/dist/handlers/context-detection.js +var TRIGGER_WORDS = { + proposal: ["proposal", "pitch", "stakeholder"], + feature: ["feature", "build", "implement", "add support"], + bug: ["bug", "fix", "broken", "regression", "defect"], + incident: ["incident", "outage", "production issue", "p0", "p1"], + poc: ["poc", "proof of concept", "spike", "feasibility"], + mvp: ["mvp", "minimum viable", "v1"], + release: ["release", "ship", "production launch"], + cicd: ["ci", "cd", "ci/cd", "pipeline", "deploy automation"] +}; +function detectFromText(text) { + const lower = text.toLowerCase(); + for (const [ctx, triggers] of Object.entries(TRIGGER_WORDS)) { + if (triggers.some((t) => lower.includes(t))) + return ctx; } - async _oninitialize(request) { - const requestedVersion = request.params.protocolVersion; - this._clientCapabilities = request.params.capabilities; - this._clientVersion = request.params.clientInfo; - const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION; + return null; +} +var QUESTION_ID = "prd_context"; +var handleContextDetection = ({ state, result }) => { + if (state.prd_context) { return { - protocolVersion, - capabilities: this.getCapabilities(), - serverInfo: this._serverInfo, - ...this._instructions && { instructions: this._instructions } + state: { ...state, current_step: "input_analysis" }, + action: { + kind: "emit_message", + message: `PRD context: ${PRD_CONTEXT_CONFIGS[state.prd_context].displayName}` + } }; } - /** - * After initialization has completed, this will be populated with the client's reported capabilities. - */ - getClientCapabilities() { - return this._clientCapabilities; - } - /** - * After initialization has completed, this will be populated with information about the client's name and version. - */ - getClientVersion() { - return this._clientVersion; + if (result?.kind === "user_answer" && result.question_id === QUESTION_ID) { + const choice = result.selected[0] ?? result.freeform ?? ""; + const parsed = PRDContextSchema.safeParse(choice); + if (!parsed.success) { + return { + state, + action: { + kind: "failed", + reason: `Invalid PRD context choice: ${choice}`, + step: "context_detection" + } + }; + } + return { + state: { + ...state, + prd_context: parsed.data, + current_step: "input_analysis" + }, + action: { + kind: "emit_message", + message: `PRD context: ${PRD_CONTEXT_CONFIGS[parsed.data].displayName}` + } + }; } - getCapabilities() { - return this._capabilities; + const detected = detectFromText(state.feature_description); + const allowed = CAPABILITIES.allowedContextTypes; + if (detected && allowed.includes(detected)) { + return { + state: { + ...state, + prd_context: detected, + current_step: "input_analysis" + }, + action: { + kind: "emit_message", + message: `PRD context detected: ${PRD_CONTEXT_CONFIGS[detected].displayName} (from trigger words)` + } + }; } - async ping() { - return this.request({ method: "ping" }, EmptyResultSchema); + const options = allowed.map((ctx) => ({ + label: ctx, + description: PRD_CONTEXT_CONFIGS[ctx].description + })); + return { + state, + action: { + kind: "ask_user", + question_id: QUESTION_ID, + header: "Which kind of PRD?", + description: "I couldn't infer the PRD type from your request. Pick the closest match \u2014 this configures clarification depth and section count.", + // source: protocol constraint. AskUserActionSchema.options enforces + // .max(4) at the schema level (types/actions.ts). Slicing here ensures + // a tier with >4 allowed contexts doesn't fail Zod parsing on the + // emitted action. Cross-audit code-reviewer H6 (Phase 3+4, 2026-04). + options: options.slice(0, 4), + multi_select: false + } + }; +}; + +// packages/orchestration/dist/handlers/input-analysis.js +import { join as join3 } from "node:path"; +var CORRELATION_ID = "input_analysis_index"; +function deriveOutputDir(codebasePath, runId) { + return join3(codebasePath, ".prd-gen", "graphs", runId); +} +var handleInputAnalysis = ({ state, result }) => { + if (!state.codebase_path) { + return { + state: { ...state, current_step: "feasibility_gate" }, + action: { + kind: "emit_message", + message: "No codebase provided. Skipping codebase analysis." + } + }; } - // Implementation - async createMessage(params, options) { - if (params.tools || params.toolChoice) { - if (!this._clientCapabilities?.sampling?.tools) { - throw new Error("Client does not support sampling tools capability."); + if (state.codebase_indexed && state.codebase_graph_path) { + return { + state: { ...state, current_step: "feasibility_gate" }, + action: { + kind: "emit_message", + message: `Codebase indexed (graph: ${state.codebase_graph_path}).` } - } - if (params.messages.length > 0) { - const lastMessage = params.messages[params.messages.length - 1]; - const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; - const hasToolResults = lastContent.some((c) => c.type === "tool_result"); - const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0; - const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; - const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); - if (hasToolResults) { - if (lastContent.some((c) => c.type !== "tool_result")) { - throw new Error("The last message must contain only tool_result content if any is present"); - } - if (!hasPreviousToolUse) { - throw new Error("tool_result blocks are not matching any tool_use from the previous message"); + }; + } + if (result?.kind === "tool_result" && result.correlation_id === CORRELATION_ID) { + if (!result.success) { + return { + state: appendError( + state, + `index_codebase failed: ${result.error ?? "unknown"}`, + // External tool failure — the pipeline gives up but it's not a + // handler bug. Cross-audit curie H1 (Phase 3+4 follow-up). + "upstream_failure" + ), + action: { + kind: "failed", + reason: `index_codebase failed: ${result.error ?? "unknown"}`, + step: "input_analysis" } - } - if (hasPreviousToolUse) { - const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); - const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); - if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) { - throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match"); + }; + } + const data = result.data ?? {}; + const graphPath = data.graph_path ?? null; + if (!graphPath) { + return { + state: appendError( + state, + `index_codebase succeeded but returned no graph_path`, + // The upstream tool advertised success but violated its own + // contract. From the orchestration layer's perspective this + // is the SAME class as the explicit-failure case above — + // a tool we can't act on. Tag it as upstream_failure so the + // structural gate doesn't conflate this with a handler bug. + "upstream_failure" + ), + action: { + kind: "failed", + reason: "index_codebase returned no graph_path", + step: "input_analysis" } + }; + } + return { + state: { + ...state, + codebase_indexed: true, + codebase_graph_path: graphPath, + current_step: "feasibility_gate" + }, + action: { + kind: "emit_message", + message: `Codebase indexed (graph: ${graphPath}).` } + }; + } + const outputDir = state.codebase_output_dir ?? deriveOutputDir(state.codebase_path, state.run_id); + return { + state: { ...state, codebase_output_dir: outputDir }, + action: { + kind: "call_pipeline_tool", + tool_name: "index_codebase", + arguments: { + path: state.codebase_path, + output_dir: outputDir, + language: "auto" + }, + correlation_id: CORRELATION_ID } - if (params.tools) { - return this.request({ method: "sampling/createMessage", params }, CreateMessageResultWithToolsSchema, options); + }; +}; + +// packages/orchestration/dist/handlers/feasibility-gate.js +var QUESTION_ID2 = "feasibility_focus"; +var EPIC_SIGNALS = [ + / and /i, + / & /, + /,\s*\w+\s*,/, + // multiple comma-separated items + /\bplus\b/i, + /\balso\b/i +]; +function looksEpic(text) { + const matches = EPIC_SIGNALS.filter((re2) => re2.test(text)).length; + return matches >= 2; +} +var handleFeasibilityGate = ({ state, result }) => { + if (result?.kind === "user_answer" && result.question_id === QUESTION_ID2) { + const focus = result.freeform ?? result.selected[0] ?? state.feature_description; + return { + state: { + ...state, + feature_description: focus, + current_step: "clarification" + }, + action: { + kind: "emit_message", + message: `Focused scope: ${focus}` + } + }; + } + if (looksEpic(state.feature_description)) { + return { + state, + action: { + kind: "ask_user", + question_id: QUESTION_ID2, + header: "This looks like an epic. Pick one focus.", + description: "Generating one PRD for multiple features at once produces shallow output. Which single piece should this PRD cover? Type a focused description.", + options: null, + multi_select: false + } + }; + } + return { + state: { ...state, current_step: "clarification" }, + action: { + kind: "emit_message", + message: "Scope acceptable. Proceeding to clarification." } - return this.request({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options); + }; +}; + +// packages/meta-prompting/dist/section-prompts.js +var COMMON_RULES = [ + "1. Output ONLY the section body. No surrounding prose, no JSON, no fences.", + "2. Start with `##
` exactly once.", + "3. Every Functional Requirement (FR-XXX) MUST cite a Source: user-request, clarification round, or codebase finding.", + "4. Acceptance Criteria use `AC-XXX` format starting from AC-001.", + "5. No `AnyCodable`, `AnyJSON` \u2014 heterogeneous JSON is an explicit type.", + "6. NFR claims (latency, throughput, fps, storage) MUST specify a measurement method.", + "7. Story-point totals must add up. No self-referencing dependencies.", + "8. Architectural patterns: ports/adapters in code examples, not frameworks in domain." +]; +var PER_SECTION_GUIDANCE = { + overview: "1-2 paragraphs. State problem, audience, success measure. No requirements here.", + goals: "Bulleted list of measurable goals. Each goal: outcome verb + target + measurement.", + requirements: "Markdown table: | ID | Requirement | Priority | Depends On | Source |. SP column FORBIDDEN here.", + user_stories: "Each story: As a , I want , so that . Include AC-XXX list per story.", + technical_specification: "Show ports (interfaces in domain) + adapters (impls in infrastructure) + composition root. No framework imports in domain.", + acceptance_criteria: "Numbered AC-001..AC-NNN. Each AC: Given/When/Then or one-line behaviour. Each AC must trace to one or more FR-XXX.", + data_model: "DDL for tables/types/enums. Every CREATE TYPE / CREATE TABLE must be referenced. NO `NOW()` in partial-index WHERE.", + api_specification: "Endpoint table: | Method | Path | Auth | Request | Response | Errors |. Match any HTTP-style ports from technical_specification.", + security_considerations: "Auth (mechanism), authz (matrix), data-at-rest, data-in-transit, secrets handling, audit logs. Cite STRIDE category per claim.", + performance_requirements: "p50/p95/p99 + measurement method (e.g., k6 script, prod APM). Verdict: SPEC-COMPLETE if method is named, NEEDS-RUNTIME otherwise.", + testing: "Coverage table: | Test name | Tests AC-XXX or FR-XXX | Type (unit/integration/e2e) | Status |. Real implementations only \u2014 no `// TODO` test bodies.", + deployment: "Phases (canary, full), rollback procedure, feature flags, monitoring/alerting hooks.", + risks: "Risk register: | Risk | Likelihood | Impact | Mitigation | Owner |. One row per risk.", + timeline: "Phases with sprint counts. Each phase total = sum of stories in that phase. Grand total = sum of phases." +}; +function renderStrategiesBlock(assignment) { + if (!assignment) + return ""; + const lines = [ + ``, + `Apply the following research-evidence-backed reasoning strategies:`, + "" + ]; + if (assignment.required.length > 0) { + lines.push(`REQUIRED (apply all of these):`); + for (const s of assignment.required) + lines.push(` - ${s}`); } - /** - * Creates an elicitation request for the given parameters. - * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`. - * @param params The parameters for the elicitation request. - * @param options Optional request options. - * @returns The result of the elicitation request. - */ - async elicitInput(params, options) { - const mode2 = params.mode ?? "form"; - switch (mode2) { - case "url": { - if (!this._clientCapabilities?.elicitation?.url) { - throw new Error("Client does not support url elicitation."); - } - const urlParams = params; - return this.request({ method: "elicitation/create", params: urlParams }, ElicitResultSchema, options); + if (assignment.optional.length > 0) { + lines.push(`OPTIONAL (apply if natural for this section):`); + for (const s of assignment.optional) + lines.push(` - ${s}`); + } + if (assignment.forbidden.length > 0) { + lines.push(`FORBIDDEN (do NOT apply \u2014 these have been shown to harm this kind of claim):`); + for (const s of assignment.forbidden) + lines.push(` - ${s}`); + } + if (assignment.researchCitations.length > 0) { + lines.push(""); + lines.push(`Citations backing this assignment:`); + for (const c of assignment.researchCitations) + lines.push(` - ${c}`); + } + lines.push(`Research-evidence baseline (population aggregate, NOT a per-section prediction): ${(assignment.expectedImprovement * 100).toFixed(1)}%`); + lines.push(`Assignment confidence: ${(assignment.assignmentConfidence * 100).toFixed(1)}%`); + lines.push(``); + return lines.join("\n"); +} +function buildSectionPrompt(input) { + const display = SECTION_DISPLAY_NAMES[input.section_type]; + const contextConfig = PRD_CONTEXT_CONFIGS[input.prd_context]; + const sectionGuidance = PER_SECTION_GUIDANCE[input.section_type] ?? "Follow the section's standard structure."; + const clarificationLines = input.clarification_qa.filter((c) => c.answer).map((c) => `Q: ${c.question} +A: ${c.answer}`).join("\n\n"); + const violationsBlock = input.prior_violations.length ? [ + ``, + `Attempt ${input.attempt - 1} produced violations:`, + input.prior_violations.map((v) => `- ${v}`).join("\n"), + `Fix every violation in this attempt.`, + `` + ].join("\n") : ""; + const strategiesBlock = renderStrategiesBlock(input.strategy_assignment); + return [ + `You draft section "${display}" of a ${contextConfig.displayName} PRD.`, + "", + `${input.feature_description}`, + "", + ``, + `PRD type: ${contextConfig.displayName}`, + `Focus: ${contextConfig.description}`, + `Attempt: ${input.attempt}`, + ``, + "", + input.recall_summary ? ` +${input.recall_summary} + +` : "", + clarificationLines ? ` +${clarificationLines} + +` : "", + violationsBlock, + violationsBlock ? "" : "", + strategiesBlock, + strategiesBlock ? "" : "", + ``, + sectionGuidance, + ``, + "", + ``, + COMMON_RULES.join("\n"), + ``, + "", + `Produce the "${display}" section now. Markdown only.` + ].filter((line) => line !== "").join("\n"); +} + +// packages/meta-prompting/dist/clarification-prompts.js +function buildClarificationPrompt(input) { + const ctx = PRD_CONTEXT_CONFIGS[input.prd_context]; + const priorBlock = input.prior_qa.length ? input.prior_qa.map((qa) => `Round ${input.round - input.prior_qa.length + 1}: +Q: ${qa.question} +A: ${qa.answer ?? "(no answer)"}`).join("\n\n") : "(no prior questions)"; + return [ + `You are eliciting requirements for a ${ctx.displayName} PRD.`, + "", + `${input.feature_description}`, + "", + `${input.round} of ${ctx.clarificationRange[1]}`, + "", + ``, + priorBlock, + ``, + "", + input.recall_summary ? ` +${input.recall_summary.slice(0, 2e3)} +` : "", + "", + ``, + `Generate ONE clarification question that:`, + `- Addresses the highest-uncertainty area not yet covered`, + `- Cannot be answered by reading prior answers or codebase context above`, + `- Has a concrete answer (not "tell me more about X")`, + ``, + "", + ``, + `Return EXACTLY ONE JSON object, nothing else:`, + `{`, + ` "question": "",`, + ` "options": ["` + ].filter((l) => l !== "").join("\n"); +} + +// packages/meta-prompting/dist/jira-prompts.js +var RULES = [ + "1. Output ONLY a markdown document. No JSON, no preamble, no fences.", + "2. AC IDs MUST match the AC-XXX IDs in the source. NEVER create new AC numbering.", + "3. Each ticket: ID (TICKET-NNN), Title, Description, Acceptance Criteria (referencing AC-XXX), Story Points (Fibonacci), Depends On, Source.", + "4. SP totals: Epic SP = sum of story SPs. Phase SP = sum of stories in phase. Grand total = sum of phases.", + "5. NEVER list a ticket as a self-dependency.", + "6. Distribute SP unevenly \u2014 real complexity is uneven.", + "7. Group tickets into Phases (Phase 1, Phase 2, ...) reflecting delivery order.", + "8. End with a Summary table: | Phase | Story Count | Total SP |." +]; +function buildJiraPrompt(input) { + const sourceBlock = input.source_sections.filter((s) => s.content).map((s) => `## Source: ${s.section_type} + +${s.content}`).join("\n\n"); + return [ + `You generate JIRA tickets from a PRD.`, + "", + `${input.feature_description}`, + "", + ``, + sourceBlock, + ``, + "", + ``, + RULES.join("\n"), + ``, + "", + `Produce the JIRA ticket document now.` + ].join("\n"); +} + +// packages/orchestration/dist/handlers/protocol-ids.js +var QUESTION_ID_CONTINUE = "clarification_continue"; +var CLARIFICATION_COMPOSE_INV_PREFIX = "clarification_compose_inv_"; +var SECTION_GENERATE_INV_PREFIX = "section_generate_"; +var SELF_CHECK_JUDGE_INV_PREFIX = "self_check_judge_"; +var JIRA_GENERATION_INV_ID = "jira_generation_engineer"; +function clarificationComposeInvocationId(round3) { + return `${CLARIFICATION_COMPOSE_INV_PREFIX}${round3}`; +} + +// packages/orchestration/dist/handlers/clarification.js +var QUESTION_ID_ANSWER = "clarification_answer"; +var COMPOSE_BATCH_PREFIX = "clarification_compose_"; +function composeBatchId(round3) { + return `${COMPOSE_BATCH_PREFIX}${round3}`; +} +var composeInvocationId = clarificationComposeInvocationId; +function isComposeResult(result, round3) { + return result?.kind === "subagent_batch_result" && result.batch_id === composeBatchId(round3); +} +function tryParseGeneratedQuestion(rawText) { + try { + const obj = extractJsonObject(rawText); + if (typeof obj.question !== "string" || !obj.question.trim()) + return null; + const options = Array.isArray(obj.options) && obj.options.every((o) => typeof o === "string") ? obj.options : null; + const rationale = typeof obj.rationale === "string" ? obj.rationale : ""; + return { question: obj.question.trim(), options, rationale }; + } catch { + return null; + } +} +function composeAction(state, round3) { + const prompt = buildClarificationPrompt({ + feature_description: state.feature_description, + prd_context: state.prd_context, + round: round3, + prior_qa: state.clarifications.map((c) => ({ + question: c.question, + answer: c.answer + })), + recall_summary: "" + }); + return { + kind: "spawn_subagents", + purpose: "draft", + batch_id: composeBatchId(round3), + invocations: [ + { + invocation_id: composeInvocationId(round3), + subagent_type: "zetetic-team-subagents:engineer", + description: `Compose clarification question (round ${round3})`, + prompt, + isolation: "none" } - case "form": { - if (!this._clientCapabilities?.elicitation?.form) { - throw new Error("Client does not support form elicitation."); - } - const formParams = params.mode === "form" ? params : { ...params, mode: "form" }; - const result = await this.request({ method: "elicitation/create", params: formParams }, ElicitResultSchema, options); - if (result.action === "accept" && result.content && formParams.requestedSchema) { - try { - const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema); - const validationResult = validator(result.content); - if (!validationResult.valid) { - throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); - } - } catch (error2) { - if (error2 instanceof McpError) { - throw error2; - } - throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error2 instanceof Error ? error2.message : String(error2)}`); - } - } - return result; + ] + }; +} +function askComposedQuestion(turn) { + const optionsForUser = turn.options && turn.options.length >= 2 && turn.options.length <= 4 ? turn.options.map((o) => ({ label: o })) : null; + return { + kind: "ask_user", + question_id: QUESTION_ID_ANSWER, + header: `Round ${turn.round}: ${turn.question}`, + description: turn.rationale || "Answer freeform if no options listed.", + options: optionsForUser, + multi_select: false + }; +} +function computeBounds(state) { + const config5 = PRD_CONTEXT_CONFIGS[state.prd_context]; + const max3 = Math.min(config5.clarificationRange[1], CAPABILITIES.maxClarificationRounds); + const min3 = Math.min(config5.clarificationRange[0], max3); + return { min: min3, max: max3 }; +} +function handleProceedOrContinue(state, result) { + const choice = (result.freeform ?? result.selected[0] ?? "").toLowerCase(); + if (choice.includes("proceed") || choice === "yes") { + return { + state: { ...state, proceed_signal: true, current_step: "budget" }, + action: { + kind: "emit_message", + message: `Clarification complete (${state.clarifications.length} rounds).` } - } + }; } - /** - * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` - * notification for the specified elicitation ID. - * - * @param elicitationId The ID of the elicitation to mark as complete. - * @param options Optional notification options. Useful when the completion notification should be related to a prior request. - * @returns A function that emits the completion notification when awaited. - */ - createElicitationCompletionNotifier(elicitationId, options) { - if (!this._clientCapabilities?.elicitation?.url) { - throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)"); - } - return () => this.notification({ - method: "notifications/elicitation/complete", - params: { - elicitationId + return { + state, + action: composeAction(state, state.clarifications.length + 1) + }; +} +function recordAnswerAndDispatch(state, result, bounds) { + const lastTurn = state.clarifications[state.clarifications.length - 1]; + if (!lastTurn || lastTurn.answer !== void 0) + return null; + const updatedTurn = { + ...lastTurn, + answer: result.freeform ?? result.selected.join(", "), + answered_at: (/* @__PURE__ */ new Date()).toISOString() + }; + const clarifications = [...state.clarifications.slice(0, -1), updatedTurn]; + const completed = clarifications.length; + if (completed >= bounds.max) { + return { + state: { + ...state, + clarifications, + proceed_signal: true, + current_step: "budget" + }, + action: { + kind: "emit_message", + message: `Reached max clarification rounds (${bounds.max}). Proceeding.` } - }, options); + }; } - async listRoots(params, options) { - return this.request({ method: "roots/list", params }, ListRootsResultSchema, options); + if (completed < bounds.min) { + return { + state: { ...state, clarifications }, + action: composeAction({ ...state, clarifications }, completed + 1) + }; } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON RPC message - * @see LoggingMessageNotification - * @param params - * @param sessionId optional for stateless and backward compatibility - */ - async sendLoggingMessage(params, sessionId) { - if (this._capabilities.logging) { - if (!this.isMessageIgnored(params.level, sessionId)) { - return this.notification({ method: "notifications/message", params }); - } + return { + state: { ...state, clarifications }, + action: { + kind: "ask_user", + question_id: QUESTION_ID_CONTINUE, + header: `Asked ${completed} questions. Proceed?`, + description: `Min for ${state.prd_context}: ${bounds.min}. Max: ${bounds.max}. 'proceed' to generate the PRD, 'continue' for more questions.`, + options: [ + { label: "proceed", description: "Generate the PRD now" }, + { label: "continue", description: "Ask another question" } + ], + multi_select: false } - } - async sendResourceUpdated(params) { - return this.notification({ - method: "notifications/resources/updated", - params - }); - } - async sendResourceListChanged() { - return this.notification({ - method: "notifications/resources/list_changed" - }); - } - async sendToolListChanged() { - return this.notification({ method: "notifications/tools/list_changed" }); - } - async sendPromptListChanged() { - return this.notification({ method: "notifications/prompts/list_changed" }); - } -}; - -// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js -var COMPLETABLE_SYMBOL = /* @__PURE__ */ Symbol.for("mcp.completable"); -function isCompletable(schema2) { - return !!schema2 && typeof schema2 === "object" && COMPLETABLE_SYMBOL in schema2; + }; } -function getCompleter(schema2) { - const meta = schema2[COMPLETABLE_SYMBOL]; - return meta?.complete; +function handleComposedQuestion(state, result, expectedRound) { + const response = result.responses.find((r) => r.invocation_id === composeInvocationId(expectedRound)); + const generated = response?.raw_text ? tryParseGeneratedQuestion(response.raw_text) : null; + const turn = generated ? { + round: expectedRound, + question: generated.question, + options: generated.options, + rationale: generated.rationale, + asked_at: (/* @__PURE__ */ new Date()).toISOString() + } : { + round: expectedRound, + question: response?.error ?? `What is the most important detail about "${state.feature_description}" that should drive this PRD?`, + options: null, + rationale: generated ? "" : "Subagent did not return a parseable question; using fallback.", + asked_at: (/* @__PURE__ */ new Date()).toISOString() + }; + return appendTurnAndAsk(state, turn); } -var McpZodTypeKind; -(function(McpZodTypeKind2) { - McpZodTypeKind2["Completable"] = "McpCompletable"; -})(McpZodTypeKind || (McpZodTypeKind = {})); - -// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js -var TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; -function validateToolName(name315) { - const warnings = []; - if (name315.length === 0) { - return { - isValid: false, - warnings: ["Tool name cannot be empty"] - }; - } - if (name315.length > 128) { +var handleClarification = ({ state, result }) => { + if (!state.prd_context) { return { - isValid: false, - warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name315.length})`] + state, + action: { + kind: "failed", + reason: "Clarification reached without PRD context", + step: "clarification" + } }; } - if (name315.includes(" ")) { - warnings.push("Tool name contains spaces, which may cause parsing issues"); - } - if (name315.includes(",")) { - warnings.push("Tool name contains commas, which may cause parsing issues"); + const bounds = computeBounds(state); + const expectedRound = state.clarifications.length + 1; + if (result?.kind === "user_answer" && result.question_id === QUESTION_ID_CONTINUE) { + return handleProceedOrContinue(state, result); } - if (name315.startsWith("-") || name315.endsWith("-")) { - warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"); + if (result?.kind === "user_answer" && result.question_id === QUESTION_ID_ANSWER) { + const out = recordAnswerAndDispatch(state, result, bounds); + if (out) + return out; } - if (name315.startsWith(".") || name315.endsWith(".")) { - warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"); + if (isComposeResult(result, expectedRound)) { + return handleComposedQuestion(state, result, expectedRound); } - if (!TOOL_NAME_REGEX.test(name315)) { - const invalidChars = name315.split("").filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index2, arr) => arr.indexOf(char) === index2); - warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"); + return { state, action: composeAction(state, expectedRound) }; +}; +function appendTurnAndAsk(state, turn) { + const clarifications = [ + ...state.clarifications, + { + round: turn.round, + question: turn.question, + asked_at: turn.asked_at + } + ]; + return { + state: { ...state, clarifications }, + action: askComposedQuestion(turn) + }; +} + +// packages/orchestration/dist/handlers/budget.js +var handleBudget = ({ state }) => { + if (!state.proceed_signal) { return { - isValid: false, - warnings + state, + action: { + kind: "failed", + reason: "budget step reached without proceed_signal \u2014 clarification did not exit cleanly", + step: "budget" + } }; } return { - isValid: true, - warnings + state: { ...state, current_step: "section_generation" }, + action: { + kind: "emit_message", + message: "Budget allocated. Starting section generation." + } + }; +}; + +// packages/orchestration/dist/handlers/section-generation-constants.js +var MAX_ATTEMPTS = 3; + +// packages/orchestration/dist/handlers/section-generation/validate-and-advance.js +function replaceSection(state, next) { + return { + ...state, + sections: state.sections.map((s) => s.section_type === next.section_type ? next : s) }; } -function issueToolNameWarning(name315, warnings) { - if (warnings.length > 0) { - console.warn(`Tool name validation warning for "${name315}":`); - for (const warning of warnings) { - console.warn(` - ${warning}`); - } - console.warn("Tool registration will proceed, but this may cause compatibility issues."); - console.warn("Consider updating the tool name to conform to the MCP tool naming standard."); - console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details."); - } +function buildExecutionResults(active, prdContext, passed) { + if (active.status !== "passed" && active.status !== "failed") + return []; + const assignment = active.strategy_assignment; + if (!assignment) + return []; + const strategies = assignment.required.length > 0 ? assignment.required : assignment.optional[0] ? [assignment.optional[0]] : []; + if (strategies.length === 0) + return []; + const attempts = Math.max(1, active.attempt); + const actualConfidenceGain = passed ? assignment.expectedImprovement : 0; + const retryCount = Math.max(0, attempts - 1); + return strategies.map((strategy) => ({ + strategy, + assignment, + actualConfidenceGain, + wasCompliant: passed, + retryCount, + prdContext + })); } -function validateAndWarnToolName(name315) { - const result = validateToolName(name315); - issueToolNameWarning(name315, result.warnings); - return result.isValid; +function applyRetryArmPolicy(state, active, violations) { + const attemptLogEntry = { + attempt: active.attempt, + violations_fed: [...active.last_violations] + }; + const arm = state.retry_policy?.arm ?? "with_prior_violations"; + const violationsForNextAttempt = arm === "without_prior_violations" ? [] : [...violations]; + return { violationsForNextAttempt, attemptLogEntry }; } - -// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js -var ExperimentalMcpServerTasks = class { - constructor(_mcpServer) { - this._mcpServer = _mcpServer; +function failSection(state, active, reason, draft, violations = []) { + const next = { + ...active, + status: "failed", + content: draft ?? active.content, + violation_count: violations.length || active.violation_count, + last_violations: [...violations] + }; + const stateWithSection = replaceSection(state, next); + let stateWithError = appendError(stateWithSection, `[section_generation:${active.section_type}] ${reason}`, "section_failure"); + if (state.prd_context) { + const execs = buildExecutionResults(next, state.prd_context, false); + if (execs.length > 0) { + stateWithError = { + ...stateWithError, + strategy_executions: [...stateWithError.strategy_executions, ...execs] + }; + } } - registerToolTask(name315, config5, handler) { - const execution = { taskSupport: "required", ...config5.execution }; - if (execution.taskSupport === "forbidden") { - throw new Error(`Cannot register task-based tool '${name315}' with taskSupport 'forbidden'. Use registerTool() instead.`); + return { + state: stateWithError, + action: { + kind: "emit_message", + level: "warn", + message: `\u2717 ${SECTION_DISPLAY_NAMES[active.section_type]}: ${reason}` } - const mcpServerInternal = this._mcpServer; - return mcpServerInternal._createRegisteredTool(name315, config5.title, config5.description, config5.inputSchema, config5.outputSchema, config5.annotations, execution, config5._meta, handler); + }; +} +function validateAndAdvance(state, active, draft, draftActionFn) { + const report = validateSection(draft, active.section_type); + const violations = report.violations.map((v) => `[${v.rule}] ${v.message}`); + const { violationsForNextAttempt, attemptLogEntry } = applyRetryArmPolicy(state, active, violations); + const activeWithLog = { + ...active, + attempt_log: [...active.attempt_log ?? [], attemptLogEntry] + }; + if (violations.length === 0) { + const next2 = { + ...activeWithLog, + status: "passed", + content: draft, + violation_count: 0, + last_violations: [] + }; + let stateWithSection = replaceSection(state, next2); + if (state.prd_context) { + const execs = buildExecutionResults(next2, state.prd_context, true); + if (execs.length > 0) { + stateWithSection = { + ...stateWithSection, + strategy_executions: [...stateWithSection.strategy_executions, ...execs] + }; + } + } + return { + state: stateWithSection, + action: { + kind: "emit_message", + message: `\u2713 ${SECTION_DISPLAY_NAMES[active.section_type]} passed validation (attempt ${active.attempt}).` + } + }; } -}; + const effectiveMaxAttempts = state.retry_policy?.maxAttempts ?? MAX_ATTEMPTS; + if (activeWithLog.attempt >= effectiveMaxAttempts) { + return failSection(state, activeWithLog, `Failed validation after ${effectiveMaxAttempts} attempts. Violations: ${violations.join("; ")}`, draft, violations); + } + const next = { + ...activeWithLog, + status: "generating", + content: draft, + attempt: activeWithLog.attempt + 1, + violation_count: violations.length, + last_violations: [...violationsForNextAttempt] + }; + const updatedState = replaceSection(state, next); + return { + state: updatedState, + action: draftActionFn(updatedState, next, "", violationsForNextAttempt) + }; +} -// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js -init_zod(); -var McpServer = class { - constructor(serverInfo, options) { - this._registeredResources = {}; - this._registeredResourceTemplates = {}; - this._registeredTools = {}; - this._registeredPrompts = {}; - this._toolHandlersInitialized = false; - this._completionHandlerInitialized = false; - this._resourceHandlersInitialized = false; - this._promptHandlersInitialized = false; - this.server = new Server(serverInfo, options); +// packages/orchestration/dist/handlers/section-generation.js +var RETRIEVE_PREFIX = "section_retrieve_"; +function correlationFor(prefix, sectionType) { + return `${prefix}${sectionType}`; +} +function ensureSectionsInitialized(state) { + if (state.sections.length > 0 || !state.prd_context) + return state; + const planned = SECTIONS_BY_CONTEXT[state.prd_context]; + const cap = CAPABILITIES.maxSections; + const allowed = planned.slice(0, cap); + const sections = allowed.map((section_type) => ({ + section_type, + status: "pending", + attempt: 0, + violation_count: 0, + last_violations: [], + attempt_log: [] + })); + return { ...state, sections }; +} +function findActiveSection(state) { + return state.sections.find((s) => s.status !== "passed" && s.status !== "failed"); +} +function recallAction(feature, sectionType) { + const template = SECTION_RECALL_TEMPLATES[sectionType]; + const query = template.replace("{feature}", feature); + return { + kind: "call_cortex_tool", + tool_name: "recall", + /** + * source: provisional heuristic. 8 results × ~500 tokens/memory ≈ 4K + * tokens of retrieval context per section, which fits comfortably + * inside the per-section retrieval budget computed by + * mcp-server/context-budget.ts (~2-5K depending on section weight). + * Cross-audit code-reviewer H6 (Phase 3+4, 2026-04). + */ + arguments: { query, max_results: 8 }, + correlation_id: correlationFor(RETRIEVE_PREFIX, sectionType) + }; +} +function draftAction(state, section, recall_summary, prior_violations) { + const display = SECTION_DISPLAY_NAMES[section.section_type]; + if (!state.prd_context) { + throw new Error(`section-generation reached without prd_context`); } - /** - * Access experimental features. - * - * WARNING: These APIs are experimental and may change without notice. - * - * @experimental - */ - get experimental() { - if (!this._experimental) { - this._experimental = { - tasks: new ExperimentalMcpServerTasks(this) - }; + const prompt = buildSectionPrompt({ + section_type: section.section_type, + feature_description: state.feature_description, + prd_context: state.prd_context, + recall_summary, + clarification_qa: state.clarifications.filter((c) => Boolean(c.answer)).map((c) => ({ question: c.question, answer: c.answer })), + prior_violations: [...prior_violations], + attempt: section.attempt, + // Phase 4 strategy-wiring (2026-04): pass the persisted assignment + // so every retry uses the SAME strategies the selector chose at the + // pending → retrieving transition. + strategy_assignment: section.strategy_assignment + }); + return { + kind: "spawn_subagents", + purpose: "draft", + batch_id: correlationFor(SECTION_GENERATE_INV_PREFIX, section.section_type), + invocations: [ + { + invocation_id: correlationFor(SECTION_GENERATE_INV_PREFIX, section.section_type), + subagent_type: "zetetic-team-subagents:engineer", + description: `Draft section: ${display}`, + prompt, + isolation: "none" + } + ] + }; +} +function failNoPrdContext(state) { + return { + state: appendError(state, "[section_generation] prd_context is null", "structural"), + action: { + kind: "failed", + reason: "section_generation reached without prd_context", + step: "section_generation" } - return this._experimental; + }; +} +function advanceToJira(init) { + return { + state: { ...init, current_step: "jira_generation" }, + action: { + kind: "emit_message", + message: "All sections processed. Generating JIRA tickets." + } + }; +} +function chooseStrategyForSection(state, section_type) { + const display = SECTION_DISPLAY_NAMES[section_type]; + return selectStrategy({ + claim: `${display}: ${state.feature_description}`, + context: section_type, + hasCodebase: state.codebase_indexed + }); +} +function startRetrieving(init, active) { + const assignment = active.strategy_assignment ?? chooseStrategyForSection(init, active.section_type); + const next = { + ...active, + status: "retrieving", + strategy_assignment: assignment + }; + return { + state: replaceSection(init, next), + action: recallAction(init.feature_description, active.section_type) + }; +} +function advanceFromRecall(init, active, data) { + const recallSummary = summarizeRecall(data); + const emptyRecall = recallSummary.length === 0; + const next = { + ...active, + status: "generating", + attempt: active.attempt + 1 + }; + const stateWithRecall = emptyRecall ? { + ...init, + cortex_recall_empty_count: init.cortex_recall_empty_count + 1 + } : init; + const updated = replaceSection(stateWithRecall, next); + return { + state: updated, + action: draftAction(updated, next, recallSummary, active.last_violations) + }; +} +function processDraft(init, active, result) { + const draft = collectDraftText(result, active.section_type); + if (!draft) { + return failSection(init, active, "Subagent returned empty draft"); } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. - */ - async connect(transport) { - return await this.server.connect(transport); + return validateAndAdvance(init, active, draft, draftAction); +} +function reissueStalled(init, active) { + if (active.status === "retrieving") { + return { + state: init, + action: recallAction(init.feature_description, active.section_type) + }; } - /** - * Closes the connection. - */ - async close() { - await this.server.close(); + return { + state: init, + action: draftAction(init, active, "", active.last_violations) + }; +} +var handleSectionGeneration = ({ state, result }) => { + if (!state.prd_context) { + return failNoPrdContext(state); + } + const init = ensureSectionsInitialized(state); + const active = findActiveSection(init); + if (!active) { + return advanceToJira(init); } - setToolRequestHandlers() { - if (this._toolHandlersInitialized) { - return; - } - this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)); - this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)); - this.server.registerCapabilities({ - tools: { - listChanged: true - } - }); - this.server.setRequestHandler(ListToolsRequestSchema, () => ({ - tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name315, tool]) => { - const toolDefinition = { - name: name315, - title: tool.title, - description: tool.description, - inputSchema: (() => { - const obj = normalizeObjectSchema(tool.inputSchema); - return obj ? toJsonSchemaCompat(obj, { - strictUnions: true, - pipeStrategy: "input" - }) : EMPTY_OBJECT_JSON_SCHEMA; - })(), - annotations: tool.annotations, - execution: tool.execution, - _meta: tool._meta - }; - if (tool.outputSchema) { - const obj = normalizeObjectSchema(tool.outputSchema); - if (obj) { - toolDefinition.outputSchema = toJsonSchemaCompat(obj, { - strictUnions: true, - pipeStrategy: "output" - }); - } - } - return toolDefinition; - }) - })); - this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { - try { - const tool = this._registeredTools[request.params.name]; - if (!tool) { - throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`); - } - if (!tool.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); - } - const isTaskRequest = !!request.params.task; - const taskSupport = tool.execution?.taskSupport; - const isTaskHandler = "createTask" in tool.handler; - if ((taskSupport === "required" || taskSupport === "optional") && !isTaskHandler) { - throw new McpError(ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`); - } - if (taskSupport === "required" && !isTaskRequest) { - throw new McpError(ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`); - } - if (taskSupport === "optional" && !isTaskRequest && isTaskHandler) { - return await this.handleAutomaticTaskPolling(tool, request, extra); - } - const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); - const result = await this.executeToolHandler(tool, args, extra); - if (isTaskRequest) { - return result; + if (active.status === "pending") { + return startRetrieving(init, active); + } + if (active.status === "retrieving" && result?.kind === "tool_result" && result.correlation_id === correlationFor(RETRIEVE_PREFIX, active.section_type)) { + return advanceFromRecall(init, active, result.data); + } + if (active.status === "generating" && result?.kind === "subagent_batch_result" && result.batch_id === correlationFor(SECTION_GENERATE_INV_PREFIX, active.section_type)) { + return processDraft(init, active, result); + } + return reissueStalled(init, active); +}; +var RECALL_MAX_RESULTS_INCLUDED = 8; +var RECALL_RESULT_TRUNCATE_CHARS = 800; +var RECALL_TRUNCATION_MARKER = "..."; +function summarizeRecall(data) { + if (!data || typeof data !== "object") + return ""; + const results = data.results; + if (!Array.isArray(results)) + return ""; + return results.slice(0, RECALL_MAX_RESULTS_INCLUDED).map((r) => r.content).filter((c) => typeof c === "string" && c.length > 0).map((c) => c.length > RECALL_RESULT_TRUNCATE_CHARS ? c.slice(0, RECALL_RESULT_TRUNCATE_CHARS) + RECALL_TRUNCATION_MARKER : c).join("\n---\n"); +} +function collectDraftText(result, sectionType) { + const expectedId = correlationFor(SECTION_GENERATE_INV_PREFIX, sectionType); + const response = result.responses.find((r) => r.invocation_id === expectedId); + if (!response) + return null; + if (response.error) + return null; + return response.raw_text?.trim() ?? null; +} + +// packages/orchestration/dist/handlers/jira-generation.js +var BATCH_ID = "jira_generation"; +function gatherSourceSections(state) { + const wanted = [ + "requirements", + "user_stories", + "acceptance_criteria" + ]; + return state.sections.filter((s) => wanted.includes(s.section_type) && s.content).map((s) => ({ + section_type: s.section_type, + content: s.content + })); +} +var handleJiraGeneration = ({ state, result }) => { + if (result?.kind === "subagent_batch_result" && result.batch_id === BATCH_ID) { + const response = result.responses.find((r) => r.invocation_id === JIRA_GENERATION_INV_ID); + if (!response || response.error || !response.raw_text) { + const withError = appendError( + state, + `[jira_generation] failed: ${response?.error ?? "no response"}`, + // The handler tolerates this (warns + continues to file_export). + // Tagging as "upstream_failure" keeps the structural-error gate + // from firing on a recoverable subagent flake (cross-audit + // curie H1, Phase 3+4 follow-up, 2026-04). + "upstream_failure" + ); + return { + state: { ...withError, current_step: "file_export" }, + action: { + kind: "emit_message", + level: "warn", + message: "JIRA generation failed; proceeding to file export anyway." } - await this.validateToolOutput(tool, result, request.params.name); - return result; - } catch (error2) { - if (error2 instanceof McpError) { - if (error2.code === ErrorCode.UrlElicitationRequired) { - throw error2; - } + }; + } + const jiraMarkdown = response.raw_text.trim(); + const updated = { + ...state, + sections: [ + ...state.sections, + { + section_type: "jira_tickets", + status: "passed", + attempt: 1, + violation_count: 0, + last_violations: [], + attempt_log: [], + content: jiraMarkdown } - return this.createToolError(error2 instanceof Error ? error2.message : String(error2)); + ], + current_step: "file_export" + }; + return { + state: updated, + action: { + kind: "emit_message", + message: "JIRA tickets generated. Writing files." } - }); - this._toolHandlersInitialized = true; + }; } - /** - * Creates a tool error result. - * - * @param errorMessage - The error message. - * @returns The tool error result. - */ - createToolError(errorMessage) { + const sourceMaterial = gatherSourceSections(state); + if (sourceMaterial.length === 0) { return { - content: [ - { - type: "text", - text: errorMessage - } - ], - isError: true + state: { ...state, current_step: "file_export" }, + action: { + kind: "emit_message", + message: "No source sections for JIRA generation. Skipping." + } }; } - /** - * Validates tool input arguments against the tool's input schema. - */ - async validateToolInput(tool, args, toolName) { - if (!tool.inputSchema) { - return void 0; + return { + state, + action: { + kind: "spawn_subagents", + purpose: "draft", + batch_id: BATCH_ID, + invocations: [ + { + invocation_id: JIRA_GENERATION_INV_ID, + subagent_type: "zetetic-team-subagents:engineer", + description: "Generate JIRA tickets from PRD", + prompt: buildJiraPrompt({ + feature_description: state.feature_description, + source_sections: sourceMaterial + }), + isolation: "none" + } + ] } - const inputObj = normalizeObjectSchema(tool.inputSchema); - const schemaToParse = inputObj ?? tool.inputSchema; - const parseResult = await safeParseAsync2(schemaToParse, args); - if (!parseResult.success) { - const error2 = "error" in parseResult ? parseResult.error : "Unknown error"; - const errorMessage = getParseErrorMessage(error2); - throw new McpError(ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`); + }; +}; + +// packages/orchestration/dist/handlers/file-export.js +var OUTPUT_DIR = "prd-output"; +function joinSections(state, types) { + return state.sections.filter((s) => types.includes(s.section_type) && s.content).sort((a, b) => SECTION_ORDER[a.section_type] - SECTION_ORDER[b.section_type]).map((s) => `## ${SECTION_DISPLAY_NAMES[s.section_type]} + +${s.content.trim()}`).join("\n\n"); +} +function jiraContent(state) { + const last = [...state.sections].reverse().find((s) => s.section_type === "jira_tickets" && s.content); + return last?.content?.trim() ?? ""; +} +function buildFileSet(state) { + const slug = state.run_id.slice(0, 8); + const base = `${OUTPUT_DIR}/${slug}`; + return [ + { + path: `${base}/01-prd.md`, + content: () => [ + `# PRD: ${state.feature_description}`, + "", + `Run ID: ${state.run_id}`, + `Context: ${state.prd_context ?? "unknown"}`, + "", + joinSections(state, [ + "overview", + "goals", + "requirements", + "user_stories", + "technical_specification", + "acceptance_criteria" + ]) + ].join("\n") + }, + { + path: `${base}/02-data-model.md`, + content: () => joinSections(state, ["data_model"]) || "_No data model section._" + }, + { + path: `${base}/03-api-spec.md`, + content: () => joinSections(state, ["api_specification"]) || "_No API spec section._" + }, + { + path: `${base}/04-security.md`, + content: () => joinSections(state, [ + "security_considerations", + "performance_requirements" + ]) || "_No security/performance sections._" + }, + { + path: `${base}/05-testing.md`, + content: () => joinSections(state, ["testing", "acceptance_criteria"]) || "_No testing section._" + }, + { + path: `${base}/06-deployment.md`, + content: () => joinSections(state, ["deployment", "timeline", "risks"]) || "_No deployment section._" + }, + { + path: `${base}/07-jira-tickets.md`, + content: () => jiraContent(state) || "_No JIRA tickets generated._" + }, + { + path: `${base}/08-source-code.md`, + content: () => joinSections(state, ["source_code"]) || "_Source code section not generated in this run._" + }, + { + path: `${base}/09-test-code.md`, + content: () => joinSections(state, ["test_code"]) || "_Test code section not generated in this run._" } - return parseResult.data; + ]; +} +var handleFileExport = ({ state, result }) => { + let nextState = state; + if (result && result.kind !== "file_written") { + nextState = appendError(state, `[file_export] unexpected result kind '${result.kind}'; re-issuing write`, "structural"); } - /** - * Validates tool output against the tool's output schema. - */ - async validateToolOutput(tool, result, toolName) { - if (!tool.outputSchema) { - return; - } - if (!("content" in result)) { - return; - } - if (result.isError) { - return; - } - if (!result.structuredContent) { - throw new McpError(ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); - } - const outputObj = normalizeObjectSchema(tool.outputSchema); - const parseResult = await safeParseAsync2(outputObj, result.structuredContent); - if (!parseResult.success) { - const error2 = "error" in parseResult ? parseResult.error : "Unknown error"; - const errorMessage = getParseErrorMessage(error2); - throw new McpError(ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`); + if (result?.kind === "file_written") { + if (!state.written_files.includes(result.path)) { + nextState = { + ...state, + written_files: [...state.written_files, result.path] + }; } } - /** - * Executes a tool handler (either regular or task-based). - */ - async executeToolHandler(tool, args, extra) { - const handler = tool.handler; - const isTaskHandler = "createTask" in handler; - if (isTaskHandler) { - if (!extra.taskStore) { - throw new Error("No task store provided."); - } - const taskExtra = { ...extra, taskStore: extra.taskStore }; - if (tool.inputSchema) { - const typedHandler = handler; - return await Promise.resolve(typedHandler.createTask(args, taskExtra)); - } else { - const typedHandler = handler; - return await Promise.resolve(typedHandler.createTask(taskExtra)); + const files = buildFileSet(nextState); + const done = new Set(nextState.written_files); + const remaining = files.filter((f) => !done.has(f.path)); + if (remaining.length === 0) { + return { + state: { ...nextState, current_step: "self_check" }, + action: { + kind: "emit_message", + message: `All ${files.length} files written. Running self-check.` } - } - if (tool.inputSchema) { - const typedHandler = handler; - return await Promise.resolve(typedHandler(args, extra)); - } else { - const typedHandler = handler; - return await Promise.resolve(typedHandler(extra)); - } + }; } - /** - * Handles automatic task polling for tools with taskSupport 'optional'. - */ - async handleAutomaticTaskPolling(tool, request, extra) { - if (!extra.taskStore) { - throw new Error("No task store provided for task-capable tool."); - } - const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); - const handler = tool.handler; - const taskExtra = { ...extra, taskStore: extra.taskStore }; - const createTaskResult = args ? await Promise.resolve(handler.createTask(args, taskExtra)) : ( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - await Promise.resolve(handler.createTask(taskExtra)) - ); - const taskId = createTaskResult.task.taskId; - let task = createTaskResult.task; - const pollInterval = task.pollInterval ?? 5e3; - while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") { - await new Promise((resolve3) => setTimeout(resolve3, pollInterval)); - const updatedTask = await extra.taskStore.getTask(taskId); - if (!updatedTask) { - throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`); - } - task = updatedTask; + const next = remaining[0]; + return { + state: nextState, + action: { + kind: "write_file", + path: next.path, + content: next.content() } - return await extra.taskStore.getTaskResult(taskId); + }; +}; + +// packages/verification/dist/judge-selector.js +function genius(name315) { + return { kind: "genius", name: name315 }; +} +function team(name315) { + return { kind: "team", name: name315 }; +} +var PANELS = { + // Substitutability, near-decomposability, pattern fit + architecture: { + genius: [genius("liskov"), genius("simon"), genius("alexander")], + team: [team("code-reviewer"), team("architect")], + high_stakes: true + }, + // Order-of-magnitude sanity, queuing limits, efficiency bounds + performance: { + genius: [genius("fermi"), genius("erlang"), genius("carnot")], + team: [team("code-reviewer")], + high_stakes: true + }, + // Invariant reasoning, happens-before, contract substitutability + correctness: { + genius: [genius("dijkstra"), genius("lamport"), genius("liskov")], + team: [team("test-engineer"), team("engineer")], + high_stakes: true + }, + // Correctness discipline, error archaeology, integrity audit + security: { + genius: [genius("dijkstra"), genius("wu"), genius("feynman")], + team: [team("security-auditor")], + high_stakes: true + }, + // Mass-balance accounting, contract substitutability, predictive table + data_model: { + genius: [genius("lavoisier"), genius("liskov"), genius("mendeleev")], + team: [team("dba"), team("code-reviewer")], + high_stakes: true + }, + // Falsifiability, integrity audit, error archaeology + test_coverage: { + genius: [genius("popper"), genius("feynman"), genius("wu")], + team: [team("test-engineer")], + high_stakes: false + }, + // Order-of-magnitude + conservation + story_point_arithmetic: { + genius: [genius("fermi"), genius("lavoisier")], + team: [], + high_stakes: false + }, + // Four-causes interrogation, claim-evidence-warrant chains + fr_traceability: { + genius: [genius("aristotle"), genius("toulmin")], + team: [team("code-reviewer")], + high_stakes: false + }, + // Fragility classification, debiasing, falsifiability + risk: { + genius: [genius("taleb"), genius("kahneman"), genius("popper")], + team: [], + high_stakes: false + }, + // Exhaustive-space audit, gaps-in-the-table + acceptance_criteria_completeness: { + genius: [genius("borges"), genius("mendeleev")], + team: [team("test-engineer")], + high_stakes: false + }, + // Generative consistency rules, exhaustive enumeration + cross_file_consistency: { + genius: [genius("panini"), genius("euler")], + team: [team("code-reviewer")], + high_stakes: true } - setCompletionRequestHandler() { - if (this._completionHandlerInitialized) { - return; - } - this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)); - this.server.registerCapabilities({ - completions: {} +}; +function selectJudges(claim) { + const panel = PANELS[claim.claim_type]; + return [...panel.genius, ...panel.team]; +} + +// packages/verification/dist/claim-extractor.js +function snippet2(content, line, before = 2, after = 2) { + const lines = content.split(/\r?\n/); + const idx = lines.findIndex((l) => l.trim() === line.trim()); + if (idx === -1) + return line; + const start = Math.max(0, idx - before); + const end = Math.min(lines.length, idx + after + 1); + return lines.slice(start, end).join("\n"); +} +function* matchAllLines(re2, content) { + for (const line of content.split(/\r?\n/)) { + const m = line.match(re2); + if (m) + yield m; + } +} +var FR_LINE_RE = /^\s*(?:-|\*|\|)?\s*(FR-\d{3,})\s*[|:\-–—]\s*(.+?)\s*(?:\||$)/i; +var extractRequirements = ({ content, section_type }) => { + const claims = []; + for (const m of matchAllLines(FR_LINE_RE, content)) { + const id = m[1].toUpperCase(); + const text = m[2].trim(); + if (!text) + continue; + claims.push({ + claim_id: id, + claim_type: "fr_traceability", + text: `Functional requirement: ${text}`, + evidence: snippet2(content, m[0]), + source_section: section_type }); - this.server.setRequestHandler(CompleteRequestSchema, async (request) => { - switch (request.params.ref.type) { - case "ref/prompt": - assertCompleteRequestPrompt(request); - return this.handlePromptCompletion(request, request.params.ref); - case "ref/resource": - assertCompleteRequestResourceTemplate(request); - return this.handleResourceCompletion(request, request.params.ref); - default: - throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); - } + } + return claims; +}; +var AC_LINE_RE = /^\s*(?:-|\*|\|)?\s*(AC-\d{3,})\s*[|:\-–—]\s*(.+?)\s*(?:\||$)/i; +var extractAcceptanceCriteria = ({ content, section_type }) => { + const claims = []; + for (const m of matchAllLines(AC_LINE_RE, content)) { + const id = m[1].toUpperCase(); + const text = m[2].trim(); + if (!text) + continue; + claims.push({ + claim_id: id, + claim_type: "acceptance_criteria_completeness", + text: `Acceptance criterion: ${text}`, + evidence: snippet2(content, m[0]), + source_section: section_type }); - this._completionHandlerInitialized = true; } - async handlePromptCompletion(request, ref) { - const prompt = this._registeredPrompts[ref.name]; - if (!prompt) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`); - } - if (!prompt.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); - } - if (!prompt.argsSchema) { - return EMPTY_COMPLETION_RESULT; - } - const promptShape = getObjectShape(prompt.argsSchema); - const field = promptShape?.[request.params.argument.name]; - if (!isCompletable(field)) { - return EMPTY_COMPLETION_RESULT; - } - const completer = getCompleter(field); - if (!completer) { - return EMPTY_COMPLETION_RESULT; + return claims; +}; +var NFR_PATTERNS = [ + { re: /\b(?:p\d{2}|p99|p95|p50)\s*[<>=≤≥]+\s*(\d+(?:\.\d+)?\s*(?:ms|s|µs|us))/gi, subtype: "LATENCY" }, + { re: /\b(\d+(?:\.\d+)?\s*(?:rps|req\/s|qps|requests?\/(?:sec|second)))/gi, subtype: "THROUGHPUT" }, + { re: /\b(\d+(?:\.\d+)?\s*fps)/gi, subtype: "FRAMERATE" }, + { re: /\b(\d+(?:\.\d+)?\s*(?:GB|MB|TB|KB)\b)/gi, subtype: "STORAGE" } +]; +var extractPerformance = ({ content, section_type }) => { + const claims = []; + for (const { re: re2, subtype } of NFR_PATTERNS) { + let counter = 0; + for (const m of content.matchAll(re2)) { + counter += 1; + claims.push({ + claim_id: `NFR-${subtype}-${counter.toString().padStart(2, "0")}`, + claim_type: "performance", + text: `Performance target: ${m[0]}`, + evidence: snippet2(content, m[0], 1, 1), + source_section: section_type + }); } - const suggestions = await completer(request.params.argument.value, request.params.context); - return createCompletionResult(suggestions); } - async handleResourceCompletion(request, ref) { - const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri); - if (!template) { - if (this._registeredResources[ref.uri]) { - return EMPTY_COMPLETION_RESULT; - } - throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); - } - const completer = template.resourceTemplate.completeCallback(request.params.argument.name); - if (!completer) { - return EMPTY_COMPLETION_RESULT; + return claims; +}; +var ARCH_PATTERNS = [ + { re: /ports?[\s\-]?(?:and|\/)?[\s\-]?adapters?/i, label: "ports-and-adapters" }, + { re: /clean\s+architecture/i, label: "clean-architecture" }, + { re: /hexagonal/i, label: "hexagonal" }, + { re: /domain[\s-]+driven\s+design|\bDDD\b/i, label: "ddd" }, + { re: /event[\s-]+driven/i, label: "event-driven" }, + { re: /micro[\s-]?services?/i, label: "microservices" }, + { re: /repository\s+pattern/i, label: "repository-pattern" }, + { re: /CQRS/i, label: "cqrs" } +]; +var extractArchitecture = ({ content, section_type }) => { + const claims = []; + for (const { re: re2, label } of ARCH_PATTERNS) { + if (re2.test(content)) { + const m = content.match(re2); + claims.push({ + claim_id: `ARCH-${label.toUpperCase()}`, + claim_type: "architecture", + text: `Architecture pattern claim: ${label}`, + evidence: snippet2(content, m[0], 3, 3), + source_section: section_type + }); } - const suggestions = await completer(request.params.argument.value, request.params.context); - return createCompletionResult(suggestions); } - setResourceRequestHandlers() { - if (this._resourceHandlersInitialized) { - return; + return claims; +}; +var SECURITY_KEYWORDS = [ + "authentication", + "authorization", + "encryption", + "secrets", + "PII", + "OAuth", + "JWT", + "TLS", + "AES", + "SHA", + "hash", + "token", + "session" +]; +var extractSecurity = ({ content, section_type }) => { + const claims = []; + const lower = content.toLowerCase(); + let counter = 0; + for (const kw of SECURITY_KEYWORDS) { + if (lower.includes(kw.toLowerCase())) { + counter += 1; + claims.push({ + claim_id: `SEC-${counter.toString().padStart(2, "0")}-${kw.toUpperCase()}`, + claim_type: "security", + text: `Security claim involving ${kw}`, + evidence: extractParagraphContaining(content, kw), + source_section: section_type + }); } - this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)); - this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)); - this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)); - this.server.registerCapabilities({ - resources: { - listChanged: true - } - }); - this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => { - const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({ - uri, - name: resource.name, - ...resource.metadata - })); - const templateResources = []; - for (const template of Object.values(this._registeredResourceTemplates)) { - if (!template.resourceTemplate.listCallback) { - continue; - } - const result = await template.resourceTemplate.listCallback(extra); - for (const resource of result.resources) { - templateResources.push({ - ...template.metadata, - // the defined resource metadata should override the template metadata if present - ...resource - }); - } - } - return { resources: [...resources, ...templateResources] }; - }); - this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => { - const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name315, template]) => ({ - name: name315, - uriTemplate: template.resourceTemplate.uriTemplate.toString(), - ...template.metadata - })); - return { resourceTemplates }; - }); - this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => { - const uri = new URL(request.params.uri); - const resource = this._registeredResources[uri.toString()]; - if (resource) { - if (!resource.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`); - } - return resource.readCallback(uri, extra); - } - for (const template of Object.values(this._registeredResourceTemplates)) { - const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); - if (variables) { - return template.readCallback(uri, variables, extra); - } - } - throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`); + } + return claims; +}; +function extractParagraphContaining(content, keyword) { + const lower = content.toLowerCase(); + const lowerKw = keyword.toLowerCase(); + const idx = lower.indexOf(lowerKw); + if (idx === -1) + return content.slice(0, 400); + const start = Math.max(0, content.lastIndexOf("\n\n", idx)); + let end = content.indexOf("\n\n", idx); + if (end === -1) + end = Math.min(content.length, idx + 400); + return content.slice(start, end).trim(); +} +var DDL_RE = /(CREATE\s+(?:TABLE|TYPE|ENUM|INDEX|VIEW)\s+\w+[\s\S]*?;)/gi; +var extractDataModel = ({ content, section_type }) => { + const claims = []; + let counter = 0; + for (const m of content.matchAll(DDL_RE)) { + counter += 1; + const ddl = m[1]; + const nameMatch = ddl.match(/CREATE\s+(?:TABLE|TYPE|ENUM|INDEX|VIEW)\s+(\w+)/i); + const name315 = nameMatch?.[1] ?? "anonymous"; + claims.push({ + claim_id: `DDL-${counter.toString().padStart(2, "0")}-${name315.toUpperCase()}`, + claim_type: "data_model", + text: `Schema definition: ${name315}`, + evidence: ddl.slice(0, 600), + source_section: section_type }); - this._resourceHandlersInitialized = true; } - setPromptRequestHandlers() { - if (this._promptHandlersInitialized) { - return; - } - this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)); - this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)); - this.server.registerCapabilities({ - prompts: { - listChanged: true - } + return claims; +}; +var TEST_FN_RE = /(?:func|def|fn|it|test)\s+(test_?\w+|\w*Test\w*)\s*\(/gi; +var extractTests = ({ content, section_type }) => { + const claims = []; + let counter = 0; + for (const m of content.matchAll(TEST_FN_RE)) { + counter += 1; + claims.push({ + claim_id: `TEST-${counter.toString().padStart(3, "0")}-${m[1].slice(0, 32)}`, + claim_type: "test_coverage", + text: `Test function: ${m[1]}`, + evidence: snippet2(content, m[0], 2, 4), + source_section: section_type }); - this.server.setRequestHandler(ListPromptsRequestSchema, () => ({ - prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name315, prompt]) => { - return { - name: name315, - title: prompt.title, - description: prompt.description, - arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : void 0 - }; - }) - })); - this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => { - const prompt = this._registeredPrompts[request.params.name]; - if (!prompt) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); - } - if (!prompt.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); - } - if (prompt.argsSchema) { - const argsObj = normalizeObjectSchema(prompt.argsSchema); - const parseResult = await safeParseAsync2(argsObj, request.params.arguments); - if (!parseResult.success) { - const error2 = "error" in parseResult ? parseResult.error : "Unknown error"; - const errorMessage = getParseErrorMessage(error2); - throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage}`); - } - const args = parseResult.data; - const cb = prompt.callback; - return await Promise.resolve(cb(args, extra)); - } else { - const cb = prompt.callback; - return await Promise.resolve(cb(extra)); - } + } + return claims; +}; +var RISK_LINE_RE = /^\s*(?:-|\*)\s*(?:\*\*Risk\*\*[:|]?\s*)?(.+?(?:risk|failure|hazard|threat|attack|vulnerab).+)$/i; +var extractRisks = ({ content, section_type }) => { + const claims = []; + let counter = 0; + for (const m of matchAllLines(RISK_LINE_RE, content)) { + counter += 1; + claims.push({ + claim_id: `RISK-${counter.toString().padStart(2, "0")}`, + claim_type: "risk", + text: m[1].trim(), + evidence: snippet2(content, m[0]), + source_section: section_type }); - this._promptHandlersInitialized = true; } - resource(name315, uriOrTemplate, ...rest) { - let metadata; - if (typeof rest[0] === "object") { - metadata = rest.shift(); - } - const readCallback = rest[0]; - if (typeof uriOrTemplate === "string") { - if (this._registeredResources[uriOrTemplate]) { - throw new Error(`Resource ${uriOrTemplate} is already registered`); - } - const registeredResource = this._createRegisteredResource(name315, void 0, uriOrTemplate, metadata, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } else { - if (this._registeredResourceTemplates[name315]) { - throw new Error(`Resource template ${name315} is already registered`); - } - const registeredResourceTemplate = this._createRegisteredResourceTemplate(name315, void 0, uriOrTemplate, metadata, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; + return claims; +}; +var SP_TOTAL_RE = /total\s*[:|=]\s*(\d+)\s*(?:sp|story\s*points?)?/gi; +var extractStoryPoints = ({ content, section_type }) => { + const claims = []; + let counter = 0; + for (const m of content.matchAll(SP_TOTAL_RE)) { + counter += 1; + claims.push({ + claim_id: `SP-TOTAL-${counter.toString().padStart(2, "0")}`, + claim_type: "story_point_arithmetic", + text: `Story-point total claim: ${m[0]}`, + evidence: snippet2(content, m[0]), + source_section: section_type + }); + } + return claims; +}; +var EXTRACTORS_BY_SECTION = { + requirements: [extractRequirements], + user_stories: [extractStoryPoints], + technical_specification: [extractArchitecture], + acceptance_criteria: [extractAcceptanceCriteria], + data_model: [extractDataModel], + api_specification: [extractRequirements], + // FR-style endpoint claims + security_considerations: [extractSecurity], + performance_requirements: [extractPerformance], + testing: [extractTests], + test_code: [extractTests], + risks: [extractRisks], + timeline: [extractStoryPoints] +}; +function extractClaims(sectionType, content) { + const extractors = EXTRACTORS_BY_SECTION[sectionType] ?? []; + const claims = []; + for (const ex of extractors) { + claims.push(...ex({ section_type: sectionType, content })); + } + return dedupeById(claims); +} +function extractClaimsFromDocument(sections) { + const claims = []; + for (const s of sections) { + claims.push(...extractClaims(s.type, s.content)); + } + return dedupeById(claims); +} +function dedupeById(claims) { + const seen = /* @__PURE__ */ new Map(); + for (const c of claims) { + if (!seen.has(c.claim_id)) + seen.set(c.claim_id, c); + } + return Array.from(seen.values()); +} + +// packages/verification/dist/consensus-strategy.js +function agentKey(agent) { + return `${agent.kind}:${agent.name}`; +} +var VERDICTS = [ + "PASS", + "SPEC-COMPLETE", + "NEEDS-RUNTIME", + "INCONCLUSIVE", + "FAIL" +]; +var VERDICT_SEVERITY = { + PASS: 0, + "SPEC-COMPLETE": 1, + "NEEDS-RUNTIME": 2, + INCONCLUSIVE: 3, + FAIL: 4 +}; +function clampUnit(x) { + if (!Number.isFinite(x)) + return 0; + return Math.min(1, Math.max(0, x)); +} +var NO_INFORMATION_FLOOR = 0.2; +function verdictToDirection(verdict) { + if (verdict === "PASS" || verdict === "SPEC-COMPLETE") { + return "specificity_arm"; + } + return "sensitivity_arm"; +} +function resolveReliability(judge, runId, claimType, direction, reliabilityProvider, reliabilityLookup, reliabilityMap) { + if (reliabilityProvider !== void 0 && runId !== void 0 && claimType !== void 0) { + const record2 = reliabilityProvider.getReliabilityForRun(runId, judge, claimType, direction); + if (record2 !== null) { + return clampUnit(record2.alpha / (record2.alpha + record2.beta)); } } - registerResource(name315, uriOrTemplate, config5, readCallback) { - if (typeof uriOrTemplate === "string") { - if (this._registeredResources[uriOrTemplate]) { - throw new Error(`Resource ${uriOrTemplate} is already registered`); - } - const registeredResource = this._createRegisteredResource(name315, config5.title, uriOrTemplate, config5, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } else { - if (this._registeredResourceTemplates[name315]) { - throw new Error(`Resource template ${name315} is already registered`); - } - const registeredResourceTemplate = this._createRegisteredResourceTemplate(name315, config5.title, uriOrTemplate, config5, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; + if (reliabilityLookup !== void 0 && claimType !== void 0) { + const record2 = reliabilityLookup(judge, claimType, direction); + if (record2 !== null) { + return clampUnit(record2.alpha / (record2.alpha + record2.beta)); } } - _createRegisteredResource(name315, title, uri, metadata, readCallback) { - const registeredResource = { - name: name315, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResource.update({ enabled: false }), - enable: () => registeredResource.update({ enabled: true }), - remove: () => registeredResource.update({ uri: null }), - update: (updates) => { - if (typeof updates.uri !== "undefined" && updates.uri !== uri) { - delete this._registeredResources[uri]; - if (updates.uri) - this._registeredResources[updates.uri] = registeredResource; - } - if (typeof updates.name !== "undefined") - registeredResource.name = updates.name; - if (typeof updates.title !== "undefined") - registeredResource.title = updates.title; - if (typeof updates.metadata !== "undefined") - registeredResource.metadata = updates.metadata; - if (typeof updates.callback !== "undefined") - registeredResource.readCallback = updates.callback; - if (typeof updates.enabled !== "undefined") - registeredResource.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResources[uri] = registeredResource; - return registeredResource; + const key = agentKey(judge); + const mapped = reliabilityMap.get(key); + if (mapped !== void 0) { + return clampUnit(mapped); } - _createRegisteredResourceTemplate(name315, title, template, metadata, readCallback) { - const registeredResourceTemplate = { - resourceTemplate: template, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResourceTemplate.update({ enabled: false }), - enable: () => registeredResourceTemplate.update({ enabled: true }), - remove: () => registeredResourceTemplate.update({ name: null }), - update: (updates) => { - if (typeof updates.name !== "undefined" && updates.name !== name315) { - delete this._registeredResourceTemplates[name315]; - if (updates.name) - this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; - } - if (typeof updates.title !== "undefined") - registeredResourceTemplate.title = updates.title; - if (typeof updates.template !== "undefined") - registeredResourceTemplate.resourceTemplate = updates.template; - if (typeof updates.metadata !== "undefined") - registeredResourceTemplate.metadata = updates.metadata; - if (typeof updates.callback !== "undefined") - registeredResourceTemplate.readCallback = updates.callback; - if (typeof updates.enabled !== "undefined") - registeredResourceTemplate.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResourceTemplates[name315] = registeredResourceTemplate; - const variableNames = template.uriTemplate.variableNames; - const hasCompleter = Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v)); - if (hasCompleter) { - this.setCompletionRequestHandler(); + return DEFAULT_RELIABILITY_PRIOR.alpha / (DEFAULT_RELIABILITY_PRIOR.alpha + DEFAULT_RELIABILITY_PRIOR.beta); +} +function uniformPrior() { + return { + PASS: 0.2, + "SPEC-COMPLETE": 0.2, + "NEEDS-RUNTIME": 0.2, + INCONCLUSIVE: 0.2, + FAIL: 0.2 + }; +} +function updatePosterior(prior, observed, reliability) { + const r = clampUnit(reliability); + const likelihood = { + PASS: 0, + "SPEC-COMPLETE": 0, + "NEEDS-RUNTIME": 0, + INCONCLUSIVE: 0, + FAIL: 0 + }; + const other = (1 - r) / 4; + for (const v of VERDICTS) { + likelihood[v] = v === observed ? r : other; + } + const posterior = { + PASS: 0, + "SPEC-COMPLETE": 0, + "NEEDS-RUNTIME": 0, + INCONCLUSIVE: 0, + FAIL: 0 + }; + let total = 0; + for (const v of VERDICTS) { + posterior[v] = prior[v] * likelihood[v]; + total += posterior[v]; + } + if (total > 0) { + for (const v of VERDICTS) + posterior[v] /= total; + } + return posterior; +} +function pickMaxVerdict(d) { + let best = "PASS"; + let bestScore = -Infinity; + for (const v of VERDICTS) { + const s = d[v]; + if (s > bestScore || s === bestScore && VERDICT_SEVERITY[v] > VERDICT_SEVERITY[best]) { + best = v; + bestScore = s; } - return registeredResourceTemplate; } - _createRegisteredPrompt(name315, title, description, argsSchema, callback) { - const registeredPrompt = { - title, - description, - argsSchema: argsSchema === void 0 ? void 0 : objectFromShape(argsSchema), - callback, - enabled: true, - disable: () => registeredPrompt.update({ enabled: false }), - enable: () => registeredPrompt.update({ enabled: true }), - remove: () => registeredPrompt.update({ name: null }), - update: (updates) => { - if (typeof updates.name !== "undefined" && updates.name !== name315) { - delete this._registeredPrompts[name315]; - if (updates.name) - this._registeredPrompts[updates.name] = registeredPrompt; - } - if (typeof updates.title !== "undefined") - registeredPrompt.title = updates.title; - if (typeof updates.description !== "undefined") - registeredPrompt.description = updates.description; - if (typeof updates.argsSchema !== "undefined") - registeredPrompt.argsSchema = objectFromShape(updates.argsSchema); - if (typeof updates.callback !== "undefined") - registeredPrompt.callback = updates.callback; - if (typeof updates.enabled !== "undefined") - registeredPrompt.enabled = updates.enabled; - this.sendPromptListChanged(); - } - }; - this._registeredPrompts[name315] = registeredPrompt; - if (argsSchema) { - const hasCompletable = Object.values(argsSchema).some((field) => { - const inner = field instanceof ZodOptional ? field._def?.innerType : field; - return isCompletable(inner); - }); - if (hasCompletable) { - this.setCompletionRequestHandler(); - } + return best; +} +function bayesian(claim_id, verdicts, config5) { + let posterior = uniformPrior(); + const reliabilityMap = config5.reliability ?? /* @__PURE__ */ new Map(); + for (const v of verdicts) { + const direction = verdictToDirection(v.verdict); + const rawReliability = resolveReliability(v.judge, config5.runId, config5.claimType, direction, config5.reliabilityProvider, config5.reliabilityLookup, reliabilityMap); + const reliability = clampUnit(rawReliability); + const confidence2 = clampUnit(v.confidence); + const adjustedReliability = reliability * confidence2; + if (adjustedReliability <= NO_INFORMATION_FLOOR) { + continue; } - return registeredPrompt; + posterior = updatePosterior(posterior, v.verdict, adjustedReliability); } - _createRegisteredTool(name315, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) { - validateAndWarnToolName(name315); - const registeredTool = { - title, - description, - inputSchema: getZodSchemaObject(inputSchema), - outputSchema: getZodSchemaObject(outputSchema), - annotations, - execution, - _meta, - handler, - enabled: true, - disable: () => registeredTool.update({ enabled: false }), - enable: () => registeredTool.update({ enabled: true }), - remove: () => registeredTool.update({ name: null }), - update: (updates) => { - if (typeof updates.name !== "undefined" && updates.name !== name315) { - if (typeof updates.name === "string") { - validateAndWarnToolName(updates.name); - } - delete this._registeredTools[name315]; - if (updates.name) - this._registeredTools[updates.name] = registeredTool; - } - if (typeof updates.title !== "undefined") - registeredTool.title = updates.title; - if (typeof updates.description !== "undefined") - registeredTool.description = updates.description; - if (typeof updates.paramsSchema !== "undefined") - registeredTool.inputSchema = objectFromShape(updates.paramsSchema); - if (typeof updates.outputSchema !== "undefined") - registeredTool.outputSchema = objectFromShape(updates.outputSchema); - if (typeof updates.callback !== "undefined") - registeredTool.handler = updates.callback; - if (typeof updates.annotations !== "undefined") - registeredTool.annotations = updates.annotations; - if (typeof updates._meta !== "undefined") - registeredTool._meta = updates._meta; - if (typeof updates.enabled !== "undefined") - registeredTool.enabled = updates.enabled; - this.sendToolListChanged(); - } + const distribution = { + PASS: 0, + "SPEC-COMPLETE": 0, + "NEEDS-RUNTIME": 0, + INCONCLUSIVE: 0, + FAIL: 0 + }; + for (const v of VERDICTS) { + distribution[v] = posterior[v]; + } + const chosen = pickMaxVerdict(distribution); + const confidence = distribution[chosen]; + const unanimous = verdicts.every((v) => v.verdict === chosen); + const dissenting = verdicts.filter((v) => v.verdict !== chosen); + return { + claim_id, + verdict: chosen, + confidence, + unanimous, + dissenting, + distribution, + strategy: "bayesian", + judges: verdicts.map((v) => v.judge) + }; +} + +// packages/verification/dist/consensus.js +var VERDICT_SEVERITY2 = { + PASS: 0, + "SPEC-COMPLETE": 1, + "NEEDS-RUNTIME": 2, + INCONCLUSIVE: 3, + FAIL: 4 +}; +var VERDICTS2 = [ + "PASS", + "SPEC-COMPLETE", + "NEEDS-RUNTIME", + "INCONCLUSIVE", + "FAIL" +]; +var DEFAULT_CONFIG = { + strategy: "weighted_average", + // source: see ConsensusConfig.fail_threshold doc-comment. + fail_threshold: 0.5 +}; +function clampUnit2(x) { + if (!Number.isFinite(x)) + return 0; + return Math.min(1, Math.max(0, x)); +} +function consensus(claim_id, verdicts, config5 = {}) { + if (verdicts.length === 0) { + return { + claim_id, + verdict: "INCONCLUSIVE", + confidence: 0, + unanimous: false, + dissenting: [], + distribution: emptyDistribution(), + strategy: config5.strategy ?? DEFAULT_CONFIG.strategy, + judges: [] }; - this._registeredTools[name315] = registeredTool; - this.setToolRequestHandlers(); - this.sendToolListChanged(); - return registeredTool; } - /** - * tool() implementation. Parses arguments passed to overrides defined above. - */ - tool(name315, ...rest) { - if (this._registeredTools[name315]) { - throw new Error(`Tool ${name315} is already registered`); - } - let description; - let inputSchema; - let outputSchema; - let annotations; - if (typeof rest[0] === "string") { - description = rest.shift(); + const strategy = config5.strategy ?? DEFAULT_CONFIG.strategy; + switch (strategy) { + case "weighted_average": + return weightedAverage(claim_id, verdicts, config5); + case "bayesian": + return bayesian(claim_id, verdicts, config5); + } +} +function weightedAverage(claim_id, verdicts, config5) { + const distribution = emptyDistribution(); + let totalWeight = 0; + for (const v of verdicts) { + const w = clampUnit2(v.confidence); + distribution[v.verdict] += w; + totalWeight += w; + } + if (totalWeight === 0) { + for (const v of verdicts) + distribution[v.verdict] += 1; + totalWeight = verdicts.length; + } + const failThreshold = config5.fail_threshold ?? DEFAULT_CONFIG.fail_threshold; + const failWeight = distribution.FAIL; + const failFrac = totalWeight > 0 ? failWeight / totalWeight : 0; + let chosen; + if (failFrac >= failThreshold) { + chosen = "FAIL"; + } else { + chosen = pickMaxVerdict2(distribution); + } + const confidence = totalWeight > 0 ? distribution[chosen] / totalWeight : 0; + const unanimous = verdicts.every((v) => v.verdict === chosen); + const dissenting = verdicts.filter((v) => v.verdict !== chosen); + return { + claim_id, + verdict: chosen, + confidence, + unanimous, + dissenting, + distribution: normalizeDistribution(distribution, totalWeight), + strategy: "weighted_average", + judges: verdicts.map((v) => v.judge) + }; +} +function emptyDistribution() { + return { + PASS: 0, + "SPEC-COMPLETE": 0, + "NEEDS-RUNTIME": 0, + INCONCLUSIVE: 0, + FAIL: 0 + }; +} +function normalizeDistribution(d, total) { + if (total <= 0) + return d; + const out = emptyDistribution(); + for (const v of VERDICTS2) + out[v] = d[v] / total; + return out; +} +function pickMaxVerdict2(d) { + let best = "PASS"; + let bestScore = -Infinity; + for (const v of VERDICTS2) { + const s = d[v]; + if (s > bestScore || s === bestScore && VERDICT_SEVERITY2[v] > VERDICT_SEVERITY2[best]) { + best = v; + bestScore = s; } - if (rest.length > 1) { - const firstArg = rest[0]; - if (isZodRawShapeCompat(firstArg)) { - inputSchema = rest.shift(); - if (rest.length > 1 && typeof rest[0] === "object" && rest[0] !== null && !isZodRawShapeCompat(rest[0])) { - annotations = rest.shift(); + } + return best; +} + +// packages/verification/dist/orchestrator.js +function planSectionVerification(sectionType, content, options = {}) { + const claims = extractClaims(sectionType, content); + const judge_requests = buildRequests(claims, options, content); + return { claims, judge_requests }; +} +function planDocumentVerification(sections, options = {}) { + const claims = extractClaimsFromDocument(sections); + const concatenated = sections.map((s) => `## ${s.type} + +${s.content}`).join("\n\n"); + const judge_requests = buildRequests(claims, options, concatenated); + return { claims, judge_requests }; +} +function buildRequests(claims, options, prdExcerpt) { + const requests = []; + const includePrd = options.include_prd_excerpt !== false; + for (const claim of claims) { + const judges = selectJudges(claim); + for (const judge of judges) { + requests.push({ + judge, + claim, + context: { + prd_excerpt: includePrd ? prdExcerpt : void 0, + codebase_excerpts: [...options.codebase_excerpts ?? []], + memory_excerpts: [...options.memory_excerpts ?? []] } - } else if (typeof firstArg === "object" && firstArg !== null) { - if (Object.values(firstArg).some((v) => typeof v === "object" && v !== null)) { - throw new Error(`Tool ${name315} expected a Zod schema or ToolAnnotations, but received an unrecognized object`); + }); + } + } + return requests; +} +function concludeSection(sectionType, verdicts, options = {}) { + return concludeFromVerdicts(sectionType, verdicts, options); +} +function concludeDocument(verdicts, options = {}) { + return concludeFromVerdicts("document", verdicts, options); +} +function groundTruthToIsFail(verdict) { + return verdict !== "PASS"; +} +function concludeFromVerdicts(scope, verdicts, options) { + const byClaim = /* @__PURE__ */ new Map(); + for (const v of verdicts) { + const list = byClaim.get(v.claim_id) ?? []; + list.push(v); + byClaim.set(v.claim_id, list); + } + const results = []; + for (const [claim_id, vs] of byClaim) { + const claimType = options.claimTypes?.get(claim_id); + const batchConfig = claimType !== void 0 ? { ...options, claimType } : options; + const result = consensus(claim_id, vs, batchConfig); + results.push(result); + if (options.onObservation !== void 0 && claimType !== void 0) { + const groundTruthIsFail = groundTruthToIsFail(result.verdict); + const claim = options.claims?.get(claim_id); + const external_grounding = claim?.external_grounding; + for (const jv of vs) { + const judgeWasCorrect = groundTruthIsFail ? jv.verdict !== "PASS" && jv.verdict !== "SPEC-COMPLETE" : jv.verdict === "PASS" || jv.verdict === "SPEC-COMPLETE"; + try { + options.onObservation({ + claim_id, + judge: jv.judge, + claimType, + observation: { groundTruthIsFail, judgeWasCorrect }, + external_grounding + }); + } catch { } - annotations = rest.shift(); } } - const callback = rest[0]; - return this._createRegisteredTool(name315, void 0, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, void 0, callback); } - /** - * Registers a tool with a config object and callback. - */ - registerTool(name315, config5, cb) { - if (this._registeredTools[name315]) { - throw new Error(`Tool ${name315} is already registered`); + const distribution = { + PASS: 0, + "SPEC-COMPLETE": 0, + "NEEDS-RUNTIME": 0, + INCONCLUSIVE: 0, + FAIL: 0 + }; + for (const r of results) + distribution[r.verdict] += 1; + const failures = results.filter((r) => r.verdict === "FAIL"); + const warnings = results.filter((r) => r.verdict === "INCONCLUSIVE" || r.verdict === "NEEDS-RUNTIME" || r.verdict === "SPEC-COMPLETE"); + const passRate = results.length > 0 ? distribution.PASS / results.length : 0; + const SUSPICIOUS_MIN_CLUSTER = 5; + const SUSPICIOUS_PASS_RATE = 1; + const distribution_suspicious = results.length >= SUSPICIOUS_MIN_CLUSTER && passRate >= SUSPICIOUS_PASS_RATE; + return { + section_type: scope, + claims_evaluated: results.length, + judges_invoked: verdicts.length, + results, + distribution, + failures, + warnings, + distribution_suspicious + }; +} + +// packages/verification/dist/judge-prompt.js +var VERDICT_TAXONOMY = ` +| Verdict | Meaning | When to use | +|---------|---------|-------------| +| PASS | Claim is structurally complete AND verifiable from the document | FR traceability, AC completeness, SP arithmetic, structural checks | +| SPEC-COMPLETE | A test or measurement method is specified, but runtime data is needed to confirm | NFR performance targets (latency, fps, throughput), scalability limits | +| NEEDS-RUNTIME | Claim cannot be verified at design time at all | Load test results, p95 latency under prod traffic, real-world storage usage | +| INCONCLUSIVE | Claim depends on an unresolved open question or external factor | Claims referencing OQ-XXX, vendor SLA, regulatory interpretation | +| FAIL | Claim is structurally invalid or contradicts other claims | Arithmetic errors, orphan references, circular dependencies | + +NFR claims about latency, fps, throughput, or storage MUST NOT receive PASS. +They receive SPEC-COMPLETE (if a test method is specified) or NEEDS-RUNTIME. +`.trim(); +var RESPONSE_SCHEMA = ` +{ + "verdict": "PASS" | "SPEC-COMPLETE" | "NEEDS-RUNTIME" | "INCONCLUSIVE" | "FAIL", + "rationale": "", + "caveats": ["", "..."], + "confidence": +} +`.trim(); +function buildJudgePrompt(req) { + const { judge, claim, context } = req; + const judgeDescription = judge.kind === "genius" ? `Apply the ${judge.name} reasoning pattern to evaluate the claim.` : `Apply your ${judge.name} role expertise to evaluate the claim.`; + const prdExcerpt = context.prd_excerpt ? ` +${context.prd_excerpt} + + +` : ""; + const codebaseSection = context.codebase_excerpts.length ? ` +${context.codebase_excerpts.join("\n---\n")} + + +` : ""; + const memorySection = context.memory_excerpts.length ? ` +${context.memory_excerpts.join("\n---\n")} + + +` : ""; + const prompt = [ + `You are acting as a verification judge for a PRD.`, + judgeDescription, + "", + ``, + `id: ${claim.claim_id}`, + `type: ${claim.claim_type}`, + `source_section: ${claim.source_section ?? "(unspecified)"}`, + `text: ${claim.text}`, + ``, + "", + ``, + claim.evidence, + ``, + "", + prdExcerpt + codebaseSection + memorySection, + ``, + VERDICT_TAXONOMY, + ``, + "", + `Return EXACTLY ONE JSON object matching this schema and nothing else (no prose before or after, no markdown fences):`, + "", + RESPONSE_SCHEMA, + "", + `Constraints:`, + `- Do NOT default to PASS. If you would assign PASS to every claim of this type, you are not doing your job.`, + `- NFR claims (latency, throughput, fps, storage) MUST NOT receive PASS. Use SPEC-COMPLETE or NEEDS-RUNTIME.`, + `- "rationale" must be specific to THIS claim, not a generic rubric.`, + `- "confidence" reflects how sure you are about the verdict, not how confident you are about the claim.` + ].join("\n"); + return { + description: `Judge ${claim.claim_id} (${judge.kind}:${judge.name})`, + subagent_type: agentSubagentType(judge), + prompt + }; +} + +// packages/orchestration/dist/handlers/self-check.js +var VERIFY_BATCH_ID = "self_check_verify"; +var RawVerdictSchema = external_exports.object({ + verdict: VerdictSchema, + rationale: external_exports.string(), + caveats: external_exports.array(external_exports.string()).default([]), + confidence: external_exports.number().min(0).max(1) +}); +function invocationIdFor(idx) { + return `${SELF_CHECK_JUDGE_INV_PREFIX}${idx.toString().padStart(4, "0")}`; +} +function gatherSections(state) { + return state.sections.filter((s) => s.content && s.section_type !== "jira_tickets").map((s) => ({ type: s.section_type, content: s.content })); +} +function buildVerifyAction(requests) { + return { + kind: "spawn_subagents", + purpose: "judge", + batch_id: VERIFY_BATCH_ID, + invocations: requests.map((req, idx) => { + const built = buildJudgePrompt(req); + return { + invocation_id: invocationIdFor(idx), + subagent_type: agentSubagentType(req.judge), + description: built.description, + prompt: built.prompt, + isolation: "none" + }; + }) + }; +} +function parseVerdicts(index2, batchResult) { + const byId = /* @__PURE__ */ new Map(); + for (const r of batchResult.responses) { + if (byId.has(r.invocation_id)) { + byId.set(r.invocation_id, { + invocation_id: r.invocation_id, + error: `duplicate invocation_id in batch: ${r.invocation_id}` + }); + } else { + byId.set(r.invocation_id, r); } - const { title, description, inputSchema, outputSchema, annotations, _meta } = config5; - return this._createRegisteredTool(name315, title, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, _meta, cb); } - prompt(name315, ...rest) { - if (this._registeredPrompts[name315]) { - throw new Error(`Prompt ${name315} is already registered`); - } - let description; - if (typeof rest[0] === "string") { - description = rest.shift(); + const out = []; + for (const entry of index2) { + const response = byId.get(entry.invocation_id); + if (!response || response.error || !response.raw_text) { + out.push({ + judge: entry.request.judge, + claim_id: entry.request.claim.claim_id, + verdict: "INCONCLUSIVE", + rationale: response?.error ?? "no response", + caveats: ["judge_invocation_failed"], + confidence: 0 + }); + continue; } - let argsSchema; - if (rest.length > 1) { - argsSchema = rest.shift(); + try { + const obj = extractJsonObject(response.raw_text); + const parsed = RawVerdictSchema.parse(obj); + out.push({ + judge: entry.request.judge, + claim_id: entry.request.claim.claim_id, + verdict: parsed.verdict, + rationale: parsed.rationale, + caveats: parsed.caveats, + confidence: parsed.confidence + }); + } catch (err) { + out.push({ + judge: entry.request.judge, + claim_id: entry.request.claim.claim_id, + verdict: "INCONCLUSIVE", + rationale: `parse failure: ${err.message}`, + caveats: ["parse_error"], + confidence: 0 + }); } - const cb = rest[0]; - const registeredPrompt = this._createRegisteredPrompt(name315, void 0, description, argsSchema, cb); - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - return registeredPrompt; } - /** - * Registers a prompt with a config object and callback. - */ - registerPrompt(name315, config5, cb) { - if (this._registeredPrompts[name315]) { - throw new Error(`Prompt ${name315} is already registered`); + return out; +} +function finalize(state, verdicts = []) { + const sections = gatherSections(state); + const docReport = validateDocument(sections); + const verificationReport = concludeDocument(verdicts); + const sectionsPassed = state.sections.filter((s) => s.status === "passed").length; + const sectionsFailed = state.sections.filter((s) => s.status === "failed").length; + const sectionsTotal = state.sections.length; + const docCritical = docReport.violations.filter((v) => v.isCritical).length; + const summary = [ + `Self-check complete.`, + `Sections: ${sectionsPassed}/${sectionsTotal} passed, ${sectionsFailed} failed.`, + `Deterministic violations: ${docReport.violations.length} (${docCritical} critical)`, + `Hard-output score: ${docReport.totalScore.toFixed(2)} / 1.00`, + `Multi-judge claims: ${verificationReport.claims_evaluated}`, + ` PASS: ${verificationReport.distribution.PASS}`, + ` SPEC-COMPLETE: ${verificationReport.distribution["SPEC-COMPLETE"]}`, + ` NEEDS-RUNTIME: ${verificationReport.distribution["NEEDS-RUNTIME"]}`, + ` INCONCLUSIVE: ${verificationReport.distribution.INCONCLUSIVE}`, + ` FAIL: ${verificationReport.distribution.FAIL}`, + verificationReport.distribution_suspicious ? ` \u26A0 Distribution suspicious \u2014 100% PASS suggests confirmatory bias.` : "" + ].filter((l) => l !== "").join("\n"); + return { + state: { ...state, current_step: "complete" }, + action: { + kind: "done", + summary, + artifacts: state.sections.map((s) => `${s.section_type}: ${s.status}`), + // Typed verification surface (Phase 3+4 cross-audit closure). Callers + // MUST consume this field, not regex-parse `summary`. The string + // remains as a human-readable artifact only. + verification: { + claims_evaluated: verificationReport.claims_evaluated, + distribution: verificationReport.distribution, + distribution_suspicious: verificationReport.distribution_suspicious + } } - const { title, description, argsSchema } = config5; - const registeredPrompt = this._createRegisteredPrompt(name315, title, description, argsSchema, cb); - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - return registeredPrompt; - } - /** - * Checks if the server is connected to a transport. - * @returns True if the server is connected - */ - isConnected() { - return this.server.transport !== void 0; - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON RPC message - * @see LoggingMessageNotification - * @param params - * @param sessionId optional for stateless and backward compatibility - */ - async sendLoggingMessage(params, sessionId) { - return this.server.sendLoggingMessage(params, sessionId); + }; +} +function handleSelfCheckPhaseA(state) { + const sections = gatherSections(state); + if (sections.length === 0) { + return finalize(state); } - /** - * Sends a resource list changed event to the client, if connected. - */ - sendResourceListChanged() { - if (this.isConnected()) { - this.server.sendResourceListChanged(); - } + const plan = planDocumentVerification(sections); + if (plan.judge_requests.length === 0) { + return finalize(state); } - /** - * Sends a tool list changed event to the client, if connected. - */ - sendToolListChanged() { - if (this.isConnected()) { - this.server.sendToolListChanged(); - } + return { + state: { + ...state, + verification_plan: { + batch_id: VERIFY_BATCH_ID, + claim_ids: plan.judge_requests.map((r) => r.claim.claim_id), + judges: plan.judge_requests.map((r) => r.judge) + } + }, + action: buildVerifyAction(plan.judge_requests) + }; +} +function handleSelfCheckPhaseB(state, result) { + const snapshot = state.verification_plan; + if (!snapshot || snapshot.batch_id !== VERIFY_BATCH_ID) { + return finalize(state); } - /** - * Sends a prompt list changed event to the client, if connected. - */ - sendPromptListChanged() { - if (this.isConnected()) { - this.server.sendPromptListChanged(); + const verdicts = parseVerdictsFromSnapshot(snapshot, state, result); + let stateAfter = { ...state, verification_plan: null }; + const mismatchSeen = /* @__PURE__ */ new Set(); + for (const v of verdicts) { + for (const caveat of v.caveats) { + if (caveat.startsWith("mismatch_kind:") && !mismatchSeen.has(caveat)) { + mismatchSeen.add(caveat); + stateAfter = appendError(stateAfter, `[self_check] plan mismatch detected \u2014 ${caveat}`, "structural"); + } } } -}; -var EMPTY_OBJECT_JSON_SCHEMA = { - type: "object", - properties: {} -}; -function isZodTypeLike(value) { - return value !== null && typeof value === "object" && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function"; -} -function isZodSchemaInstance(obj) { - return "_def" in obj || "_zod" in obj || isZodTypeLike(obj); + return finalize(stateAfter, verdicts); } -function isZodRawShapeCompat(obj) { - if (typeof obj !== "object" || obj === null) { - return false; +var handleSelfCheck = ({ state, result }) => { + if (result?.kind === "subagent_batch_result" && result.batch_id === VERIFY_BATCH_ID) { + return handleSelfCheckPhaseB(state, result); } - if (isZodSchemaInstance(obj)) { - return false; + return handleSelfCheckPhaseA(state); +}; +function parseVerdictsFromSnapshot(snapshot, state, batchResult) { + const sections = gatherSections(state); + const rederived = planDocumentVerification(sections).judge_requests; + const sameLength = rederived.length === snapshot.claim_ids.length; + const sameOrder = sameLength && rederived.every((r, i2) => r.claim.claim_id === snapshot.claim_ids[i2]); + if (sameOrder) { + const index2 = rederived.map((req, idx) => ({ + request: req, + invocation_id: invocationIdFor(idx) + })); + return parseVerdicts(index2, batchResult); } - if (Object.keys(obj).length === 0) { - return true; + const snapshotSet = new Set(snapshot.claim_ids); + const rederivedIds = rederived.map((r) => r.claim.claim_id); + const sameSet = sameLength && rederivedIds.every((id) => snapshotSet.has(id)); + const mismatchKind = sameSet ? "ordering_regression" : "content_mutation"; + const byId = new Map(batchResult.responses.map((r) => [r.invocation_id, r])); + const out = []; + for (let idx = 0; idx < snapshot.claim_ids.length; idx++) { + const claim_id = snapshot.claim_ids[idx]; + const judge = snapshot.judges[idx]; + const response = byId.get(invocationIdFor(idx)); + out.push({ + judge, + claim_id, + verdict: "INCONCLUSIVE", + rationale: response?.error ?? "Plan mismatch between Phase A and Phase B \u2014 original verdict cannot be parsed without JudgeRequest context", + caveats: ["plan_mismatch", `mismatch_kind:${mismatchKind}`], + confidence: 0 + }); } - return Object.values(obj).some(isZodTypeLike); + return out; } -function getZodSchemaObject(schema2) { - if (!schema2) { - return void 0; - } - if (isZodRawShapeCompat(schema2)) { - return objectFromShape(schema2); - } - if (!isZodSchemaInstance(schema2)) { - throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object"); + +// packages/orchestration/dist/runner.js +var HANDLERS = { + banner: handleBanner, + preflight: handlePreflight, + context_detection: handleContextDetection, + input_analysis: handleInputAnalysis, + feasibility_gate: handleFeasibilityGate, + clarification: handleClarification, + budget: handleBudget, + section_generation: handleSectionGeneration, + jira_generation: handleJiraGeneration, + file_export: handleFileExport, + self_check: handleSelfCheck, + complete: ({ state }) => ({ + state, + action: { + kind: "done", + summary: "Pipeline already complete.", + artifacts: [] + } + }) +}; +var COALESCE_CAP = 16; +function step(input) { + const messages = []; + let currentState = input.state; + let pendingResult = input.result; + for (let i2 = 0; i2 < COALESCE_CAP; i2++) { + const out = invoke(currentState, pendingResult); + currentState = out.state; + pendingResult = void 0; + if (out.action.kind === "emit_message") { + const level = out.action.level ?? "info"; + messages.push({ text: out.action.message, level }); + if (currentState.current_step === "complete") { + return { + state: touch(currentState), + action: terminalFromMessages(messages), + messages + }; + } + continue; + } + return { + state: touch(currentState), + action: out.action, + // narrowed: kind !== "emit_message" + messages + }; } - return schema2; + const stateWithError = appendError(currentState, `[runner] coalesce cap (${COALESCE_CAP}) exceeded; suspected handler loop on step '${currentState.current_step}'`, "structural"); + return { + state: touch(stateWithError), + action: { + kind: "failed", + reason: `Runner exceeded emit_message coalesce cap (${COALESCE_CAP}). The pipeline may have an infinite handler loop on step '${currentState.current_step}'.`, + step: currentState.current_step + }, + messages + }; } -function promptArgumentsFromSchema(schema2) { - const shape = getObjectShape(schema2); - if (!shape) - return []; - return Object.entries(shape).map(([name315, field]) => { - const description = getSchemaDescription(field); - const isOptional = isSchemaOptional(field); +function terminalFromMessages(messages) { + const errorMsgs = messages.filter((m) => m.level === "error"); + if (errorMsgs.length > 0) { return { - name: name315, - description, - required: !isOptional + kind: "failed", + reason: errorMsgs.map((m) => m.text).join("\n"), + step: "complete" }; - }); + } + const summary = messages.map((m) => m.level === "info" ? m.text : `[${m.level.toUpperCase()}] ${m.text}`).join("\n"); + return { kind: "done", summary, artifacts: [] }; } -function getMethodValue(schema2) { - const shape = getObjectShape(schema2); - const methodSchema = shape?.method; - if (!methodSchema) { - throw new Error("Schema is missing a method literal"); +function invoke(state, result) { + const handler = HANDLERS[state.current_step]; + if (!handler) { + return { + state, + action: { + kind: "failed", + reason: `No handler for step '${state.current_step}'`, + step: state.current_step + } + }; } - const value = getLiteralValue(methodSchema); - if (typeof value === "string") { - return value; + try { + return handler({ state, result }); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + return { + state: appendError(state, `[${state.current_step}] ${message}`, "structural"), + action: { + kind: "failed", + reason: message, + step: state.current_step + } + }; } - throw new Error("Schema method literal must be a string"); -} -function createCompletionResult(suggestions) { - return { - completion: { - values: suggestions.slice(0, 100), - total: suggestions.length, - hasMore: suggestions.length > 100 - } - }; } -var EMPTY_COMPLETION_RESULT = { - completion: { - values: [], - hasMore: false - } -}; -// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js -import process2 from "node:process"; - -// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js -var ReadBuffer = class { - append(chunk) { - this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; +// packages/orchestration/dist/run-store.js +var InMemoryRunStore = class { + runs = /* @__PURE__ */ new Map(); + get(runId) { + return this.runs.get(runId); } - readMessage() { - if (!this._buffer) { - return null; - } - const index2 = this._buffer.indexOf("\n"); - if (index2 === -1) { - return null; - } - const line = this._buffer.toString("utf8", 0, index2).replace(/\r$/, ""); - this._buffer = this._buffer.subarray(index2 + 1); - return deserializeMessage(line); + set(state) { + this.runs.set(state.run_id, state); } - clear() { - this._buffer = void 0; + delete(runId) { + this.runs.delete(runId); + } + list() { + return Array.from(this.runs.values()); } }; -function deserializeMessage(line) { - return JSONRPCMessageSchema.parse(JSON.parse(line)); + +// packages/orchestration/dist/canned-dispatcher.js +function defaultFakeSectionDraft(section_type) { + const heading = `## ${section_type}`; + switch (section_type) { + case "requirements": + return [ + heading, + "", + "- FR-001: The system supports OAuth login via Google and GitHub.", + "- FR-002: The system stores session tokens in HttpOnly cookies." + ].join("\n"); + case "acceptance_criteria": + return [ + heading, + "", + "- AC-001: A user with valid Google credentials can sign in.", + "- AC-002: A user with invalid credentials sees an error message." + ].join("\n"); + case "technical_specification": + return [ + heading, + "", + "We use ports-and-adapters architecture. The OAuth domain port is", + "implemented by Google and GitHub adapters at the infrastructure layer." + ].join("\n"); + case "performance_requirements": + return [ + heading, + "", + "p95 < 250ms for token validation under nominal load." + ].join("\n"); + case "security_considerations": + return [ + heading, + "", + "All session tokens use AES-256-GCM. Authentication uses OAuth 2.0." + ].join("\n"); + default: + return [heading, "", "Canned synthetic content."].join("\n"); + } } -function serializeMessage(message) { - return JSON.stringify(message) + "\n"; +function fakeJudgeVerdict() { + return JSON.stringify({ + verdict: "PASS", + rationale: "Canned synthetic verdict.", + caveats: [], + confidence: 0.9 + }); } - -// node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@3.25.76/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js -var StdioServerTransport = class { - constructor(_stdin = process2.stdin, _stdout = process2.stdout) { - this._stdin = _stdin; - this._stdout = _stdout; - this._readBuffer = new ReadBuffer(); - this._started = false; - this._ondata = (chunk) => { - this._readBuffer.append(chunk); - this.processReadBuffer(); - }; - this._onerror = (error2) => { - this.onerror?.(error2); - }; +function fakeClarificationQuestion() { + return JSON.stringify({ + question: "What is the primary success metric?", + options: null, + rationale: "Canned placeholder." + }); +} +function makeCannedDispatcher(opts = {}) { + const freeform_answer = opts.freeform_answer ?? "canned-answer"; + const graph_path = opts.graph_path ?? "/tmp/canned/graph"; + const fake_section_draft = opts.fake_section_draft ?? defaultFakeSectionDraft; + function pickFakeAgentResponse(invocation_id) { + if (invocation_id.startsWith(SELF_CHECK_JUDGE_INV_PREFIX)) { + return fakeJudgeVerdict(); + } + if (invocation_id.startsWith(CLARIFICATION_COMPOSE_INV_PREFIX)) { + return fakeClarificationQuestion(); + } + if (invocation_id.startsWith(SECTION_GENERATE_INV_PREFIX)) { + const section_type = invocation_id.slice(SECTION_GENERATE_INV_PREFIX.length); + return fake_section_draft(section_type); + } + if (invocation_id === JIRA_GENERATION_INV_ID) { + return "## JIRA Tickets\n\nCanned JIRA placeholder."; + } + return "Canned synthetic response."; } - /** - * Starts listening for messages on stdin. - */ - async start() { - if (this._started) { - throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); + function craftUserAnswer(action) { + if (action.question_id === QUESTION_ID_CONTINUE) { + return { + kind: "user_answer", + question_id: action.question_id, + selected: ["proceed"] + }; } - this._started = true; - this._stdin.on("data", this._ondata); - this._stdin.on("error", this._onerror); + if (action.options && action.options.length > 0) { + return { + kind: "user_answer", + question_id: action.question_id, + selected: [action.options[0].label] + }; + } + return { + kind: "user_answer", + question_id: action.question_id, + selected: [], + freeform: freeform_answer + }; } - processReadBuffer() { - while (true) { - try { - const message = this._readBuffer.readMessage(); - if (message === null) { - break; + function craftPipelineToolResult(action) { + if (action.tool_name === "index_codebase") { + return { + kind: "tool_result", + correlation_id: action.correlation_id, + success: true, + data: { + graph_path, + symbols_indexed: 0, + files_parsed: 0, + duration_ms: 1 } - this.onmessage?.(message); - } catch (error2) { - this.onerror?.(error2); - } + }; } + return { + kind: "tool_result", + correlation_id: action.correlation_id, + success: true, + data: {} + }; } - async close() { - this._stdin.off("data", this._ondata); - this._stdin.off("error", this._onerror); - const remainingDataListeners = this._stdin.listenerCount("data"); - if (remainingDataListeners === 0) { - this._stdin.pause(); + function craftCortexToolResult(action) { + if (action.tool_name === "recall") { + return { + kind: "tool_result", + correlation_id: action.correlation_id, + success: true, + data: { results: [], total: 0 } + }; } - this._readBuffer.clear(); - this.onclose?.(); + return { + kind: "tool_result", + correlation_id: action.correlation_id, + success: true, + data: {} + }; } - send(message) { - return new Promise((resolve3) => { - const json2 = serializeMessage(message); - if (this._stdout.write(json2)) { - resolve3(); - } else { - this._stdout.once("drain", resolve3); - } - }); + function craftSubagentBatchResult(action) { + const responses = action.invocations.map((inv2) => ({ + invocation_id: inv2.invocation_id, + raw_text: pickFakeAgentResponse(inv2.invocation_id) + })); + return { + kind: "subagent_batch_result", + batch_id: action.batch_id, + responses + }; } -}; - -// packages/mcp-server/dist/index.js -init_zod(); -await init_dist(); -await init_dist(); -await init_dist2(); -import { readFileSync as readFileSync7, existsSync as existsSync10 } from "node:fs"; -import { join as join12, dirname as dirname6 } from "node:path"; -import { fileURLToPath as fileURLToPath2 } from "node:url"; - -// packages/mcp-server/dist/budget-tools.js -init_zod(); -await init_dist(); + function craftFileWritten(action) { + return { + kind: "file_written", + path: action.path, + bytes: Buffer.byteLength(action.content, "utf8") + }; + } + return function dispatch(action) { + switch (action.kind) { + case "ask_user": + return craftUserAnswer(action); + case "call_pipeline_tool": + return craftPipelineToolResult(action); + case "call_cortex_tool": + return craftCortexToolResult(action); + case "spawn_subagents": + return craftSubagentBatchResult(action); + case "write_file": + return craftFileWritten(action); + case "done": + case "failed": + return void 0; + default: { + const _exhaustive = action; + throw new Error(`cannedDispatcher: unhandled action.kind=${action.kind}. Add a case to the dispatch switch.`); + } + } + }; +} // packages/mcp-server/dist/context-budget.js -await init_dist6(); var SECTION_GENERATION_TOKENS = { overview: 1500, goals: 1e3, @@ -35210,16 +33357,7 @@ function registerBudgetTools(server2) { }); } -// packages/mcp-server/dist/pipeline-tools.js -init_zod(); -await init_dist6(); -await init_dist5(); -await init_dist(); -await init_dist3(); - // packages/benchmark/dist/src/runner.js -await init_dist2(); -await init_dist2(); import { readFileSync, readdirSync, existsSync as existsSync3, writeFileSync } from "node:fs"; import { join as join4 } from "node:path"; function loadScenarios(fixturesDir) { @@ -35381,9 +33519,38 @@ if (process.argv[1]?.endsWith("runner.js")) { }); } -// packages/benchmark/dist/src/index.js -await init_pipeline_kpis(); -init_instrumentation(); +// packages/benchmark/dist/src/instrumentation.js +var MISMATCH_PREFIX = "[self_check] plan mismatch detected \u2014 mismatch_kind:"; +var KNOWN_MISMATCH_KINDS = ["content_mutation", "ordering_regression"]; +function isKnownKind(s) { + return KNOWN_MISMATCH_KINDS.includes(s); +} +function extractMismatchEvents(state) { + const events = []; + for (const err of state.errors) { + if (!err.startsWith(MISMATCH_PREFIX)) + continue; + const kind = err.slice(MISMATCH_PREFIX.length).trim(); + if (!isKnownKind(kind)) { + throw new Error(`instrumentation: unknown mismatch_kind '${kind}' in state.errors. Update KNOWN_MISMATCH_KINDS or fix the handler emitter. Raw: ${err}`); + } + events.push({ kind, raw: err }); + } + const distinct = Array.from(new Set(events.map((e3) => e3.kind))); + return { + fired: events.length > 0, + distinctKinds: distinct, + events + }; +} +var MISMATCH_DIAGNOSTIC_PREFIX = MISMATCH_PREFIX; +var MISMATCH_KINDS = KNOWN_MISMATCH_KINDS; + +// packages/benchmark/dist/src/pipeline-kpis.js +var defaultBenchmarkDispatcher = makeCannedDispatcher({ + freeform_answer: "benchmark-answer", + graph_path: "/tmp/benchmark/graph" +}); // packages/benchmark/dist/src/consensus-reliability-adapter.js function fnv1a32(input) { @@ -35420,7 +33587,6 @@ var BenchmarkConsensusReliabilityProvider = class { // packages/benchmark/dist/calibration/heldout-seals.js import { appendFileSync, existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync2 } from "node:fs"; -init_zod(); import { dirname } from "node:path"; var MaxAttemptsHeldoutLockSchema = external_exports.object({ schema_version: external_exports.literal(1), @@ -35501,8 +33667,6 @@ function appendObservationLog(obs, logPath = JUDGE_OBSERVATION_LOG_PATH) { } // packages/benchmark/dist/src/calibrated-gates-loader.js -init_zod(); -await init_pipeline_kpis(); var CalibratedGateEntrySchema = external_exports.object({ gate_name: external_exports.string().min(1), calibrated: external_exports.number(), @@ -35523,7 +33687,6 @@ var CalibratedGatesFileSchema = external_exports.object({ }); // packages/benchmark/dist/calibration/calibration-seams.js -await init_dist6(); function fnv1a322(input) { const FNV_OFFSET_BASIS = 2166136261; const FNV_PRIME = 16777619; @@ -35551,11 +33714,181 @@ function getMaxAttemptsForRun(runId, calibratedValue) { } // packages/benchmark/dist/calibration/mismatch-fire-rate.js -init_clopper_pearson(); -init_xmr(); -init_instrumentation(); import { readFileSync as readFileSync3, readdirSync as readdirSync2, existsSync as existsSync5 } from "node:fs"; import { join as join5 } from "node:path"; + +// packages/benchmark/dist/calibration/clopper-pearson.js +var MAX_ITER = 100; +var EPS = 1e-12; +var FPMIN = 1e-300; +function logGamma(x) { + const cof = [ + 76.18009172947146, + -86.50532032941678, + 24.01409824083091, + -1.231739572450155, + 0.001208650973866179, + -5395239384953e-18 + ]; + let y = x; + let tmp = x + 5.5; + tmp -= (x + 0.5) * Math.log(tmp); + let ser = 1.000000000190015; + for (const c of cof) { + y += 1; + ser += c / y; + } + return -tmp + Math.log(2.5066282746310007 * ser / x); +} +function betacf(a, b, x) { + const qab = a + b; + const qap = a + 1; + const qam = a - 1; + let c = 1; + let d = 1 - qab * x / qap; + if (Math.abs(d) < FPMIN) + d = FPMIN; + d = 1 / d; + let h = d; + for (let m = 1; m <= MAX_ITER; m++) { + const m2 = 2 * m; + let aa = m * (b - m) * x / ((qam + m2) * (a + m2)); + d = 1 + aa * d; + if (Math.abs(d) < FPMIN) + d = FPMIN; + c = 1 + aa / c; + if (Math.abs(c) < FPMIN) + c = FPMIN; + d = 1 / d; + h *= d * c; + aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)); + d = 1 + aa * d; + if (Math.abs(d) < FPMIN) + d = FPMIN; + c = 1 + aa / c; + if (Math.abs(c) < FPMIN) + c = FPMIN; + d = 1 / d; + const del = d * c; + h *= del; + if (Math.abs(del - 1) < EPS) + return h; + } + return h; +} +function betaiRegularized(a, b, x) { + if (x <= 0) + return 0; + if (x >= 1) + return 1; + const bt = Math.exp(logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log(1 - x)); + if (x < (a + 1) / (a + b + 2)) { + return bt * betacf(a, b, x) / a; + } + return 1 - bt * betacf(b, a, 1 - x) / b; +} +function betaInv(p, a, b) { + if (p <= 0) + return 0; + if (p >= 1) + return 1; + let lo = 0; + let hi = 1; + for (let i2 = 0; i2 < 80; i2++) { + const mid = (lo + hi) / 2; + if (betaiRegularized(a, b, mid) < p) + lo = mid; + else + hi = mid; + } + return (lo + hi) / 2; +} +function clopperPearson(successes, trials, confidence = 0.95) { + if (trials <= 0) { + throw new Error("trials must be > 0"); + } + if (successes < 0 || successes > trials) { + throw new Error(`successes must be in [0, trials]`); + } + const alpha = 1 - confidence; + const lower = successes === 0 ? 0 : betaInv(alpha / 2, successes, trials - successes + 1); + const upper = successes === trials ? 1 : betaInv(1 - alpha / 2, successes + 1, trials - successes); + return { + pointEstimate: successes / trials, + lower, + upper, + confidence, + successes, + trials + }; +} + +// packages/benchmark/dist/calibration/xmr.js +var D2_FOR_N2 = 1.128; +var SIGMA_MULTIPLIER = 3; +var RUN_LENGTH_THRESHOLD = 8; +function computeLimits(baseline) { + if (baseline.length < 2) { + throw new Error("XmR requires at least 2 baseline points"); + } + const mean2 = baseline.reduce((s, v) => s + v, 0) / baseline.length; + const ranges = []; + for (let i2 = 1; i2 < baseline.length; i2++) { + ranges.push(Math.abs(baseline[i2] - baseline[i2 - 1])); + } + const meanMR = ranges.reduce((s, v) => s + v, 0) / ranges.length; + const sigmaEstimate = meanMR / D2_FOR_N2; + const halfWidth = SIGMA_MULTIPLIER * sigmaEstimate; + return { + centerline: mean2, + upperControlLimit: mean2 + halfWidth, + lowerControlLimit: mean2 - halfWidth, + meanMovingRange: meanMR, + basePoints: baseline.length + }; +} +function scanSeries(series, limits) { + const signals = []; + for (let i2 = 0; i2 < series.length; i2++) { + const v = series[i2]; + if (v > limits.upperControlLimit || v < limits.lowerControlLimit) { + signals.push({ index: i2, value: v, rule: "outside_3sigma" }); + } + } + let runSide = null; + let runLength = 0; + for (let i2 = 0; i2 < series.length; i2++) { + const side = series[i2] > limits.centerline ? "above" : series[i2] < limits.centerline ? "below" : null; + if (side === null) { + runSide = null; + runLength = 0; + continue; + } + if (side === runSide) { + runLength += 1; + } else { + runSide = side; + runLength = 1; + } + if (runLength === RUN_LENGTH_THRESHOLD) { + signals.push({ index: i2, value: series[i2], rule: "run_of_8" }); + } + } + return { + limits, + signals, + inControl: signals.length === 0 + }; +} +function xmrAnalyze(series, baselineCount) { + if (baselineCount < 2 || baselineCount > series.length) { + throw new Error(`baselineCount must be in [2, series.length]; got ${baselineCount}`); + } + const limits = computeLimits(series.slice(0, baselineCount)); + return scanSeries(series, limits); +} + +// packages/benchmark/dist/calibration/mismatch-fire-rate.js var PRE_REGISTERED_SEED = 828927509507; var PRD_CONTEXT_DOMAIN = [ "proposal", @@ -35768,30 +34101,7 @@ if (process.argv[1]?.endsWith("mismatch-fire-rate.js") || process.argv[1]?.endsW }); } -// packages/benchmark/dist/calibration/index.js -init_clopper_pearson(); -init_xmr(); -init_machine_class(); - -// packages/benchmark/dist/calibration/gate-tuning-seams.js -init_machine_class(); - -// packages/benchmark/dist/calibration/calibrate-gates.js -await init_pipeline_kpis(); -init_clopper_pearson(); -init_machine_class(); -init_gate_stats(); -init_event_rate(); -import { writeFileSync as writeFileSync4, mkdirSync as mkdirSync6, existsSync as existsSync9, readFileSync as readFileSync6 } from "node:fs"; -import { dirname as dirname5, join as join8 } from "node:path"; -import { execSync as execSync3 } from "node:child_process"; - // packages/benchmark/dist/calibration/calibration-outputs.js -init_zod(); -import { readFileSync as readFileSync4, writeFileSync as writeFileSync2, mkdirSync as mkdirSync4, existsSync as existsSync6 } from "node:fs"; -import { dirname as dirname2 } from "node:path"; -var GATE_CALIBRATION_K100_PATH = "packages/benchmark/calibration/data/gate-calibration-K100.json"; -var EVENT_RATE_K50_PATH = "packages/benchmark/calibration/data/event-rate-K50.json"; var XmRRecordSchema = external_exports.object({ centerline: external_exports.number(), upperControlLimit: external_exports.number(), @@ -35864,298 +34174,6 @@ var EventRateK50Schema = external_exports.object({ diverges_beyond_tolerance: external_exports.boolean(), recompute_recommended: external_exports.boolean() }); -function writeGateCalibrationK100(artefact, path = GATE_CALIBRATION_K100_PATH) { - const parsed = GateCalibrationK100Schema.safeParse(artefact); - if (!parsed.success) { - throw new Error(`writeGateCalibrationK100: artefact failed schema validation: -` + parsed.error.issues.map((i2) => ` ${i2.path.join(".") || ""}: ${i2.message}`).join("\n")); - } - const dir = dirname2(path); - if (!existsSync6(dir)) - mkdirSync4(dir, { recursive: true }); - writeFileSync2(path, JSON.stringify(parsed.data, null, 2) + "\n", "utf8"); -} -function writeEventRateK50(artefact, path = EVENT_RATE_K50_PATH) { - const parsed = EventRateK50Schema.safeParse(artefact); - if (!parsed.success) { - throw new Error(`writeEventRateK50: artefact failed schema validation: -` + parsed.error.issues.map((i2) => ` ${i2.path.join(".") || ""}: ${i2.message}`).join("\n")); - } - const dir = dirname2(path); - if (!existsSync6(dir)) - mkdirSync4(dir, { recursive: true }); - writeFileSync2(path, JSON.stringify(parsed.data, null, 2) + "\n", "utf8"); -} - -// packages/benchmark/dist/calibration/calibrate-gates.js -init_frozen_baseline(); -init_calibrate_gates_constants(); -init_calibrate_gates_cli(); -var GATE_ESTIMAND2 = { - iteration_count_max: "p95", - wall_time_ms_max: "p95", - section_fail_count_max: "p95", - error_count_max: "p95", - mean_section_attempts_max: "p95", - cortex_recall_empty_count_max: "p95" -}; -var GATE_EXTRACTORS2 = { - iteration_count_max: (k) => k.iteration_count, - wall_time_ms_max: (k) => k.wall_time_ms, - section_fail_count_max: (k) => k.section_fail_count, - error_count_max: (k) => k.error_count, - mean_section_attempts_max: (k) => k.mean_section_attempts, - cortex_recall_empty_count_max: (k) => k.cortex_recall_empty_count, - distribution_pass_rate_max: null, - safety_cap_hit_allowed: null, - structural_error_count_max: null -}; -function mulberry322(seed) { - let state = seed >>> 0; - return () => { - state = state + 1831565813 >>> 0; - let t = state; - t = Math.imul(t ^ t >>> 15, t | 1); - t ^= t + Math.imul(t ^ t >>> 7, t | 61); - return ((t ^ t >>> 14) >>> 0) / 4294967296; - }; -} -function driveRuns(args) { - const rng = mulberry322(args.seed); - const out = []; - for (let i2 = 0; i2 < args.k; i2++) { - const runId = `${args.runIdPrefix}-${i2}-${Math.floor(rng() * 4294967295).toString(16).padStart(8, "0")}`; - const input = { - run_id: runId, - feature_description: args.featureDescription, - codebase_path: args.codebasePath - }; - out.push(measurePipeline(input)); - } - return out; -} -function buildSuspendedEntry2(gateName, k) { - const v = KPI_GATES[gateName]; - const numericV = typeof v === "boolean" ? v ? 1 : 0 : v; - return { - gate_name: gateName, - estimand_type: "p95", - k_observed: k, - provisional: numericV, - calibrated: numericV, - ci_upper: null, - ci_lower: null, - would_tighten: false, - would_loosen: false, - passes_threshold: false, - xmr_path: null, - machine_class: null - }; -} -function buildNumericEntry2(args) { - const { gateName, values, machineClass, outputDir } = args; - if (values.length < 2) { - throw new Error(`buildNumericEntry: ${gateName} has <2 observations (K=${values.length})`); - } - const isWallTime = gateName === "wall_time_ms_max"; - const provisional = KPI_GATES[gateName]; - const stats = computeGateStats(values); - const calibrated = stats.p95; - const xmrFileName = isWallTime ? `${gateName}.${machineClass}.json` : `${gateName}.json`; - const xmrPath = join8(outputDir, "gate-calibration-K100.xmr", xmrFileName); - const entry = { - gate_name: gateName, - estimand_type: GATE_ESTIMAND2[gateName] ?? "p95", - k_observed: values.length, - provisional, - calibrated, - ci_upper: stats.ci_upper, - ci_lower: stats.ci_lower, - would_tighten: calibrated < provisional, - would_loosen: calibrated > provisional, - // §4.5 promotion criterion: 95% CI excludes the provisional value AND - // the calibrated value departs by ≥5% relative. - passes_threshold: (stats.ci_upper < provisional || stats.ci_lower > provisional) && Math.abs(calibrated - provisional) / Math.max(provisional, 1e-9) >= 0.05, - xmr_path: xmrPath, - machine_class: isWallTime ? machineClass : null - }; - return { entry, xmrFile: { path: xmrPath, record: stats.xmr } }; -} -function buildCalibrationEntries2(args) { - const entries = []; - const xmrFiles = []; - for (const gateName of Object.keys(KPI_GATES)) { - const extractor = GATE_EXTRACTORS2[gateName]; - if (extractor == null) { - entries.push(buildSuspendedEntry2(gateName, args.kpis.length)); - continue; - } - const values = args.kpis.map((k) => extractor(k)); - const { entry, xmrFile } = buildNumericEntry2({ - gateName, - values, - machineClass: args.machineClass, - outputDir: args.outputDir - }); - entries.push(entry); - xmrFiles.push(xmrFile); - } - return { entries, xmrFiles }; -} -function preflightFrozenBaselineCheck(outputDir, skipCheck) { - const currentHash = computePipelineKpisContentHash(); - if (skipCheck) - return currentHash; - const existingPath = join8(outputDir, "gate-calibration-K100.json"); - if (!existsSync9(existingPath)) - return currentHash; - let existing; - try { - existing = JSON.parse(readFileSync6(existingPath, "utf8")); - } catch { - return currentHash; - } - if (existing.gates && existing.gates.length > 0 && existing.frozen_baseline_content_hash && existing.frozen_baseline_content_hash !== currentHash) { - throw new Error(`frozen-baseline content hash mismatch: - recorded: ${existing.frozen_baseline_content_hash} - current: ${currentHash} -Per docs/PHASE_4_PLAN.md \xA74.5 (Popper AP-1 ratchet protection): re-run requires committing to a frozen baseline. Either revert pipeline-kpis.ts to the recorded hash or accept that calibration must be re-done from scratch (delete the existing JSON and re-run with --skip-frozen-baseline-check on the first new run).`); - } - return currentHash; -} -function buildEventRateArtefact(options, headCommit, nowIso) { - const eventRateKpis = driveRuns({ - k: options.eventRateK, - seed: PRE_REGISTERED_SEED_42, - runIdPrefix: "phase42-eventrate", - featureDescription: options.featureDescription, - codebasePath: options.codebasePath - }); - const { totalAttempts, events } = measureEventRate(eventRateKpis); - const measuredRate = totalAttempts > 0 ? events / totalAttempts : 0; - const cp = totalAttempts > 0 ? clopperPearson(events, totalAttempts, 0.95) : { lower: 0, upper: 0, pointEstimate: 0 }; - const diverges = Math.abs(measuredRate - PROVISIONAL_EVENT_RATE) > EVENT_RATE_TOLERANCE; - return { - schema_version: 1, - commit_hash: headCommit, - seed_used: PRE_REGISTERED_SEED_42, - timestamp: nowIso, - k_target: options.eventRateK, - k_observed: eventRateKpis.length, - total_attempts: totalAttempts, - total_events: events, - measured_event_rate: measuredRate, - ci95_clopper_pearson: { lower: cp.lower, upper: cp.upper }, - provisional_anchor: PROVISIONAL_EVENT_RATE, - diverges_beyond_tolerance: diverges, - recompute_recommended: diverges - }; -} -function persistArtefacts(result, outputDir) { - writeGateCalibrationK100(result.gateCalibration, join8(outputDir, "gate-calibration-K100.json")); - writeEventRateK50(result.eventRate, join8(outputDir, "event-rate-K50.json")); - for (const xmr of result.xmrFiles) { - const dir = dirname5(xmr.path); - if (!existsSync9(dir)) - mkdirSync6(dir, { recursive: true }); - writeFileSync4(xmr.path, JSON.stringify(xmr.record, null, 2) + "\n", "utf8"); - } -} -function resolveHeadCommit2() { - try { - return execSync3("git rev-parse HEAD", { encoding: "utf8" }).trim(); - } catch { - return "unknown"; - } -} -function runCalibration(options) { - if (options.k < 2) { - throw new Error(`runCalibration: k must be \u2265 2 (got ${options.k})`); - } - if (options.eventRateK < 1) { - throw new Error(`runCalibration: eventRateK must be \u2265 1 (got ${options.eventRateK})`); - } - const currentHash = preflightFrozenBaselineCheck(options.outputDir, options.skipFrozenBaselineCheck); - const kpis = driveRuns({ - k: options.k, - seed: PRE_REGISTERED_SEED_45, - runIdPrefix: "phase45-calib", - featureDescription: options.featureDescription, - codebasePath: options.codebasePath - }); - const machineClass = detectMachineClass(); - const { entries, xmrFiles } = buildCalibrationEntries2({ - kpis, - machineClass, - outputDir: options.outputDir - }); - const nowIso = (/* @__PURE__ */ new Date()).toISOString(); - const headCommit = resolveHeadCommit2(); - const gateCalibration = { - schema_version: 1, - commit_hash: headCommit, - seed_used: PRE_REGISTERED_SEED_45, - timestamp: nowIso, - k_target: options.k, - k_achieved: kpis.length, - frozen_baseline_commit: options.frozenBaselineCommit, - frozen_baseline_content_hash: currentHash, - gates: [...entries] - }; - const eventRate = buildEventRateArtefact(options, headCommit, nowIso); - const summary = buildSummary(gateCalibration, eventRate); - if (!options.inMemoryOnly) { - persistArtefacts({ gateCalibration, eventRate, xmrFiles }, options.outputDir); - } - return { gateCalibration, eventRate, xmrFiles, summary }; -} -async function main2(argv) { - const mode2 = parseFlag(argv, "mode") ?? "canned"; - if (mode2 === "production") { - const { runProductionFromCli: runProductionFromCli2 } = await init_calibrate_gates_production_cli().then(() => calibrate_gates_production_cli_exports); - await runProductionFromCli2({ argv }); - return; - } - if (mode2 !== "canned") { - throw new Error(`calibrate-gates: --mode must be "canned" or "production" (got "${mode2}")`); - } - const k = Number(parseFlag(argv, "k") ?? DEFAULT_K); - const eventRateK = Number(parseFlag(argv, "event-rate-k") ?? DEFAULT_EVENT_RATE_K); - const outputDir = parseFlag(argv, "output-dir") ?? "packages/benchmark/calibration/data"; - const skipFrozenBaselineCheck = hasFlag(argv, "skip-frozen-baseline-check"); - const frozenBaselineCommit = parseFlag(argv, "frozen-baseline-commit") ?? resolveFrozenBaselineCommit(); - const result = runCalibration({ - k, - eventRateK, - outputDir, - frozenBaselineCommit, - skipFrozenBaselineCheck, - featureDescription: "build a feature for OAuth login", - codebasePath: "/tmp/benchmark", - inMemoryOnly: false - }); - for (const line of result.summary) - console.log(line); -} -var invokedDirectly2 = (() => { - try { - return typeof process !== "undefined" && Array.isArray(process.argv) && process.argv[1] !== void 0 && (process.argv[1].endsWith("calibrate-gates.js") || process.argv[1].endsWith("calibrate-gates.ts")); - } catch { - return false; - } -})(); -if (invokedDirectly2) { - main2(process.argv.slice(2)).catch((err) => { - console.error(err); - process.exit(1); - }); -} - -// packages/benchmark/dist/calibration/index.js -init_calibrate_gates_constants(); -init_gate_stats(); -init_event_rate(); -init_frozen_baseline(); // packages/benchmark/dist/calibration/schema-oracle.js import { createRequire } from "module"; @@ -42374,7 +40392,7 @@ function filterRegExp(array2, regexp) { } return Array.prototype.filter.call(array2, (entry) => regexp.test(entry)); } -function join9(array2, separator) { +function join6(array2, separator) { return Array.prototype.join.call(array2, separator); } function identify(a) { @@ -61377,8 +59395,8 @@ var createFunctionAssignmentNode = /* @__PURE__ */ factory(name213, dependencies var evalExpr = this.expr._compile(math2, childArgNames); var name315 = this.name; var params = this.params; - var signature = join9(this.types, ","); - var syntax = name315 + "(" + join9(this.params, ", ") + ")"; + var signature = join6(this.types, ","); + var syntax = name315 + "(" + join6(this.params, ", ") + ")"; return function evalFunctionAssignmentNode(scope, args, context) { var signatures = {}; signatures[signature] = function() { @@ -70162,7 +68180,7 @@ function createRealSymmetric(_ref) { multiply: multiply2, add: add3 } = _ref; - function main4(arr, N) { + function main3(arr, N) { var prec = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : config5.relTol; var type2 = arguments.length > 3 ? arguments[3] : void 0; var computeVectors = arguments.length > 4 ? arguments[4] : void 0; @@ -70400,7 +68418,7 @@ function createRealSymmetric(_ref) { eigenvectors }; } - return main4; + return main3; } // node_modules/.pnpm/mathjs@13.2.3/node_modules/mathjs/lib/esm/function/matrix/eigs.js @@ -72996,7 +71014,7 @@ var createSimplify = /* @__PURE__ */ factory(name279, dependencies280, (_ref) => typed: typed3, parse: parse6, equal: equal2, - resolve: resolve3, + resolve: resolve2, simplifyConstant: simplifyConstant2, simplifyCore: simplifyCore2, AccessorNode: AccessorNode2, @@ -73573,7 +71591,7 @@ var createSimplify = /* @__PURE__ */ factory(name279, dependencies280, (_ref) => var options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {}; var debug = options.consoleDebug; rules = _buildRules(rules || simplify2.rules, options.context); - var res = resolve3(expr, scope); + var res = resolve2(expr, scope); res = removeParens(res); var visited = {}; var str2 = res.toString({ @@ -78869,7 +76887,7 @@ var parse5 = createParse({ numeric: numeric2, typed: typed2 }); -var resolve2 = createResolve({ +var resolve = createResolve({ ConstantNode, FunctionNode, OperatorNode, @@ -78940,7 +76958,7 @@ var simplify = createSimplify({ SymbolNode, equal, parse: parse5, - resolve: resolve2, + resolve, simplifyConstant, simplifyCore, typed: typed2 @@ -79273,7 +77291,7 @@ var help = createHelp({ permutations, planckMass, polynomialRoot, - resolve: resolve2, + resolve, setSize, simplifyConstant, solveODE, @@ -79533,9 +77551,9 @@ async function mathOracle(payload) { // packages/benchmark/dist/calibration/code-oracle.js import { execFileSync } from "child_process"; -import { mkdtempSync, writeFileSync as writeFileSync5, rmSync } from "fs"; +import { mkdtempSync, writeFileSync as writeFileSync2, rmSync } from "fs"; import { tmpdir } from "os"; -import { join as join10 } from "path"; +import { join as join7 } from "path"; // packages/benchmark/dist/calibration/oracle-errors.js var OracleUnavailableError = class _OracleUnavailableError extends Error { @@ -79578,10 +77596,10 @@ async function codeOracle(payload) { tscVersion = execFileSync(tscBin, ["--version"], { timeout: 3e3, stdio: "pipe" }).toString().trim(); } catch { } - const tempDir = mkdtempSync(join10(tmpdir(), "prd-gen-code-oracle-")); - const snippetFile = join10(tempDir, "snippet.ts"); + const tempDir = mkdtempSync(join7(tmpdir(), "prd-gen-code-oracle-")); + const snippetFile = join7(tempDir, "snippet.ts"); try { - writeFileSync5(snippetFile, snippet3, "utf8"); + writeFileSync2(snippetFile, snippet3, "utf8"); let compilesCleanly; let stderr = ""; try { @@ -79613,7 +77631,6 @@ function snippetSummary(snippet3) { } // packages/benchmark/dist/calibration/spec-oracle.js -await init_dist2(); var MAX_VIOLATION_IDS_IN_EVIDENCE = 5; async function specOracle(payload) { const { markdown, section_type, expected_passes } = payload; @@ -79655,15 +77672,10 @@ async function invokeOracle(input) { } } -// packages/benchmark/dist/calibration/index.js -await init_calibrate_gates_production(); -await init_calibrate_gates_production_cli(); - // packages/mcp-server/dist/reliability-wiring.js -await init_dist(); -import { join as join11 } from "node:path"; +import { join as join8 } from "node:path"; import { homedir as homedir3 } from "node:os"; -var DEFAULT_RELIABILITY_DB_PATH = join11(homedir3(), ".prd-gen", "reliability.db"); +var DEFAULT_RELIABILITY_DB_PATH = join8(homedir3(), ".prd-gen", "reliability.db"); var _reliabilityRepo = void 0; var _reliabilityProvider = void 0; function getReliabilityRepo() { @@ -80029,29 +78041,29 @@ function registerPipelineTools(server2) { } // packages/mcp-server/dist/index.js -var __dirname = dirname6(fileURLToPath2(import.meta.url)); -var PLUGIN_ROOT = process.env.CLAUDE_PLUGIN_ROOT ?? join12(__dirname, "..", "..", ".."); +var __dirname = dirname2(fileURLToPath(import.meta.url)); +var PLUGIN_ROOT = process.env.CLAUDE_PLUGIN_ROOT ?? join9(__dirname, "..", "..", ".."); function loadSkillConfig() { const configPaths = [ process.env.PRD_GEN_SKILL_CONFIG, - join12(PLUGIN_ROOT, "skill-config.json"), - join12(PLUGIN_ROOT, "packages", "skill", "skill-config.json") + join9(PLUGIN_ROOT, "skill-config.json"), + join9(PLUGIN_ROOT, "packages", "skill", "skill-config.json") ].filter(Boolean); for (const p of configPaths) { - if (existsSync10(p)) { - return JSON.parse(readFileSync7(p, "utf-8")); + if (existsSync6(p)) { + return JSON.parse(readFileSync4(p, "utf-8")); } } return { version: "2.0.0", status: "config_not_found" }; } function loadSkillMd() { const skillPaths = [ - join12(PLUGIN_ROOT, "skills", "prd-spec-generator", "SKILL.md"), - join12(PLUGIN_ROOT, "packages", "skill", "SKILL.md") + join9(PLUGIN_ROOT, "skills", "prd-spec-generator", "SKILL.md"), + join9(PLUGIN_ROOT, "packages", "skill", "SKILL.md") ]; for (const p of skillPaths) { - if (existsSync10(p)) { - return readFileSync7(p, "utf-8"); + if (existsSync6(p)) { + return readFileSync4(p, "utf-8"); } } return "SKILL.md not found"; @@ -80205,14 +78217,14 @@ server.tool("get_strategy_effectiveness", "Get strategy performance data \u2014 isError: true }; } - const performance3 = repo.getStrategyPerformance(min_executions); + const performance = repo.getStrategyPerformance(min_executions); const adjustments = repo.getHistoricalAdjustments(min_executions); return { content: [ { type: "text", text: JSON.stringify({ - performance: performance3, + performance, adjustments: Object.fromEntries(adjustments) }, null, 2) } @@ -80221,7 +78233,7 @@ server.tool("get_strategy_effectiveness", "Get strategy performance data \u2014 }); registerBudgetTools(server); registerPipelineTools(server); -async function main3() { +async function main2() { const reliabilityHealth = checkReliabilityHealth(); if (!reliabilityHealth.healthy) { console.error(`[prd-gen] reliability.db health check FAILED: ${reliabilityHealth.message}`); @@ -80229,7 +78241,7 @@ async function main3() { const transport = new StdioServerTransport(); await server.connect(transport); } -main3().catch((error2) => { +main2().catch((error2) => { console.error("MCP server failed to start:", error2); process.exit(1); }); diff --git a/packages/benchmark/calibration/index.ts b/packages/benchmark/calibration/index.ts index 0f22f34..8844ffd 100644 --- a/packages/benchmark/calibration/index.ts +++ b/packages/benchmark/calibration/index.ts @@ -78,11 +78,10 @@ export { // Consumed only by the composition root (@prd-gen/mcp-server). export { BenchmarkConsensusReliabilityProvider } from "./consensus-reliability-adapter.js"; -// Phase 4.5 — calibration runner + outputs (Wave D / D3). -export { - runCalibration, - type RunnerResult, -} from "./calibrate-gates.js"; +// Phase 4.5 — calibration outputs + constants (Wave D / D3). +// NOTE: the script-only runner `runCalibration` (and `selectModeFromArgv`) are +// intentionally NOT re-exported from this barrel — see the §2.2 boundary note +// at the foot of this file. export { PRE_REGISTERED_SEED_45, PRE_REGISTERED_SEED_42, @@ -129,23 +128,25 @@ export { } from "./external-oracle.js"; export { OracleUnavailableError } from "./oracle-errors.js"; -// Wave F2 — production-mode calibration runner. -// Companion to runCalibration (canned-baseline). Output is written to a -// parallel artefact (gate-calibration-K100-production.json). -export { - runProductionCalibration, - PRE_REGISTERED_SEED_45_PRODUCTION, - DEFAULT_K_PRODUCTION, - PRODUCTION_OUTPUT_BASENAME, - type ProductionRunnerOptions, - type ProductionRunnerResult, - type ProductionGateCalibration, -} from "./calibrate-gates-production.js"; - -// Wave F final remediation — CLI entry extracted to its own module to keep -// calibrate-gates-production.ts under the §4.1 500-LOC cap. The re-export -// here preserves the public surface for any consumer that imports it from -// the calibration barrel. -export { runProductionFromCli } from "./calibrate-gates-production-cli.js"; - -export { selectModeFromArgv } from "./calibrate-gates.js"; +// ─── §2.2 layer boundary: script-only runners are NOT re-exported here ─────── +// +// `calibrate-gates.ts`, `calibrate-gates-production.ts`, and +// `calibrate-gates-production-cli.ts` are *script-only* modules (top-level +// await, FS writes, deterministic CLI side effects — see the layer-contract +// banner in calibrate-gates-production.ts §2.2). Re-exporting their runners +// (`runCalibration`, `selectModeFromArgv`, `runProductionCalibration`, +// `runProductionFromCli`) from this *library* barrel pulled the whole +// top-level-await script island into every static consumer of +// `@prd-gen/benchmark/calibration`. +// +// The composition root (@prd-gen/mcp-server) imports this barrel only for the +// library-safe oracle + stats seams above. esbuild, bundling the MCP server, +// must initialise every statically-reachable module — so the script island's +// top-level await was awaited at server startup and never settled, deadlocking +// `server.connect()` (the MCP `initialize` handshake never completed). +// +// The runners have no barrel consumers; the CLIs and their tests import them +// directly from their own modules (e.g. `./calibrate-gates.js`). Keeping them +// out of the library barrel is the fix. +// +// source: this PR — MCP startup deadlock root-cause; coding-standards.md §2.2.