40280 lines
1.3 MiB
40280 lines
1.3 MiB
// @bun
|
|
var __create = Object.create;
|
|
var __getProtoOf = Object.getPrototypeOf;
|
|
var __defProp = Object.defineProperty;
|
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
function __accessProp(key) {
|
|
return this[key];
|
|
}
|
|
var __toESMCache_node;
|
|
var __toESMCache_esm;
|
|
var __toESM = (mod, isNodeMode, target) => {
|
|
var canCache = mod != null && typeof mod === "object";
|
|
if (canCache) {
|
|
var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
|
|
var cached = cache.get(mod);
|
|
if (cached)
|
|
return cached;
|
|
}
|
|
target = mod != null ? __create(__getProtoOf(mod)) : {};
|
|
const to = isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
|
|
if (mod && typeof mod === "object" || typeof mod === "function") {
|
|
for (let key of __getOwnPropNames(mod))
|
|
if (!__hasOwnProp.call(to, key))
|
|
__defProp(to, key, {
|
|
get: __accessProp.bind(mod, key),
|
|
enumerable: true
|
|
});
|
|
}
|
|
if (canCache)
|
|
cache.set(mod, to);
|
|
return to;
|
|
};
|
|
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/code.js
|
|
var require_code = __commonJS(function(exports) {
|
|
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 = undefined;
|
|
|
|
class _CodeOrName {
|
|
}
|
|
exports._CodeOrName = _CodeOrName;
|
|
exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
|
|
|
|
class Name 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() {
|
|
return false;
|
|
}
|
|
get names() {
|
|
return { [this.str]: 1 };
|
|
}
|
|
}
|
|
exports.Name = Name;
|
|
|
|
class _Code 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 !== undefined ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, "");
|
|
}
|
|
get names() {
|
|
var _a;
|
|
return (_a = this._names) !== null && _a !== undefined ? _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 i = 0;
|
|
while (i < args.length) {
|
|
addCodeArg(code, args[i]);
|
|
code.push(strs[++i]);
|
|
}
|
|
return new _Code(code);
|
|
}
|
|
exports._ = _;
|
|
var plus = new _Code("+");
|
|
function str(strs, ...args) {
|
|
const expr = [safeStringify(strs[0])];
|
|
let i = 0;
|
|
while (i < args.length) {
|
|
expr.push(plus);
|
|
addCodeArg(expr, args[i]);
|
|
expr.push(plus, safeStringify(strs[++i]));
|
|
}
|
|
optimize(expr);
|
|
return new _Code(expr);
|
|
}
|
|
exports.str = str;
|
|
function addCodeArg(code, arg) {
|
|
if (arg instanceof _Code)
|
|
code.push(...arg._items);
|
|
else if (arg instanceof Name)
|
|
code.push(arg);
|
|
else
|
|
code.push(interpolate(arg));
|
|
}
|
|
exports.addCodeArg = addCodeArg;
|
|
function optimize(expr) {
|
|
let i = 1;
|
|
while (i < expr.length - 1) {
|
|
if (expr[i] === plus) {
|
|
const res = mergeExprItems(expr[i - 1], expr[i + 1]);
|
|
if (res !== undefined) {
|
|
expr.splice(i - 1, 3, res);
|
|
continue;
|
|
}
|
|
expr[i++] = "+";
|
|
}
|
|
i++;
|
|
}
|
|
}
|
|
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 : str`${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 stringify(x) {
|
|
return new _Code(safeStringify(x));
|
|
}
|
|
exports.stringify = stringify;
|
|
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/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/scope.js
|
|
var require_scope = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = undefined;
|
|
var code_1 = require_code();
|
|
|
|
class ValueError extends Error {
|
|
constructor(name) {
|
|
super(`CodeGen: "code" for ${name} not defined`);
|
|
this.value = name.value;
|
|
}
|
|
}
|
|
var UsedValueState;
|
|
(function(UsedValueState) {
|
|
UsedValueState[UsedValueState["Started"] = 0] = "Started";
|
|
UsedValueState[UsedValueState["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")
|
|
};
|
|
|
|
class Scope {
|
|
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 === undefined ? undefined : _a._prefixes) === null || _b === undefined ? undefined : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) {
|
|
throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
|
|
}
|
|
return this._names[prefix] = { prefix, index: 0 };
|
|
}
|
|
}
|
|
exports.Scope = Scope;
|
|
|
|
class ValueScopeName 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`;
|
|
|
|
class ValueScope 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 === undefined)
|
|
throw new Error("CodeGen: ref must be passed in value");
|
|
const name = this.toName(nameOrPrefix);
|
|
const { prefix } = name;
|
|
const valueKey = (_a = value.key) !== null && _a !== undefined ? _a : value.ref;
|
|
let vs = this._values[prefix];
|
|
if (vs) {
|
|
const _name = vs.get(valueKey);
|
|
if (_name)
|
|
return _name;
|
|
} else {
|
|
vs = this._values[prefix] = new Map;
|
|
}
|
|
vs.set(valueKey, name);
|
|
const s = this._scope[prefix] || (this._scope[prefix] = []);
|
|
const itemIndex = s.length;
|
|
s[itemIndex] = value.ref;
|
|
name.setValue(value, { property: prefix, itemIndex });
|
|
return name;
|
|
}
|
|
getValue(prefix, keyOrRef) {
|
|
const vs = this._values[prefix];
|
|
if (!vs)
|
|
return;
|
|
return vs.get(keyOrRef);
|
|
}
|
|
scopeRefs(scopeName, values = this._values) {
|
|
return this._reduceValues(values, (name) => {
|
|
if (name.scopePath === undefined)
|
|
throw new Error(`CodeGen: name "${name}" has no value`);
|
|
return (0, code_1._)`${scopeName}${name.scopePath}`;
|
|
});
|
|
}
|
|
scopeCode(values = this._values, usedValues, getCode) {
|
|
return this._reduceValues(values, (name) => {
|
|
if (name.value === undefined)
|
|
throw new Error(`CodeGen: name "${name}" has no value`);
|
|
return name.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] || new Map;
|
|
vs.forEach((name) => {
|
|
if (nameSet.has(name))
|
|
return;
|
|
nameSet.set(name, UsedValueState.Started);
|
|
let c = valueCode(name);
|
|
if (c) {
|
|
const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;
|
|
code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`;
|
|
} else if (c = getCode === null || getCode === undefined ? undefined : getCode(name)) {
|
|
code = (0, code_1._)`${code}${c}${this.opts._n}`;
|
|
} else {
|
|
throw new ValueError(name);
|
|
}
|
|
nameSet.set(name, UsedValueState.Completed);
|
|
});
|
|
}
|
|
return code;
|
|
}
|
|
}
|
|
exports.ValueScope = ValueScope;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/codegen/index.js
|
|
var require_codegen = __commonJS(function(exports) {
|
|
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._ = undefined;
|
|
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("+")
|
|
};
|
|
|
|
class Node {
|
|
optimizeNodes() {
|
|
return this;
|
|
}
|
|
optimizeNames(_names, _constants) {
|
|
return this;
|
|
}
|
|
}
|
|
|
|
class Def extends Node {
|
|
constructor(varKind, name, rhs) {
|
|
super();
|
|
this.varKind = varKind;
|
|
this.name = name;
|
|
this.rhs = rhs;
|
|
}
|
|
render({ es5, _n }) {
|
|
const varKind = es5 ? scope_1.varKinds.var : this.varKind;
|
|
const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}`;
|
|
return `${varKind} ${this.name}${rhs};` + _n;
|
|
}
|
|
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 : {};
|
|
}
|
|
}
|
|
|
|
class Assign extends Node {
|
|
constructor(lhs, rhs, sideEffects) {
|
|
super();
|
|
this.lhs = lhs;
|
|
this.rhs = rhs;
|
|
this.sideEffects = sideEffects;
|
|
}
|
|
render({ _n }) {
|
|
return `${this.lhs} = ${this.rhs};` + _n;
|
|
}
|
|
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 names() {
|
|
const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
|
|
return addExprNames(names, this.rhs);
|
|
}
|
|
}
|
|
|
|
class AssignOp extends Assign {
|
|
constructor(lhs, op, rhs, sideEffects) {
|
|
super(lhs, rhs, sideEffects);
|
|
this.op = op;
|
|
}
|
|
render({ _n }) {
|
|
return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
|
|
}
|
|
}
|
|
|
|
class Label extends Node {
|
|
constructor(label) {
|
|
super();
|
|
this.label = label;
|
|
this.names = {};
|
|
}
|
|
render({ _n }) {
|
|
return `${this.label}:` + _n;
|
|
}
|
|
}
|
|
|
|
class Break extends Node {
|
|
constructor(label) {
|
|
super();
|
|
this.label = label;
|
|
this.names = {};
|
|
}
|
|
render({ _n }) {
|
|
const label = this.label ? ` ${this.label}` : "";
|
|
return `break${label};` + _n;
|
|
}
|
|
}
|
|
|
|
class Throw extends Node {
|
|
constructor(error) {
|
|
super();
|
|
this.error = error;
|
|
}
|
|
render({ _n }) {
|
|
return `throw ${this.error};` + _n;
|
|
}
|
|
get names() {
|
|
return this.error.names;
|
|
}
|
|
}
|
|
|
|
class AnyCode extends Node {
|
|
constructor(code) {
|
|
super();
|
|
this.code = code;
|
|
}
|
|
render({ _n }) {
|
|
return `${this.code};` + _n;
|
|
}
|
|
optimizeNodes() {
|
|
return `${this.code}` ? this : undefined;
|
|
}
|
|
optimizeNames(names, constants) {
|
|
this.code = optimizeExpr(this.code, names, constants);
|
|
return this;
|
|
}
|
|
get names() {
|
|
return this.code instanceof code_1._CodeOrName ? this.code.names : {};
|
|
}
|
|
}
|
|
|
|
class ParentNode extends Node {
|
|
constructor(nodes = []) {
|
|
super();
|
|
this.nodes = nodes;
|
|
}
|
|
render(opts) {
|
|
return this.nodes.reduce((code, n) => code + n.render(opts), "");
|
|
}
|
|
optimizeNodes() {
|
|
const { nodes } = this;
|
|
let i = nodes.length;
|
|
while (i--) {
|
|
const n = nodes[i].optimizeNodes();
|
|
if (Array.isArray(n))
|
|
nodes.splice(i, 1, ...n);
|
|
else if (n)
|
|
nodes[i] = n;
|
|
else
|
|
nodes.splice(i, 1);
|
|
}
|
|
return nodes.length > 0 ? this : undefined;
|
|
}
|
|
optimizeNames(names, constants) {
|
|
const { nodes } = this;
|
|
let i = nodes.length;
|
|
while (i--) {
|
|
const n = nodes[i];
|
|
if (n.optimizeNames(names, constants))
|
|
continue;
|
|
subtractNames(names, n.names);
|
|
nodes.splice(i, 1);
|
|
}
|
|
return nodes.length > 0 ? this : undefined;
|
|
}
|
|
get names() {
|
|
return this.nodes.reduce((names, n) => addNames(names, n.names), {});
|
|
}
|
|
}
|
|
|
|
class BlockNode extends ParentNode {
|
|
render(opts) {
|
|
return "{" + opts._n + super.render(opts) + "}" + opts._n;
|
|
}
|
|
}
|
|
|
|
class Root extends ParentNode {
|
|
}
|
|
|
|
class Else extends BlockNode {
|
|
}
|
|
Else.kind = "else";
|
|
|
|
class If extends BlockNode {
|
|
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;
|
|
}
|
|
optimizeNodes() {
|
|
super.optimizeNodes();
|
|
const cond = this.condition;
|
|
if (cond === true)
|
|
return this.nodes;
|
|
let e = this.else;
|
|
if (e) {
|
|
const ns = e.optimizeNodes();
|
|
e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
|
|
}
|
|
if (e) {
|
|
if (cond === false)
|
|
return e instanceof If ? e : e.nodes;
|
|
if (this.nodes.length)
|
|
return this;
|
|
return new If(not(cond), e instanceof If ? [e] : e.nodes);
|
|
}
|
|
if (cond === false || !this.nodes.length)
|
|
return;
|
|
return this;
|
|
}
|
|
optimizeNames(names, constants) {
|
|
var _a;
|
|
this.else = (_a = this.else) === null || _a === undefined ? undefined : _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";
|
|
|
|
class For extends BlockNode {
|
|
}
|
|
For.kind = "for";
|
|
|
|
class ForLoop extends For {
|
|
constructor(iteration) {
|
|
super();
|
|
this.iteration = iteration;
|
|
}
|
|
render(opts) {
|
|
return `for(${this.iteration})` + super.render(opts);
|
|
}
|
|
optimizeNames(names, constants) {
|
|
if (!super.optimizeNames(names, constants))
|
|
return;
|
|
this.iteration = optimizeExpr(this.iteration, names, constants);
|
|
return this;
|
|
}
|
|
get names() {
|
|
return addNames(super.names, this.iteration.names);
|
|
}
|
|
}
|
|
|
|
class ForRange extends For {
|
|
constructor(varKind, name, from, to) {
|
|
super();
|
|
this.varKind = varKind;
|
|
this.name = name;
|
|
this.from = from;
|
|
this.to = to;
|
|
}
|
|
render(opts) {
|
|
const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
|
|
const { name, from, to } = this;
|
|
return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
|
|
}
|
|
get names() {
|
|
const names = addExprNames(super.names, this.from);
|
|
return addExprNames(names, this.to);
|
|
}
|
|
}
|
|
|
|
class ForIter extends For {
|
|
constructor(loop, varKind, name, iterable) {
|
|
super();
|
|
this.loop = loop;
|
|
this.varKind = varKind;
|
|
this.name = name;
|
|
this.iterable = iterable;
|
|
}
|
|
render(opts) {
|
|
return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
|
|
}
|
|
optimizeNames(names, constants) {
|
|
if (!super.optimizeNames(names, constants))
|
|
return;
|
|
this.iterable = optimizeExpr(this.iterable, names, constants);
|
|
return this;
|
|
}
|
|
get names() {
|
|
return addNames(super.names, this.iterable.names);
|
|
}
|
|
}
|
|
|
|
class Func extends BlockNode {
|
|
constructor(name, args, async) {
|
|
super();
|
|
this.name = name;
|
|
this.args = args;
|
|
this.async = async;
|
|
}
|
|
render(opts) {
|
|
const _async = this.async ? "async " : "";
|
|
return `${_async}function ${this.name}(${this.args})` + super.render(opts);
|
|
}
|
|
}
|
|
Func.kind = "func";
|
|
|
|
class Return extends ParentNode {
|
|
render(opts) {
|
|
return "return " + super.render(opts);
|
|
}
|
|
}
|
|
Return.kind = "return";
|
|
|
|
class Try extends BlockNode {
|
|
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;
|
|
}
|
|
optimizeNodes() {
|
|
var _a, _b;
|
|
super.optimizeNodes();
|
|
(_a = this.catch) === null || _a === undefined || _a.optimizeNodes();
|
|
(_b = this.finally) === null || _b === undefined || _b.optimizeNodes();
|
|
return this;
|
|
}
|
|
optimizeNames(names, constants) {
|
|
var _a, _b;
|
|
super.optimizeNames(names, constants);
|
|
(_a = this.catch) === null || _a === undefined || _a.optimizeNames(names, constants);
|
|
(_b = this.finally) === null || _b === undefined || _b.optimizeNames(names, constants);
|
|
return this;
|
|
}
|
|
get names() {
|
|
const names = super.names;
|
|
if (this.catch)
|
|
addNames(names, this.catch.names);
|
|
if (this.finally)
|
|
addNames(names, this.finally.names);
|
|
return names;
|
|
}
|
|
}
|
|
|
|
class Catch extends BlockNode {
|
|
constructor(error) {
|
|
super();
|
|
this.error = error;
|
|
}
|
|
render(opts) {
|
|
return `catch(${this.error})` + super.render(opts);
|
|
}
|
|
}
|
|
Catch.kind = "catch";
|
|
|
|
class Finally extends BlockNode {
|
|
render(opts) {
|
|
return "finally" + super.render(opts);
|
|
}
|
|
}
|
|
Finally.kind = "finally";
|
|
|
|
class CodeGen {
|
|
constructor(extScope, opts = {}) {
|
|
this._values = {};
|
|
this._blockStarts = [];
|
|
this._constants = {};
|
|
this.opts = { ...opts, _n: opts.lines ? `
|
|
` : "" };
|
|
this._extScope = extScope;
|
|
this._scope = new scope_1.Scope({ parent: extScope });
|
|
this._nodes = [new Root];
|
|
}
|
|
toString() {
|
|
return this._root.render(this.opts);
|
|
}
|
|
name(prefix) {
|
|
return this._scope.name(prefix);
|
|
}
|
|
scopeName(prefix) {
|
|
return this._extScope.name(prefix);
|
|
}
|
|
scopeValue(prefixOrName, value) {
|
|
const name = this._extScope.value(prefixOrName, value);
|
|
const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set);
|
|
vs.add(name);
|
|
return name;
|
|
}
|
|
getScopeValue(prefix, keyOrRef) {
|
|
return this._extScope.getValue(prefix, keyOrRef);
|
|
}
|
|
scopeRefs(scopeName) {
|
|
return this._extScope.scopeRefs(scopeName, this._values);
|
|
}
|
|
scopeCode() {
|
|
return this._extScope.scopeCode(this._values);
|
|
}
|
|
_def(varKind, nameOrPrefix, rhs, constant) {
|
|
const name = this._scope.toName(nameOrPrefix);
|
|
if (rhs !== undefined && constant)
|
|
this._constants[name.str] = rhs;
|
|
this._leafNode(new Def(varKind, name, rhs));
|
|
return name;
|
|
}
|
|
const(nameOrPrefix, rhs, _constant) {
|
|
return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
|
|
}
|
|
let(nameOrPrefix, rhs, _constant) {
|
|
return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
|
|
}
|
|
var(nameOrPrefix, rhs, _constant) {
|
|
return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
|
|
}
|
|
assign(lhs, rhs, sideEffects) {
|
|
return this._leafNode(new Assign(lhs, rhs, sideEffects));
|
|
}
|
|
add(lhs, rhs) {
|
|
return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
|
|
}
|
|
code(c) {
|
|
if (typeof c == "function")
|
|
c();
|
|
else if (c !== code_1.nil)
|
|
this._leafNode(new AnyCode(c));
|
|
return this;
|
|
}
|
|
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);
|
|
}
|
|
}
|
|
code.push("}");
|
|
return new code_1._Code(code);
|
|
}
|
|
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;
|
|
}
|
|
elseIf(condition) {
|
|
return this._elseNode(new If(condition));
|
|
}
|
|
else() {
|
|
return this._elseNode(new Else);
|
|
}
|
|
endIf() {
|
|
return this._endBlockNode(If, Else);
|
|
}
|
|
_for(node, forBody) {
|
|
this._blockNode(node);
|
|
if (forBody)
|
|
this.code(forBody).endFor();
|
|
return this;
|
|
}
|
|
for(iteration, forBody) {
|
|
return this._for(new ForLoop(iteration), forBody);
|
|
}
|
|
forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
|
|
const name = this._scope.toName(nameOrPrefix);
|
|
return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
|
|
}
|
|
forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
|
|
const name = 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`, (i) => {
|
|
this.var(name, (0, code_1._)`${arr}[${i}]`);
|
|
forBody(name);
|
|
});
|
|
}
|
|
return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
|
|
}
|
|
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);
|
|
}
|
|
const name = this._scope.toName(nameOrPrefix);
|
|
return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
|
|
}
|
|
endFor() {
|
|
return this._endBlockNode(For);
|
|
}
|
|
label(label) {
|
|
return this._leafNode(new Label(label));
|
|
}
|
|
break(label) {
|
|
return this._leafNode(new Break(label));
|
|
}
|
|
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);
|
|
}
|
|
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 error = this.name("e");
|
|
this._currNode = node.catch = new Catch(error);
|
|
catchCode(error);
|
|
}
|
|
if (finallyCode) {
|
|
this._currNode = node.finally = new Finally;
|
|
this.code(finallyCode);
|
|
}
|
|
return this._endBlockNode(Catch, Finally);
|
|
}
|
|
throw(error) {
|
|
return this._leafNode(new Throw(error));
|
|
}
|
|
block(body, nodeCount) {
|
|
this._blockStarts.push(this._nodes.length);
|
|
if (body)
|
|
this.code(body).endBlock(nodeCount);
|
|
return this;
|
|
}
|
|
endBlock(nodeCount) {
|
|
const len = this._blockStarts.pop();
|
|
if (len === undefined)
|
|
throw new Error("CodeGen: not in self-balancing block");
|
|
const toClose = this._nodes.length - len;
|
|
if (toClose < 0 || nodeCount !== undefined && toClose !== nodeCount) {
|
|
throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
|
|
}
|
|
this._nodes.length = len;
|
|
return this;
|
|
}
|
|
func(name, args = code_1.nil, async, funcBody) {
|
|
this._blockNode(new Func(name, args, async));
|
|
if (funcBody)
|
|
this.code(funcBody).endFunc();
|
|
return this;
|
|
}
|
|
endFunc() {
|
|
return this._endBlockNode(Func);
|
|
}
|
|
optimize(n = 1) {
|
|
while (n-- > 0) {
|
|
this._root.optimizeNodes();
|
|
this._root.optimizeNames(this._root.names, this._constants);
|
|
}
|
|
}
|
|
_leafNode(node) {
|
|
this._currNode.nodes.push(node);
|
|
return this;
|
|
}
|
|
_blockNode(node) {
|
|
this._currNode.nodes.push(node);
|
|
this._nodes.push(node);
|
|
}
|
|
_endBlockNode(N1, N2) {
|
|
const n = this._currNode;
|
|
if (n instanceof N1 || N2 && n instanceof N2) {
|
|
this._nodes.pop();
|
|
return this;
|
|
}
|
|
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"');
|
|
}
|
|
this._currNode = n.else = node;
|
|
return this;
|
|
}
|
|
get _root() {
|
|
return this._nodes[0];
|
|
}
|
|
get _currNode() {
|
|
const ns = this._nodes;
|
|
return ns[ns.length - 1];
|
|
}
|
|
set _currNode(node) {
|
|
const ns = this._nodes;
|
|
ns[ns.length - 1] = node;
|
|
}
|
|
}
|
|
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 === undefined || names[n.str] !== 1)
|
|
return n;
|
|
delete names[n.str];
|
|
return c;
|
|
}
|
|
function canOptimize(e) {
|
|
return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== undefined);
|
|
}
|
|
}
|
|
function subtractNames(names, from) {
|
|
for (const n in from)
|
|
names[n] = (names[n] || 0) - (from[n] || 0);
|
|
}
|
|
function not(x) {
|
|
return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`;
|
|
}
|
|
exports.not = not;
|
|
var andCode = mappend(exports.operators.AND);
|
|
function and(...args) {
|
|
return args.reduce(andCode);
|
|
}
|
|
exports.and = and;
|
|
var orCode = mappend(exports.operators.OR);
|
|
function or(...args) {
|
|
return args.reduce(orCode);
|
|
}
|
|
exports.or = or;
|
|
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.20.0/node_modules/ajv/dist/compile/util.js
|
|
var require_util = __commonJS(function(exports) {
|
|
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 = undefined;
|
|
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, schema) {
|
|
if (typeof schema == "boolean")
|
|
return schema;
|
|
if (Object.keys(schema).length === 0)
|
|
return true;
|
|
checkUnknownRules(it, schema);
|
|
return !schemaHasRules(schema, it.self.RULES.all);
|
|
}
|
|
exports.alwaysValidSchema = alwaysValidSchema;
|
|
function checkUnknownRules(it, schema = it.schema) {
|
|
const { opts, self: self2 } = it;
|
|
if (!opts.strictSchema)
|
|
return;
|
|
if (typeof schema === "boolean")
|
|
return;
|
|
const rules = self2.RULES.keywords;
|
|
for (const key in schema) {
|
|
if (!rules[key])
|
|
checkStrictMode(it, `unknown keyword: "${key}"`);
|
|
}
|
|
}
|
|
exports.checkUnknownRules = checkUnknownRules;
|
|
function schemaHasRules(schema, rules) {
|
|
if (typeof schema == "boolean")
|
|
return !schema;
|
|
for (const key in schema)
|
|
if (rules[key])
|
|
return true;
|
|
return false;
|
|
}
|
|
exports.schemaHasRules = schemaHasRules;
|
|
function schemaHasRulesButRef(schema, RULES) {
|
|
if (typeof schema == "boolean")
|
|
return !schema;
|
|
for (const key in schema)
|
|
if (key !== "$ref" && RULES.all[key])
|
|
return true;
|
|
return false;
|
|
}
|
|
exports.schemaHasRulesButRef = schemaHasRulesButRef;
|
|
function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {
|
|
if (!$data) {
|
|
if (typeof schema == "number" || typeof schema == "boolean")
|
|
return schema;
|
|
if (typeof schema == "string")
|
|
return (0, codegen_1._)`${schema}`;
|
|
}
|
|
return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;
|
|
}
|
|
exports.schemaRefOrVal = schemaRefOrVal;
|
|
function unescapeFragment(str) {
|
|
return unescapeJsonPointer(decodeURIComponent(str));
|
|
}
|
|
exports.unescapeFragment = unescapeFragment;
|
|
function escapeFragment(str) {
|
|
return encodeURIComponent(escapeJsonPointer(str));
|
|
}
|
|
exports.escapeFragment = escapeFragment;
|
|
function escapeJsonPointer(str) {
|
|
if (typeof str == "number")
|
|
return `${str}`;
|
|
return str.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
}
|
|
exports.escapeJsonPointer = escapeJsonPointer;
|
|
function unescapeJsonPointer(str) {
|
|
return str.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, resultToName }) {
|
|
return (gen, from, to, toName) => {
|
|
const res = to === undefined ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to);
|
|
return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
|
|
};
|
|
}
|
|
exports.mergeEvaluated = {
|
|
props: makeMergeEvaluated({
|
|
mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => {
|
|
gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`));
|
|
}),
|
|
mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => {
|
|
if (from === true) {
|
|
gen.assign(to, true);
|
|
} else {
|
|
gen.assign(to, (0, codegen_1._)`${to} || {}`);
|
|
setEvaluated(gen, to, from);
|
|
}
|
|
}),
|
|
mergeValues: (from, to) => from === true ? true : { ...from, ...to },
|
|
resultToName: evaluatedPropsToName
|
|
}),
|
|
items: makeMergeEvaluated({
|
|
mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
|
|
mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)),
|
|
mergeValues: (from, to) => from === true ? true : Math.max(from, to),
|
|
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 !== undefined)
|
|
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(Type) {
|
|
Type[Type["Num"] = 0] = "Num";
|
|
Type[Type["Str"] = 1] = "Str";
|
|
})(Type || (exports.Type = Type = {}));
|
|
function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
|
|
if (dataProp instanceof codegen_1.Name) {
|
|
const isNumber = dataPropType === Type.Num;
|
|
return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (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, mode = it.opts.strictSchema) {
|
|
if (!mode)
|
|
return;
|
|
msg = `strict mode: ${msg}`;
|
|
if (mode === true)
|
|
throw new Error(msg);
|
|
it.self.logger.warn(msg);
|
|
}
|
|
exports.checkStrictMode = checkStrictMode;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/names.js
|
|
var require_names = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var names = {
|
|
data: new codegen_1.Name("data"),
|
|
valCxt: new codegen_1.Name("valCxt"),
|
|
instancePath: new codegen_1.Name("instancePath"),
|
|
parentData: new codegen_1.Name("parentData"),
|
|
parentDataProperty: new codegen_1.Name("parentDataProperty"),
|
|
rootData: new codegen_1.Name("rootData"),
|
|
dynamicAnchors: new codegen_1.Name("dynamicAnchors"),
|
|
vErrors: new codegen_1.Name("vErrors"),
|
|
errors: new codegen_1.Name("errors"),
|
|
this: new codegen_1.Name("this"),
|
|
self: new codegen_1.Name("self"),
|
|
scope: new codegen_1.Name("scope"),
|
|
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.20.0/node_modules/ajv/dist/compile/errors.js
|
|
var require_errors = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = undefined;
|
|
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`
|
|
};
|
|
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)`
|
|
};
|
|
function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) {
|
|
const { it } = cxt;
|
|
const { gen, compositeRule, allErrors } = it;
|
|
const errObj = errorObjectCode(cxt, error, errorPaths);
|
|
if (overrideAllErrors !== null && overrideAllErrors !== undefined ? overrideAllErrors : compositeRule || allErrors) {
|
|
addError(gen, errObj);
|
|
} else {
|
|
returnErrors(it, (0, codegen_1._)`[${errObj}]`);
|
|
}
|
|
}
|
|
exports.reportError = reportError;
|
|
function reportExtraError(cxt, error = exports.keywordError, errorPaths) {
|
|
const { it } = cxt;
|
|
const { gen, compositeRule, allErrors } = it;
|
|
const errObj = errorObjectCode(cxt, error, 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 === undefined)
|
|
throw new Error("ajv implementation error");
|
|
const err = gen.name("err");
|
|
gen.forRange("i", errsCount, names_1.default.errors, (i) => {
|
|
gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`);
|
|
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}++`);
|
|
}
|
|
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 E = {
|
|
keyword: new codegen_1.Name("keyword"),
|
|
schemaPath: new codegen_1.Name("schemaPath"),
|
|
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, error, errorPaths) {
|
|
const { createErrors } = cxt.it;
|
|
if (createErrors === false)
|
|
return (0, codegen_1._)`{}`;
|
|
return errorObject(cxt, error, errorPaths);
|
|
}
|
|
function errorObject(cxt, error, errorPaths = {}) {
|
|
const { gen, it } = cxt;
|
|
const keyValues = [
|
|
errorInstancePath(it, errorPaths),
|
|
errorSchemaPath(cxt, errorPaths)
|
|
];
|
|
extraErrorProps(cxt, error, 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)}`;
|
|
}
|
|
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]);
|
|
}
|
|
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.20.0/node_modules/ajv/dist/compile/validate/boolSchema.js
|
|
var require_boolSchema = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = undefined;
|
|
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, validateName } = it;
|
|
if (schema === false) {
|
|
falseSchemaError(it, false);
|
|
} else if (typeof schema == "object" && schema.$async === true) {
|
|
gen.return(names_1.default.data);
|
|
} else {
|
|
gen.assign((0, codegen_1._)`${validateName}.errors`, null);
|
|
gen.return(true);
|
|
}
|
|
}
|
|
exports.topBoolOrEmptySchema = topBoolOrEmptySchema;
|
|
function boolOrEmptySchema(it, valid) {
|
|
const { gen, schema } = it;
|
|
if (schema === false) {
|
|
gen.var(valid, false);
|
|
falseSchemaError(it);
|
|
} else {
|
|
gen.var(valid, true);
|
|
}
|
|
}
|
|
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, undefined, overrideAllErrors);
|
|
}
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/rules.js
|
|
var require_rules = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.getRules = exports.isJSONType = undefined;
|
|
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.20.0/node_modules/ajv/dist/compile/validate/applicability.js
|
|
var require_applicability = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = undefined;
|
|
function schemaHasRulesForType({ schema, self: self2 }, type) {
|
|
const group = self2.RULES.types[type];
|
|
return group && group !== true && shouldUseGroup(schema, group);
|
|
}
|
|
exports.schemaHasRulesForType = schemaHasRulesForType;
|
|
function shouldUseGroup(schema, group) {
|
|
return group.rules.some((rule) => shouldUseRule(schema, rule));
|
|
}
|
|
exports.shouldUseGroup = shouldUseGroup;
|
|
function shouldUseRule(schema, rule) {
|
|
var _a;
|
|
return schema[rule.keyword] !== undefined || ((_a = rule.definition.implements) === null || _a === undefined ? undefined : _a.some((kwd) => schema[kwd] !== undefined));
|
|
}
|
|
exports.shouldUseRule = shouldUseRule;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/dataType.js
|
|
var require_dataType = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = undefined;
|
|
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(DataType) {
|
|
DataType[DataType["Correct"] = 0] = "Correct";
|
|
DataType[DataType["Wrong"] = 1] = "Wrong";
|
|
})(DataType || (exports.DataType = DataType = {}));
|
|
function getSchemaTypes(schema) {
|
|
const types = getJSONTypes(schema.type);
|
|
const hasNull = types.includes("null");
|
|
if (hasNull) {
|
|
if (schema.nullable === false)
|
|
throw new Error("type: null contradicts nullable: false");
|
|
} else {
|
|
if (!types.length && schema.nullable !== undefined) {
|
|
throw new Error('"nullable" cannot be used without "type"');
|
|
}
|
|
if (schema.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);
|
|
});
|
|
}
|
|
return checkTypes;
|
|
}
|
|
exports.coerceAndCheckDataType = coerceAndCheckDataType;
|
|
var COERCIBLE = 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)));
|
|
}
|
|
gen.if((0, codegen_1._)`${coerced} !== undefined`);
|
|
for (const t of coerceTo) {
|
|
if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") {
|
|
coerceSpecificType(t);
|
|
}
|
|
}
|
|
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);
|
|
return;
|
|
case "array":
|
|
gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number"
|
|
|| ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`);
|
|
}
|
|
}
|
|
}
|
|
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}`;
|
|
}
|
|
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);
|
|
}
|
|
}
|
|
exports.checkDataType = checkDataType;
|
|
function checkDataTypes(dataTypes, data, strictNums, correct) {
|
|
if (dataTypes.length === 1) {
|
|
return checkDataType(dataTypes[0], data, strictNums, correct);
|
|
}
|
|
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 }) => `must be ${schema}`,
|
|
params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (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 } = it;
|
|
const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
|
|
return {
|
|
gen,
|
|
keyword: "type",
|
|
data,
|
|
schema: schema.type,
|
|
schemaCode,
|
|
schemaValue: schemaCode,
|
|
parentSchema: schema,
|
|
params: {},
|
|
it
|
|
};
|
|
}
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/defaults.js
|
|
var require_defaults = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.assignDefaults = undefined;
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
function assignDefaults(it, ty) {
|
|
const { properties, items } = it.schema;
|
|
if (ty === "object" && properties) {
|
|
for (const key in properties) {
|
|
assignDefault(it, key, properties[key].default);
|
|
}
|
|
} else if (ty === "array" && Array.isArray(items)) {
|
|
items.forEach((sch, i) => assignDefault(it, i, sch.default));
|
|
}
|
|
}
|
|
exports.assignDefaults = assignDefaults;
|
|
function assignDefault(it, prop, defaultValue) {
|
|
const { gen, compositeRule, data, opts } = it;
|
|
if (defaultValue === undefined)
|
|
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;
|
|
}
|
|
let condition = (0, codegen_1._)`${childData} === undefined`;
|
|
if (opts.useDefaults === "empty") {
|
|
condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`;
|
|
}
|
|
gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
|
|
}
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/code.js
|
|
var require_code2 = __commonJS(function(exports) {
|
|
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 = undefined;
|
|
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 } }, properties, missing) {
|
|
return (0, codegen_1.or)(...properties.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", {
|
|
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;
|
|
}
|
|
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, (i) => {
|
|
cxt.subschema({
|
|
keyword,
|
|
dataProp: i,
|
|
dataPropType: util_1.Type.Num
|
|
}, valid);
|
|
gen.if((0, codegen_1.not)(valid), notValid);
|
|
});
|
|
}
|
|
}
|
|
exports.validateArray = validateArray;
|
|
function validateUnion(cxt) {
|
|
const { gen, schema, keyword, it } = cxt;
|
|
if (!Array.isArray(schema))
|
|
throw new Error("ajv implementation error");
|
|
const alwaysValid = schema.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(() => schema.forEach((_sch, i) => {
|
|
const schCxt = cxt.subschema({
|
|
keyword,
|
|
schemaProp: i,
|
|
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.20.0/node_modules/ajv/dist/compile/validate/keyword.js
|
|
var require_keyword = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = undefined;
|
|
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, parentSchema, it } = cxt;
|
|
const macroSchema = def.macro.call(it.self, schema, 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, parentSchema, $data, it } = cxt;
|
|
checkAsyncKeyword(it, def);
|
|
const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
|
|
const validateRef = useKeyword(gen, keyword, validate);
|
|
const valid = gen.let("valid");
|
|
cxt.block$data(valid, validateKeyword);
|
|
cxt.ok((_a = def.valid) !== null && _a !== undefined ? _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));
|
|
}
|
|
}
|
|
function validateAsync() {
|
|
const ruleErrs = gen.let("ruleErrs", null);
|
|
gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e)));
|
|
return ruleErrs;
|
|
}
|
|
function validateSync() {
|
|
const validateErrs = (0, codegen_1._)`${validateRef}.errors`;
|
|
gen.assign(validateErrs, null);
|
|
assignValid(codegen_1.nil);
|
|
return validateErrs;
|
|
}
|
|
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);
|
|
}
|
|
function reportErrs(errors) {
|
|
var _a;
|
|
gen.if((0, codegen_1.not)((_a = def.valid) !== null && _a !== undefined ? _a : valid), errors);
|
|
}
|
|
}
|
|
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 === undefined)
|
|
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(schema, schemaType, allowUndefined = false) {
|
|
return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined");
|
|
}
|
|
exports.validSchemaType = validSchemaType;
|
|
function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def, keyword) {
|
|
if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
|
|
throw new Error("ajv implementation error");
|
|
}
|
|
const deps = def.dependencies;
|
|
if (deps === null || deps === undefined ? undefined : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
|
|
throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
|
|
}
|
|
if (def.validateSchema) {
|
|
const valid = def.validateSchema(schema[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);
|
|
}
|
|
}
|
|
}
|
|
exports.validateKeywordUsage = validateKeywordUsage;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/subschema.js
|
|
var require_subschema = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = undefined;
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
|
|
if (keyword !== undefined && schema !== undefined) {
|
|
throw new Error('both "keyword" and "schema" passed, only one allowed');
|
|
}
|
|
if (keyword !== undefined) {
|
|
const sch = it.schema[keyword];
|
|
return schemaProp === undefined ? {
|
|
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)}`
|
|
};
|
|
}
|
|
if (schema !== undefined) {
|
|
if (schemaPath === undefined || errSchemaPath === undefined || topSchemaRef === undefined) {
|
|
throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
|
|
}
|
|
return {
|
|
schema,
|
|
schemaPath,
|
|
topSchemaRef,
|
|
errSchemaPath
|
|
};
|
|
}
|
|
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 !== undefined && dataProp !== undefined) {
|
|
throw new Error('both "data" and "dataProp" passed, only one allowed');
|
|
}
|
|
const { gen } = it;
|
|
if (dataProp !== undefined) {
|
|
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 !== undefined) {
|
|
const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true);
|
|
dataContextProps(nextData);
|
|
if (propertyName !== undefined)
|
|
subschema.propertyName = propertyName;
|
|
}
|
|
if (dataTypes)
|
|
subschema.dataTypes = dataTypes;
|
|
function dataContextProps(_nextData) {
|
|
subschema.data = _nextData;
|
|
subschema.dataLevel = it.dataLevel + 1;
|
|
subschema.dataTypes = [];
|
|
it.definedProperties = new Set;
|
|
subschema.parentData = it.data;
|
|
subschema.dataNames = [...it.dataNames, _nextData];
|
|
}
|
|
}
|
|
exports.extendSubschemaData = extendSubschemaData;
|
|
function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
|
|
if (compositeRule !== undefined)
|
|
subschema.compositeRule = compositeRule;
|
|
if (createErrors !== undefined)
|
|
subschema.createErrors = createErrors;
|
|
if (allErrors !== undefined)
|
|
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(function(exports, module) {
|
|
module.exports = function equal(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, i, keys;
|
|
if (Array.isArray(a)) {
|
|
length = a.length;
|
|
if (length != b.length)
|
|
return false;
|
|
for (i = length;i-- !== 0; )
|
|
if (!equal(a[i], b[i]))
|
|
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 (i = length;i-- !== 0; )
|
|
if (!Object.prototype.hasOwnProperty.call(b, keys[i]))
|
|
return false;
|
|
for (i = length;i-- !== 0; ) {
|
|
var key = keys[i];
|
|
if (!equal(a[key], b[key]))
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
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(function(exports, module) {
|
|
var traverse = module.exports = function(schema, 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, schema, "", schema);
|
|
};
|
|
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
|
|
};
|
|
function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
|
|
if (schema && typeof schema == "object" && !Array.isArray(schema)) {
|
|
pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
|
|
for (var key in schema) {
|
|
var sch = schema[key];
|
|
if (Array.isArray(sch)) {
|
|
if (key in traverse.arrayKeywords) {
|
|
for (var i = 0;i < sch.length; i++)
|
|
_traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);
|
|
}
|
|
} 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, schema, prop);
|
|
}
|
|
} else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) {
|
|
_traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
|
|
}
|
|
}
|
|
post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
|
|
}
|
|
}
|
|
function escapeJsonPtr(str) {
|
|
return str.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
}
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/resolve.js
|
|
var require_resolve = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = undefined;
|
|
var util_1 = require_util();
|
|
var equal = require_fast_deep_equal();
|
|
var traverse = require_json_schema_traverse();
|
|
var SIMPLE_INLINED = new Set([
|
|
"type",
|
|
"format",
|
|
"pattern",
|
|
"maxLength",
|
|
"minLength",
|
|
"maxProperties",
|
|
"minProperties",
|
|
"maxItems",
|
|
"minItems",
|
|
"maximum",
|
|
"minimum",
|
|
"uniqueItems",
|
|
"multipleOf",
|
|
"required",
|
|
"enum",
|
|
"const"
|
|
]);
|
|
function inlineRef(schema, limit = true) {
|
|
if (typeof schema == "boolean")
|
|
return true;
|
|
if (limit === true)
|
|
return !hasRef(schema);
|
|
if (!limit)
|
|
return false;
|
|
return countKeys(schema) <= limit;
|
|
}
|
|
exports.inlineRef = inlineRef;
|
|
var REF_KEYWORDS = new Set([
|
|
"$ref",
|
|
"$recursiveRef",
|
|
"$recursiveAnchor",
|
|
"$dynamicRef",
|
|
"$dynamicAnchor"
|
|
]);
|
|
function hasRef(schema) {
|
|
for (const key in schema) {
|
|
if (REF_KEYWORDS.has(key))
|
|
return true;
|
|
const sch = schema[key];
|
|
if (Array.isArray(sch) && sch.some(hasRef))
|
|
return true;
|
|
if (typeof sch == "object" && hasRef(sch))
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
function countKeys(schema) {
|
|
let count = 0;
|
|
for (const key in schema) {
|
|
if (key === "$ref")
|
|
return Infinity;
|
|
count++;
|
|
if (SIMPLE_INLINED.has(key))
|
|
continue;
|
|
if (typeof schema[key] == "object") {
|
|
(0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));
|
|
}
|
|
if (count === Infinity)
|
|
return Infinity;
|
|
}
|
|
return count;
|
|
}
|
|
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(schema, baseId) {
|
|
if (typeof schema == "boolean")
|
|
return {};
|
|
const { schemaId, uriResolver } = this.opts;
|
|
const schId = normalizeId(schema[schemaId] || baseId);
|
|
const baseIds = { "": schId };
|
|
const pathPrefix = getFullPath(uriResolver, schId, false);
|
|
const localRefs = {};
|
|
const schemaRefs = new Set;
|
|
traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
|
|
if (parentJsonPtr === undefined)
|
|
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 !== undefined && !equal(sch1, sch2))
|
|
throw ambiguos(ref);
|
|
}
|
|
function ambiguos(ref) {
|
|
return new Error(`reference "${ref}" resolves to more than one schema`);
|
|
}
|
|
}
|
|
exports.getSchemaRefs = getSchemaRefs;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/validate/index.js
|
|
var require_validate = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.getData = exports.KeywordCxt = exports.validateFunctionCode = undefined;
|
|
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;
|
|
}
|
|
}
|
|
validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
|
|
}
|
|
exports.validateFunctionCode = validateFunctionCode;
|
|
function validateFunction({ gen, validateName, schema, 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(schema, 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(schema, opts)).code(body));
|
|
}
|
|
}
|
|
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, opts, gen } = it;
|
|
validateFunction(it, () => {
|
|
if (opts.$comment && schema.$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(schema, opts) {
|
|
const schId = typeof schema == "object" && schema[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, self: self2 }) {
|
|
if (typeof schema == "boolean")
|
|
return !schema;
|
|
for (const key in schema)
|
|
if (self2.RULES.all[key])
|
|
return true;
|
|
return false;
|
|
}
|
|
function isSchemaObj(it) {
|
|
return typeof it.schema != "boolean";
|
|
}
|
|
function subSchemaObjCode(it, valid) {
|
|
const { schema, gen, opts } = it;
|
|
if (opts.$comment && schema.$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, errSchemaPath, opts, self: self2 } = it;
|
|
if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) {
|
|
self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
|
|
}
|
|
}
|
|
function checkNoDefault(it) {
|
|
const { schema, opts } = it;
|
|
if (schema.default !== undefined && 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, errSchemaPath, opts }) {
|
|
const msg = schema.$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, data, allErrors, opts, self: self2 } = it;
|
|
const { RULES } = self2;
|
|
if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
|
|
gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition));
|
|
return;
|
|
}
|
|
if (!opts.jtd)
|
|
checkStrictTypes(it, types);
|
|
gen.block(() => {
|
|
for (const group of RULES.rules)
|
|
groupKeywords(group);
|
|
groupKeywords(RULES.post);
|
|
});
|
|
function groupKeywords(group) {
|
|
if (!(0, applicability_1.shouldUseGroup)(schema, group))
|
|
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, 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)(schema, 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;
|
|
}
|
|
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 } = rule.definition;
|
|
if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
|
|
strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
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);
|
|
}
|
|
|
|
class KeywordCxt {
|
|
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);
|
|
}
|
|
}
|
|
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();
|
|
}
|
|
}
|
|
pass(condition, failAction) {
|
|
this.failResult((0, codegen_1.not)(condition), undefined, failAction);
|
|
}
|
|
fail(condition) {
|
|
if (condition === undefined) {
|
|
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();
|
|
}
|
|
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;
|
|
}
|
|
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 === undefined)
|
|
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, assign) {
|
|
if (assign)
|
|
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);
|
|
}
|
|
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;
|
|
}
|
|
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;
|
|
}
|
|
}
|
|
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: undefined, props: undefined };
|
|
subschemaCode(nextContext, valid);
|
|
return nextContext;
|
|
}
|
|
mergeEvaluated(schemaCxt, toName) {
|
|
const { it, gen } = this;
|
|
if (!it.opts.unevaluated)
|
|
return;
|
|
if (it.props !== true && schemaCxt.props !== undefined) {
|
|
it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
|
|
}
|
|
if (it.items !== true && schemaCxt.items !== undefined) {
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
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 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;
|
|
}
|
|
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}`;
|
|
}
|
|
}
|
|
return expr;
|
|
function errorMsg(pointerType, up) {
|
|
return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
|
|
}
|
|
}
|
|
exports.getData = getData;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/validation_error.js
|
|
var require_validation_error = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
|
class ValidationError extends Error {
|
|
constructor(errors) {
|
|
super("validation failed");
|
|
this.errors = errors;
|
|
this.ajv = this.validation = true;
|
|
}
|
|
}
|
|
exports.default = ValidationError;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/ref_error.js
|
|
var require_ref_error = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var resolve_1 = require_resolve();
|
|
|
|
class MissingRefError 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));
|
|
}
|
|
}
|
|
exports.default = MissingRefError;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/compile/index.js
|
|
var require_compile = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = undefined;
|
|
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();
|
|
|
|
class SchemaEnv {
|
|
constructor(env) {
|
|
var _a;
|
|
this.refs = {};
|
|
this.dynamicAnchors = {};
|
|
let schema;
|
|
if (typeof env.schema == "object")
|
|
schema = env.schema;
|
|
this.schema = env.schema;
|
|
this.schemaId = env.schemaId;
|
|
this.root = env.root || this;
|
|
this.baseId = (_a = env.baseId) !== null && _a !== undefined ? _a : (0, resolve_1.normalizeId)(schema === null || schema === undefined ? undefined : schema[env.schemaId || "$id"]);
|
|
this.schemaPath = env.schemaPath;
|
|
this.localRefs = env.localRefs;
|
|
this.meta = env.meta;
|
|
this.$async = schema === null || schema === undefined ? undefined : schema.$async;
|
|
this.refs = {};
|
|
}
|
|
}
|
|
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],
|
|
dataLevel: 0,
|
|
dataTypes: [],
|
|
definedProperties: 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 validate = makeValidate(this, this.scope.get());
|
|
this.scope.value(validateName, { ref: validate });
|
|
validate.errors = null;
|
|
validate.schema = sch.schema;
|
|
validate.schemaEnv = sch;
|
|
if (sch.$async)
|
|
validate.$async = true;
|
|
if (this.opts.code.source === true) {
|
|
validate.source = { validateName, validateCode, scopeValues: gen._values };
|
|
}
|
|
if (this.opts.unevaluated) {
|
|
const { props, items } = schemaCxt;
|
|
validate.evaluated = {
|
|
props: props instanceof codegen_1.Name ? undefined : props,
|
|
items: items instanceof codegen_1.Name ? undefined : items,
|
|
dynamicProps: props instanceof codegen_1.Name,
|
|
dynamicItems: items instanceof codegen_1.Name
|
|
};
|
|
if (validate.source)
|
|
validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
|
|
}
|
|
sch.validate = validate;
|
|
return sch;
|
|
} catch (e) {
|
|
delete sch.validate;
|
|
delete sch.validateName;
|
|
if (sourceCode)
|
|
this.logger.error("Error compiling schema, function code:", sourceCode);
|
|
throw e;
|
|
} 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 = resolve.call(this, root, ref);
|
|
if (_sch === undefined) {
|
|
const schema = (_a = root.localRefs) === null || _a === undefined ? undefined : _a[ref];
|
|
const { schemaId } = this.opts;
|
|
if (schema)
|
|
_sch = new SchemaEnv({ schema, schemaId, root, baseId });
|
|
}
|
|
if (_sch === undefined)
|
|
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 resolve(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, undefined);
|
|
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 === undefined ? undefined : sch.schema) !== "object")
|
|
return;
|
|
return getJsonPointer.call(this, p, sch);
|
|
}
|
|
if (typeof (schOrRef === null || schOrRef === undefined ? undefined : schOrRef.schema) !== "object")
|
|
return;
|
|
if (!schOrRef.validate)
|
|
compileSchema.call(this, schOrRef);
|
|
if (id === (0, resolve_1.normalizeId)(ref)) {
|
|
const { schema } = schOrRef;
|
|
const { schemaId } = this.opts;
|
|
const schId = schema[schemaId];
|
|
if (schId)
|
|
baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
|
|
return new SchemaEnv({ schema, schemaId, root, baseId });
|
|
}
|
|
return getJsonPointer.call(this, p, schOrRef);
|
|
}
|
|
exports.resolveSchema = resolveSchema;
|
|
var PREVENT_SCOPE_CHANGE = new Set([
|
|
"properties",
|
|
"patternProperties",
|
|
"enum",
|
|
"dependencies",
|
|
"definitions"
|
|
]);
|
|
function getJsonPointer(parsedRef, { baseId, schema, root }) {
|
|
var _a;
|
|
if (((_a = parsedRef.fragment) === null || _a === undefined ? undefined : _a[0]) !== "/")
|
|
return;
|
|
for (const part of parsedRef.fragment.slice(1).split("/")) {
|
|
if (typeof schema === "boolean")
|
|
return;
|
|
const partSchema = schema[(0, util_1.unescapeFragment)(part)];
|
|
if (partSchema === undefined)
|
|
return;
|
|
schema = partSchema;
|
|
const schId = typeof schema === "object" && schema[this.opts.schemaId];
|
|
if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
|
|
baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
|
|
}
|
|
}
|
|
let env;
|
|
if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
|
|
const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
|
|
env = resolveSchema.call(this, root, $ref);
|
|
}
|
|
const { schemaId } = this.opts;
|
|
env = env || new SchemaEnv({ schema, schemaId, root, baseId });
|
|
if (env.schema !== env.root.schema)
|
|
return env;
|
|
return;
|
|
}
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/data.json
|
|
var require_data = __commonJS(function(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
|
|
};
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/fast-uri@3.1.5/node_modules/fast-uri/lib/utils.js
|
|
var require_utils = __commonJS(function(exports, module) {
|
|
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);
|
|
var isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu);
|
|
var isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu);
|
|
var isPathCharacter = RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);
|
|
function stringArrayToHexStripped(input) {
|
|
let acc = "";
|
|
let code = 0;
|
|
let i = 0;
|
|
for (i = 0;i < input.length; i++) {
|
|
code = input[i].charCodeAt(0);
|
|
if (code === 48) {
|
|
continue;
|
|
}
|
|
if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) {
|
|
return "";
|
|
}
|
|
acc += input[i];
|
|
break;
|
|
}
|
|
for (i += 1;i < input.length; i++) {
|
|
code = input[i].charCodeAt(0);
|
|
if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) {
|
|
return "";
|
|
}
|
|
acc += input[i];
|
|
}
|
|
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 hex = stringArrayToHexStripped(buffer);
|
|
if (hex !== "") {
|
|
address.push(hex);
|
|
} else {
|
|
output.error = true;
|
|
return false;
|
|
}
|
|
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 i = 0;i < input.length; i++) {
|
|
const cursor = input[i];
|
|
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 (i > 0 && input[i - 1] === ":") {
|
|
endipv6Encountered = true;
|
|
}
|
|
address.push(":");
|
|
continue;
|
|
} else if (cursor === "%") {
|
|
if (!consume(buffer, address, output)) {
|
|
break;
|
|
}
|
|
consume = consumeIsZone;
|
|
} else {
|
|
buffer.push(cursor);
|
|
continue;
|
|
}
|
|
}
|
|
if (buffer.length) {
|
|
if (consume === consumeIsZone) {
|
|
output.zone = buffer.join("");
|
|
} else if (endIpv6) {
|
|
address.push(buffer.join(""));
|
|
} else {
|
|
address.push(stringArrayToHexStripped(buffer));
|
|
}
|
|
}
|
|
output.address = address.join("");
|
|
return output;
|
|
}
|
|
function normalizeIPv6(host) {
|
|
if (findToken(host, ":") < 2) {
|
|
return { host, isIPV6: false };
|
|
}
|
|
const ipv6 = getIPV6(host);
|
|
if (!ipv6.error) {
|
|
let newHost = ipv6.address;
|
|
let escapedHost = ipv6.address;
|
|
if (ipv6.zone) {
|
|
newHost += "%" + ipv6.zone;
|
|
escapedHost += "%25" + ipv6.zone;
|
|
}
|
|
return { host: newHost, isIPV6: true, escapedHost };
|
|
} else {
|
|
return { host, isIPV6: false };
|
|
}
|
|
}
|
|
function findToken(str, token) {
|
|
let ind = 0;
|
|
for (let i = 0;i < str.length; i++) {
|
|
if (str[i] === 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;
|
|
} 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);
|
|
}
|
|
}
|
|
return output.join("");
|
|
}
|
|
var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" };
|
|
var HOST_DELIM_RE = /[@/?#:]/g;
|
|
var HOST_DELIM_NO_COLON_RE = /[@/?#]/g;
|
|
function reescapeHostDelimiters(host, isIP) {
|
|
const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE;
|
|
re.lastIndex = 0;
|
|
return host.replace(re, (ch) => HOST_DELIMS[ch]);
|
|
}
|
|
function normalizePercentEncoding(input, decodeUnreserved = false) {
|
|
if (input.indexOf("%") === -1) {
|
|
return input;
|
|
}
|
|
let output = "";
|
|
for (let i = 0;i < input.length; i++) {
|
|
if (input[i] === "%" && i + 2 < input.length) {
|
|
const hex = input.slice(i + 1, i + 3);
|
|
if (isHexPair(hex)) {
|
|
const normalizedHex = hex.toUpperCase();
|
|
const decoded = String.fromCharCode(parseInt(normalizedHex, 16));
|
|
if (decodeUnreserved && isUnreserved(decoded)) {
|
|
output += decoded;
|
|
} else {
|
|
output += "%" + normalizedHex;
|
|
}
|
|
i += 2;
|
|
continue;
|
|
}
|
|
}
|
|
output += input[i];
|
|
}
|
|
return output;
|
|
}
|
|
function normalizePathEncoding(input) {
|
|
let output = "";
|
|
for (let i = 0;i < input.length; i++) {
|
|
if (input[i] === "%" && i + 2 < input.length) {
|
|
const hex = input.slice(i + 1, i + 3);
|
|
if (isHexPair(hex)) {
|
|
const normalizedHex = hex.toUpperCase();
|
|
const decoded = String.fromCharCode(parseInt(normalizedHex, 16));
|
|
if (decoded !== "." && isUnreserved(decoded)) {
|
|
output += decoded;
|
|
} else {
|
|
output += "%" + normalizedHex;
|
|
}
|
|
i += 2;
|
|
continue;
|
|
}
|
|
}
|
|
if (isPathCharacter(input[i])) {
|
|
output += input[i];
|
|
} else {
|
|
output += escape(input[i]);
|
|
}
|
|
}
|
|
return output;
|
|
}
|
|
function escapePreservingEscapes(input) {
|
|
let output = "";
|
|
for (let i = 0;i < input.length; i++) {
|
|
if (input[i] === "%" && i + 2 < input.length) {
|
|
const hex = input.slice(i + 1, i + 3);
|
|
if (isHexPair(hex)) {
|
|
output += "%" + hex.toUpperCase();
|
|
i += 2;
|
|
continue;
|
|
}
|
|
}
|
|
output += escape(input[i]);
|
|
}
|
|
return output;
|
|
}
|
|
function recomposeAuthority(component) {
|
|
const uriTokens = [];
|
|
if (component.userinfo !== undefined) {
|
|
uriTokens.push(component.userinfo);
|
|
uriTokens.push("@");
|
|
}
|
|
if (component.host !== undefined) {
|
|
let host = unescape(component.host);
|
|
if (!isIPv4(host)) {
|
|
const ipV6res = normalizeIPv6(host);
|
|
if (ipV6res.isIPV6 === true) {
|
|
host = `[${ipV6res.escapedHost}]`;
|
|
} else {
|
|
host = reescapeHostDelimiters(host, false);
|
|
}
|
|
}
|
|
uriTokens.push(host);
|
|
}
|
|
if (typeof component.port === "number" || typeof component.port === "string") {
|
|
uriTokens.push(":");
|
|
uriTokens.push(String(component.port));
|
|
}
|
|
return uriTokens.length ? uriTokens.join("") : undefined;
|
|
}
|
|
module.exports = {
|
|
nonSimpleDomain,
|
|
recomposeAuthority,
|
|
reescapeHostDelimiters,
|
|
normalizePercentEncoding,
|
|
normalizePathEncoding,
|
|
escapePreservingEscapes,
|
|
removeDotSegments,
|
|
isIPv4,
|
|
isUUID,
|
|
normalizeIPv6,
|
|
stringArrayToHexStripped
|
|
};
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/fast-uri@3.1.5/node_modules/fast-uri/lib/schemes.js
|
|
var require_schemes = __commonJS(function(exports, module) {
|
|
var { isUUID } = require_utils();
|
|
var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;
|
|
var supportedSchemeNames = [
|
|
"http",
|
|
"https",
|
|
"ws",
|
|
"wss",
|
|
"urn",
|
|
"urn:uuid"
|
|
];
|
|
function isValidSchemeName(name) {
|
|
return supportedSchemeNames.indexOf(name) !== -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;
|
|
}
|
|
}
|
|
function httpParse(component) {
|
|
if (!component.host) {
|
|
component.error = component.error || "HTTP URIs must have a host.";
|
|
}
|
|
return component;
|
|
}
|
|
function httpSerialize(component) {
|
|
const secure = String(component.scheme).toLowerCase() === "https";
|
|
if (component.port === (secure ? 443 : 80) || component.port === "") {
|
|
component.port = undefined;
|
|
}
|
|
if (!component.path) {
|
|
component.path = "/";
|
|
}
|
|
return component;
|
|
}
|
|
function wsParse(wsComponent) {
|
|
wsComponent.secure = wsIsSecure(wsComponent);
|
|
wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : "");
|
|
wsComponent.path = undefined;
|
|
wsComponent.query = undefined;
|
|
return wsComponent;
|
|
}
|
|
function wsSerialize(wsComponent) {
|
|
if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") {
|
|
wsComponent.port = undefined;
|
|
}
|
|
if (typeof wsComponent.secure === "boolean") {
|
|
wsComponent.scheme = wsComponent.secure ? "wss" : "ws";
|
|
wsComponent.secure = undefined;
|
|
}
|
|
if (wsComponent.resourceName) {
|
|
const [path, query] = wsComponent.resourceName.split("?");
|
|
wsComponent.path = path && path !== "/" ? path : undefined;
|
|
wsComponent.query = query;
|
|
wsComponent.resourceName = undefined;
|
|
}
|
|
wsComponent.fragment = undefined;
|
|
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 = undefined;
|
|
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 === undefined) {
|
|
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 = undefined;
|
|
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 = {
|
|
scheme: "http",
|
|
domainHost: true,
|
|
parse: httpParse,
|
|
serialize: httpSerialize
|
|
};
|
|
var https = {
|
|
scheme: "https",
|
|
domainHost: http.domainHost,
|
|
parse: httpParse,
|
|
serialize: httpSerialize
|
|
};
|
|
var ws = {
|
|
scheme: "ws",
|
|
domainHost: true,
|
|
parse: wsParse,
|
|
serialize: wsSerialize
|
|
};
|
|
var wss = {
|
|
scheme: "wss",
|
|
domainHost: ws.domainHost,
|
|
parse: ws.parse,
|
|
serialize: ws.serialize
|
|
};
|
|
var urn = {
|
|
scheme: "urn",
|
|
parse: urnParse,
|
|
serialize: urnSerialize,
|
|
skipNormalize: true
|
|
};
|
|
var urnuuid = {
|
|
scheme: "urn:uuid",
|
|
parse: urnuuidParse,
|
|
serialize: urnuuidSerialize,
|
|
skipNormalize: true
|
|
};
|
|
var SCHEMES = {
|
|
http,
|
|
https,
|
|
ws,
|
|
wss,
|
|
urn,
|
|
"urn:uuid": urnuuid
|
|
};
|
|
Object.setPrototypeOf(SCHEMES, null);
|
|
function getSchemeHandler(scheme) {
|
|
return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || undefined;
|
|
}
|
|
module.exports = {
|
|
wsIsSecure,
|
|
SCHEMES,
|
|
isValidSchemeName,
|
|
getSchemeHandler
|
|
};
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/fast-uri@3.1.5/node_modules/fast-uri/index.js
|
|
var require_fast_uri = __commonJS(function(exports, module) {
|
|
var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, escapePreservingEscapes, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils();
|
|
var { SCHEMES, getSchemeHandler } = require_schemes();
|
|
function normalize(uri, options) {
|
|
if (typeof uri === "string") {
|
|
uri = normalizeString(uri, options);
|
|
} else if (typeof uri === "object") {
|
|
uri = parse(serialize(uri, options), options);
|
|
}
|
|
return uri;
|
|
}
|
|
function resolve(baseURI, relativeURI, options) {
|
|
const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
|
|
const { parsed: baseParsed, malformedAuthorityOrPort: baseMalformed } = parseWithStatus(baseURI, schemelessOptions);
|
|
const { parsed: relativeParsed, malformedAuthorityOrPort: relativeMalformed } = parseWithStatus(relativeURI, schemelessOptions);
|
|
if (baseMalformed || relativeMalformed) {
|
|
throw new Error(baseParsed.error || relativeParsed.error || "URI is malformed.");
|
|
}
|
|
const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true);
|
|
schemelessOptions.skipEscape = true;
|
|
return serialize(resolved, schemelessOptions);
|
|
}
|
|
function resolveComponent(base, relative, options, skipNormalization) {
|
|
const target = {};
|
|
if (!skipNormalization) {
|
|
base = parse(serialize(base, options), options);
|
|
relative = parse(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 !== undefined || relative.host !== undefined || relative.port !== undefined) {
|
|
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 !== undefined) {
|
|
target.query = relative.query;
|
|
} else {
|
|
target.query = base.query;
|
|
}
|
|
} else {
|
|
if (relative.path[0] === "/") {
|
|
target.path = removeDotSegments(relative.path);
|
|
} else {
|
|
if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !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 equal(uriA, uriB, options) {
|
|
const normalizedA = normalizeComparableURI(uriA, options);
|
|
const normalizedB = normalizeComparableURI(uriB, options);
|
|
return normalizedA !== undefined && normalizedB !== undefined && normalizedA.toLowerCase() === normalizedB.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 !== undefined) {
|
|
if (!options.skipEscape) {
|
|
component.path = escapePreservingEscapes(component.path);
|
|
if (component.scheme !== undefined) {
|
|
component.path = component.path.split("%3A").join(":");
|
|
}
|
|
} else {
|
|
component.path = normalizePercentEncoding(component.path);
|
|
}
|
|
}
|
|
if (options.reference !== "suffix" && component.scheme) {
|
|
uriTokens.push(component.scheme, ":");
|
|
}
|
|
const authority = recomposeAuthority(component);
|
|
if (authority !== undefined) {
|
|
if (options.reference !== "suffix") {
|
|
uriTokens.push("//");
|
|
}
|
|
uriTokens.push(authority);
|
|
if (component.path && component.path[0] !== "/") {
|
|
uriTokens.push("/");
|
|
}
|
|
}
|
|
if (component.path !== undefined) {
|
|
let s = component.path;
|
|
if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
|
|
s = removeDotSegments(s);
|
|
}
|
|
if (authority === undefined && s[0] === "/" && s[1] === "/") {
|
|
s = "/%2F" + s.slice(2);
|
|
}
|
|
uriTokens.push(s);
|
|
}
|
|
if (component.query !== undefined) {
|
|
uriTokens.push("?", component.query);
|
|
}
|
|
if (component.fragment !== undefined) {
|
|
uriTokens.push("#", component.fragment);
|
|
}
|
|
return uriTokens.join("");
|
|
}
|
|
var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
|
|
var AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/;
|
|
var AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;
|
|
function getParseError(parsed, matches) {
|
|
if (matches[2] !== undefined && parsed.path && parsed.path[0] !== "/") {
|
|
return 'URI path must start with "/" when authority is present.';
|
|
}
|
|
if (typeof parsed.port === "number" && (parsed.port < 0 || parsed.port > 65535)) {
|
|
return "URI port is malformed.";
|
|
}
|
|
return;
|
|
}
|
|
function parseWithStatus(uri, opts) {
|
|
const options = Object.assign({}, opts);
|
|
const parsed = {
|
|
scheme: undefined,
|
|
userinfo: undefined,
|
|
host: "",
|
|
port: undefined,
|
|
path: "",
|
|
query: undefined,
|
|
fragment: undefined
|
|
};
|
|
let malformedAuthorityOrPort = false;
|
|
let isIP = false;
|
|
if (options.reference === "suffix") {
|
|
if (options.scheme) {
|
|
uri = options.scheme + ":" + uri;
|
|
} else {
|
|
uri = "//" + uri;
|
|
}
|
|
}
|
|
const authorityMatch = uri.match(AUTHORITY_PREFIX);
|
|
if (authorityMatch !== null && authorityMatch[1].indexOf("\\") !== -1) {
|
|
parsed.error = "URI authority must not contain a literal backslash.";
|
|
malformedAuthorityOrPort = true;
|
|
}
|
|
const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION);
|
|
if (introducerMatch !== null) {
|
|
const region = introducerMatch[1];
|
|
const normalizedRegion = region.replace(/[\t\n\r]/g, "");
|
|
if (normalizedRegion.length >= 2) {
|
|
if (normalizedRegion.slice(0, 2) !== "//") {
|
|
parsed.error = parsed.error || "URI authority must not contain a literal backslash.";
|
|
malformedAuthorityOrPort = true;
|
|
} else if (region.length !== normalizedRegion.length) {
|
|
parsed.error = parsed.error || "URI authority introducer must not contain whitespace.";
|
|
malformedAuthorityOrPort = true;
|
|
}
|
|
}
|
|
}
|
|
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];
|
|
}
|
|
const parseError = getParseError(parsed, matches);
|
|
if (parseError !== undefined) {
|
|
parsed.error = parsed.error || parseError;
|
|
malformedAuthorityOrPort = true;
|
|
}
|
|
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 === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) {
|
|
parsed.reference = "same-document";
|
|
} else if (parsed.scheme === undefined) {
|
|
parsed.reference = "relative";
|
|
} else if (parsed.fragment === undefined) {
|
|
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 = new URL("http://" + parsed.host).hostname;
|
|
} catch (e) {
|
|
parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
|
|
}
|
|
}
|
|
}
|
|
if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
|
|
if (uri.indexOf("%") !== -1) {
|
|
if (parsed.scheme !== undefined) {
|
|
parsed.scheme = unescape(parsed.scheme);
|
|
}
|
|
if (parsed.host !== undefined) {
|
|
parsed.host = reescapeHostDelimiters(unescape(parsed.host), isIP);
|
|
}
|
|
}
|
|
if (parsed.path) {
|
|
parsed.path = normalizePathEncoding(parsed.path);
|
|
}
|
|
if (parsed.fragment) {
|
|
try {
|
|
parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment));
|
|
} catch {
|
|
parsed.error = parsed.error || "URI malformed";
|
|
}
|
|
}
|
|
}
|
|
if (schemeHandler && schemeHandler.parse) {
|
|
schemeHandler.parse(parsed, options);
|
|
}
|
|
} else {
|
|
parsed.error = parsed.error || "URI can not be parsed.";
|
|
}
|
|
return { parsed, malformedAuthorityOrPort };
|
|
}
|
|
function parse(uri, opts) {
|
|
return parseWithStatus(uri, opts).parsed;
|
|
}
|
|
function normalizeString(uri, opts) {
|
|
return normalizeStringWithStatus(uri, opts).normalized;
|
|
}
|
|
function normalizeStringWithStatus(uri, opts) {
|
|
const { parsed, malformedAuthorityOrPort } = parseWithStatus(uri, opts);
|
|
return {
|
|
normalized: malformedAuthorityOrPort ? uri : serialize(parsed, opts),
|
|
malformedAuthorityOrPort
|
|
};
|
|
}
|
|
function normalizeComparableURI(uri, opts) {
|
|
if (typeof uri === "string") {
|
|
const { normalized, malformedAuthorityOrPort } = normalizeStringWithStatus(uri, opts);
|
|
return malformedAuthorityOrPort ? undefined : normalized;
|
|
}
|
|
if (typeof uri === "object") {
|
|
return serialize(uri, opts);
|
|
}
|
|
}
|
|
var fastUri = {
|
|
SCHEMES,
|
|
normalize,
|
|
resolve,
|
|
resolveComponent,
|
|
equal,
|
|
serialize,
|
|
parse
|
|
};
|
|
module.exports = fastUri;
|
|
module.exports.default = fastUri;
|
|
module.exports.fastUri = fastUri;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/uri.js
|
|
var require_uri = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var uri = require_fast_uri();
|
|
uri.code = 'require("ajv/dist/runtime/uri").default';
|
|
exports.default = uri;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/core.js
|
|
var require_core = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = undefined;
|
|
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 $dataRefSchema = require_data();
|
|
var uri_1 = require_uri();
|
|
var defaultRegExp = (str, flags) => new RegExp(str, flags);
|
|
defaultRegExp.code = "new RegExp";
|
|
var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
|
|
var EXT_SCOPE_NAMES = 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 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 === undefined ? undefined : _a.optimize;
|
|
const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
|
|
const regExp = (_c = (_b = o.code) === null || _b === undefined ? undefined : _b.regExp) !== null && _c !== undefined ? _c : defaultRegExp;
|
|
const uriResolver = (_d = o.uriResolver) !== null && _d !== undefined ? _d : uri_1.default;
|
|
return {
|
|
strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== undefined ? _e : s) !== null && _f !== undefined ? _f : true,
|
|
strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== undefined ? _g : s) !== null && _h !== undefined ? _h : true,
|
|
strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== undefined ? _j : s) !== null && _k !== undefined ? _k : "log",
|
|
strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== undefined ? _l : s) !== null && _m !== undefined ? _m : "log",
|
|
strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== undefined ? _o : s) !== null && _p !== undefined ? _p : false,
|
|
code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
|
|
loopRequired: (_q = o.loopRequired) !== null && _q !== undefined ? _q : MAX_EXPRESSION,
|
|
loopEnum: (_r = o.loopEnum) !== null && _r !== undefined ? _r : MAX_EXPRESSION,
|
|
meta: (_s = o.meta) !== null && _s !== undefined ? _s : true,
|
|
messages: (_t = o.messages) !== null && _t !== undefined ? _t : true,
|
|
inlineRefs: (_u = o.inlineRefs) !== null && _u !== undefined ? _u : true,
|
|
schemaId: (_v = o.schemaId) !== null && _v !== undefined ? _v : "$id",
|
|
addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== undefined ? _w : true,
|
|
validateSchema: (_x = o.validateSchema) !== null && _x !== undefined ? _x : true,
|
|
validateFormats: (_y = o.validateFormats) !== null && _y !== undefined ? _y : true,
|
|
unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== undefined ? _z : true,
|
|
int32range: (_0 = o.int32range) !== null && _0 !== undefined ? _0 : true,
|
|
uriResolver
|
|
};
|
|
}
|
|
|
|
class Ajv {
|
|
constructor(opts = {}) {
|
|
this.schemas = {};
|
|
this.refs = {};
|
|
this.formats = Object.create(null);
|
|
this._compilations = new Set;
|
|
this._loading = {};
|
|
this._cache = 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 : undefined;
|
|
}
|
|
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(schema, _meta) {
|
|
const sch = this._addSchema(schema, _meta);
|
|
return sch.validate || this._compileSchemaEnv(sch);
|
|
}
|
|
compileAsync(schema, meta) {
|
|
if (typeof this.opts.loadSchema != "function") {
|
|
throw new Error("options.loadSchema should be a function");
|
|
}
|
|
const { loadSchema } = this.opts;
|
|
return runCompileAsync.call(this, schema, 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 (e) {
|
|
if (!(e instanceof ref_error_1.default))
|
|
throw e;
|
|
checkLoaded.call(this, e);
|
|
await loadMissingSchema.call(this, e.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];
|
|
}
|
|
}
|
|
}
|
|
addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) {
|
|
if (Array.isArray(schema)) {
|
|
for (const sch of schema)
|
|
this.addSchema(sch, undefined, _meta, _validateSchema);
|
|
return this;
|
|
}
|
|
let id;
|
|
if (typeof schema === "object") {
|
|
const { schemaId } = this.opts;
|
|
id = schema[schemaId];
|
|
if (id !== undefined && 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(schema, _meta, key, _validateSchema, true);
|
|
return this;
|
|
}
|
|
addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) {
|
|
this.addSchema(schema, key, true, _validateSchema);
|
|
return this;
|
|
}
|
|
validateSchema(schema, throwOrLogError) {
|
|
if (typeof schema == "boolean")
|
|
return true;
|
|
let $schema;
|
|
$schema = schema.$schema;
|
|
if ($schema !== undefined && 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, schema);
|
|
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;
|
|
}
|
|
getSchema(keyRef) {
|
|
let sch;
|
|
while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
|
|
keyRef = sch;
|
|
if (sch === undefined) {
|
|
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);
|
|
}
|
|
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");
|
|
}
|
|
}
|
|
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 === undefined) {
|
|
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;
|
|
}
|
|
getKeyword(keyword) {
|
|
const rule = this.RULES.all[keyword];
|
|
return typeof rule == "object" ? rule.definition : !!rule;
|
|
}
|
|
removeKeyword(keyword) {
|
|
const { RULES } = this;
|
|
delete RULES.keywords[keyword];
|
|
delete RULES.all[keyword];
|
|
for (const group of RULES.rules) {
|
|
const i = group.rules.findIndex((rule) => rule.keyword === keyword);
|
|
if (i >= 0)
|
|
group.rules.splice(i, 1);
|
|
}
|
|
return this;
|
|
}
|
|
addFormat(name, format) {
|
|
if (typeof format == "string")
|
|
format = new RegExp(format);
|
|
this.formats[name] = format;
|
|
return this;
|
|
}
|
|
errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) {
|
|
if (!errors || errors.length === 0)
|
|
return "No errors";
|
|
return errors.map((e) => `${dataVar}${e.instancePath} ${e.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 keywords = metaSchema;
|
|
for (const seg of segments)
|
|
keywords = keywords[seg];
|
|
for (const key in rules) {
|
|
const rule = rules[key];
|
|
if (typeof rule != "object")
|
|
continue;
|
|
const { $data } = rule.definition;
|
|
const schema = keywords[key];
|
|
if ($data && schema)
|
|
keywords[key] = schemaOrData(schema);
|
|
}
|
|
}
|
|
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];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
_addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
|
|
let id;
|
|
const { schemaId } = this.opts;
|
|
if (typeof schema == "object") {
|
|
id = schema[schemaId];
|
|
} else {
|
|
if (this.opts.jtd)
|
|
throw new Error("schema must be object");
|
|
else if (typeof schema != "boolean")
|
|
throw new Error("schema must be object or boolean");
|
|
}
|
|
let sch = this._cache.get(schema);
|
|
if (sch !== undefined)
|
|
return sch;
|
|
baseId = (0, resolve_1.normalizeId)(id || baseId);
|
|
const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
|
|
sch = new compile_1.SchemaEnv({ schema, 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(schema, 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;
|
|
}
|
|
}
|
|
}
|
|
Ajv.ValidationError = validation_error_1.default;
|
|
Ajv.MissingRefError = ref_error_1.default;
|
|
exports.default = Ajv;
|
|
function checkOptions(checkOpts, options, msg, log = "error") {
|
|
for (const key in checkOpts) {
|
|
const opt = key;
|
|
if (opt in options)
|
|
this.logger[log](`${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 name in this.opts.formats) {
|
|
const format = this.opts.formats[name];
|
|
if (format)
|
|
this.addFormat(name, format);
|
|
}
|
|
}
|
|
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 === undefined)
|
|
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 } = this;
|
|
(0, util_1.eachItem)(keyword, (kwd) => {
|
|
if (RULES.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 === undefined ? undefined : definition.post;
|
|
if (dataType && post)
|
|
throw new Error('keyword with "post" flag cannot have "type"');
|
|
const { RULES } = this;
|
|
let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType);
|
|
if (!ruleGroup) {
|
|
ruleGroup = { type: dataType, rules: [] };
|
|
RULES.rules.push(ruleGroup);
|
|
}
|
|
RULES.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);
|
|
RULES.all[keyword] = rule;
|
|
(_a = definition.implements) === null || _a === undefined || _a.forEach((kwd) => this.addKeyword(kwd));
|
|
}
|
|
function addBeforeRule(ruleGroup, rule, before) {
|
|
const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
|
|
if (i >= 0) {
|
|
ruleGroup.rules.splice(i, 0, rule);
|
|
} else {
|
|
ruleGroup.rules.push(rule);
|
|
this.logger.warn(`rule ${before} is not defined`);
|
|
}
|
|
}
|
|
function keywordMetaschema(def) {
|
|
let { metaSchema } = def;
|
|
if (metaSchema === undefined)
|
|
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(schema) {
|
|
return { anyOf: [schema, $dataRef] };
|
|
}
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/id.js
|
|
var require_id = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var def = {
|
|
keyword: "id",
|
|
code() {
|
|
throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/ref.js
|
|
var require_ref = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.callRef = exports.getValidate = undefined;
|
|
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 === undefined)
|
|
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.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);
|
|
}, (e) => {
|
|
gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));
|
|
addErrorsFrom(e);
|
|
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 === undefined ? undefined : sch.validate) === null || _a === undefined ? undefined : _a.evaluated;
|
|
if (it.props !== true) {
|
|
if (schEvaluated && !schEvaluated.dynamicProps) {
|
|
if (schEvaluated.props !== undefined) {
|
|
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 !== undefined) {
|
|
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.callRef = callRef;
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/core/index.js
|
|
var require_core2 = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var id_1 = require_id();
|
|
var ref_1 = require_ref();
|
|
var core = [
|
|
"$schema",
|
|
"$id",
|
|
"$defs",
|
|
"$vocabulary",
|
|
{ keyword: "$comment" },
|
|
"definitions",
|
|
id_1.default,
|
|
ref_1.default
|
|
];
|
|
exports.default = core;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js
|
|
var require_limitNumber = __commonJS(function(exports) {
|
|
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 error = {
|
|
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,
|
|
code(cxt) {
|
|
const { keyword, data, schemaCode } = cxt;
|
|
cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js
|
|
var require_multipleOf = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var error = {
|
|
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,
|
|
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}))`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/runtime/ucs2length.js
|
|
var require_ucs2length = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
function ucs2length(str) {
|
|
const len = str.length;
|
|
let length = 0;
|
|
let pos = 0;
|
|
let value;
|
|
while (pos < len) {
|
|
length++;
|
|
value = str.charCodeAt(pos++);
|
|
if (value >= 55296 && value <= 56319 && pos < len) {
|
|
value = str.charCodeAt(pos);
|
|
if ((value & 64512) === 56320)
|
|
pos++;
|
|
}
|
|
}
|
|
return length;
|
|
}
|
|
exports.default = ucs2length;
|
|
ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js
|
|
var require_limitLength = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var ucs2length_1 = require_ucs2length();
|
|
var error = {
|
|
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,
|
|
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}`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/pattern.js
|
|
var require_pattern = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var code_1 = require_code2();
|
|
var util_1 = require_util();
|
|
var codegen_1 = require_codegen();
|
|
var error = {
|
|
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,
|
|
code(cxt) {
|
|
const { gen, data, $data, schema, 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, schema);
|
|
cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`);
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js
|
|
var require_limitProperties = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var error = {
|
|
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,
|
|
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}`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/required.js
|
|
var require_required = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var code_1 = require_code2();
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var error = {
|
|
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,
|
|
code(cxt) {
|
|
const { gen, schema, schemaCode, data, $data, it } = cxt;
|
|
const { opts } = it;
|
|
if (!$data && schema.length === 0)
|
|
return;
|
|
const useLoop = schema.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 schema) {
|
|
if ((props === null || props === undefined ? undefined : props[requiredKey]) === undefined && !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 allErrorsMode() {
|
|
if (useLoop || $data) {
|
|
cxt.block$data(codegen_1.nil, loopAllRequired);
|
|
} else {
|
|
for (const prop of schema) {
|
|
(0, code_1.checkReportMissingProp)(cxt, prop);
|
|
}
|
|
}
|
|
}
|
|
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, schema, missing));
|
|
(0, code_1.reportMissingProp)(cxt, missing);
|
|
gen.else();
|
|
}
|
|
}
|
|
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 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);
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js
|
|
var require_limitItems = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var error = {
|
|
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,
|
|
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.20.0/node_modules/ajv/dist/runtime/equal.js
|
|
var require_equal = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var equal = require_fast_deep_equal();
|
|
equal.code = 'require("ajv/dist/runtime/equal").default';
|
|
exports.default = equal;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js
|
|
var require_uniqueItems = __commonJS(function(exports) {
|
|
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 error = {
|
|
message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
|
|
params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}`
|
|
};
|
|
var def = {
|
|
keyword: "uniqueItems",
|
|
type: "array",
|
|
schemaType: "boolean",
|
|
$data: true,
|
|
error,
|
|
code(cxt) {
|
|
const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
|
|
if (!$data && !schema)
|
|
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 i = gen.let("i", (0, codegen_1._)`${data}.length`);
|
|
const j = gen.let("j");
|
|
cxt.setParams({ i, j });
|
|
gen.assign(valid, true);
|
|
gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
|
|
}
|
|
function canOptimize() {
|
|
return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
|
|
}
|
|
function loopN(i, 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._)`;${i}--;`, () => {
|
|
gen.let(item, (0, codegen_1._)`${data}[${i}]`);
|
|
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}] = ${i}`);
|
|
});
|
|
}
|
|
function loopN2(i, j) {
|
|
const eql = (0, util_1.useFunc)(gen, equal_1.default);
|
|
const outer = gen.name("outer");
|
|
gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => {
|
|
cxt.error();
|
|
gen.assign(valid, false).break(outer);
|
|
})));
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/const.js
|
|
var require_const = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var equal_1 = require_equal();
|
|
var error = {
|
|
message: "must be equal to constant",
|
|
params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`
|
|
};
|
|
var def = {
|
|
keyword: "const",
|
|
$data: true,
|
|
error,
|
|
code(cxt) {
|
|
const { gen, data, $data, schemaCode, schema } = cxt;
|
|
if ($data || schema && typeof schema == "object") {
|
|
cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
|
|
} else {
|
|
cxt.fail((0, codegen_1._)`${schema} !== ${data}`);
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/enum.js
|
|
var require_enum = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var equal_1 = require_equal();
|
|
var error = {
|
|
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,
|
|
code(cxt) {
|
|
const { gen, data, $data, schema, schemaCode, it } = cxt;
|
|
if (!$data && schema.length === 0)
|
|
throw new Error("enum must have non-empty array");
|
|
const useLoop = schema.length >= it.opts.loopEnum;
|
|
let eql;
|
|
const getEql = () => eql !== null && eql !== undefined ? 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(schema))
|
|
throw new Error("ajv implementation error");
|
|
const vSchema = gen.const("vSchema", schemaCode);
|
|
valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
|
|
}
|
|
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 equalCode(vSchema, i) {
|
|
const sch = schema[i];
|
|
return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`;
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/validation/index.js
|
|
var require_validation = __commonJS(function(exports) {
|
|
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 = [
|
|
limitNumber_1.default,
|
|
multipleOf_1.default,
|
|
limitLength_1.default,
|
|
pattern_1.default,
|
|
limitProperties_1.default,
|
|
required_1.default,
|
|
limitItems_1.default,
|
|
uniqueItems_1.default,
|
|
{ keyword: "type", schemaType: ["string", "array"] },
|
|
{ keyword: "nullable", schemaType: "boolean" },
|
|
const_1.default,
|
|
enum_1.default
|
|
];
|
|
exports.default = validation;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js
|
|
var require_additionalItems = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.validateAdditionalItems = undefined;
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var error = {
|
|
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,
|
|
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, data, keyword, it } = cxt;
|
|
it.items = true;
|
|
const len = gen.const("len", (0, codegen_1._)`${data}.length`);
|
|
if (schema === false) {
|
|
cxt.setParams({ len: items.length });
|
|
cxt.pass((0, codegen_1._)`${len} <= ${items.length}`);
|
|
} else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
|
|
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, (i) => {
|
|
cxt.subschema({ keyword, dataProp: i, 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.20.0/node_modules/ajv/dist/vocabularies/applicator/items.js
|
|
var require_items = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.validateTuple = undefined;
|
|
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, it } = cxt;
|
|
if (Array.isArray(schema))
|
|
return validateTuple(cxt, "additionalItems", schema);
|
|
it.items = true;
|
|
if ((0, util_1.alwaysValidSchema)(it, schema))
|
|
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, i) => {
|
|
if ((0, util_1.alwaysValidSchema)(it, sch))
|
|
return;
|
|
gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({
|
|
keyword,
|
|
schemaProp: i,
|
|
dataProp: i
|
|
}, 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.20.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js
|
|
var require_prefixItems = __commonJS(function(exports) {
|
|
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.20.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js
|
|
var require_items2020 = __commonJS(function(exports) {
|
|
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 error = {
|
|
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,
|
|
code(cxt) {
|
|
const { schema, parentSchema, it } = cxt;
|
|
const { prefixItems } = parentSchema;
|
|
it.items = true;
|
|
if ((0, util_1.alwaysValidSchema)(it, schema))
|
|
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.20.0/node_modules/ajv/dist/vocabularies/applicator/contains.js
|
|
var require_contains = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var error = {
|
|
message: ({ params: { min, max } }) => max === undefined ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`,
|
|
params: ({ params: { min, max } }) => max === undefined ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}`
|
|
};
|
|
var def = {
|
|
keyword: "contains",
|
|
type: "array",
|
|
schemaType: ["object", "boolean"],
|
|
before: "uniqueItems",
|
|
trackErrors: true,
|
|
error,
|
|
code(cxt) {
|
|
const { gen, schema, parentSchema, data, it } = cxt;
|
|
let min;
|
|
let max;
|
|
const { minContains, maxContains } = parentSchema;
|
|
if (it.opts.next) {
|
|
min = minContains === undefined ? 1 : minContains;
|
|
max = maxContains;
|
|
} else {
|
|
min = 1;
|
|
}
|
|
const len = gen.const("len", (0, codegen_1._)`${data}.length`);
|
|
cxt.setParams({ min, max });
|
|
if (max === undefined && min === 0) {
|
|
(0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
|
|
return;
|
|
}
|
|
if (max !== undefined && min > max) {
|
|
(0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
|
|
cxt.fail();
|
|
return;
|
|
}
|
|
if ((0, util_1.alwaysValidSchema)(it, schema)) {
|
|
let cond = (0, codegen_1._)`${len} >= ${min}`;
|
|
if (max !== undefined)
|
|
cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;
|
|
cxt.pass(cond);
|
|
return;
|
|
}
|
|
it.items = true;
|
|
const valid = gen.name("valid");
|
|
if (max === undefined && min === 1) {
|
|
validateItems(valid, () => gen.if(valid, () => gen.break()));
|
|
} else if (min === 0) {
|
|
gen.let(valid, true);
|
|
if (max !== undefined)
|
|
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 count = gen.let("count", 0);
|
|
validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
|
|
}
|
|
function validateItems(_valid, block) {
|
|
gen.forRange("i", 0, len, (i) => {
|
|
cxt.subschema({
|
|
keyword: "contains",
|
|
dataProp: i,
|
|
dataPropType: util_1.Type.Num,
|
|
compositeRule: true
|
|
}, _valid);
|
|
block();
|
|
});
|
|
}
|
|
function checkLimits(count) {
|
|
gen.code((0, codegen_1._)`${count}++`);
|
|
if (max === undefined) {
|
|
gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
|
|
} else {
|
|
gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());
|
|
if (min === 1)
|
|
gen.assign(valid, true);
|
|
else
|
|
gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));
|
|
}
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js
|
|
var require_dependencies = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = undefined;
|
|
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}}`
|
|
};
|
|
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 }) {
|
|
const propertyDeps = {};
|
|
const schemaDeps = {};
|
|
for (const key in schema) {
|
|
if (key === "__proto__")
|
|
continue;
|
|
const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
|
|
deps[key] = schema[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);
|
|
}
|
|
});
|
|
} else {
|
|
gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
|
|
(0, code_1.reportMissingProp)(cxt, missing);
|
|
gen.else();
|
|
}
|
|
}
|
|
}
|
|
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));
|
|
cxt.ok(valid);
|
|
}
|
|
}
|
|
exports.validateSchemaDeps = validateSchemaDeps;
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js
|
|
var require_propertyNames = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var error = {
|
|
message: "property name must be valid",
|
|
params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}`
|
|
};
|
|
var def = {
|
|
keyword: "propertyNames",
|
|
type: "object",
|
|
schemaType: ["object", "boolean"],
|
|
error,
|
|
code(cxt) {
|
|
const { gen, schema, data, it } = cxt;
|
|
if ((0, util_1.alwaysValidSchema)(it, schema))
|
|
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.20.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js
|
|
var require_additionalProperties = __commonJS(function(exports) {
|
|
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 error = {
|
|
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,
|
|
code(cxt) {
|
|
const { gen, schema, 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, schema))
|
|
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})`));
|
|
}
|
|
return (0, codegen_1.not)(definedProp);
|
|
}
|
|
function deleteAdditional(key) {
|
|
gen.code((0, codegen_1._)`delete ${data}[${key}]`);
|
|
}
|
|
function additionalPropertyCode(key) {
|
|
if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) {
|
|
deleteAdditional(key);
|
|
return;
|
|
}
|
|
if (schema === false) {
|
|
cxt.setParams({ additionalProperty: key });
|
|
cxt.error();
|
|
if (!allErrors)
|
|
gen.break();
|
|
return;
|
|
}
|
|
if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
|
|
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());
|
|
}
|
|
}
|
|
}
|
|
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
|
|
});
|
|
}
|
|
cxt.subschema(subschema, valid);
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/properties.js
|
|
var require_properties = __commonJS(function(exports) {
|
|
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, parentSchema, data, it } = cxt;
|
|
if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) {
|
|
additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
|
|
}
|
|
const allProps = (0, code_1.allSchemaProperties)(schema);
|
|
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 properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
|
|
if (properties.length === 0)
|
|
return;
|
|
const valid = gen.name("valid");
|
|
for (const prop of properties) {
|
|
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();
|
|
}
|
|
cxt.it.definedProperties.add(prop);
|
|
cxt.ok(valid);
|
|
}
|
|
function hasDefault(prop) {
|
|
return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined;
|
|
}
|
|
function applyPropertySchema(prop) {
|
|
cxt.subschema({
|
|
keyword: "properties",
|
|
schemaProp: prop,
|
|
dataProp: prop
|
|
}, valid);
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js
|
|
var require_patternProperties = __commonJS(function(exports) {
|
|
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, data, parentSchema, it } = cxt;
|
|
const { opts } = it;
|
|
const patterns = (0, code_1.allSchemaProperties)(schema);
|
|
const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[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);
|
|
}
|
|
}
|
|
}
|
|
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 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());
|
|
}
|
|
});
|
|
});
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/not.js
|
|
var require_not = __commonJS(function(exports) {
|
|
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, it } = cxt;
|
|
if ((0, util_1.alwaysValidSchema)(it, schema)) {
|
|
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.20.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js
|
|
var require_anyOf = __commonJS(function(exports) {
|
|
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.20.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js
|
|
var require_oneOf = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var error = {
|
|
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,
|
|
code(cxt) {
|
|
const { gen, schema, parentSchema, it } = cxt;
|
|
if (!Array.isArray(schema))
|
|
throw new Error("ajv implementation error");
|
|
if (it.opts.discriminator && parentSchema.discriminator)
|
|
return;
|
|
const schArr = schema;
|
|
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, i) => {
|
|
let schCxt;
|
|
if ((0, util_1.alwaysValidSchema)(it, sch)) {
|
|
gen.var(schValid, true);
|
|
} else {
|
|
schCxt = cxt.subschema({
|
|
keyword: "oneOf",
|
|
schemaProp: i,
|
|
compositeRule: true
|
|
}, schValid);
|
|
}
|
|
if (i > 0) {
|
|
gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else();
|
|
}
|
|
gen.if(schValid, () => {
|
|
gen.assign(valid, true);
|
|
gen.assign(passing, i);
|
|
if (schCxt)
|
|
cxt.mergeEvaluated(schCxt, codegen_1.Name);
|
|
});
|
|
});
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js
|
|
var require_allOf = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var util_1 = require_util();
|
|
var def = {
|
|
keyword: "allOf",
|
|
schemaType: "array",
|
|
code(cxt) {
|
|
const { gen, schema, it } = cxt;
|
|
if (!Array.isArray(schema))
|
|
throw new Error("ajv implementation error");
|
|
const valid = gen.name("valid");
|
|
schema.forEach((sch, i) => {
|
|
if ((0, util_1.alwaysValidSchema)(it, sch))
|
|
return;
|
|
const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
|
|
cxt.ok(valid);
|
|
cxt.mergeEvaluated(schCxt);
|
|
});
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/if.js
|
|
var require_if = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var util_1 = require_util();
|
|
var error = {
|
|
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,
|
|
code(cxt) {
|
|
const { gen, parentSchema, it } = cxt;
|
|
if (parentSchema.then === undefined && parentSchema.else === undefined) {
|
|
(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 schema = it.schema[keyword];
|
|
return schema !== undefined && !(0, util_1.alwaysValidSchema)(it, schema);
|
|
}
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js
|
|
var require_thenElse = __commonJS(function(exports) {
|
|
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 === undefined)
|
|
(0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/applicator/index.js
|
|
var require_applicator = __commonJS(function(exports) {
|
|
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 = [
|
|
not_1.default,
|
|
anyOf_1.default,
|
|
oneOf_1.default,
|
|
allOf_1.default,
|
|
if_1.default,
|
|
thenElse_1.default,
|
|
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.20.0/node_modules/ajv/dist/vocabularies/format/format.js
|
|
var require_format = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var codegen_1 = require_codegen();
|
|
var error = {
|
|
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,
|
|
code(cxt, ruleType) {
|
|
const { gen, data, $data, schema, 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 format = gen.let("format");
|
|
gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, 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} && !${format}`;
|
|
}
|
|
function invalidFmt() {
|
|
const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`;
|
|
const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
|
|
return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
|
|
}
|
|
}
|
|
function validateFormat() {
|
|
const formatDef = self2.formats[schema];
|
|
if (!formatDef) {
|
|
unknownFormat();
|
|
return;
|
|
}
|
|
if (formatDef === true)
|
|
return;
|
|
const [fmtType, format, fmtRef] = getFormat(formatDef);
|
|
if (fmtType === ruleType)
|
|
cxt.pass(validCondition());
|
|
function unknownFormat() {
|
|
if (opts.strictSchema === false) {
|
|
self2.logger.warn(unknownMsg());
|
|
return;
|
|
}
|
|
throw new Error(unknownMsg());
|
|
function unknownMsg() {
|
|
return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
|
|
}
|
|
}
|
|
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)(schema)}` : undefined;
|
|
const fmt = gen.scopeValue("formats", { key: schema, 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];
|
|
}
|
|
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 format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`;
|
|
}
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/format/index.js
|
|
var require_format2 = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var format_1 = require_format();
|
|
var format = [format_1.default];
|
|
exports.default = format;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/metadata.js
|
|
var require_metadata = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.contentVocabulary = exports.metadataVocabulary = undefined;
|
|
exports.metadataVocabulary = [
|
|
"title",
|
|
"description",
|
|
"default",
|
|
"deprecated",
|
|
"readOnly",
|
|
"writeOnly",
|
|
"examples"
|
|
];
|
|
exports.contentVocabulary = [
|
|
"contentMediaType",
|
|
"contentEncoding",
|
|
"contentSchema"
|
|
];
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/draft7.js
|
|
var require_draft7 = __commonJS(function(exports) {
|
|
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.20.0/node_modules/ajv/dist/vocabularies/discriminator/types.js
|
|
var require_types = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.DiscrError = undefined;
|
|
var DiscrError;
|
|
(function(DiscrError) {
|
|
DiscrError["Tag"] = "tag";
|
|
DiscrError["Mapping"] = "mapping";
|
|
})(DiscrError || (exports.DiscrError = DiscrError = {}));
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/vocabularies/discriminator/index.js
|
|
var require_discriminator = __commonJS(function(exports) {
|
|
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 error = {
|
|
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, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`
|
|
};
|
|
var def = {
|
|
keyword: "discriminator",
|
|
type: "object",
|
|
schemaType: "object",
|
|
error,
|
|
code(cxt) {
|
|
const { gen, data, schema, parentSchema, it } = cxt;
|
|
const { oneOf } = parentSchema;
|
|
if (!it.opts.discriminator) {
|
|
throw new Error("discriminator: requires discriminator option");
|
|
}
|
|
const tagName = schema.propertyName;
|
|
if (typeof tagName != "string")
|
|
throw new Error("discriminator: requires propertyName");
|
|
if (schema.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 tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`);
|
|
gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
|
|
cxt.ok(valid);
|
|
function validateMapping() {
|
|
const mapping = getMapping();
|
|
gen.if(false);
|
|
for (const tagValue in mapping) {
|
|
gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`);
|
|
gen.assign(valid, applyTagSchema(mapping[tagValue]));
|
|
}
|
|
gen.else();
|
|
cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
|
|
gen.endIf();
|
|
}
|
|
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 getMapping() {
|
|
var _a;
|
|
const oneOfMapping = {};
|
|
const topRequired = hasRequired(parentSchema);
|
|
let tagRequired = true;
|
|
for (let i = 0;i < oneOf.length; i++) {
|
|
let sch = oneOf[i];
|
|
if ((sch === null || sch === undefined ? undefined : 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 === undefined)
|
|
throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
|
|
}
|
|
const propSch = (_a = sch === null || sch === undefined ? undefined : sch.properties) === null || _a === undefined ? undefined : _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, i);
|
|
}
|
|
if (!tagRequired)
|
|
throw new Error(`discriminator: "${tagName}" must be required`);
|
|
return oneOfMapping;
|
|
function hasRequired({ required }) {
|
|
return Array.isArray(required) && required.includes(tagName);
|
|
}
|
|
function addMappings(sch, i) {
|
|
if (sch.const) {
|
|
addMapping(sch.const, i);
|
|
} else if (sch.enum) {
|
|
for (const tagValue of sch.enum) {
|
|
addMapping(tagValue, i);
|
|
}
|
|
} else {
|
|
throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
|
|
}
|
|
}
|
|
function addMapping(tagValue, i) {
|
|
if (typeof tagValue != "string" || tagValue in oneOfMapping) {
|
|
throw new Error(`discriminator: "${tagName}" values must be unique strings`);
|
|
}
|
|
oneOfMapping[tagValue] = i;
|
|
}
|
|
}
|
|
}
|
|
};
|
|
exports.default = def;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv@8.20.0/node_modules/ajv/dist/refs/json-schema-draft-07.json
|
|
var require_json_schema_draft_07 = __commonJS(function(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/ajv@8.20.0/node_modules/ajv/dist/ajv.js
|
|
var require_ajv = __commonJS(function(exports, module) {
|
|
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 = undefined;
|
|
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";
|
|
|
|
class Ajv 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 : undefined);
|
|
}
|
|
}
|
|
exports.Ajv = Ajv;
|
|
module.exports = exports = Ajv;
|
|
module.exports.Ajv = Ajv;
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.default = Ajv;
|
|
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-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/formats.js
|
|
var require_formats = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.formatNames = exports.fastFormats = exports.fullFormats = undefined;
|
|
function fmtDef(validate, compare) {
|
|
return { validate, compare };
|
|
}
|
|
exports.fullFormats = {
|
|
date: fmtDef(date, compareDate),
|
|
time: fmtDef(getTime(true), compareTime),
|
|
"date-time": fmtDef(getDateTime(true), compareDateTime),
|
|
"iso-time": fmtDef(getTime(), compareIsoTime),
|
|
"iso-date-time": fmtDef(getDateTime(), compareIsoDateTime),
|
|
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": /^(?:(?:[^\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,
|
|
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,
|
|
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: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,
|
|
"json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/,
|
|
"json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,
|
|
"relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,
|
|
byte,
|
|
int32: { type: "number", validate: validateInt32 },
|
|
int64: { type: "number", validate: validateInt64 },
|
|
float: { type: "number", validate: validateNumber },
|
|
double: { type: "number", validate: validateNumber },
|
|
password: true,
|
|
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: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
|
|
"uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
|
|
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 date(str) {
|
|
const matches = DATE.exec(str);
|
|
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;
|
|
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 time(str) {
|
|
const matches = TIME.exec(str);
|
|
if (!matches)
|
|
return false;
|
|
const hr = +matches[1];
|
|
const min = +matches[2];
|
|
const sec = +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 && min <= 59 && sec < 60)
|
|
return true;
|
|
const utcMin = min - tzM * tzSign;
|
|
const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0);
|
|
return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;
|
|
};
|
|
}
|
|
function compareTime(s1, s2) {
|
|
if (!(s1 && s2))
|
|
return;
|
|
const t1 = new Date("2020-01-01T" + s1).valueOf();
|
|
const t2 = new Date("2020-01-01T" + s2).valueOf();
|
|
if (!(t1 && t2))
|
|
return;
|
|
return t1 - t2;
|
|
}
|
|
function compareIsoTime(t1, t2) {
|
|
if (!(t1 && t2))
|
|
return;
|
|
const a1 = TIME.exec(t1);
|
|
const a2 = TIME.exec(t2);
|
|
if (!(a1 && a2))
|
|
return;
|
|
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 time = getTime(strictTimeZone);
|
|
return function date_time(str) {
|
|
const dateTime = str.split(DATE_TIME_SEPARATOR);
|
|
return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]);
|
|
};
|
|
}
|
|
function compareDateTime(dt1, dt2) {
|
|
if (!(dt1 && dt2))
|
|
return;
|
|
const d1 = new Date(dt1).valueOf();
|
|
const d2 = new Date(dt2).valueOf();
|
|
if (!(d1 && d2))
|
|
return;
|
|
return d1 - d2;
|
|
}
|
|
function compareIsoDateTime(dt1, dt2) {
|
|
if (!(dt1 && dt2))
|
|
return;
|
|
const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);
|
|
const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR);
|
|
const res = compareDate(d1, d2);
|
|
if (res === undefined)
|
|
return;
|
|
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(str) {
|
|
return NOT_URI_FRAGMENT.test(str) && URI.test(str);
|
|
}
|
|
var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;
|
|
function byte(str) {
|
|
BYTE.lastIndex = 0;
|
|
return BYTE.test(str);
|
|
}
|
|
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(str) {
|
|
if (Z_ANCHOR.test(str))
|
|
return false;
|
|
try {
|
|
new RegExp(str);
|
|
return true;
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
}
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/limit.js
|
|
var require_limit = __commonJS(function(exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.formatLimitDefinition = undefined;
|
|
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 error = {
|
|
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,
|
|
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)));
|
|
}
|
|
function validateFormat() {
|
|
const format = fCxt.schema;
|
|
const fmtDef = self2.formats[format];
|
|
if (!fmtDef || fmtDef === true)
|
|
return;
|
|
if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") {
|
|
throw new Error(`"${keyword}": format "${format}" does not define "compare" function`);
|
|
}
|
|
const fmt = gen.scopeValue("formats", {
|
|
key: format,
|
|
ref: fmtDef,
|
|
code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : undefined
|
|
});
|
|
cxt.fail$data(compareCode(fmt));
|
|
}
|
|
function compareCode(fmt) {
|
|
return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;
|
|
}
|
|
},
|
|
dependencies: ["format"]
|
|
};
|
|
var formatLimitPlugin = (ajv) => {
|
|
ajv.addKeyword(exports.formatLimitDefinition);
|
|
return ajv;
|
|
};
|
|
exports.default = formatLimitPlugin;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.20.0/node_modules/ajv-formats/dist/index.js
|
|
var require_dist = __commonJS(function(exports, module) {
|
|
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 = (ajv, opts = { keywords: true }) => {
|
|
if (Array.isArray(opts)) {
|
|
addFormats(ajv, opts, formats_1.fullFormats, fullName);
|
|
return ajv;
|
|
}
|
|
const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];
|
|
const list = opts.formats || formats_1.formatNames;
|
|
addFormats(ajv, list, formats, exportName);
|
|
if (opts.keywords)
|
|
(0, limit_1.default)(ajv);
|
|
return ajv;
|
|
};
|
|
formatsPlugin.get = (name, mode = "full") => {
|
|
const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats;
|
|
const f = formats[name];
|
|
if (!f)
|
|
throw new Error(`Unknown format "${name}"`);
|
|
return f;
|
|
};
|
|
function addFormats(ajv, list, fs, exportName) {
|
|
var _a;
|
|
var _b;
|
|
(_a = (_b = ajv.opts.code).formats) !== null && _a !== undefined || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`);
|
|
for (const f of list)
|
|
ajv.addFormat(f, fs[f]);
|
|
}
|
|
module.exports = exports = formatsPlugin;
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.default = formatsPlugin;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
|
|
var require_src = __commonJS(function(exports, module) {
|
|
var ESC = "\x1B";
|
|
var CSI = `${ESC}[`;
|
|
var beep = "\x07";
|
|
var cursor = {
|
|
to(x, y) {
|
|
if (!y)
|
|
return `${CSI}${x + 1}G`;
|
|
return `${CSI}${y + 1};${x + 1}H`;
|
|
},
|
|
move(x, y) {
|
|
let ret = "";
|
|
if (x < 0)
|
|
ret += `${CSI}${-x}D`;
|
|
else if (x > 0)
|
|
ret += `${CSI}${x}C`;
|
|
if (y < 0)
|
|
ret += `${CSI}${-y}A`;
|
|
else if (y > 0)
|
|
ret += `${CSI}${y}B`;
|
|
return ret;
|
|
},
|
|
up: (count = 1) => `${CSI}${count}A`,
|
|
down: (count = 1) => `${CSI}${count}B`,
|
|
forward: (count = 1) => `${CSI}${count}C`,
|
|
backward: (count = 1) => `${CSI}${count}D`,
|
|
nextLine: (count = 1) => `${CSI}E`.repeat(count),
|
|
prevLine: (count = 1) => `${CSI}F`.repeat(count),
|
|
left: `${CSI}G`,
|
|
hide: `${CSI}?25l`,
|
|
show: `${CSI}?25h`,
|
|
save: `${ESC}7`,
|
|
restore: `${ESC}8`
|
|
};
|
|
var scroll = {
|
|
up: (count = 1) => `${CSI}S`.repeat(count),
|
|
down: (count = 1) => `${CSI}T`.repeat(count)
|
|
};
|
|
var erase = {
|
|
screen: `${CSI}2J`,
|
|
up: (count = 1) => `${CSI}1J`.repeat(count),
|
|
down: (count = 1) => `${CSI}J`.repeat(count),
|
|
line: `${CSI}2K`,
|
|
lineEnd: `${CSI}K`,
|
|
lineStart: `${CSI}1K`,
|
|
lines(count) {
|
|
let clear = "";
|
|
for (let i = 0;i < count; i++)
|
|
clear += this.line + (i < count - 1 ? cursor.up() : "");
|
|
if (count)
|
|
clear += cursor.left;
|
|
return clear;
|
|
}
|
|
};
|
|
module.exports = { cursor, scroll, erase, beep };
|
|
});
|
|
|
|
// src/services/run-subagent-output-mcp.ts
|
|
import process5 from "process";
|
|
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/helpers/util.js
|
|
var util;
|
|
(function(util) {
|
|
util.assertEqual = (_) => {};
|
|
function assertIs(_arg) {}
|
|
util.assertIs = assertIs;
|
|
function assertNever(_x) {
|
|
throw new Error;
|
|
}
|
|
util.assertNever = assertNever;
|
|
util.arrayToEnum = (items) => {
|
|
const obj = {};
|
|
for (const item of items) {
|
|
obj[item] = item;
|
|
}
|
|
return obj;
|
|
};
|
|
util.getValidEnumValues = (obj) => {
|
|
const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
|
|
const filtered = {};
|
|
for (const k of validKeys) {
|
|
filtered[k] = obj[k];
|
|
}
|
|
return util.objectValues(filtered);
|
|
};
|
|
util.objectValues = (obj) => {
|
|
return util.objectKeys(obj).map(function(e) {
|
|
return obj[e];
|
|
});
|
|
};
|
|
util.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
|
|
const keys = [];
|
|
for (const key in object) {
|
|
if (Object.prototype.hasOwnProperty.call(object, key)) {
|
|
keys.push(key);
|
|
}
|
|
}
|
|
return keys;
|
|
};
|
|
util.find = (arr, checker) => {
|
|
for (const item of arr) {
|
|
if (checker(item))
|
|
return item;
|
|
}
|
|
return;
|
|
};
|
|
util.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
|
|
function joinValues(array, separator = " | ") {
|
|
return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
|
|
}
|
|
util.joinValues = joinValues;
|
|
util.jsonStringifyReplacer = (_, value) => {
|
|
if (typeof value === "bigint") {
|
|
return value.toString();
|
|
}
|
|
return value;
|
|
};
|
|
})(util || (util = {}));
|
|
var objectUtil;
|
|
(function(objectUtil) {
|
|
objectUtil.mergeShapes = (first, second) => {
|
|
return {
|
|
...first,
|
|
...second
|
|
};
|
|
};
|
|
})(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;
|
|
}
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/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"
|
|
]);
|
|
class ZodError extends Error {
|
|
get errors() {
|
|
return this.issues;
|
|
}
|
|
constructor(issues) {
|
|
super();
|
|
this.issues = [];
|
|
this.addIssue = (sub) => {
|
|
this.issues = [...this.issues, sub];
|
|
};
|
|
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;
|
|
}
|
|
format(_mapper) {
|
|
const mapper = _mapper || function(issue) {
|
|
return issue.message;
|
|
};
|
|
const fieldErrors = { _errors: [] };
|
|
const processError = (error) => {
|
|
for (const issue of error.issues) {
|
|
if (issue.code === "invalid_union") {
|
|
issue.unionErrors.map(processError);
|
|
} else if (issue.code === "invalid_return_type") {
|
|
processError(issue.returnTypeError);
|
|
} else if (issue.code === "invalid_arguments") {
|
|
processError(issue.argumentsError);
|
|
} else if (issue.path.length === 0) {
|
|
fieldErrors._errors.push(mapper(issue));
|
|
} else {
|
|
let curr = fieldErrors;
|
|
let i = 0;
|
|
while (i < issue.path.length) {
|
|
const el = issue.path[i];
|
|
const terminal = i === issue.path.length - 1;
|
|
if (!terminal) {
|
|
curr[el] = curr[el] || { _errors: [] };
|
|
} else {
|
|
curr[el] = curr[el] || { _errors: [] };
|
|
curr[el]._errors.push(mapper(issue));
|
|
}
|
|
curr = curr[el];
|
|
i++;
|
|
}
|
|
}
|
|
}
|
|
};
|
|
processError(this);
|
|
return fieldErrors;
|
|
}
|
|
static assert(value) {
|
|
if (!(value instanceof ZodError)) {
|
|
throw new Error(`Not a ZodError: ${value}`);
|
|
}
|
|
}
|
|
toString() {
|
|
return this.message;
|
|
}
|
|
get message() {
|
|
return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
|
|
}
|
|
get isEmpty() {
|
|
return this.issues.length === 0;
|
|
}
|
|
flatten(mapper = (issue) => issue.message) {
|
|
const fieldErrors = Object.create(null);
|
|
const formErrors = [];
|
|
for (const sub of this.issues) {
|
|
if (sub.path.length > 0) {
|
|
const firstEl = sub.path[0];
|
|
fieldErrors[firstEl] = fieldErrors[firstEl] || [];
|
|
fieldErrors[firstEl].push(mapper(sub));
|
|
} else {
|
|
formErrors.push(mapper(sub));
|
|
}
|
|
}
|
|
return { formErrors, fieldErrors };
|
|
}
|
|
get formErrors() {
|
|
return this.flatten();
|
|
}
|
|
}
|
|
ZodError.create = (issues) => {
|
|
const error = new ZodError(issues);
|
|
return error;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/locales/en.js
|
|
var errorMap = (issue, _ctx) => {
|
|
let message;
|
|
switch (issue.code) {
|
|
case ZodIssueCode.invalid_type:
|
|
if (issue.received === ZodParsedType.undefined) {
|
|
message = "Required";
|
|
} else {
|
|
message = `Expected ${issue.expected}, received ${issue.received}`;
|
|
}
|
|
break;
|
|
case ZodIssueCode.invalid_literal:
|
|
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
|
|
break;
|
|
case ZodIssueCode.unrecognized_keys:
|
|
message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
|
|
break;
|
|
case ZodIssueCode.invalid_union:
|
|
message = `Invalid input`;
|
|
break;
|
|
case ZodIssueCode.invalid_union_discriminator:
|
|
message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
|
|
break;
|
|
case ZodIssueCode.invalid_enum_value:
|
|
message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.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 issue.validation === "object") {
|
|
if ("includes" in issue.validation) {
|
|
message = `Invalid input: must include "${issue.validation.includes}"`;
|
|
if (typeof issue.validation.position === "number") {
|
|
message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
|
|
}
|
|
} else if ("startsWith" in issue.validation) {
|
|
message = `Invalid input: must start with "${issue.validation.startsWith}"`;
|
|
} else if ("endsWith" in issue.validation) {
|
|
message = `Invalid input: must end with "${issue.validation.endsWith}"`;
|
|
} else {
|
|
util.assertNever(issue.validation);
|
|
}
|
|
} else if (issue.validation !== "regex") {
|
|
message = `Invalid ${issue.validation}`;
|
|
} else {
|
|
message = "Invalid";
|
|
}
|
|
break;
|
|
case ZodIssueCode.too_small:
|
|
if (issue.type === "array")
|
|
message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
|
|
else if (issue.type === "string")
|
|
message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
|
|
else if (issue.type === "number")
|
|
message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
|
|
else if (issue.type === "bigint")
|
|
message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
|
|
else if (issue.type === "date")
|
|
message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
|
|
else
|
|
message = "Invalid input";
|
|
break;
|
|
case ZodIssueCode.too_big:
|
|
if (issue.type === "array")
|
|
message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
|
|
else if (issue.type === "string")
|
|
message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
|
|
else if (issue.type === "number")
|
|
message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
|
|
else if (issue.type === "bigint")
|
|
message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
|
|
else if (issue.type === "date")
|
|
message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.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 ${issue.multipleOf}`;
|
|
break;
|
|
case ZodIssueCode.not_finite:
|
|
message = "Number must be finite";
|
|
break;
|
|
default:
|
|
message = _ctx.defaultError;
|
|
util.assertNever(issue);
|
|
}
|
|
return { message };
|
|
};
|
|
var en_default = errorMap;
|
|
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/errors.js
|
|
var overrideErrorMap = en_default;
|
|
function getErrorMap() {
|
|
return overrideErrorMap;
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/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 !== undefined) {
|
|
return {
|
|
...issueData,
|
|
path: fullPath,
|
|
message: issueData.message
|
|
};
|
|
}
|
|
let errorMessage = "";
|
|
const maps = errorMaps.filter((m) => !!m).slice().reverse();
|
|
for (const map of maps) {
|
|
errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
|
|
}
|
|
return {
|
|
...issueData,
|
|
path: fullPath,
|
|
message: errorMessage
|
|
};
|
|
};
|
|
function addIssueToContext(ctx, issueData) {
|
|
const overrideMap = getErrorMap();
|
|
const issue = makeIssue({
|
|
issueData,
|
|
data: ctx.data,
|
|
path: ctx.path,
|
|
errorMaps: [
|
|
ctx.common.contextualErrorMap,
|
|
ctx.schemaErrorMap,
|
|
overrideMap,
|
|
overrideMap === en_default ? undefined : en_default
|
|
].filter((x) => !!x)
|
|
});
|
|
ctx.common.issues.push(issue);
|
|
}
|
|
|
|
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 };
|
|
}
|
|
static async mergeObjectAsync(status, pairs) {
|
|
const syncPairs = [];
|
|
for (const pair of pairs) {
|
|
const key = await pair.key;
|
|
const value = await pair.value;
|
|
syncPairs.push({
|
|
key,
|
|
value
|
|
});
|
|
}
|
|
return ParseStatus.mergeObjectSync(status, syncPairs);
|
|
}
|
|
static mergeObjectSync(status, pairs) {
|
|
const finalObject = {};
|
|
for (const pair of pairs) {
|
|
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 };
|
|
}
|
|
}
|
|
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;
|
|
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/helpers/errorUtil.js
|
|
var errorUtil;
|
|
(function(errorUtil) {
|
|
errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
|
|
errorUtil.toString = (message) => typeof message === "string" ? message : message?.message;
|
|
})(errorUtil || (errorUtil = {}));
|
|
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/types.js
|
|
class ParseInputLazyPath {
|
|
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;
|
|
}
|
|
}
|
|
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 error = new ZodError(ctx.common.issues);
|
|
this._error = error;
|
|
return this._error;
|
|
}
|
|
};
|
|
}
|
|
};
|
|
function processCreateParams(params) {
|
|
if (!params)
|
|
return {};
|
|
const { errorMap, invalid_type_error, required_error, description } = params;
|
|
if (errorMap && (invalid_type_error || required_error)) {
|
|
throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
|
|
}
|
|
if (errorMap)
|
|
return { errorMap, 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 };
|
|
}
|
|
|
|
class ZodType {
|
|
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
|
|
};
|
|
}
|
|
_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;
|
|
}
|
|
_parseAsync(input) {
|
|
const result = this._parse(input);
|
|
return Promise.resolve(result);
|
|
}
|
|
parse(data, params) {
|
|
const result = this.safeParse(data, params);
|
|
if (result.success)
|
|
return result.data;
|
|
throw result.error;
|
|
}
|
|
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
|
|
};
|
|
}
|
|
}
|
|
return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
|
|
value: result.value
|
|
} : {
|
|
issues: ctx.common.issues
|
|
});
|
|
}
|
|
async parseAsync(data, params) {
|
|
const result = await this.safeParseAsync(data, params);
|
|
if (result.success)
|
|
return result.data;
|
|
throw result.error;
|
|
}
|
|
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(check, 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 = check(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;
|
|
}
|
|
});
|
|
}
|
|
refinement(check, refinementData) {
|
|
return this._refinement((val, ctx) => {
|
|
if (!check(val)) {
|
|
ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
|
|
return false;
|
|
} else {
|
|
return true;
|
|
}
|
|
});
|
|
}
|
|
_refinement(refinement) {
|
|
return new ZodEffects({
|
|
schema: this,
|
|
typeName: ZodFirstPartyTypeKind.ZodEffects,
|
|
effect: { type: "refinement", refinement }
|
|
});
|
|
}
|
|
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)
|
|
};
|
|
}
|
|
optional() {
|
|
return ZodOptional.create(this, this._def);
|
|
}
|
|
nullable() {
|
|
return ZodNullable.create(this, this._def);
|
|
}
|
|
nullish() {
|
|
return this.nullable().optional();
|
|
}
|
|
array() {
|
|
return ZodArray.create(this);
|
|
}
|
|
promise() {
|
|
return ZodPromise.create(this, this._def);
|
|
}
|
|
or(option) {
|
|
return ZodUnion.create([this, option], this._def);
|
|
}
|
|
and(incoming) {
|
|
return ZodIntersection.create(this, incoming, this._def);
|
|
}
|
|
transform(transform) {
|
|
return new ZodEffects({
|
|
...processCreateParams(this._def),
|
|
schema: this,
|
|
typeName: ZodFirstPartyTypeKind.ZodEffects,
|
|
effect: { type: "transform", transform }
|
|
});
|
|
}
|
|
default(def) {
|
|
const defaultValueFunc = typeof def === "function" ? def : () => def;
|
|
return new ZodDefault({
|
|
...processCreateParams(this._def),
|
|
innerType: this,
|
|
defaultValue: defaultValueFunc,
|
|
typeName: ZodFirstPartyTypeKind.ZodDefault
|
|
});
|
|
}
|
|
brand() {
|
|
return new ZodBranded({
|
|
typeName: ZodFirstPartyTypeKind.ZodBranded,
|
|
type: this,
|
|
...processCreateParams(this._def)
|
|
});
|
|
}
|
|
catch(def) {
|
|
const catchValueFunc = typeof def === "function" ? def : () => def;
|
|
return new ZodCatch({
|
|
...processCreateParams(this._def),
|
|
innerType: this,
|
|
catchValue: catchValueFunc,
|
|
typeName: ZodFirstPartyTypeKind.ZodCatch
|
|
});
|
|
}
|
|
describe(description) {
|
|
const This = this.constructor;
|
|
return new This({
|
|
...this._def,
|
|
description
|
|
});
|
|
}
|
|
pipe(target) {
|
|
return ZodPipeline.create(this, target);
|
|
}
|
|
readonly() {
|
|
return ZodReadonly.create(this);
|
|
}
|
|
isOptional() {
|
|
return this.safeParse(undefined).success;
|
|
}
|
|
isNullable() {
|
|
return this.safeParse(null).success;
|
|
}
|
|
}
|
|
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+)?`;
|
|
}
|
|
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, version) {
|
|
if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
|
|
return true;
|
|
}
|
|
if ((version === "v6" || !version) && 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 base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
|
|
const decoded = JSON.parse(atob(base64));
|
|
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, version) {
|
|
if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
|
|
return true;
|
|
}
|
|
if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
class ZodString extends ZodType {
|
|
_parse(input) {
|
|
if (this._def.coerce) {
|
|
input.data = String(input.data);
|
|
}
|
|
const parsedType = this._getType(input);
|
|
if (parsedType !== ZodParsedType.string) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.string,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
const status = new ParseStatus;
|
|
let ctx = undefined;
|
|
for (const check of this._def.checks) {
|
|
if (check.kind === "min") {
|
|
if (input.data.length < check.value) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_small,
|
|
minimum: check.value,
|
|
type: "string",
|
|
inclusive: true,
|
|
exact: false,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "max") {
|
|
if (input.data.length > check.value) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_big,
|
|
maximum: check.value,
|
|
type: "string",
|
|
inclusive: true,
|
|
exact: false,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "length") {
|
|
const tooBig = input.data.length > check.value;
|
|
const tooSmall = input.data.length < check.value;
|
|
if (tooBig || tooSmall) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
if (tooBig) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_big,
|
|
maximum: check.value,
|
|
type: "string",
|
|
inclusive: true,
|
|
exact: true,
|
|
message: check.message
|
|
});
|
|
} else if (tooSmall) {
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_small,
|
|
minimum: check.value,
|
|
type: "string",
|
|
inclusive: true,
|
|
exact: true,
|
|
message: check.message
|
|
});
|
|
}
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "email") {
|
|
if (!emailRegex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "email",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.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: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "uuid") {
|
|
if (!uuidRegex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "uuid",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "nanoid") {
|
|
if (!nanoidRegex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "nanoid",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "cuid") {
|
|
if (!cuidRegex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "cuid",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "cuid2") {
|
|
if (!cuid2Regex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "cuid2",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "ulid") {
|
|
if (!ulidRegex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "ulid",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "url") {
|
|
try {
|
|
new URL(input.data);
|
|
} catch {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "url",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "regex") {
|
|
check.regex.lastIndex = 0;
|
|
const testResult = check.regex.test(input.data);
|
|
if (!testResult) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "regex",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "trim") {
|
|
input.data = input.data.trim();
|
|
} else if (check.kind === "includes") {
|
|
if (!input.data.includes(check.value, check.position)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_string,
|
|
validation: { includes: check.value, position: check.position },
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "toLowerCase") {
|
|
input.data = input.data.toLowerCase();
|
|
} else if (check.kind === "toUpperCase") {
|
|
input.data = input.data.toUpperCase();
|
|
} else if (check.kind === "startsWith") {
|
|
if (!input.data.startsWith(check.value)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_string,
|
|
validation: { startsWith: check.value },
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "endsWith") {
|
|
if (!input.data.endsWith(check.value)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_string,
|
|
validation: { endsWith: check.value },
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "datetime") {
|
|
const regex = datetimeRegex(check);
|
|
if (!regex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_string,
|
|
validation: "datetime",
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "date") {
|
|
const regex = dateRegex;
|
|
if (!regex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_string,
|
|
validation: "date",
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "time") {
|
|
const regex = timeRegex(check);
|
|
if (!regex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_string,
|
|
validation: "time",
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "duration") {
|
|
if (!durationRegex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "duration",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "ip") {
|
|
if (!isValidIP(input.data, check.version)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "ip",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "jwt") {
|
|
if (!isValidJWT(input.data, check.alg)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "jwt",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "cidr") {
|
|
if (!isValidCidr(input.data, check.version)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "cidr",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "base64") {
|
|
if (!base64Regex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "base64",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "base64url") {
|
|
if (!base64urlRegex.test(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
validation: "base64url",
|
|
code: ZodIssueCode.invalid_string,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else {
|
|
util.assertNever(check);
|
|
}
|
|
}
|
|
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(check) {
|
|
return new ZodString({
|
|
...this._def,
|
|
checks: [...this._def.checks, check]
|
|
});
|
|
}
|
|
email(message) {
|
|
return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
|
|
}
|
|
url(message) {
|
|
return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
|
|
}
|
|
emoji(message) {
|
|
return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
|
|
}
|
|
uuid(message) {
|
|
return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
|
|
}
|
|
nanoid(message) {
|
|
return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
|
|
}
|
|
cuid(message) {
|
|
return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
|
|
}
|
|
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)
|
|
});
|
|
}
|
|
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)
|
|
});
|
|
}
|
|
nonempty(message) {
|
|
return this.min(1, errorUtil.errToObj(message));
|
|
}
|
|
trim() {
|
|
return new ZodString({
|
|
...this._def,
|
|
checks: [...this._def.checks, { kind: "trim" }]
|
|
});
|
|
}
|
|
toLowerCase() {
|
|
return new ZodString({
|
|
...this._def,
|
|
checks: [...this._def.checks, { kind: "toLowerCase" }]
|
|
});
|
|
}
|
|
toUpperCase() {
|
|
return new ZodString({
|
|
...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 min = null;
|
|
for (const ch of this._def.checks) {
|
|
if (ch.kind === "min") {
|
|
if (min === null || ch.value > min)
|
|
min = ch.value;
|
|
}
|
|
}
|
|
return min;
|
|
}
|
|
get maxLength() {
|
|
let max = null;
|
|
for (const ch of this._def.checks) {
|
|
if (ch.kind === "max") {
|
|
if (max === null || ch.value < max)
|
|
max = ch.value;
|
|
}
|
|
}
|
|
return max;
|
|
}
|
|
}
|
|
ZodString.create = (params) => {
|
|
return new ZodString({
|
|
checks: [],
|
|
typeName: ZodFirstPartyTypeKind.ZodString,
|
|
coerce: params?.coerce ?? false,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
function floatSafeRemainder(val, step) {
|
|
const valDecCount = (val.toString().split(".")[1] || "").length;
|
|
const stepDecCount = (step.toString().split(".")[1] || "").length;
|
|
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
|
|
const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
|
|
const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
|
|
return valInt % stepInt / 10 ** decCount;
|
|
}
|
|
|
|
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 parsedType = this._getType(input);
|
|
if (parsedType !== ZodParsedType.number) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.number,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
let ctx = undefined;
|
|
const status = new ParseStatus;
|
|
for (const check of this._def.checks) {
|
|
if (check.kind === "int") {
|
|
if (!util.isInteger(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: "integer",
|
|
received: "float",
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "min") {
|
|
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
|
|
if (tooSmall) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_small,
|
|
minimum: check.value,
|
|
type: "number",
|
|
inclusive: check.inclusive,
|
|
exact: false,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "max") {
|
|
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
|
|
if (tooBig) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_big,
|
|
maximum: check.value,
|
|
type: "number",
|
|
inclusive: check.inclusive,
|
|
exact: false,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "multipleOf") {
|
|
if (floatSafeRemainder(input.data, check.value) !== 0) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.not_multiple_of,
|
|
multipleOf: check.value,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "finite") {
|
|
if (!Number.isFinite(input.data)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.not_finite,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else {
|
|
util.assertNever(check);
|
|
}
|
|
}
|
|
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(check) {
|
|
return new ZodNumber({
|
|
...this._def,
|
|
checks: [...this._def.checks, check]
|
|
});
|
|
}
|
|
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)
|
|
});
|
|
}
|
|
multipleOf(value, message) {
|
|
return this._addCheck({
|
|
kind: "multipleOf",
|
|
value,
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
finite(message) {
|
|
return this._addCheck({
|
|
kind: "finite",
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
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)
|
|
});
|
|
}
|
|
get minValue() {
|
|
let min = null;
|
|
for (const ch of this._def.checks) {
|
|
if (ch.kind === "min") {
|
|
if (min === null || ch.value > min)
|
|
min = ch.value;
|
|
}
|
|
}
|
|
return min;
|
|
}
|
|
get maxValue() {
|
|
let max = null;
|
|
for (const ch of this._def.checks) {
|
|
if (ch.kind === "max") {
|
|
if (max === null || ch.value < max)
|
|
max = ch.value;
|
|
}
|
|
}
|
|
return max;
|
|
}
|
|
get isInt() {
|
|
return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
|
|
}
|
|
get isFinite() {
|
|
let max = null;
|
|
let min = 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 (min === null || ch.value > min)
|
|
min = ch.value;
|
|
} else if (ch.kind === "max") {
|
|
if (max === null || ch.value < max)
|
|
max = ch.value;
|
|
}
|
|
}
|
|
return Number.isFinite(min) && Number.isFinite(max);
|
|
}
|
|
}
|
|
ZodNumber.create = (params) => {
|
|
return new ZodNumber({
|
|
checks: [],
|
|
typeName: ZodFirstPartyTypeKind.ZodNumber,
|
|
coerce: params?.coerce || false,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
|
|
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 parsedType = this._getType(input);
|
|
if (parsedType !== ZodParsedType.bigint) {
|
|
return this._getInvalidInput(input);
|
|
}
|
|
let ctx = undefined;
|
|
const status = new ParseStatus;
|
|
for (const check of this._def.checks) {
|
|
if (check.kind === "min") {
|
|
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
|
|
if (tooSmall) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_small,
|
|
type: "bigint",
|
|
minimum: check.value,
|
|
inclusive: check.inclusive,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "max") {
|
|
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
|
|
if (tooBig) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_big,
|
|
type: "bigint",
|
|
maximum: check.value,
|
|
inclusive: check.inclusive,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "multipleOf") {
|
|
if (input.data % check.value !== BigInt(0)) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.not_multiple_of,
|
|
multipleOf: check.value,
|
|
message: check.message
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else {
|
|
util.assertNever(check);
|
|
}
|
|
}
|
|
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(check) {
|
|
return new ZodBigInt({
|
|
...this._def,
|
|
checks: [...this._def.checks, check]
|
|
});
|
|
}
|
|
positive(message) {
|
|
return this._addCheck({
|
|
kind: "min",
|
|
value: BigInt(0),
|
|
inclusive: false,
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
negative(message) {
|
|
return this._addCheck({
|
|
kind: "max",
|
|
value: BigInt(0),
|
|
inclusive: false,
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
nonpositive(message) {
|
|
return this._addCheck({
|
|
kind: "max",
|
|
value: BigInt(0),
|
|
inclusive: true,
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
nonnegative(message) {
|
|
return this._addCheck({
|
|
kind: "min",
|
|
value: BigInt(0),
|
|
inclusive: true,
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
multipleOf(value, message) {
|
|
return this._addCheck({
|
|
kind: "multipleOf",
|
|
value,
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
get minValue() {
|
|
let min = null;
|
|
for (const ch of this._def.checks) {
|
|
if (ch.kind === "min") {
|
|
if (min === null || ch.value > min)
|
|
min = ch.value;
|
|
}
|
|
}
|
|
return min;
|
|
}
|
|
get maxValue() {
|
|
let max = null;
|
|
for (const ch of this._def.checks) {
|
|
if (ch.kind === "max") {
|
|
if (max === null || ch.value < max)
|
|
max = ch.value;
|
|
}
|
|
}
|
|
return max;
|
|
}
|
|
}
|
|
ZodBigInt.create = (params) => {
|
|
return new ZodBigInt({
|
|
checks: [],
|
|
typeName: ZodFirstPartyTypeKind.ZodBigInt,
|
|
coerce: params?.coerce ?? false,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
|
|
class ZodBoolean extends ZodType {
|
|
_parse(input) {
|
|
if (this._def.coerce) {
|
|
input.data = Boolean(input.data);
|
|
}
|
|
const parsedType = this._getType(input);
|
|
if (parsedType !== 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);
|
|
}
|
|
}
|
|
ZodBoolean.create = (params) => {
|
|
return new ZodBoolean({
|
|
typeName: ZodFirstPartyTypeKind.ZodBoolean,
|
|
coerce: params?.coerce || false,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
|
|
class ZodDate extends ZodType {
|
|
_parse(input) {
|
|
if (this._def.coerce) {
|
|
input.data = new Date(input.data);
|
|
}
|
|
const parsedType = this._getType(input);
|
|
if (parsedType !== ZodParsedType.date) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.date,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
if (Number.isNaN(input.data.getTime())) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_date
|
|
});
|
|
return INVALID;
|
|
}
|
|
const status = new ParseStatus;
|
|
let ctx = undefined;
|
|
for (const check of this._def.checks) {
|
|
if (check.kind === "min") {
|
|
if (input.data.getTime() < check.value) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_small,
|
|
message: check.message,
|
|
inclusive: true,
|
|
exact: false,
|
|
minimum: check.value,
|
|
type: "date"
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else if (check.kind === "max") {
|
|
if (input.data.getTime() > check.value) {
|
|
ctx = this._getOrReturnCtx(input, ctx);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.too_big,
|
|
message: check.message,
|
|
inclusive: true,
|
|
exact: false,
|
|
maximum: check.value,
|
|
type: "date"
|
|
});
|
|
status.dirty();
|
|
}
|
|
} else {
|
|
util.assertNever(check);
|
|
}
|
|
}
|
|
return {
|
|
status: status.value,
|
|
value: new Date(input.data.getTime())
|
|
};
|
|
}
|
|
_addCheck(check) {
|
|
return new ZodDate({
|
|
...this._def,
|
|
checks: [...this._def.checks, check]
|
|
});
|
|
}
|
|
min(minDate, message) {
|
|
return this._addCheck({
|
|
kind: "min",
|
|
value: minDate.getTime(),
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
max(maxDate, message) {
|
|
return this._addCheck({
|
|
kind: "max",
|
|
value: maxDate.getTime(),
|
|
message: errorUtil.toString(message)
|
|
});
|
|
}
|
|
get minDate() {
|
|
let min = null;
|
|
for (const ch of this._def.checks) {
|
|
if (ch.kind === "min") {
|
|
if (min === null || ch.value > min)
|
|
min = ch.value;
|
|
}
|
|
}
|
|
return min != null ? new Date(min) : null;
|
|
}
|
|
get maxDate() {
|
|
let max = null;
|
|
for (const ch of this._def.checks) {
|
|
if (ch.kind === "max") {
|
|
if (max === null || ch.value < max)
|
|
max = ch.value;
|
|
}
|
|
}
|
|
return max != null ? new Date(max) : null;
|
|
}
|
|
}
|
|
ZodDate.create = (params) => {
|
|
return new ZodDate({
|
|
checks: [],
|
|
coerce: params?.coerce || false,
|
|
typeName: ZodFirstPartyTypeKind.ZodDate,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
|
|
class ZodSymbol extends ZodType {
|
|
_parse(input) {
|
|
const parsedType = this._getType(input);
|
|
if (parsedType !== 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);
|
|
}
|
|
}
|
|
ZodSymbol.create = (params) => {
|
|
return new ZodSymbol({
|
|
typeName: ZodFirstPartyTypeKind.ZodSymbol,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
|
|
class ZodUndefined extends ZodType {
|
|
_parse(input) {
|
|
const parsedType = this._getType(input);
|
|
if (parsedType !== ZodParsedType.undefined) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.undefined,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
return OK(input.data);
|
|
}
|
|
}
|
|
ZodUndefined.create = (params) => {
|
|
return new ZodUndefined({
|
|
typeName: ZodFirstPartyTypeKind.ZodUndefined,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
|
|
class ZodNull extends ZodType {
|
|
_parse(input) {
|
|
const parsedType = this._getType(input);
|
|
if (parsedType !== 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);
|
|
}
|
|
}
|
|
ZodNull.create = (params) => {
|
|
return new ZodNull({
|
|
typeName: ZodFirstPartyTypeKind.ZodNull,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
|
|
class ZodAny extends ZodType {
|
|
constructor() {
|
|
super(...arguments);
|
|
this._any = true;
|
|
}
|
|
_parse(input) {
|
|
return OK(input.data);
|
|
}
|
|
}
|
|
ZodAny.create = (params) => {
|
|
return new ZodAny({
|
|
typeName: ZodFirstPartyTypeKind.ZodAny,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
|
|
class ZodUnknown extends ZodType {
|
|
constructor() {
|
|
super(...arguments);
|
|
this._unknown = true;
|
|
}
|
|
_parse(input) {
|
|
return OK(input.data);
|
|
}
|
|
}
|
|
ZodUnknown.create = (params) => {
|
|
return new ZodUnknown({
|
|
typeName: ZodFirstPartyTypeKind.ZodUnknown,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
|
|
class ZodNever extends ZodType {
|
|
_parse(input) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.never,
|
|
received: ctx.parsedType
|
|
});
|
|
return INVALID;
|
|
}
|
|
}
|
|
ZodNever.create = (params) => {
|
|
return new ZodNever({
|
|
typeName: ZodFirstPartyTypeKind.ZodNever,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
|
|
class ZodVoid extends ZodType {
|
|
_parse(input) {
|
|
const parsedType = this._getType(input);
|
|
if (parsedType !== 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)
|
|
});
|
|
};
|
|
|
|
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 : undefined,
|
|
maximum: tooBig ? def.exactLength.value : undefined,
|
|
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, i) => {
|
|
return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
|
|
})).then((result) => {
|
|
return ParseStatus.mergeArray(status, result);
|
|
});
|
|
}
|
|
const result = [...ctx.data].map((item, i) => {
|
|
return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
|
|
});
|
|
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 = (schema, params) => {
|
|
return new ZodArray({
|
|
type: schema,
|
|
minLength: null,
|
|
maxLength: null,
|
|
exactLength: null,
|
|
typeName: ZodFirstPartyTypeKind.ZodArray,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
function deepPartialify(schema) {
|
|
if (schema instanceof ZodObject) {
|
|
const newShape = {};
|
|
for (const key in schema.shape) {
|
|
const fieldSchema = schema.shape[key];
|
|
newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
|
|
}
|
|
return new ZodObject({
|
|
...schema._def,
|
|
shape: () => newShape
|
|
});
|
|
} else if (schema instanceof ZodArray) {
|
|
return new ZodArray({
|
|
...schema._def,
|
|
type: deepPartialify(schema.element)
|
|
});
|
|
} else if (schema instanceof ZodOptional) {
|
|
return ZodOptional.create(deepPartialify(schema.unwrap()));
|
|
} else if (schema instanceof ZodNullable) {
|
|
return ZodNullable.create(deepPartialify(schema.unwrap()));
|
|
} else if (schema instanceof ZodTuple) {
|
|
return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
|
|
} else {
|
|
return schema;
|
|
}
|
|
}
|
|
|
|
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 parsedType = this._getType(input);
|
|
if (parsedType !== ZodParsedType.object) {
|
|
const ctx = this._getOrReturnCtx(input);
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_type,
|
|
expected: ZodParsedType.object,
|
|
received: ctx.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 pairs = [];
|
|
for (const key of shapeKeys) {
|
|
const keyValidator = shape[key];
|
|
const value = ctx.data[key];
|
|
pairs.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) {
|
|
pairs.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];
|
|
pairs.push({
|
|
key: { status: "valid", value: key },
|
|
value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
|
|
alwaysSet: key in ctx.data
|
|
});
|
|
}
|
|
}
|
|
if (ctx.common.async) {
|
|
return Promise.resolve().then(async () => {
|
|
const syncPairs = [];
|
|
for (const pair of pairs) {
|
|
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, pairs);
|
|
}
|
|
}
|
|
get shape() {
|
|
return this._def.shape();
|
|
}
|
|
strict(message) {
|
|
errorUtil.errToObj;
|
|
return new ZodObject({
|
|
...this._def,
|
|
unknownKeys: "strict",
|
|
...message !== undefined ? {
|
|
errorMap: (issue, ctx) => {
|
|
const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
|
|
if (issue.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"
|
|
});
|
|
}
|
|
extend(augmentation) {
|
|
return new ZodObject({
|
|
...this._def,
|
|
shape: () => ({
|
|
...this._def.shape(),
|
|
...augmentation
|
|
})
|
|
});
|
|
}
|
|
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;
|
|
}
|
|
setKey(key, schema) {
|
|
return this.augment({ [key]: schema });
|
|
}
|
|
catchall(index) {
|
|
return new ZodObject({
|
|
...this._def,
|
|
catchall: index
|
|
});
|
|
}
|
|
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
|
|
});
|
|
}
|
|
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
|
|
});
|
|
}
|
|
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
|
|
});
|
|
}
|
|
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;
|
|
}
|
|
}
|
|
return new ZodObject({
|
|
...this._def,
|
|
shape: () => newShape
|
|
});
|
|
}
|
|
keyof() {
|
|
return createZodEnum(util.objectKeys(this.shape));
|
|
}
|
|
}
|
|
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)
|
|
});
|
|
};
|
|
|
|
class ZodUnion 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 = undefined;
|
|
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((issues) => new ZodError(issues));
|
|
addIssueToContext(ctx, {
|
|
code: ZodIssueCode.invalid_union,
|
|
unionErrors
|
|
});
|
|
return INVALID;
|
|
}
|
|
}
|
|
get options() {
|
|
return this._def.options;
|
|
}
|
|
}
|
|
ZodUnion.create = (types, params) => {
|
|
return new ZodUnion({
|
|
options: types,
|
|
typeName: ZodFirstPartyTypeKind.ZodUnion,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var getDiscriminator = (type) => {
|
|
if (type instanceof ZodLazy) {
|
|
return getDiscriminator(type.schema);
|
|
} else if (type instanceof ZodEffects) {
|
|
return getDiscriminator(type.innerType());
|
|
} else if (type instanceof ZodLiteral) {
|
|
return [type.value];
|
|
} else if (type instanceof ZodEnum) {
|
|
return type.options;
|
|
} else if (type instanceof ZodNativeEnum) {
|
|
return util.objectValues(type.enum);
|
|
} else if (type instanceof ZodDefault) {
|
|
return getDiscriminator(type._def.innerType);
|
|
} else if (type instanceof ZodUndefined) {
|
|
return [undefined];
|
|
} else if (type instanceof ZodNull) {
|
|
return [null];
|
|
} else if (type instanceof ZodOptional) {
|
|
return [undefined, ...getDiscriminator(type.unwrap())];
|
|
} else if (type instanceof ZodNullable) {
|
|
return [null, ...getDiscriminator(type.unwrap())];
|
|
} else if (type instanceof ZodBranded) {
|
|
return getDiscriminator(type.unwrap());
|
|
} else if (type instanceof ZodReadonly) {
|
|
return getDiscriminator(type.unwrap());
|
|
} else if (type instanceof ZodCatch) {
|
|
return getDiscriminator(type._def.innerType);
|
|
} else {
|
|
return [];
|
|
}
|
|
};
|
|
|
|
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
|
|
});
|
|
}
|
|
}
|
|
get discriminator() {
|
|
return this._def.discriminator;
|
|
}
|
|
get options() {
|
|
return this._def.options;
|
|
}
|
|
get optionsMap() {
|
|
return this._def.optionsMap;
|
|
}
|
|
static create(discriminator, options, params) {
|
|
const optionsMap = new Map;
|
|
for (const type of options) {
|
|
const discriminatorValues = getDiscriminator(type.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, type);
|
|
}
|
|
}
|
|
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 index = 0;index < a.length; index++) {
|
|
const itemA = a[index];
|
|
const itemB = b[index];
|
|
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 };
|
|
}
|
|
}
|
|
|
|
class ZodIntersection 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)
|
|
});
|
|
};
|
|
|
|
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 schema = this._def.items[itemIndex] || this._def.rest;
|
|
if (!schema)
|
|
return null;
|
|
return schema._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
|
|
});
|
|
}
|
|
}
|
|
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)
|
|
});
|
|
};
|
|
|
|
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 pairs = [];
|
|
const keyType = this._def.keyType;
|
|
const valueType = this._def.valueType;
|
|
for (const key in ctx.data) {
|
|
pairs.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, pairs);
|
|
} else {
|
|
return ParseStatus.mergeObjectSync(status, pairs);
|
|
}
|
|
}
|
|
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)
|
|
});
|
|
}
|
|
}
|
|
|
|
class ZodMap 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 pairs = [...ctx.data.entries()].map(([key, value], index) => {
|
|
return {
|
|
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
|
|
value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
|
|
};
|
|
});
|
|
if (ctx.common.async) {
|
|
const finalMap = new Map;
|
|
return Promise.resolve().then(async () => {
|
|
for (const pair of pairs) {
|
|
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 = new Map;
|
|
for (const pair of pairs) {
|
|
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 };
|
|
}
|
|
}
|
|
}
|
|
ZodMap.create = (keyType, valueType, params) => {
|
|
return new ZodMap({
|
|
valueType,
|
|
keyType,
|
|
typeName: ZodFirstPartyTypeKind.ZodMap,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
|
|
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(elements) {
|
|
const parsedSet = new Set;
|
|
for (const element of elements) {
|
|
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, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
|
|
if (ctx.common.async) {
|
|
return Promise.all(elements).then((elements) => finalizeSet(elements));
|
|
} else {
|
|
return finalizeSet(elements);
|
|
}
|
|
}
|
|
min(minSize, message) {
|
|
return new ZodSet({
|
|
...this._def,
|
|
minSize: { value: minSize, message: errorUtil.toString(message) }
|
|
});
|
|
}
|
|
max(maxSize, message) {
|
|
return new ZodSet({
|
|
...this._def,
|
|
maxSize: { value: maxSize, message: errorUtil.toString(message) }
|
|
});
|
|
}
|
|
size(size, message) {
|
|
return this.min(size, message).max(size, message);
|
|
}
|
|
nonempty(message) {
|
|
return this.min(1, message);
|
|
}
|
|
}
|
|
ZodSet.create = (valueType, params) => {
|
|
return new ZodSet({
|
|
valueType,
|
|
minSize: null,
|
|
maxSize: null,
|
|
typeName: ZodFirstPartyTypeKind.ZodSet,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
|
|
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, error) {
|
|
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: error
|
|
}
|
|
});
|
|
}
|
|
function makeReturnsIssue(returns, error) {
|
|
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: error
|
|
}
|
|
});
|
|
}
|
|
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 error = new ZodError([]);
|
|
const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
|
|
error.addIssue(makeArgsIssue(args, e));
|
|
throw error;
|
|
});
|
|
const result = await Reflect.apply(fn, this, parsedArgs);
|
|
const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
|
|
error.addIssue(makeReturnsIssue(result, e));
|
|
throw error;
|
|
});
|
|
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;
|
|
});
|
|
}
|
|
}
|
|
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)
|
|
});
|
|
}
|
|
}
|
|
|
|
class ZodLazy 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)
|
|
});
|
|
};
|
|
|
|
class ZodLiteral 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)
|
|
});
|
|
};
|
|
function createZodEnum(values, params) {
|
|
return new ZodEnum({
|
|
values,
|
|
typeName: ZodFirstPartyTypeKind.ZodEnum,
|
|
...processCreateParams(params)
|
|
});
|
|
}
|
|
|
|
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;
|
|
|
|
class ZodNativeEnum 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)
|
|
});
|
|
};
|
|
|
|
class ZodPromise 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;
|
|
}
|
|
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 = (schema, params) => {
|
|
return new ZodPromise({
|
|
type: schema,
|
|
typeName: ZodFirstPartyTypeKind.ZodPromise,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
|
|
class ZodEffects 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: (arg) => {
|
|
addIssueToContext(ctx, arg);
|
|
if (arg.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 (processed) => {
|
|
if (status.value === "aborted")
|
|
return INVALID;
|
|
const result = await this._def.schema._parseAsync({
|
|
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;
|
|
});
|
|
} 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
|
|
}));
|
|
});
|
|
}
|
|
}
|
|
util.assertNever(effect);
|
|
}
|
|
}
|
|
ZodEffects.create = (schema, effect, params) => {
|
|
return new ZodEffects({
|
|
schema,
|
|
typeName: ZodFirstPartyTypeKind.ZodEffects,
|
|
effect,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
|
|
return new ZodEffects({
|
|
schema,
|
|
effect: { type: "preprocess", transform: preprocess },
|
|
typeName: ZodFirstPartyTypeKind.ZodEffects,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
class ZodOptional extends ZodType {
|
|
_parse(input) {
|
|
const parsedType = this._getType(input);
|
|
if (parsedType === ZodParsedType.undefined) {
|
|
return OK(undefined);
|
|
}
|
|
return this._def.innerType._parse(input);
|
|
}
|
|
unwrap() {
|
|
return this._def.innerType;
|
|
}
|
|
}
|
|
ZodOptional.create = (type, params) => {
|
|
return new ZodOptional({
|
|
innerType: type,
|
|
typeName: ZodFirstPartyTypeKind.ZodOptional,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
|
|
class ZodNullable extends ZodType {
|
|
_parse(input) {
|
|
const parsedType = this._getType(input);
|
|
if (parsedType === ZodParsedType.null) {
|
|
return OK(null);
|
|
}
|
|
return this._def.innerType._parse(input);
|
|
}
|
|
unwrap() {
|
|
return this._def.innerType;
|
|
}
|
|
}
|
|
ZodNullable.create = (type, params) => {
|
|
return new ZodNullable({
|
|
innerType: type,
|
|
typeName: ZodFirstPartyTypeKind.ZodNullable,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
|
|
class ZodDefault 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
|
|
});
|
|
}
|
|
removeDefault() {
|
|
return this._def.innerType;
|
|
}
|
|
}
|
|
ZodDefault.create = (type, params) => {
|
|
return new ZodDefault({
|
|
innerType: type,
|
|
typeName: ZodFirstPartyTypeKind.ZodDefault,
|
|
defaultValue: typeof params.default === "function" ? params.default : () => params.default,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
|
|
class ZodCatch 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((result) => {
|
|
return {
|
|
status: "valid",
|
|
value: result.status === "valid" ? result.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
|
|
})
|
|
};
|
|
}
|
|
}
|
|
removeCatch() {
|
|
return this._def.innerType;
|
|
}
|
|
}
|
|
ZodCatch.create = (type, params) => {
|
|
return new ZodCatch({
|
|
innerType: type,
|
|
typeName: ZodFirstPartyTypeKind.ZodCatch,
|
|
catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
|
|
class ZodNaN extends ZodType {
|
|
_parse(input) {
|
|
const parsedType = this._getType(input);
|
|
if (parsedType !== 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 };
|
|
}
|
|
}
|
|
ZodNaN.create = (params) => {
|
|
return new ZodNaN({
|
|
typeName: ZodFirstPartyTypeKind.ZodNaN,
|
|
...processCreateParams(params)
|
|
});
|
|
};
|
|
var BRAND = Symbol("zod_brand");
|
|
|
|
class ZodBranded extends ZodType {
|
|
_parse(input) {
|
|
const { ctx } = this._processInputParams(input);
|
|
const data = ctx.data;
|
|
return this._def.type._parse({
|
|
data,
|
|
path: ctx.path,
|
|
parent: ctx
|
|
});
|
|
}
|
|
unwrap() {
|
|
return this._def.type;
|
|
}
|
|
}
|
|
|
|
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
|
|
});
|
|
}
|
|
}
|
|
}
|
|
static create(a, b) {
|
|
return new ZodPipeline({
|
|
in: a,
|
|
out: b,
|
|
typeName: ZodFirstPartyTypeKind.ZodPipeline
|
|
});
|
|
}
|
|
}
|
|
|
|
class ZodReadonly 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);
|
|
}
|
|
unwrap() {
|
|
return this._def.innerType;
|
|
}
|
|
}
|
|
ZodReadonly.create = (type, params) => {
|
|
return new ZodReadonly({
|
|
innerType: type,
|
|
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 custom(check, _params = {}, fatal) {
|
|
if (check)
|
|
return ZodAny.create().superRefine((data, ctx) => {
|
|
const r = check(data);
|
|
if (r instanceof Promise) {
|
|
return r.then((r) => {
|
|
if (!r) {
|
|
const params = cleanParams(_params, data);
|
|
const _fatal = params.fatal ?? fatal ?? true;
|
|
ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
|
|
}
|
|
});
|
|
}
|
|
if (!r) {
|
|
const params = cleanParams(_params, data);
|
|
const _fatal = params.fatal ?? fatal ?? true;
|
|
ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
|
|
}
|
|
return;
|
|
});
|
|
return ZodAny.create();
|
|
}
|
|
var late = {
|
|
object: ZodObject.lazycreate
|
|
};
|
|
var ZodFirstPartyTypeKind;
|
|
(function(ZodFirstPartyTypeKind) {
|
|
ZodFirstPartyTypeKind["ZodString"] = "ZodString";
|
|
ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
|
|
ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
|
|
ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
|
|
ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
|
|
ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
|
|
ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
|
|
ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
|
|
ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
|
|
ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
|
|
ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
|
|
ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
|
|
ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
|
|
ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
|
|
ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
|
|
ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
|
|
ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
|
|
ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
|
|
ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
|
|
ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
|
|
ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
|
|
ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
|
|
ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
|
|
ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
|
|
ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
|
|
ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
|
|
ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
|
|
ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
|
|
ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
|
|
ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
|
|
ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
|
|
ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
|
|
ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
|
|
ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
|
|
ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
|
|
ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
|
|
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
|
|
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;
|
|
// ../../../node_modules/.pnpm/dequal@2.0.3/node_modules/dequal/lite/index.mjs
|
|
var has = Object.prototype.hasOwnProperty;
|
|
function dequal(foo, bar) {
|
|
var ctor, len;
|
|
if (foo === bar)
|
|
return true;
|
|
if (foo && bar && (ctor = foo.constructor) === bar.constructor) {
|
|
if (ctor === Date)
|
|
return foo.getTime() === bar.getTime();
|
|
if (ctor === RegExp)
|
|
return foo.toString() === bar.toString();
|
|
if (ctor === Array) {
|
|
if ((len = foo.length) === bar.length) {
|
|
while (len-- && dequal(foo[len], bar[len]))
|
|
;
|
|
}
|
|
return len === -1;
|
|
}
|
|
if (!ctor || typeof foo === "object") {
|
|
len = 0;
|
|
for (ctor in foo) {
|
|
if (has.call(foo, ctor) && ++len && !has.call(bar, ctor))
|
|
return false;
|
|
if (!(ctor in bar) || !dequal(foo[ctor], bar[ctor]))
|
|
return false;
|
|
}
|
|
return Object.keys(bar).length === len;
|
|
}
|
|
}
|
|
return foo !== foo && bar !== bar;
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js
|
|
function deepCompareStrict(a, b) {
|
|
const typeofa = typeof a;
|
|
if (typeofa !== typeof b) {
|
|
return false;
|
|
}
|
|
if (Array.isArray(a)) {
|
|
if (!Array.isArray(b)) {
|
|
return false;
|
|
}
|
|
const length = a.length;
|
|
if (length !== b.length) {
|
|
return false;
|
|
}
|
|
for (let i = 0;i < length; i++) {
|
|
if (!deepCompareStrict(a[i], b[i])) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
if (typeofa === "object") {
|
|
if (!a || !b) {
|
|
return a === b;
|
|
}
|
|
const aKeys = Object.keys(a);
|
|
const bKeys = Object.keys(b);
|
|
const length = aKeys.length;
|
|
if (length !== bKeys.length) {
|
|
return false;
|
|
}
|
|
for (const k of aKeys) {
|
|
if (!deepCompareStrict(a[k], b[k])) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
return a === b;
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/pointer.js
|
|
function encodePointer(p) {
|
|
return encodeURI(escapePointer(p));
|
|
}
|
|
function escapePointer(p) {
|
|
return p.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/dereference.js
|
|
var schemaArrayKeyword = {
|
|
prefixItems: true,
|
|
items: true,
|
|
allOf: true,
|
|
anyOf: true,
|
|
oneOf: true
|
|
};
|
|
var schemaMapKeyword = {
|
|
$defs: true,
|
|
definitions: true,
|
|
properties: true,
|
|
patternProperties: true,
|
|
dependentSchemas: true
|
|
};
|
|
var ignoredKeyword = {
|
|
id: true,
|
|
$id: true,
|
|
$ref: true,
|
|
$schema: true,
|
|
$anchor: true,
|
|
$vocabulary: true,
|
|
$comment: true,
|
|
default: true,
|
|
enum: true,
|
|
const: true,
|
|
required: true,
|
|
type: 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
|
|
};
|
|
var initialBaseURI = typeof self !== "undefined" && self.location && self.location.origin !== "null" ? new URL(self.location.origin + self.location.pathname + location.search) : new URL("https://github.com/cfworker");
|
|
function dereference(schema, lookup = Object.create(null), baseURI = initialBaseURI, basePointer = "") {
|
|
if (schema && typeof schema === "object" && !Array.isArray(schema)) {
|
|
const id = schema.$id || schema.id;
|
|
if (id) {
|
|
const url = new URL(id, baseURI.href);
|
|
if (url.hash.length > 1) {
|
|
lookup[url.href] = schema;
|
|
} else {
|
|
url.hash = "";
|
|
if (basePointer === "") {
|
|
baseURI = url;
|
|
} else {
|
|
dereference(schema, lookup, baseURI);
|
|
}
|
|
}
|
|
}
|
|
} else if (schema !== true && schema !== false) {
|
|
return lookup;
|
|
}
|
|
const schemaURI = baseURI.href + (basePointer ? "#" + basePointer : "");
|
|
if (lookup[schemaURI] !== undefined) {
|
|
throw new Error(`Duplicate schema URI "${schemaURI}".`);
|
|
}
|
|
lookup[schemaURI] = schema;
|
|
if (schema === true || schema === false) {
|
|
return lookup;
|
|
}
|
|
if (schema.__absolute_uri__ === undefined) {
|
|
Object.defineProperty(schema, "__absolute_uri__", {
|
|
enumerable: false,
|
|
value: schemaURI
|
|
});
|
|
}
|
|
if (schema.$ref && schema.__absolute_ref__ === undefined) {
|
|
const url = new URL(schema.$ref, baseURI.href);
|
|
url.hash = url.hash;
|
|
Object.defineProperty(schema, "__absolute_ref__", {
|
|
enumerable: false,
|
|
value: url.href
|
|
});
|
|
}
|
|
if (schema.$recursiveRef && schema.__absolute_recursive_ref__ === undefined) {
|
|
const url = new URL(schema.$recursiveRef, baseURI.href);
|
|
url.hash = url.hash;
|
|
Object.defineProperty(schema, "__absolute_recursive_ref__", {
|
|
enumerable: false,
|
|
value: url.href
|
|
});
|
|
}
|
|
if (schema.$anchor) {
|
|
const url = new URL("#" + schema.$anchor, baseURI.href);
|
|
lookup[url.href] = schema;
|
|
}
|
|
for (let key in schema) {
|
|
if (ignoredKeyword[key]) {
|
|
continue;
|
|
}
|
|
const keyBase = `${basePointer}/${encodePointer(key)}`;
|
|
const subSchema = schema[key];
|
|
if (Array.isArray(subSchema)) {
|
|
if (schemaArrayKeyword[key]) {
|
|
const length = subSchema.length;
|
|
for (let i = 0;i < length; i++) {
|
|
dereference(subSchema[i], lookup, baseURI, `${keyBase}/${i}`);
|
|
}
|
|
}
|
|
} else if (schemaMapKeyword[key]) {
|
|
for (let subKey in subSchema) {
|
|
dereference(subSchema[subKey], lookup, baseURI, `${keyBase}/${encodePointer(subKey)}`);
|
|
}
|
|
} else {
|
|
dereference(subSchema, lookup, baseURI, keyBase);
|
|
}
|
|
}
|
|
return lookup;
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/format.js
|
|
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];
|
|
var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;
|
|
var 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;
|
|
var URIREF = /^(?:[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;
|
|
var URITEMPLATE = /^(?:(?:[^\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;
|
|
var URL_ = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!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-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;
|
|
var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
|
|
var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
|
|
var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
|
|
var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
|
|
var EMAIL = (input) => {
|
|
if (input[0] === '"')
|
|
return false;
|
|
const [name, host, ...rest] = input.split("@");
|
|
if (!name || !host || rest.length !== 0 || name.length > 64 || host.length > 253)
|
|
return false;
|
|
if (name[0] === "." || name.endsWith(".") || name.includes(".."))
|
|
return false;
|
|
if (!/^[a-z0-9.-]+$/i.test(host) || !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name))
|
|
return false;
|
|
return host.split(".").every((part) => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part));
|
|
};
|
|
var IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/;
|
|
var 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;
|
|
var DURATION = (input) => input.length > 1 && input.length < 80 && (/^P\d+([.,]\d+)?W$/.test(input) || /^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(input) && /^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(input));
|
|
function bind(r) {
|
|
return r.test.bind(r);
|
|
}
|
|
var format = {
|
|
date,
|
|
time: time.bind(undefined, false),
|
|
"date-time": date_time,
|
|
duration: DURATION,
|
|
uri,
|
|
"uri-reference": bind(URIREF),
|
|
"uri-template": bind(URITEMPLATE),
|
|
url: bind(URL_),
|
|
email: EMAIL,
|
|
hostname: bind(HOSTNAME),
|
|
ipv4: bind(IPV4),
|
|
ipv6: bind(IPV6),
|
|
regex,
|
|
uuid: bind(UUID),
|
|
"json-pointer": bind(JSON_POINTER),
|
|
"json-pointer-uri-fragment": bind(JSON_POINTER_URI_FRAGMENT),
|
|
"relative-json-pointer": bind(RELATIVE_JSON_POINTER)
|
|
};
|
|
function isLeapYear(year) {
|
|
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
}
|
|
function date(str) {
|
|
const matches = str.match(DATE);
|
|
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 time(full, str) {
|
|
const matches = str.match(TIME);
|
|
if (!matches)
|
|
return false;
|
|
const hour = +matches[1];
|
|
const minute = +matches[2];
|
|
const second = +matches[3];
|
|
const timeZone = !!matches[5];
|
|
return (hour <= 23 && minute <= 59 && second <= 59 || hour == 23 && minute == 59 && second == 60) && (!full || timeZone);
|
|
}
|
|
var DATE_TIME_SEPARATOR = /t|\s/i;
|
|
function date_time(str) {
|
|
const dateTime = str.split(DATE_TIME_SEPARATOR);
|
|
return dateTime.length == 2 && date(dateTime[0]) && time(true, dateTime[1]);
|
|
}
|
|
var NOT_URI_FRAGMENT = /\/|:/;
|
|
var URI_PATTERN = /^(?:[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(str) {
|
|
return NOT_URI_FRAGMENT.test(str) && URI_PATTERN.test(str);
|
|
}
|
|
var Z_ANCHOR = /[^\\]\\Z/;
|
|
function regex(str) {
|
|
if (Z_ANCHOR.test(str))
|
|
return false;
|
|
try {
|
|
new RegExp(str, "u");
|
|
return true;
|
|
} catch (e) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js
|
|
function ucs2length(s) {
|
|
let result = 0;
|
|
let length = s.length;
|
|
let index = 0;
|
|
let charCode;
|
|
while (index < length) {
|
|
result++;
|
|
charCode = s.charCodeAt(index++);
|
|
if (charCode >= 55296 && charCode <= 56319 && index < length) {
|
|
charCode = s.charCodeAt(index);
|
|
if ((charCode & 64512) == 56320) {
|
|
index++;
|
|
}
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/validate.js
|
|
function validate(instance, schema, draft = "2019-09", lookup = dereference(schema), shortCircuit = true, recursiveAnchor = null, instanceLocation = "#", schemaLocation = "#", evaluated = Object.create(null)) {
|
|
if (schema === true) {
|
|
return { valid: true, errors: [] };
|
|
}
|
|
if (schema === false) {
|
|
return {
|
|
valid: false,
|
|
errors: [
|
|
{
|
|
instanceLocation,
|
|
keyword: "false",
|
|
keywordLocation: instanceLocation,
|
|
error: "False boolean schema."
|
|
}
|
|
]
|
|
};
|
|
}
|
|
const rawInstanceType = typeof instance;
|
|
let instanceType;
|
|
switch (rawInstanceType) {
|
|
case "boolean":
|
|
case "number":
|
|
case "string":
|
|
instanceType = rawInstanceType;
|
|
break;
|
|
case "object":
|
|
if (instance === null) {
|
|
instanceType = "null";
|
|
} else if (Array.isArray(instance)) {
|
|
instanceType = "array";
|
|
} else {
|
|
instanceType = "object";
|
|
}
|
|
break;
|
|
default:
|
|
throw new Error(`Instances of "${rawInstanceType}" type are not supported.`);
|
|
}
|
|
const { $ref, $recursiveRef, $recursiveAnchor, type: $type, const: $const, enum: $enum, required: $required, not: $not, anyOf: $anyOf, allOf: $allOf, oneOf: $oneOf, if: $if, then: $then, else: $else, format: $format, properties: $properties, patternProperties: $patternProperties, additionalProperties: $additionalProperties, unevaluatedProperties: $unevaluatedProperties, minProperties: $minProperties, maxProperties: $maxProperties, propertyNames: $propertyNames, dependentRequired: $dependentRequired, dependentSchemas: $dependentSchemas, dependencies: $dependencies, prefixItems: $prefixItems, items: $items, additionalItems: $additionalItems, unevaluatedItems: $unevaluatedItems, contains: $contains, minContains: $minContains, maxContains: $maxContains, minItems: $minItems, maxItems: $maxItems, uniqueItems: $uniqueItems, minimum: $minimum, maximum: $maximum, exclusiveMinimum: $exclusiveMinimum, exclusiveMaximum: $exclusiveMaximum, multipleOf: $multipleOf, minLength: $minLength, maxLength: $maxLength, pattern: $pattern, __absolute_ref__, __absolute_recursive_ref__ } = schema;
|
|
const errors = [];
|
|
if ($recursiveAnchor === true && recursiveAnchor === null) {
|
|
recursiveAnchor = schema;
|
|
}
|
|
if ($recursiveRef === "#") {
|
|
const refSchema = recursiveAnchor === null ? lookup[__absolute_recursive_ref__] : recursiveAnchor;
|
|
const keywordLocation = `${schemaLocation}/$recursiveRef`;
|
|
const result = validate(instance, recursiveAnchor === null ? schema : recursiveAnchor, draft, lookup, shortCircuit, refSchema, instanceLocation, keywordLocation, evaluated);
|
|
if (!result.valid) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "$recursiveRef",
|
|
keywordLocation,
|
|
error: "A subschema had errors."
|
|
}, ...result.errors);
|
|
}
|
|
}
|
|
if ($ref !== undefined) {
|
|
const uri = __absolute_ref__ || $ref;
|
|
const refSchema = lookup[uri];
|
|
if (refSchema === undefined) {
|
|
let message = `Unresolved $ref "${$ref}".`;
|
|
if (__absolute_ref__ && __absolute_ref__ !== $ref) {
|
|
message += ` Absolute URI "${__absolute_ref__}".`;
|
|
}
|
|
message += `
|
|
Known schemas:
|
|
- ${Object.keys(lookup).join(`
|
|
- `)}`;
|
|
throw new Error(message);
|
|
}
|
|
const keywordLocation = `${schemaLocation}/$ref`;
|
|
const result = validate(instance, refSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated);
|
|
if (!result.valid) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "$ref",
|
|
keywordLocation,
|
|
error: "A subschema had errors."
|
|
}, ...result.errors);
|
|
}
|
|
if (draft === "4" || draft === "7") {
|
|
return { valid: errors.length === 0, errors };
|
|
}
|
|
}
|
|
if (Array.isArray($type)) {
|
|
let length = $type.length;
|
|
let valid = false;
|
|
for (let i = 0;i < length; i++) {
|
|
if (instanceType === $type[i] || $type[i] === "integer" && instanceType === "number" && instance % 1 === 0 && instance === instance) {
|
|
valid = true;
|
|
break;
|
|
}
|
|
}
|
|
if (!valid) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "type",
|
|
keywordLocation: `${schemaLocation}/type`,
|
|
error: `Instance type "${instanceType}" is invalid. Expected "${$type.join('", "')}".`
|
|
});
|
|
}
|
|
} else if ($type === "integer") {
|
|
if (instanceType !== "number" || instance % 1 || instance !== instance) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "type",
|
|
keywordLocation: `${schemaLocation}/type`,
|
|
error: `Instance type "${instanceType}" is invalid. Expected "${$type}".`
|
|
});
|
|
}
|
|
} else if ($type !== undefined && instanceType !== $type) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "type",
|
|
keywordLocation: `${schemaLocation}/type`,
|
|
error: `Instance type "${instanceType}" is invalid. Expected "${$type}".`
|
|
});
|
|
}
|
|
if ($const !== undefined) {
|
|
if (instanceType === "object" || instanceType === "array") {
|
|
if (!deepCompareStrict(instance, $const)) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "const",
|
|
keywordLocation: `${schemaLocation}/const`,
|
|
error: `Instance does not match ${JSON.stringify($const)}.`
|
|
});
|
|
}
|
|
} else if (instance !== $const) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "const",
|
|
keywordLocation: `${schemaLocation}/const`,
|
|
error: `Instance does not match ${JSON.stringify($const)}.`
|
|
});
|
|
}
|
|
}
|
|
if ($enum !== undefined) {
|
|
if (instanceType === "object" || instanceType === "array") {
|
|
if (!$enum.some((value) => deepCompareStrict(instance, value))) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "enum",
|
|
keywordLocation: `${schemaLocation}/enum`,
|
|
error: `Instance does not match any of ${JSON.stringify($enum)}.`
|
|
});
|
|
}
|
|
} else if (!$enum.some((value) => instance === value)) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "enum",
|
|
keywordLocation: `${schemaLocation}/enum`,
|
|
error: `Instance does not match any of ${JSON.stringify($enum)}.`
|
|
});
|
|
}
|
|
}
|
|
if ($not !== undefined) {
|
|
const keywordLocation = `${schemaLocation}/not`;
|
|
const result = validate(instance, $not, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation);
|
|
if (result.valid) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "not",
|
|
keywordLocation,
|
|
error: 'Instance matched "not" schema.'
|
|
});
|
|
}
|
|
}
|
|
let subEvaluateds = [];
|
|
if ($anyOf !== undefined) {
|
|
const keywordLocation = `${schemaLocation}/anyOf`;
|
|
const errorsLength = errors.length;
|
|
let anyValid = false;
|
|
for (let i = 0;i < $anyOf.length; i++) {
|
|
const subSchema = $anyOf[i];
|
|
const subEvaluated = Object.create(evaluated);
|
|
const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated);
|
|
errors.push(...result.errors);
|
|
anyValid = anyValid || result.valid;
|
|
if (result.valid) {
|
|
subEvaluateds.push(subEvaluated);
|
|
}
|
|
}
|
|
if (anyValid) {
|
|
errors.length = errorsLength;
|
|
} else {
|
|
errors.splice(errorsLength, 0, {
|
|
instanceLocation,
|
|
keyword: "anyOf",
|
|
keywordLocation,
|
|
error: "Instance does not match any subschemas."
|
|
});
|
|
}
|
|
}
|
|
if ($allOf !== undefined) {
|
|
const keywordLocation = `${schemaLocation}/allOf`;
|
|
const errorsLength = errors.length;
|
|
let allValid = true;
|
|
for (let i = 0;i < $allOf.length; i++) {
|
|
const subSchema = $allOf[i];
|
|
const subEvaluated = Object.create(evaluated);
|
|
const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated);
|
|
errors.push(...result.errors);
|
|
allValid = allValid && result.valid;
|
|
if (result.valid) {
|
|
subEvaluateds.push(subEvaluated);
|
|
}
|
|
}
|
|
if (allValid) {
|
|
errors.length = errorsLength;
|
|
} else {
|
|
errors.splice(errorsLength, 0, {
|
|
instanceLocation,
|
|
keyword: "allOf",
|
|
keywordLocation,
|
|
error: `Instance does not match every subschema.`
|
|
});
|
|
}
|
|
}
|
|
if ($oneOf !== undefined) {
|
|
const keywordLocation = `${schemaLocation}/oneOf`;
|
|
const errorsLength = errors.length;
|
|
const matches = $oneOf.filter((subSchema, i) => {
|
|
const subEvaluated = Object.create(evaluated);
|
|
const result = validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated);
|
|
errors.push(...result.errors);
|
|
if (result.valid) {
|
|
subEvaluateds.push(subEvaluated);
|
|
}
|
|
return result.valid;
|
|
}).length;
|
|
if (matches === 1) {
|
|
errors.length = errorsLength;
|
|
} else {
|
|
errors.splice(errorsLength, 0, {
|
|
instanceLocation,
|
|
keyword: "oneOf",
|
|
keywordLocation,
|
|
error: `Instance does not match exactly one subschema (${matches} matches).`
|
|
});
|
|
}
|
|
}
|
|
if (instanceType === "object" || instanceType === "array") {
|
|
Object.assign(evaluated, ...subEvaluateds);
|
|
}
|
|
if ($if !== undefined) {
|
|
const keywordLocation = `${schemaLocation}/if`;
|
|
const conditionResult = validate(instance, $if, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated).valid;
|
|
if (conditionResult) {
|
|
if ($then !== undefined) {
|
|
const thenResult = validate(instance, $then, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/then`, evaluated);
|
|
if (!thenResult.valid) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "if",
|
|
keywordLocation,
|
|
error: `Instance does not match "then" schema.`
|
|
}, ...thenResult.errors);
|
|
}
|
|
}
|
|
} else if ($else !== undefined) {
|
|
const elseResult = validate(instance, $else, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/else`, evaluated);
|
|
if (!elseResult.valid) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "if",
|
|
keywordLocation,
|
|
error: `Instance does not match "else" schema.`
|
|
}, ...elseResult.errors);
|
|
}
|
|
}
|
|
}
|
|
if (instanceType === "object") {
|
|
if ($required !== undefined) {
|
|
for (const key of $required) {
|
|
if (!(key in instance)) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "required",
|
|
keywordLocation: `${schemaLocation}/required`,
|
|
error: `Instance does not have required property "${key}".`
|
|
});
|
|
}
|
|
}
|
|
}
|
|
const keys = Object.keys(instance);
|
|
if ($minProperties !== undefined && keys.length < $minProperties) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "minProperties",
|
|
keywordLocation: `${schemaLocation}/minProperties`,
|
|
error: `Instance does not have at least ${$minProperties} properties.`
|
|
});
|
|
}
|
|
if ($maxProperties !== undefined && keys.length > $maxProperties) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "maxProperties",
|
|
keywordLocation: `${schemaLocation}/maxProperties`,
|
|
error: `Instance does not have at least ${$maxProperties} properties.`
|
|
});
|
|
}
|
|
if ($propertyNames !== undefined) {
|
|
const keywordLocation = `${schemaLocation}/propertyNames`;
|
|
for (const key in instance) {
|
|
const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;
|
|
const result = validate(key, $propertyNames, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation);
|
|
if (!result.valid) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "propertyNames",
|
|
keywordLocation,
|
|
error: `Property name "${key}" does not match schema.`
|
|
}, ...result.errors);
|
|
}
|
|
}
|
|
}
|
|
if ($dependentRequired !== undefined) {
|
|
const keywordLocation = `${schemaLocation}/dependantRequired`;
|
|
for (const key in $dependentRequired) {
|
|
if (key in instance) {
|
|
const required = $dependentRequired[key];
|
|
for (const dependantKey of required) {
|
|
if (!(dependantKey in instance)) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "dependentRequired",
|
|
keywordLocation,
|
|
error: `Instance has "${key}" but does not have "${dependantKey}".`
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if ($dependentSchemas !== undefined) {
|
|
for (const key in $dependentSchemas) {
|
|
const keywordLocation = `${schemaLocation}/dependentSchemas`;
|
|
if (key in instance) {
|
|
const result = validate(instance, $dependentSchemas[key], draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`, evaluated);
|
|
if (!result.valid) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "dependentSchemas",
|
|
keywordLocation,
|
|
error: `Instance has "${key}" but does not match dependant schema.`
|
|
}, ...result.errors);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if ($dependencies !== undefined) {
|
|
const keywordLocation = `${schemaLocation}/dependencies`;
|
|
for (const key in $dependencies) {
|
|
if (key in instance) {
|
|
const propsOrSchema = $dependencies[key];
|
|
if (Array.isArray(propsOrSchema)) {
|
|
for (const dependantKey of propsOrSchema) {
|
|
if (!(dependantKey in instance)) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "dependencies",
|
|
keywordLocation,
|
|
error: `Instance has "${key}" but does not have "${dependantKey}".`
|
|
});
|
|
}
|
|
}
|
|
} else {
|
|
const result = validate(instance, propsOrSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`);
|
|
if (!result.valid) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "dependencies",
|
|
keywordLocation,
|
|
error: `Instance has "${key}" but does not match dependant schema.`
|
|
}, ...result.errors);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
const thisEvaluated = Object.create(null);
|
|
let stop = false;
|
|
if ($properties !== undefined) {
|
|
const keywordLocation = `${schemaLocation}/properties`;
|
|
for (const key in $properties) {
|
|
if (!(key in instance)) {
|
|
continue;
|
|
}
|
|
const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;
|
|
const result = validate(instance[key], $properties[key], draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(key)}`);
|
|
if (result.valid) {
|
|
evaluated[key] = thisEvaluated[key] = true;
|
|
} else {
|
|
stop = shortCircuit;
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "properties",
|
|
keywordLocation,
|
|
error: `Property "${key}" does not match schema.`
|
|
}, ...result.errors);
|
|
if (stop)
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (!stop && $patternProperties !== undefined) {
|
|
const keywordLocation = `${schemaLocation}/patternProperties`;
|
|
for (const pattern in $patternProperties) {
|
|
const regex = new RegExp(pattern, "u");
|
|
const subSchema = $patternProperties[pattern];
|
|
for (const key in instance) {
|
|
if (!regex.test(key)) {
|
|
continue;
|
|
}
|
|
const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;
|
|
const result = validate(instance[key], subSchema, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(pattern)}`);
|
|
if (result.valid) {
|
|
evaluated[key] = thisEvaluated[key] = true;
|
|
} else {
|
|
stop = shortCircuit;
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "patternProperties",
|
|
keywordLocation,
|
|
error: `Property "${key}" matches pattern "${pattern}" but does not match associated schema.`
|
|
}, ...result.errors);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (!stop && $additionalProperties !== undefined) {
|
|
const keywordLocation = `${schemaLocation}/additionalProperties`;
|
|
for (const key in instance) {
|
|
if (thisEvaluated[key]) {
|
|
continue;
|
|
}
|
|
const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;
|
|
const result = validate(instance[key], $additionalProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation);
|
|
if (result.valid) {
|
|
evaluated[key] = true;
|
|
} else {
|
|
stop = shortCircuit;
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "additionalProperties",
|
|
keywordLocation,
|
|
error: `Property "${key}" does not match additional properties schema.`
|
|
}, ...result.errors);
|
|
}
|
|
}
|
|
} else if (!stop && $unevaluatedProperties !== undefined) {
|
|
const keywordLocation = `${schemaLocation}/unevaluatedProperties`;
|
|
for (const key in instance) {
|
|
if (!evaluated[key]) {
|
|
const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;
|
|
const result = validate(instance[key], $unevaluatedProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation);
|
|
if (result.valid) {
|
|
evaluated[key] = true;
|
|
} else {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "unevaluatedProperties",
|
|
keywordLocation,
|
|
error: `Property "${key}" does not match unevaluated properties schema.`
|
|
}, ...result.errors);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} else if (instanceType === "array") {
|
|
if ($maxItems !== undefined && instance.length > $maxItems) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "maxItems",
|
|
keywordLocation: `${schemaLocation}/maxItems`,
|
|
error: `Array has too many items (${instance.length} > ${$maxItems}).`
|
|
});
|
|
}
|
|
if ($minItems !== undefined && instance.length < $minItems) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "minItems",
|
|
keywordLocation: `${schemaLocation}/minItems`,
|
|
error: `Array has too few items (${instance.length} < ${$minItems}).`
|
|
});
|
|
}
|
|
const length = instance.length;
|
|
let i = 0;
|
|
let stop = false;
|
|
if ($prefixItems !== undefined) {
|
|
const keywordLocation = `${schemaLocation}/prefixItems`;
|
|
const length2 = Math.min($prefixItems.length, length);
|
|
for (;i < length2; i++) {
|
|
const result = validate(instance[i], $prefixItems[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`);
|
|
evaluated[i] = true;
|
|
if (!result.valid) {
|
|
stop = shortCircuit;
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "prefixItems",
|
|
keywordLocation,
|
|
error: `Items did not match schema.`
|
|
}, ...result.errors);
|
|
if (stop)
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if ($items !== undefined) {
|
|
const keywordLocation = `${schemaLocation}/items`;
|
|
if (Array.isArray($items)) {
|
|
const length2 = Math.min($items.length, length);
|
|
for (;i < length2; i++) {
|
|
const result = validate(instance[i], $items[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`);
|
|
evaluated[i] = true;
|
|
if (!result.valid) {
|
|
stop = shortCircuit;
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "items",
|
|
keywordLocation,
|
|
error: `Items did not match schema.`
|
|
}, ...result.errors);
|
|
if (stop)
|
|
break;
|
|
}
|
|
}
|
|
} else {
|
|
for (;i < length; i++) {
|
|
const result = validate(instance[i], $items, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation);
|
|
evaluated[i] = true;
|
|
if (!result.valid) {
|
|
stop = shortCircuit;
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "items",
|
|
keywordLocation,
|
|
error: `Items did not match schema.`
|
|
}, ...result.errors);
|
|
if (stop)
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (!stop && $additionalItems !== undefined) {
|
|
const keywordLocation = `${schemaLocation}/additionalItems`;
|
|
for (;i < length; i++) {
|
|
const result = validate(instance[i], $additionalItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation);
|
|
evaluated[i] = true;
|
|
if (!result.valid) {
|
|
stop = shortCircuit;
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "additionalItems",
|
|
keywordLocation,
|
|
error: `Items did not match additional items schema.`
|
|
}, ...result.errors);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if ($contains !== undefined) {
|
|
if (length === 0 && $minContains === undefined) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "contains",
|
|
keywordLocation: `${schemaLocation}/contains`,
|
|
error: `Array is empty. It must contain at least one item matching the schema.`
|
|
});
|
|
} else if ($minContains !== undefined && length < $minContains) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "minContains",
|
|
keywordLocation: `${schemaLocation}/minContains`,
|
|
error: `Array has less items (${length}) than minContains (${$minContains}).`
|
|
});
|
|
} else {
|
|
const keywordLocation = `${schemaLocation}/contains`;
|
|
const errorsLength = errors.length;
|
|
let contained = 0;
|
|
for (let j = 0;j < length; j++) {
|
|
const result = validate(instance[j], $contains, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${j}`, keywordLocation);
|
|
if (result.valid) {
|
|
evaluated[j] = true;
|
|
contained++;
|
|
} else {
|
|
errors.push(...result.errors);
|
|
}
|
|
}
|
|
if (contained >= ($minContains || 0)) {
|
|
errors.length = errorsLength;
|
|
}
|
|
if ($minContains === undefined && $maxContains === undefined && contained === 0) {
|
|
errors.splice(errorsLength, 0, {
|
|
instanceLocation,
|
|
keyword: "contains",
|
|
keywordLocation,
|
|
error: `Array does not contain item matching schema.`
|
|
});
|
|
} else if ($minContains !== undefined && contained < $minContains) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "minContains",
|
|
keywordLocation: `${schemaLocation}/minContains`,
|
|
error: `Array must contain at least ${$minContains} items matching schema. Only ${contained} items were found.`
|
|
});
|
|
} else if ($maxContains !== undefined && contained > $maxContains) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "maxContains",
|
|
keywordLocation: `${schemaLocation}/maxContains`,
|
|
error: `Array may contain at most ${$maxContains} items matching schema. ${contained} items were found.`
|
|
});
|
|
}
|
|
}
|
|
}
|
|
if (!stop && $unevaluatedItems !== undefined) {
|
|
const keywordLocation = `${schemaLocation}/unevaluatedItems`;
|
|
for (i;i < length; i++) {
|
|
if (evaluated[i]) {
|
|
continue;
|
|
}
|
|
const result = validate(instance[i], $unevaluatedItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation);
|
|
evaluated[i] = true;
|
|
if (!result.valid) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "unevaluatedItems",
|
|
keywordLocation,
|
|
error: `Items did not match unevaluated items schema.`
|
|
}, ...result.errors);
|
|
}
|
|
}
|
|
}
|
|
if ($uniqueItems) {
|
|
for (let j = 0;j < length; j++) {
|
|
const a = instance[j];
|
|
const ao = typeof a === "object" && a !== null;
|
|
for (let k = 0;k < length; k++) {
|
|
if (j === k) {
|
|
continue;
|
|
}
|
|
const b = instance[k];
|
|
const bo = typeof b === "object" && b !== null;
|
|
if (a === b || ao && bo && deepCompareStrict(a, b)) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "uniqueItems",
|
|
keywordLocation: `${schemaLocation}/uniqueItems`,
|
|
error: `Duplicate items at indexes ${j} and ${k}.`
|
|
});
|
|
j = Number.MAX_SAFE_INTEGER;
|
|
k = Number.MAX_SAFE_INTEGER;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} else if (instanceType === "number") {
|
|
if (draft === "4") {
|
|
if ($minimum !== undefined && ($exclusiveMinimum === true && instance <= $minimum || instance < $minimum)) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "minimum",
|
|
keywordLocation: `${schemaLocation}/minimum`,
|
|
error: `${instance} is less than ${$exclusiveMinimum ? "or equal to " : ""} ${$minimum}.`
|
|
});
|
|
}
|
|
if ($maximum !== undefined && ($exclusiveMaximum === true && instance >= $maximum || instance > $maximum)) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "maximum",
|
|
keywordLocation: `${schemaLocation}/maximum`,
|
|
error: `${instance} is greater than ${$exclusiveMaximum ? "or equal to " : ""} ${$maximum}.`
|
|
});
|
|
}
|
|
} else {
|
|
if ($minimum !== undefined && instance < $minimum) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "minimum",
|
|
keywordLocation: `${schemaLocation}/minimum`,
|
|
error: `${instance} is less than ${$minimum}.`
|
|
});
|
|
}
|
|
if ($maximum !== undefined && instance > $maximum) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "maximum",
|
|
keywordLocation: `${schemaLocation}/maximum`,
|
|
error: `${instance} is greater than ${$maximum}.`
|
|
});
|
|
}
|
|
if ($exclusiveMinimum !== undefined && instance <= $exclusiveMinimum) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "exclusiveMinimum",
|
|
keywordLocation: `${schemaLocation}/exclusiveMinimum`,
|
|
error: `${instance} is less than ${$exclusiveMinimum}.`
|
|
});
|
|
}
|
|
if ($exclusiveMaximum !== undefined && instance >= $exclusiveMaximum) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "exclusiveMaximum",
|
|
keywordLocation: `${schemaLocation}/exclusiveMaximum`,
|
|
error: `${instance} is greater than or equal to ${$exclusiveMaximum}.`
|
|
});
|
|
}
|
|
}
|
|
if ($multipleOf !== undefined) {
|
|
const remainder = instance % $multipleOf;
|
|
if (Math.abs(0 - remainder) >= 0.00000011920929 && Math.abs($multipleOf - remainder) >= 0.00000011920929) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "multipleOf",
|
|
keywordLocation: `${schemaLocation}/multipleOf`,
|
|
error: `${instance} is not a multiple of ${$multipleOf}.`
|
|
});
|
|
}
|
|
}
|
|
} else if (instanceType === "string") {
|
|
const length = $minLength === undefined && $maxLength === undefined ? 0 : ucs2length(instance);
|
|
if ($minLength !== undefined && length < $minLength) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "minLength",
|
|
keywordLocation: `${schemaLocation}/minLength`,
|
|
error: `String is too short (${length} < ${$minLength}).`
|
|
});
|
|
}
|
|
if ($maxLength !== undefined && length > $maxLength) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "maxLength",
|
|
keywordLocation: `${schemaLocation}/maxLength`,
|
|
error: `String is too long (${length} > ${$maxLength}).`
|
|
});
|
|
}
|
|
if ($pattern !== undefined && !new RegExp($pattern, "u").test(instance)) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "pattern",
|
|
keywordLocation: `${schemaLocation}/pattern`,
|
|
error: `String does not match pattern.`
|
|
});
|
|
}
|
|
if ($format !== undefined && format[$format] && !format[$format](instance)) {
|
|
errors.push({
|
|
instanceLocation,
|
|
keyword: "format",
|
|
keywordLocation: `${schemaLocation}/format`,
|
|
error: `String does not match format "${$format}".`
|
|
});
|
|
}
|
|
}
|
|
return { valid: errors.length === 0, errors };
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/validator.js
|
|
class Validator {
|
|
schema;
|
|
draft;
|
|
shortCircuit;
|
|
lookup;
|
|
constructor(schema, draft = "2019-09", shortCircuit = true) {
|
|
this.schema = schema;
|
|
this.draft = draft;
|
|
this.shortCircuit = shortCircuit;
|
|
this.lookup = dereference(schema);
|
|
}
|
|
validate(instance) {
|
|
return validate(instance, this.schema, this.draft, this.lookup, this.shortCircuit);
|
|
}
|
|
addSchema(schema, id) {
|
|
if (id) {
|
|
schema = { ...schema, $id: id };
|
|
}
|
|
dereference(schema, this.lookup);
|
|
}
|
|
}
|
|
|
|
// ../json-schema-to-zod/dist/index.mjs
|
|
var half = (arr) => {
|
|
return [arr.slice(0, arr.length / 2), arr.slice(arr.length / 2)];
|
|
};
|
|
var its = {
|
|
an: {
|
|
object: (x) => x.type === "object" || !x.type && (x.properties !== undefined || x.additionalProperties !== undefined || x.patternProperties !== undefined),
|
|
array: (x) => x.type === "array",
|
|
anyOf: (x) => x.anyOf !== undefined,
|
|
allOf: (x) => x.allOf !== undefined,
|
|
enum: (x) => x.enum !== undefined
|
|
},
|
|
a: {
|
|
nullable: (x) => x.nullable === true,
|
|
multipleType: (x) => Array.isArray(x.type),
|
|
not: (x) => x.not !== undefined,
|
|
const: (x) => x.const !== undefined,
|
|
primitive: (x, p) => x.type === p,
|
|
conditional: (x) => Boolean("if" in x && x.if && "then" in x && "else" in x && x.then && x.else),
|
|
oneOf: (x) => x.oneOf !== undefined
|
|
}
|
|
};
|
|
var originalIndex = Symbol("Original index");
|
|
var ensureOriginalIndex = (arr) => {
|
|
const newArr = [];
|
|
for (let i = 0;i < arr.length; i++) {
|
|
const item = arr[i];
|
|
if (typeof item === "boolean")
|
|
newArr.push(item ? { [originalIndex]: i } : {
|
|
[originalIndex]: i,
|
|
not: {}
|
|
});
|
|
else if (originalIndex in item)
|
|
return arr;
|
|
else
|
|
newArr.push({
|
|
...item,
|
|
[originalIndex]: i
|
|
});
|
|
}
|
|
return newArr;
|
|
};
|
|
var isClosedObjectBranch = (branch) => typeof branch === "object" && its.an.object(branch) && branch.properties !== undefined && Object.keys(branch.properties).length > 0 && branch.additionalProperties === undefined && branch.patternProperties === undefined && !("$ref" in branch);
|
|
var intersect = (branches, refs) => {
|
|
if (branches.length === 1) {
|
|
const item = branches[0];
|
|
return parseSchema(item, {
|
|
...refs,
|
|
path: [
|
|
...refs.path,
|
|
"allOf",
|
|
item[originalIndex]
|
|
]
|
|
});
|
|
}
|
|
const [left, right] = half(branches);
|
|
return intersectionType(intersect(left, refs), intersect(right, refs));
|
|
};
|
|
function parseAllOf(jsonSchema, refs) {
|
|
if (jsonSchema.allOf.length === 0)
|
|
return neverType();
|
|
if (jsonSchema.allOf.length === 1)
|
|
return intersect(ensureOriginalIndex(jsonSchema.allOf), refs);
|
|
const opened = jsonSchema.allOf.map((branch) => isClosedObjectBranch(branch) ? {
|
|
...branch,
|
|
additionalProperties: true
|
|
} : branch);
|
|
const parsed = intersect(ensureOriginalIndex(opened), refs);
|
|
if (!jsonSchema.allOf.every(isClosedObjectBranch))
|
|
return parsed;
|
|
const declaredKeys = new Set(jsonSchema.allOf.flatMap((branch) => Object.keys(branch.properties ?? {})));
|
|
return parsed.superRefine((value, ctx) => {
|
|
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
return;
|
|
const unrecognizedKeys = Object.keys(value).filter((key) => !declaredKeys.has(key));
|
|
if (unrecognizedKeys.length > 0)
|
|
ctx.addIssue({
|
|
code: ZodIssueCode.unrecognized_keys,
|
|
keys: unrecognizedKeys,
|
|
message: `Unrecognized key(s) in object: ${unrecognizedKeys.map((key) => `'${key}'`).join(", ")}`
|
|
});
|
|
});
|
|
}
|
|
var parseAnyOf = (jsonSchema, refs) => {
|
|
return jsonSchema.anyOf.length ? jsonSchema.anyOf.length === 1 ? parseSchema(jsonSchema.anyOf[0], {
|
|
...refs,
|
|
path: [
|
|
...refs.path,
|
|
"anyOf",
|
|
0
|
|
]
|
|
}) : unionType(jsonSchema.anyOf.map((schema, i) => parseSchema(schema, {
|
|
...refs,
|
|
path: [
|
|
...refs.path,
|
|
"anyOf",
|
|
i
|
|
]
|
|
}))) : anyType();
|
|
};
|
|
function extendSchemaWithMessage(zodSchema, jsonSchema, key, extend) {
|
|
const value = jsonSchema[key];
|
|
if (value !== undefined) {
|
|
const errorMessage = jsonSchema.errorMessage?.[key];
|
|
return extend(zodSchema, value, errorMessage);
|
|
}
|
|
return zodSchema;
|
|
}
|
|
var parseArray = (jsonSchema, refs) => {
|
|
if (its.an.anyOf(jsonSchema)) {
|
|
const types = /* @__PURE__ */ new Set;
|
|
const itemsSchemas = [];
|
|
jsonSchema.anyOf.forEach((option) => {
|
|
if (typeof option === "object" && option.type)
|
|
types.add(typeof option.type === "string" ? option.type : option.type[0]);
|
|
if (typeof option === "object" && option.items) {
|
|
const optionItems = option.items;
|
|
if (!Array.isArray(optionItems) && typeof optionItems === "object")
|
|
itemsSchemas.push(optionItems);
|
|
}
|
|
});
|
|
let finalItems;
|
|
if (itemsSchemas.length === 1)
|
|
finalItems = itemsSchemas[0];
|
|
else if (itemsSchemas.length > 1)
|
|
finalItems = { anyOf: itemsSchemas };
|
|
const newSchema = {
|
|
...types.size > 0 ? { type: Array.from(types) } : { type: "array" },
|
|
...finalItems && { items: finalItems }
|
|
};
|
|
[
|
|
"default",
|
|
"description",
|
|
"examples",
|
|
"title"
|
|
].forEach((field) => {
|
|
const value = jsonSchema[field];
|
|
if (value !== undefined)
|
|
newSchema[field] = value;
|
|
});
|
|
return parseSchema(newSchema, refs);
|
|
}
|
|
if (Array.isArray(jsonSchema.items)) {
|
|
const parsedItems = jsonSchema.items.map((item, index) => parseSchema(item, {
|
|
...refs,
|
|
path: [
|
|
...refs.path,
|
|
"items",
|
|
index
|
|
]
|
|
}));
|
|
const prefixSchemas = parsedItems.map((_, length) => tupleType(parsedItems.slice(0, length)));
|
|
const fullTuple = tupleType(parsedItems);
|
|
let fullLengthSchema;
|
|
if (jsonSchema.additionalItems === false)
|
|
fullLengthSchema = fullTuple;
|
|
else if (jsonSchema.additionalItems && jsonSchema.additionalItems !== true)
|
|
fullLengthSchema = fullTuple.rest(parseSchema(jsonSchema.additionalItems, {
|
|
...refs,
|
|
path: [...refs.path, "additionalItems"]
|
|
}));
|
|
else
|
|
fullLengthSchema = fullTuple.rest(anyType());
|
|
const variants = [...prefixSchemas, fullLengthSchema];
|
|
let tupleSchema = variants.length === 1 ? variants[0] : unionType(variants);
|
|
if (typeof jsonSchema.minItems === "number")
|
|
tupleSchema = tupleSchema.refine((value) => value.length >= jsonSchema.minItems, { message: `Array must contain at least ${jsonSchema.minItems} element(s)` });
|
|
if (typeof jsonSchema.maxItems === "number")
|
|
tupleSchema = tupleSchema.refine((value) => value.length <= jsonSchema.maxItems, { message: `Array must contain at most ${jsonSchema.maxItems} element(s)` });
|
|
return tupleSchema;
|
|
}
|
|
let zodSchema = !jsonSchema.items ? arrayType(anyType()) : arrayType(parseSchema(jsonSchema.items, {
|
|
...refs,
|
|
path: [...refs.path, "items"]
|
|
}));
|
|
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minItems", (zs, minItems, errorMessage) => zs.min(minItems, errorMessage));
|
|
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maxItems", (zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage));
|
|
if (typeof jsonSchema.min === "number" && typeof jsonSchema.minItems !== "number")
|
|
zodSchema = extendSchemaWithMessage(zodSchema, {
|
|
...jsonSchema,
|
|
minItems: jsonSchema.min
|
|
}, "minItems", (zs, minItems, errorMessage) => zs.min(minItems, errorMessage));
|
|
if (typeof jsonSchema.max === "number" && typeof jsonSchema.maxItems !== "number")
|
|
zodSchema = extendSchemaWithMessage(zodSchema, {
|
|
...jsonSchema,
|
|
maxItems: jsonSchema.max
|
|
}, "maxItems", (zs, maxItems, errorMessage) => zs.max(maxItems, errorMessage));
|
|
return zodSchema;
|
|
};
|
|
var parseBoolean = (_jsonSchema) => {
|
|
return booleanType();
|
|
};
|
|
var parseLiteralValues = (values) => {
|
|
if (values.length === 0)
|
|
return neverType();
|
|
if (values.every((value) => value === null || typeof value !== "object")) {
|
|
if (values.length === 1)
|
|
return literalType(values[0]);
|
|
if (values.every((value) => typeof value === "string"))
|
|
return enumType(values);
|
|
return unionType(values.map((value) => literalType(value)));
|
|
}
|
|
return custom((value) => values.some((candidate) => dequal(value, candidate)));
|
|
};
|
|
var parseConst = (jsonSchema, refs) => {
|
|
const { const: value, ...baseSchema } = jsonSchema;
|
|
return parseSchema(baseSchema, {
|
|
...refs,
|
|
seen: new Map(refs.seen)
|
|
}, true).and(parseLiteralValues([value]));
|
|
};
|
|
var parseDefault = (_jsonSchema) => {
|
|
return anyType();
|
|
};
|
|
var parseEnum = (jsonSchema, refs) => {
|
|
const { enum: values, ...baseSchema } = jsonSchema;
|
|
return parseSchema(baseSchema, {
|
|
...refs,
|
|
seen: new Map(refs.seen)
|
|
}, true).and(parseLiteralValues(values));
|
|
};
|
|
var parseIfThenElse = (jsonSchema, refs) => {
|
|
const $if = parseSchema(jsonSchema.if, {
|
|
...refs,
|
|
path: [...refs.path, "if"]
|
|
});
|
|
const $then = parseSchema(jsonSchema.then, {
|
|
...refs,
|
|
path: [...refs.path, "then"]
|
|
});
|
|
const $else = parseSchema(jsonSchema.else, {
|
|
...refs,
|
|
path: [...refs.path, "else"]
|
|
});
|
|
return unionType([$then, $else]).superRefine((value, ctx) => {
|
|
const result = $if.safeParse(value).success ? $then.safeParse(value) : $else.safeParse(value);
|
|
if (!result.success)
|
|
result.error.errors.forEach((error) => ctx.addIssue(error));
|
|
});
|
|
};
|
|
var parseMultipleType = (jsonSchema, refs) => {
|
|
return unionType(jsonSchema.type.map((type) => parseSchema({
|
|
...jsonSchema,
|
|
type
|
|
}, refs)));
|
|
};
|
|
var parseNot = (jsonSchema, refs) => {
|
|
return anyType().refine((value) => !parseSchema(jsonSchema.not, {
|
|
...refs,
|
|
path: [...refs.path, "not"]
|
|
}).safeParse(value).success, "Invalid input: Should NOT be valid against schema");
|
|
};
|
|
var parseNull = (_jsonSchema) => {
|
|
return nullType();
|
|
};
|
|
var omit = (obj, ...keys) => Object.keys(obj).reduce((acc, key) => {
|
|
if (!keys.includes(key))
|
|
acc[key] = obj[key];
|
|
return acc;
|
|
}, {});
|
|
var parseNullable = (jsonSchema, refs) => {
|
|
const hasNullDefault = jsonSchema.default === null;
|
|
const zodSchema = parseSchema(hasNullDefault ? omit(omit(jsonSchema, "nullable"), "default") : omit(jsonSchema, "nullable"), refs, true).nullable();
|
|
return hasNullDefault ? zodSchema.default(null) : zodSchema;
|
|
};
|
|
var toDecimalInteger = (value) => {
|
|
if (!Number.isFinite(value))
|
|
return;
|
|
const negative = value < 0;
|
|
const [coefficient, exponentText] = Math.abs(value).toString().toLowerCase().split("e");
|
|
const exponent = exponentText === undefined ? 0 : Number(exponentText);
|
|
const [whole, fraction = ""] = coefficient.split(".");
|
|
let digits = `${whole}${fraction}`.replace(/^0+(?=\d)/, "");
|
|
let scale = fraction.length - exponent;
|
|
if (scale < 0) {
|
|
digits += "0".repeat(-scale);
|
|
scale = 0;
|
|
}
|
|
return {
|
|
integer: BigInt(`${negative ? "-" : ""}${digits}`),
|
|
scale
|
|
};
|
|
};
|
|
var isJsonMultipleOf = (value, multiple) => {
|
|
const dividend = toDecimalInteger(value);
|
|
const divisor = toDecimalInteger(multiple);
|
|
if (!dividend || !divisor || divisor.integer === 0n)
|
|
return false;
|
|
const scale = Math.max(dividend.scale, divisor.scale);
|
|
return dividend.integer * 10n ** BigInt(scale - dividend.scale) % (divisor.integer * 10n ** BigInt(scale - divisor.scale)) === 0n;
|
|
};
|
|
var parseNumber = (jsonSchema) => {
|
|
let zodSchema = numberType();
|
|
let isInteger = false;
|
|
if (jsonSchema.type === "integer") {
|
|
isInteger = true;
|
|
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "type", (zs, _, errorMsg) => zs.int(errorMsg));
|
|
} else if (jsonSchema.format === "int64") {
|
|
isInteger = true;
|
|
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "format", (zs, _, errorMsg) => zs.int(errorMsg));
|
|
}
|
|
if (typeof jsonSchema.minimum === "number")
|
|
if (jsonSchema.exclusiveMinimum === true)
|
|
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minimum", (zs, minimum, errorMsg) => zs.gt(minimum, errorMsg));
|
|
else
|
|
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "minimum", (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg));
|
|
if (typeof jsonSchema.exclusiveMinimum === "number")
|
|
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "exclusiveMinimum", (zs, exclusiveMinimum, errorMsg) => zs.gt(exclusiveMinimum, errorMsg));
|
|
if (typeof jsonSchema.maximum === "number")
|
|
if (jsonSchema.exclusiveMaximum === true)
|
|
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maximum", (zs, maximum, errorMsg) => zs.lt(maximum, errorMsg));
|
|
else
|
|
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "maximum", (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg));
|
|
if (typeof jsonSchema.exclusiveMaximum === "number")
|
|
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "exclusiveMaximum", (zs, exclusiveMaximum, errorMsg) => zs.lt(exclusiveMaximum, errorMsg));
|
|
if (typeof jsonSchema.min === "number" && typeof jsonSchema.minimum !== "number")
|
|
zodSchema = extendSchemaWithMessage(zodSchema, {
|
|
...jsonSchema,
|
|
minimum: jsonSchema.min
|
|
}, "minimum", (zs, minimum, errorMsg) => zs.gte(minimum, errorMsg));
|
|
if (typeof jsonSchema.max === "number" && typeof jsonSchema.maximum !== "number")
|
|
zodSchema = extendSchemaWithMessage(zodSchema, {
|
|
...jsonSchema,
|
|
maximum: jsonSchema.max
|
|
}, "maximum", (zs, maximum, errorMsg) => zs.lte(maximum, errorMsg));
|
|
if (typeof jsonSchema.multipleOf === "number") {
|
|
const errorMessage = jsonSchema.errorMessage?.multipleOf;
|
|
if (jsonSchema.multipleOf === 1)
|
|
return isInteger ? zodSchema : zodSchema.int(errorMessage);
|
|
return zodSchema.refine((value) => isJsonMultipleOf(value, jsonSchema.multipleOf), { message: errorMessage ?? `Number must be a multiple of ${jsonSchema.multipleOf}` });
|
|
}
|
|
return zodSchema;
|
|
};
|
|
var parseOneOf = (jsonSchema, refs) => {
|
|
if (!jsonSchema.oneOf.length)
|
|
return anyType();
|
|
if (jsonSchema.oneOf.length === 1)
|
|
return parseSchema(jsonSchema.oneOf[0], {
|
|
...refs,
|
|
path: [
|
|
...refs.path,
|
|
"oneOf",
|
|
0
|
|
]
|
|
});
|
|
return anyType().superRefine((x, ctx) => {
|
|
const schemas = jsonSchema.oneOf.map((schema, i) => parseSchema(schema, {
|
|
...refs,
|
|
path: [
|
|
...refs.path,
|
|
"oneOf",
|
|
i
|
|
]
|
|
}));
|
|
const unionErrors = schemas.reduce((errors, schema) => ((result) => result.error ? [...errors, result.error] : errors)(schema.safeParse(x)), []);
|
|
if (schemas.length - unionErrors.length !== 1)
|
|
ctx.addIssue({
|
|
path: ctx.path,
|
|
code: "invalid_union",
|
|
unionErrors,
|
|
message: "Invalid input: Should pass single schema"
|
|
});
|
|
});
|
|
};
|
|
function parseObjectProperties(objectSchema, refs) {
|
|
if (!objectSchema.properties)
|
|
return;
|
|
const propertyKeys = Object.keys(objectSchema.properties);
|
|
if (propertyKeys.length === 0)
|
|
return;
|
|
const properties = {};
|
|
for (const key of propertyKeys) {
|
|
const propJsonSchema = objectSchema.properties[key];
|
|
const propZodSchema = parseSchema(propJsonSchema, {
|
|
...refs,
|
|
path: [
|
|
...refs.path,
|
|
"properties",
|
|
key
|
|
]
|
|
});
|
|
const required = Array.isArray(objectSchema.required) ? objectSchema.required.includes(key) : false;
|
|
if (!required && propJsonSchema && typeof propJsonSchema === "object" && "default" in propJsonSchema)
|
|
if (propJsonSchema.default === null) {
|
|
const hasAnyOfWithNull = propJsonSchema.anyOf && Array.isArray(propJsonSchema.anyOf) && propJsonSchema.anyOf.some((schema) => typeof schema === "object" && schema !== null && schema.type === "null");
|
|
const hasOneOfWithNull = propJsonSchema.oneOf && Array.isArray(propJsonSchema.oneOf) && propJsonSchema.oneOf.some((schema) => typeof schema === "object" && schema !== null && schema.type === "null");
|
|
const isNullable = "nullable" in propJsonSchema && propJsonSchema.nullable === true;
|
|
if (hasAnyOfWithNull || hasOneOfWithNull || isNullable)
|
|
properties[key] = propZodSchema.optional().default(null);
|
|
else
|
|
properties[key] = propZodSchema.nullable().optional().default(null);
|
|
} else
|
|
properties[key] = propZodSchema.optional().default(propJsonSchema.default);
|
|
else
|
|
properties[key] = required ? propZodSchema : propZodSchema.optional();
|
|
}
|
|
return objectType(properties);
|
|
}
|
|
function parseDynamicKeyObject(normalizedSchema, propertiesSchema, additionalProperties, refs) {
|
|
const patterns = Object.entries(normalizedSchema.patternProperties ?? {}).map(([pattern, schema]) => ({
|
|
regex: new RegExp(pattern),
|
|
parser: parseSchema(schema, {
|
|
...refs,
|
|
path: [
|
|
...refs.path,
|
|
"patternProperties",
|
|
pattern
|
|
]
|
|
})
|
|
}));
|
|
const declaredKeys = new Set(Object.keys(normalizedSchema.properties ?? {}));
|
|
const rejectsUnmatched = additionalProperties instanceof ZodNever || additionalProperties === undefined && declaredKeys.size > 0;
|
|
const validatesUnmatched = additionalProperties !== undefined && !(additionalProperties instanceof ZodNever) && normalizedSchema.additionalProperties !== true;
|
|
return (propertiesSchema ?? objectType({})).passthrough().transform((value, ctx) => {
|
|
const result = { ...value };
|
|
const unrecognizedKeys = [];
|
|
for (const key of Object.keys(value)) {
|
|
const matching = patterns.filter(({ regex }) => regex.test(key));
|
|
for (const { parser } of matching) {
|
|
const parsed = parser.safeParse(value[key]);
|
|
if (!parsed.success)
|
|
ctx.addIssue({
|
|
path: [...ctx.path, key],
|
|
code: "custom",
|
|
message: `Invalid input: key "${key}" must match its patternProperties schema`,
|
|
params: { issues: parsed.error.issues }
|
|
});
|
|
else if (!declaredKeys.has(key))
|
|
result[key] = parsed.data;
|
|
}
|
|
if (matching.length > 0 || declaredKeys.has(key))
|
|
continue;
|
|
if (rejectsUnmatched)
|
|
unrecognizedKeys.push(key);
|
|
else if (validatesUnmatched) {
|
|
const parsed = additionalProperties.safeParse(value[key]);
|
|
if (!parsed.success)
|
|
ctx.addIssue({
|
|
path: [...ctx.path, key],
|
|
code: "custom",
|
|
message: `Invalid input: key "${key}" must match the additionalProperties schema`,
|
|
params: { issues: parsed.error.issues }
|
|
});
|
|
else
|
|
result[key] = parsed.data;
|
|
}
|
|
}
|
|
if (unrecognizedKeys.length > 0)
|
|
ctx.addIssue({
|
|
path: [...ctx.path],
|
|
code: "unrecognized_keys",
|
|
keys: unrecognizedKeys,
|
|
message: `Unrecognized key(s) in object: ${unrecognizedKeys.map((key) => `'${key}'`).join(", ")}`
|
|
});
|
|
return result;
|
|
});
|
|
}
|
|
function parseObject(objectSchema, refs) {
|
|
const hasPatternProperties = Object.keys(objectSchema.patternProperties ?? {}).length > 0;
|
|
const normalizedSchema = objectSchema.type === "object" ? objectSchema : {
|
|
...objectSchema,
|
|
type: "object"
|
|
};
|
|
const propertiesSchema = parseObjectProperties(normalizedSchema, refs);
|
|
const additionalProperties = normalizedSchema.additionalProperties !== undefined ? parseSchema(normalizedSchema.additionalProperties, {
|
|
...refs,
|
|
path: [...refs.path, "additionalProperties"]
|
|
}) : undefined;
|
|
const isAdditionalPropertiesTrue = normalizedSchema.additionalProperties === true;
|
|
let output;
|
|
if (hasPatternProperties)
|
|
output = parseDynamicKeyObject(normalizedSchema, propertiesSchema, additionalProperties, refs);
|
|
else if (propertiesSchema)
|
|
if (additionalProperties)
|
|
if (additionalProperties instanceof ZodNever)
|
|
output = propertiesSchema.strict();
|
|
else if (isAdditionalPropertiesTrue)
|
|
output = propertiesSchema.passthrough();
|
|
else
|
|
output = propertiesSchema.catchall(additionalProperties);
|
|
else
|
|
output = propertiesSchema.strict();
|
|
else if (additionalProperties)
|
|
if (additionalProperties instanceof ZodNever)
|
|
output = objectType({}).strict();
|
|
else if (isAdditionalPropertiesTrue)
|
|
output = objectType({}).passthrough();
|
|
else
|
|
output = recordType(additionalProperties);
|
|
else
|
|
output = objectType({}).passthrough();
|
|
if (its.an.anyOf(objectSchema))
|
|
output = output.and(parseAnyOf({
|
|
...objectSchema,
|
|
anyOf: objectSchema.anyOf.map((x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? {
|
|
...x,
|
|
type: "object"
|
|
} : x)
|
|
}, refs));
|
|
if (its.a.oneOf(objectSchema))
|
|
output = output.and(parseOneOf({
|
|
...objectSchema,
|
|
oneOf: objectSchema.oneOf.map((x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? {
|
|
...x,
|
|
type: "object"
|
|
} : x)
|
|
}, refs));
|
|
if (its.an.allOf(objectSchema))
|
|
output = output.and(parseAllOf({
|
|
...objectSchema,
|
|
allOf: objectSchema.allOf.map((x) => typeof x === "object" && !x.type && (x.properties ?? x.additionalProperties ?? x.patternProperties) ? {
|
|
...x,
|
|
type: "object"
|
|
} : x)
|
|
}, refs));
|
|
return output;
|
|
}
|
|
var parseString = (jsonSchema) => {
|
|
let zodSchema = stringType();
|
|
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "format", (zs, format, errorMsg) => {
|
|
switch (format) {
|
|
case "email":
|
|
return zs.email(errorMsg);
|
|
case "ip":
|
|
return zs.ip(errorMsg);
|
|
case "ipv4":
|
|
return zs.ip({
|
|
version: "v4",
|
|
message: errorMsg
|
|
});
|
|
case "ipv6":
|
|
return zs.ip({
|
|
version: "v6",
|
|
message: errorMsg
|
|
});
|
|
case "uri":
|
|
return zs.url(errorMsg);
|
|
case "uuid":
|
|
return zs.uuid(errorMsg);
|
|
case "date-time":
|
|
return zs.datetime({
|
|
offset: true,
|
|
message: errorMsg
|
|
});
|
|
case "time":
|
|
return zs.time(errorMsg);
|
|
case "date":
|
|
return zs.date(errorMsg);
|
|
case "binary":
|
|
return zs.base64(errorMsg);
|
|
case "duration":
|
|
return zs.duration(errorMsg);
|
|
default:
|
|
return zs;
|
|
}
|
|
});
|
|
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "contentEncoding", (zs, _, errorMsg) => zs.base64(errorMsg));
|
|
zodSchema = extendSchemaWithMessage(zodSchema, jsonSchema, "pattern", (zs, pattern, errorMsg) => zs.regex(new RegExp(pattern), errorMsg));
|
|
const errorMessages = jsonSchema.errorMessage;
|
|
const minLength = typeof jsonSchema.minLength === "number" ? jsonSchema.minLength : typeof jsonSchema.min === "number" ? jsonSchema.min : undefined;
|
|
const maxLength = typeof jsonSchema.maxLength === "number" ? jsonSchema.maxLength : typeof jsonSchema.max === "number" ? jsonSchema.max : undefined;
|
|
let result = zodSchema;
|
|
if (minLength !== undefined)
|
|
result = result.refine((value) => codePointLength(value) >= minLength, { message: errorMessages?.minLength ?? `String must contain at least ${minLength} character(s)` });
|
|
if (maxLength !== undefined)
|
|
result = result.refine((value) => codePointLength(value) <= maxLength, { message: errorMessages?.maxLength ?? `String must contain at most ${maxLength} character(s)` });
|
|
return result;
|
|
};
|
|
var codePointLength = (value) => [...value].length;
|
|
var SCALAR_CONSTRAINT_KEYS = [
|
|
"minLength",
|
|
"maxLength",
|
|
"pattern",
|
|
"minimum",
|
|
"maximum",
|
|
"exclusiveMinimum",
|
|
"exclusiveMaximum",
|
|
"multipleOf"
|
|
];
|
|
var hasTypelessScalarConstraints = (schema) => schema.type === undefined && SCALAR_CONSTRAINT_KEYS.some((key) => schema[key] !== undefined);
|
|
var parseTypelessConstraints = (schema) => {
|
|
const stringSchema = parseString({
|
|
...schema,
|
|
type: "string"
|
|
});
|
|
const numberSchema = parseNumber({
|
|
...schema,
|
|
type: "number"
|
|
});
|
|
return anyType().superRefine((value, ctx) => {
|
|
const applicable = typeof value === "string" ? stringSchema : typeof value === "number" ? numberSchema : undefined;
|
|
if (applicable === undefined)
|
|
return;
|
|
const result = applicable.safeParse(value);
|
|
if (!result.success)
|
|
for (const issue of result.error.issues)
|
|
ctx.addIssue(issue);
|
|
});
|
|
};
|
|
var REQUIRES_WHOLE_SCHEMA_VALIDATION = /* @__PURE__ */ new Set([
|
|
"$ref",
|
|
"additionalItems",
|
|
"allOf",
|
|
"anyOf",
|
|
"contains",
|
|
"dependencies",
|
|
"else",
|
|
"if",
|
|
"maxProperties",
|
|
"minProperties",
|
|
"not",
|
|
"oneOf",
|
|
"propertyNames",
|
|
"then",
|
|
"uniqueItems"
|
|
]);
|
|
var TYPELESS_TYPE_SCOPED_KEYWORDS = /* @__PURE__ */ new Set([
|
|
"properties",
|
|
"patternProperties",
|
|
"additionalProperties",
|
|
"propertyNames",
|
|
"required",
|
|
"dependencies",
|
|
"minProperties",
|
|
"maxProperties",
|
|
"items",
|
|
"additionalItems",
|
|
"contains",
|
|
"minItems",
|
|
"maxItems",
|
|
"uniqueItems"
|
|
]);
|
|
var SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([
|
|
"$defs",
|
|
"definitions",
|
|
"dependencies",
|
|
"patternProperties",
|
|
"properties"
|
|
]);
|
|
var SCHEMA_ARRAY_KEYWORDS = /* @__PURE__ */ new Set([
|
|
"allOf",
|
|
"anyOf",
|
|
"oneOf"
|
|
]);
|
|
var SCHEMA_VALUE_KEYWORDS = /* @__PURE__ */ new Set([
|
|
"additionalItems",
|
|
"additionalProperties",
|
|
"contains",
|
|
"else",
|
|
"if",
|
|
"items",
|
|
"not",
|
|
"propertyNames",
|
|
"then"
|
|
]);
|
|
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
var hasRequiredDefault = (schema) => {
|
|
if (!Array.isArray(schema.required) || !isObject(schema.properties))
|
|
return false;
|
|
return schema.required.some((name) => {
|
|
const property = schema.properties?.[name];
|
|
return isObject(property) && property.default !== undefined;
|
|
});
|
|
};
|
|
var hasUnparsedRequiredProperty = (schema) => {
|
|
if (!Array.isArray(schema.required))
|
|
return false;
|
|
const declared = new Set(Object.keys(schema.properties ?? {}));
|
|
return schema.required.some((name) => !declared.has(name));
|
|
};
|
|
var requiresWholeSchemaValidation = (schema, seen = /* @__PURE__ */ new WeakSet) => {
|
|
if (!isObject(schema) || seen.has(schema))
|
|
return false;
|
|
seen.add(schema);
|
|
if (Object.keys(schema).some((key) => REQUIRES_WHOLE_SCHEMA_VALIDATION.has(key)) || schema.type === undefined && Object.keys(schema).some((key) => TYPELESS_TYPE_SCOPED_KEYWORDS.has(key)) || hasUnparsedRequiredProperty(schema) || hasRequiredDefault(schema))
|
|
return true;
|
|
for (const [key, child] of Object.entries(schema))
|
|
if (SCHEMA_MAP_KEYWORDS.has(key) && isObject(child)) {
|
|
if (Object.values(child).some((value) => requiresWholeSchemaValidation(value, seen)))
|
|
return true;
|
|
} else if (SCHEMA_ARRAY_KEYWORDS.has(key) && Array.isArray(child)) {
|
|
if (child.some((value) => requiresWholeSchemaValidation(value, seen)))
|
|
return true;
|
|
} else if (SCHEMA_VALUE_KEYWORDS.has(key)) {
|
|
if ((Array.isArray(child) ? child : [child]).some((value) => requiresWholeSchemaValidation(value, seen)))
|
|
return true;
|
|
}
|
|
return false;
|
|
};
|
|
var requiresPermissiveMaterialization = (schema) => isObject(schema) && (("$ref" in schema) || schema.type === undefined && (Object.keys(schema).some((key) => TYPELESS_TYPE_SCOPED_KEYWORDS.has(key)) || [
|
|
"if",
|
|
"then",
|
|
"else",
|
|
"not"
|
|
].some((key) => (key in schema))));
|
|
var guardSchemaAt = (node, refs) => isObject(refs.root) && refs.path.length > 0 ? {
|
|
...refs.root,
|
|
$ref: `#/${refs.path.map((part) => encodePointer(String(part))).join("/")}`
|
|
} : node;
|
|
var normalizeExclusiveBounds = (value, seen) => {
|
|
if (!isObject(value) || seen.has(value))
|
|
return;
|
|
seen.add(value);
|
|
if (value.exclusiveMinimum === true && typeof value.minimum === "number") {
|
|
value.exclusiveMinimum = value.minimum;
|
|
delete value.minimum;
|
|
} else if (typeof value.exclusiveMinimum === "boolean")
|
|
delete value.exclusiveMinimum;
|
|
if (value.exclusiveMaximum === true && typeof value.maximum === "number") {
|
|
value.exclusiveMaximum = value.maximum;
|
|
delete value.maximum;
|
|
} else if (typeof value.exclusiveMaximum === "boolean")
|
|
delete value.exclusiveMaximum;
|
|
for (const [key, child] of Object.entries(value))
|
|
if (SCHEMA_MAP_KEYWORDS.has(key) && isObject(child))
|
|
Object.values(child).forEach((nested) => normalizeExclusiveBounds(nested, seen));
|
|
else if (SCHEMA_ARRAY_KEYWORDS.has(key) && Array.isArray(child))
|
|
child.forEach((nested) => normalizeExclusiveBounds(nested, seen));
|
|
else if (SCHEMA_VALUE_KEYWORDS.has(key))
|
|
(Array.isArray(child) ? child : [child]).forEach((nested) => normalizeExclusiveBounds(nested, seen));
|
|
};
|
|
var withWholeSchemaValidation = (jsonSchema, parsedSchema) => {
|
|
const interpreterSchema = structuredClone(jsonSchema);
|
|
normalizeExclusiveBounds(interpreterSchema, /* @__PURE__ */ new WeakSet);
|
|
const validator = new Validator(interpreterSchema, "7", false);
|
|
const guardedSchema = anyType().superRefine((value, ctx) => {
|
|
let result;
|
|
try {
|
|
result = validator.validate(value);
|
|
} catch (cause) {
|
|
ctx.addIssue({
|
|
code: ZodIssueCode.custom,
|
|
message: `JSON Schema validation failed: ${String(cause)}`
|
|
});
|
|
return;
|
|
}
|
|
if (!result.valid)
|
|
ctx.addIssue({
|
|
code: ZodIssueCode.custom,
|
|
message: result.errors[0]?.error ?? "Input does not satisfy the complete JSON Schema."
|
|
});
|
|
}).pipe(parsedSchema);
|
|
return parsedSchema.description ? guardedSchema.describe(parsedSchema.description) : guardedSchema;
|
|
};
|
|
var addDescribes = (jsonSchema, zodSchema) => {
|
|
let description = "";
|
|
if (jsonSchema.description)
|
|
description = jsonSchema.description;
|
|
else if (jsonSchema.title)
|
|
description = jsonSchema.title;
|
|
if (jsonSchema.example !== undefined) {
|
|
const exampleText = `Example: ${JSON.stringify(jsonSchema.example)}`;
|
|
description = description ? `${description}
|
|
${exampleText}` : exampleText;
|
|
} else if (jsonSchema.examples !== undefined && Array.isArray(jsonSchema.examples)) {
|
|
const examples = jsonSchema.examples;
|
|
if (examples.length > 0) {
|
|
const exampleText = examples.length === 1 ? `Example: ${JSON.stringify(examples[0])}` : `Examples:
|
|
${examples.map((ex) => ` ${JSON.stringify(ex)}`).join(`
|
|
`)}`;
|
|
description = description ? `${description}
|
|
${exampleText}` : exampleText;
|
|
}
|
|
}
|
|
if (description)
|
|
zodSchema = zodSchema.describe(description);
|
|
return zodSchema;
|
|
};
|
|
var addDefaults = (jsonSchema, zodSchema, refs) => {
|
|
if (jsonSchema.default !== undefined) {
|
|
if (jsonSchema.default === null) {
|
|
if (refs?.path.some((segment) => segment === "anyOf" || segment === "oneOf") && jsonSchema.type && jsonSchema.type !== "null" && !jsonSchema.nullable)
|
|
return zodSchema;
|
|
}
|
|
zodSchema = zodSchema.default(jsonSchema.default);
|
|
}
|
|
return zodSchema;
|
|
};
|
|
var addAnnotations = (jsonSchema, zodSchema) => {
|
|
if (jsonSchema.readOnly)
|
|
zodSchema = zodSchema.readonly();
|
|
return zodSchema;
|
|
};
|
|
var selectParser = (schema, refs) => {
|
|
if (requiresPermissiveMaterialization(schema))
|
|
return withWholeSchemaValidation(guardSchemaAt(schema, refs), anyType());
|
|
else if (its.a.nullable(schema))
|
|
return parseNullable(schema, refs);
|
|
else if (its.an.enum(schema))
|
|
return parseEnum(schema, refs);
|
|
else if (its.a.const(schema))
|
|
return parseConst(schema, refs);
|
|
else if (its.an.object(schema))
|
|
return parseObject(schema, refs);
|
|
else if (its.an.array(schema))
|
|
return parseArray(schema, refs);
|
|
else if (its.an.anyOf(schema))
|
|
return parseAnyOf(schema, refs);
|
|
else if (its.an.allOf(schema))
|
|
return parseAllOf(schema, refs);
|
|
else if (its.a.oneOf(schema))
|
|
return parseOneOf(schema, refs);
|
|
else if (its.a.not(schema))
|
|
return parseNot(schema, refs);
|
|
else if (hasTypelessScalarConstraints(schema))
|
|
return parseTypelessConstraints(schema);
|
|
else if (its.a.multipleType(schema))
|
|
return parseMultipleType(schema, refs);
|
|
else if (its.a.primitive(schema, "string"))
|
|
return parseString(schema);
|
|
else if (its.a.primitive(schema, "number") || its.a.primitive(schema, "integer"))
|
|
return parseNumber(schema);
|
|
else if (its.a.primitive(schema, "boolean"))
|
|
return parseBoolean(schema);
|
|
else if (its.a.primitive(schema, "null"))
|
|
return parseNull(schema);
|
|
else if (its.a.conditional(schema))
|
|
return parseIfThenElse(schema, refs);
|
|
else
|
|
return parseDefault(schema);
|
|
};
|
|
var parseSchema = (jsonSchema, refs = {
|
|
seen: /* @__PURE__ */ new Map,
|
|
path: []
|
|
}, blockMeta) => {
|
|
if (typeof jsonSchema !== "object")
|
|
return jsonSchema ? anyType() : neverType();
|
|
if (refs.parserOverride) {
|
|
const custom2 = refs.parserOverride(jsonSchema, refs);
|
|
if (custom2 instanceof ZodType)
|
|
return custom2;
|
|
}
|
|
let seen = refs.seen.get(jsonSchema);
|
|
if (seen) {
|
|
if (seen.r !== undefined)
|
|
return seen.r;
|
|
if (refs.depth === undefined || seen.n >= refs.depth)
|
|
return anyType();
|
|
seen.n += 1;
|
|
} else {
|
|
seen = {
|
|
r: undefined,
|
|
n: 0
|
|
};
|
|
refs.seen.set(jsonSchema, seen);
|
|
}
|
|
let parsedZodSchema = selectParser(jsonSchema, refs);
|
|
if (!blockMeta) {
|
|
if (!refs.withoutDescribes)
|
|
parsedZodSchema = addDescribes(jsonSchema, parsedZodSchema);
|
|
if (!refs.withoutDefaults)
|
|
parsedZodSchema = addDefaults(jsonSchema, parsedZodSchema, refs);
|
|
parsedZodSchema = addAnnotations(jsonSchema, parsedZodSchema);
|
|
}
|
|
seen.r = parsedZodSchema;
|
|
return parsedZodSchema;
|
|
};
|
|
var jsonSchemaToZod = (schema, options = {}) => {
|
|
const parsedSchema = parseSchema(schema, {
|
|
path: [],
|
|
seen: /* @__PURE__ */ new Map,
|
|
root: schema,
|
|
...options
|
|
});
|
|
return requiresWholeSchemaValidation(schema) ? withWholeSchemaValidation(schema, parsedSchema) : parsedSchema;
|
|
};
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Function.js
|
|
var isFunction = (input) => typeof input === "function";
|
|
var dual = function(arity, body) {
|
|
if (typeof arity === "function") {
|
|
return function() {
|
|
if (arity(arguments)) {
|
|
return body.apply(this, arguments);
|
|
}
|
|
return (self2) => body(self2, ...arguments);
|
|
};
|
|
}
|
|
switch (arity) {
|
|
case 0:
|
|
case 1:
|
|
throw new RangeError(`Invalid arity ${arity}`);
|
|
case 2:
|
|
return function(a, b) {
|
|
if (arguments.length >= 2) {
|
|
return body(a, b);
|
|
}
|
|
return function(self2) {
|
|
return body(self2, a);
|
|
};
|
|
};
|
|
case 3:
|
|
return function(a, b, c) {
|
|
if (arguments.length >= 3) {
|
|
return body(a, b, c);
|
|
}
|
|
return function(self2) {
|
|
return body(self2, a, b);
|
|
};
|
|
};
|
|
case 4:
|
|
return function(a, b, c, d) {
|
|
if (arguments.length >= 4) {
|
|
return body(a, b, c, d);
|
|
}
|
|
return function(self2) {
|
|
return body(self2, a, b, c);
|
|
};
|
|
};
|
|
case 5:
|
|
return function(a, b, c, d, e) {
|
|
if (arguments.length >= 5) {
|
|
return body(a, b, c, d, e);
|
|
}
|
|
return function(self2) {
|
|
return body(self2, a, b, c, d);
|
|
};
|
|
};
|
|
default:
|
|
return function() {
|
|
if (arguments.length >= arity) {
|
|
return body.apply(this, arguments);
|
|
}
|
|
const args = arguments;
|
|
return function(self2) {
|
|
return body(self2, ...args);
|
|
};
|
|
};
|
|
}
|
|
};
|
|
var identity = (a) => a;
|
|
var constant = (value) => () => value;
|
|
var constTrue = /* @__PURE__ */ constant(true);
|
|
var constFalse = /* @__PURE__ */ constant(false);
|
|
var constUndefined = /* @__PURE__ */ constant(undefined);
|
|
var constVoid = constUndefined;
|
|
function pipe(a, ab, bc, cd, de, ef, fg, gh, hi) {
|
|
switch (arguments.length) {
|
|
case 1:
|
|
return a;
|
|
case 2:
|
|
return ab(a);
|
|
case 3:
|
|
return bc(ab(a));
|
|
case 4:
|
|
return cd(bc(ab(a)));
|
|
case 5:
|
|
return de(cd(bc(ab(a))));
|
|
case 6:
|
|
return ef(de(cd(bc(ab(a)))));
|
|
case 7:
|
|
return fg(ef(de(cd(bc(ab(a))))));
|
|
case 8:
|
|
return gh(fg(ef(de(cd(bc(ab(a)))))));
|
|
case 9:
|
|
return hi(gh(fg(ef(de(cd(bc(ab(a))))))));
|
|
default: {
|
|
let ret = arguments[0];
|
|
for (let i = 1;i < arguments.length; i++) {
|
|
ret = arguments[i](ret);
|
|
}
|
|
return ret;
|
|
}
|
|
}
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Equivalence.js
|
|
var make = (isEquivalent) => (self2, that) => self2 === that || isEquivalent(self2, that);
|
|
var isStrictEquivalent = (x, y) => x === y;
|
|
var strict = () => isStrictEquivalent;
|
|
var number = /* @__PURE__ */ strict();
|
|
var mapInput = /* @__PURE__ */ dual(2, (self2, f) => make((x, y) => self2(f(x), f(y))));
|
|
var Date2 = /* @__PURE__ */ mapInput(number, (date) => date.getTime());
|
|
var array = (item) => make((self2, that) => {
|
|
if (self2.length !== that.length) {
|
|
return false;
|
|
}
|
|
for (let i = 0;i < self2.length; i++) {
|
|
const isEq = item(self2[i], that[i]);
|
|
if (!isEq) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/GlobalValue.js
|
|
var globalStoreId = `effect/GlobalValue`;
|
|
var globalStore;
|
|
var globalValue = (id, compute) => {
|
|
if (!globalStore) {
|
|
globalThis[globalStoreId] ??= new Map;
|
|
globalStore = globalThis[globalStoreId];
|
|
}
|
|
if (!globalStore.has(id)) {
|
|
globalStore.set(id, compute());
|
|
}
|
|
return globalStore.get(id);
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Predicate.js
|
|
var isString = (input) => typeof input === "string";
|
|
var isNumber = (input) => typeof input === "number";
|
|
var isBoolean = (input) => typeof input === "boolean";
|
|
var isBigInt = (input) => typeof input === "bigint";
|
|
var isSymbol = (input) => typeof input === "symbol";
|
|
var isFunction2 = isFunction;
|
|
var isUndefined = (input) => input === undefined;
|
|
var isNever = (_) => false;
|
|
var isRecordOrArray = (input) => typeof input === "object" && input !== null;
|
|
var isObject2 = (input) => isRecordOrArray(input) || isFunction2(input);
|
|
var hasProperty = /* @__PURE__ */ dual(2, (self2, property) => isObject2(self2) && (property in self2));
|
|
var isTagged = /* @__PURE__ */ dual(2, (self2, tag) => hasProperty(self2, "_tag") && self2["_tag"] === tag);
|
|
var isNullable = (input) => input === null || input === undefined;
|
|
var isNotNullable = (input) => input !== null && input !== undefined;
|
|
var isDate = (input) => input instanceof Date;
|
|
var isIterable = (input) => typeof input === "string" || hasProperty(input, Symbol.iterator);
|
|
var isRecord = (input) => isRecordOrArray(input) && !Array.isArray(input);
|
|
var isPromiseLike = (input) => hasProperty(input, "then") && isFunction2(input.then);
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/errors.js
|
|
var getBugErrorMessage = (message) => `BUG: ${message} - please report an issue at https://github.com/Effect-TS/effect/issues`;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Utils.js
|
|
class SingleShotGen {
|
|
self;
|
|
called = false;
|
|
constructor(self2) {
|
|
this.self = self2;
|
|
}
|
|
next(a) {
|
|
return this.called ? {
|
|
value: a,
|
|
done: true
|
|
} : (this.called = true, {
|
|
value: this.self,
|
|
done: false
|
|
});
|
|
}
|
|
return(a) {
|
|
return {
|
|
value: a,
|
|
done: true
|
|
};
|
|
}
|
|
throw(e) {
|
|
throw e;
|
|
}
|
|
[Symbol.iterator]() {
|
|
return new SingleShotGen(this.self);
|
|
}
|
|
}
|
|
var defaultIncHi = 335903614;
|
|
var defaultIncLo = 4150755663;
|
|
var MUL_HI = 1481765933 >>> 0;
|
|
var MUL_LO = 1284865837 >>> 0;
|
|
var BIT_53 = 9007199254740992;
|
|
var BIT_27 = 134217728;
|
|
|
|
class PCGRandom {
|
|
_state;
|
|
constructor(seedHi, seedLo, incHi, incLo) {
|
|
if (isNullable(seedLo) && isNullable(seedHi)) {
|
|
seedLo = Math.random() * 4294967295 >>> 0;
|
|
seedHi = 0;
|
|
} else if (isNullable(seedLo)) {
|
|
seedLo = seedHi;
|
|
seedHi = 0;
|
|
}
|
|
if (isNullable(incLo) && isNullable(incHi)) {
|
|
incLo = this._state ? this._state[3] : defaultIncLo;
|
|
incHi = this._state ? this._state[2] : defaultIncHi;
|
|
} else if (isNullable(incLo)) {
|
|
incLo = incHi;
|
|
incHi = 0;
|
|
}
|
|
this._state = new Int32Array([0, 0, incHi >>> 0, ((incLo || 0) | 1) >>> 0]);
|
|
this._next();
|
|
add64(this._state, this._state[0], this._state[1], seedHi >>> 0, seedLo >>> 0);
|
|
this._next();
|
|
return this;
|
|
}
|
|
getState() {
|
|
return [this._state[0], this._state[1], this._state[2], this._state[3]];
|
|
}
|
|
setState(state) {
|
|
this._state[0] = state[0];
|
|
this._state[1] = state[1];
|
|
this._state[2] = state[2];
|
|
this._state[3] = state[3] | 1;
|
|
}
|
|
integer(max) {
|
|
return Math.round(this.number() * Number.MAX_SAFE_INTEGER) % max;
|
|
}
|
|
number() {
|
|
const hi = (this._next() & 67108863) * 1;
|
|
const lo = (this._next() & 134217727) * 1;
|
|
return (hi * BIT_27 + lo) / BIT_53;
|
|
}
|
|
_next() {
|
|
const oldHi = this._state[0] >>> 0;
|
|
const oldLo = this._state[1] >>> 0;
|
|
mul64(this._state, oldHi, oldLo, MUL_HI, MUL_LO);
|
|
add64(this._state, this._state[0], this._state[1], this._state[2], this._state[3]);
|
|
let xsHi = oldHi >>> 18;
|
|
let xsLo = (oldLo >>> 18 | oldHi << 14) >>> 0;
|
|
xsHi = (xsHi ^ oldHi) >>> 0;
|
|
xsLo = (xsLo ^ oldLo) >>> 0;
|
|
const xorshifted = (xsLo >>> 27 | xsHi << 5) >>> 0;
|
|
const rot = oldHi >>> 27;
|
|
const rot2 = (-rot >>> 0 & 31) >>> 0;
|
|
return (xorshifted >>> rot | xorshifted << rot2) >>> 0;
|
|
}
|
|
}
|
|
function mul64(out, aHi, aLo, bHi, bLo) {
|
|
let c1 = (aLo >>> 16) * (bLo & 65535) >>> 0;
|
|
let c0 = (aLo & 65535) * (bLo >>> 16) >>> 0;
|
|
let lo = (aLo & 65535) * (bLo & 65535) >>> 0;
|
|
let hi = (aLo >>> 16) * (bLo >>> 16) + ((c0 >>> 16) + (c1 >>> 16)) >>> 0;
|
|
c0 = c0 << 16 >>> 0;
|
|
lo = lo + c0 >>> 0;
|
|
if (lo >>> 0 < c0 >>> 0) {
|
|
hi = hi + 1 >>> 0;
|
|
}
|
|
c1 = c1 << 16 >>> 0;
|
|
lo = lo + c1 >>> 0;
|
|
if (lo >>> 0 < c1 >>> 0) {
|
|
hi = hi + 1 >>> 0;
|
|
}
|
|
hi = hi + Math.imul(aLo, bHi) >>> 0;
|
|
hi = hi + Math.imul(aHi, bLo) >>> 0;
|
|
out[0] = hi;
|
|
out[1] = lo;
|
|
}
|
|
function add64(out, aHi, aLo, bHi, bLo) {
|
|
let hi = aHi + bHi >>> 0;
|
|
const lo = aLo + bLo >>> 0;
|
|
if (lo >>> 0 < aLo >>> 0) {
|
|
hi = hi + 1 | 0;
|
|
}
|
|
out[0] = hi;
|
|
out[1] = lo;
|
|
}
|
|
var YieldWrapTypeId = /* @__PURE__ */ Symbol.for("effect/Utils/YieldWrap");
|
|
|
|
class YieldWrap {
|
|
#value;
|
|
constructor(value) {
|
|
this.#value = value;
|
|
}
|
|
[YieldWrapTypeId]() {
|
|
return this.#value;
|
|
}
|
|
}
|
|
function yieldWrapGet(self2) {
|
|
if (typeof self2 === "object" && self2 !== null && YieldWrapTypeId in self2) {
|
|
return self2[YieldWrapTypeId]();
|
|
}
|
|
throw new Error(getBugErrorMessage("yieldWrapGet"));
|
|
}
|
|
var structuralRegionState = /* @__PURE__ */ globalValue("effect/Utils/isStructuralRegion", () => ({
|
|
enabled: false,
|
|
tester: undefined
|
|
}));
|
|
var standard = {
|
|
effect_internal_function: (body) => {
|
|
return body();
|
|
}
|
|
};
|
|
var forced = {
|
|
effect_internal_function: (body) => {
|
|
try {
|
|
return body();
|
|
} finally {}
|
|
}
|
|
};
|
|
var isNotOptimizedAway = /* @__PURE__ */ standard.effect_internal_function(() => new Error().stack)?.includes("effect_internal_function") === true;
|
|
var internalCall = isNotOptimizedAway ? standard.effect_internal_function : forced.effect_internal_function;
|
|
var genConstructor = function* () {}.constructor;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Hash.js
|
|
var randomHashCache = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/Hash/randomHashCache"), () => new WeakMap);
|
|
var symbol = /* @__PURE__ */ Symbol.for("effect/Hash");
|
|
var hash = (self2) => {
|
|
if (structuralRegionState.enabled === true) {
|
|
return 0;
|
|
}
|
|
switch (typeof self2) {
|
|
case "number":
|
|
return number2(self2);
|
|
case "bigint":
|
|
return string(self2.toString(10));
|
|
case "boolean":
|
|
return string(String(self2));
|
|
case "symbol":
|
|
return string(String(self2));
|
|
case "string":
|
|
return string(self2);
|
|
case "undefined":
|
|
return string("undefined");
|
|
case "function":
|
|
case "object": {
|
|
if (self2 === null) {
|
|
return string("null");
|
|
} else if (self2 instanceof Date) {
|
|
if (Number.isNaN(self2.getTime())) {
|
|
return string("Invalid Date");
|
|
}
|
|
return hash(self2.toISOString());
|
|
} else if (self2 instanceof URL) {
|
|
return hash(self2.href);
|
|
} else if (isHash(self2)) {
|
|
return self2[symbol]();
|
|
} else {
|
|
return random(self2);
|
|
}
|
|
}
|
|
default:
|
|
throw new Error(`BUG: unhandled typeof ${typeof self2} - please report an issue at https://github.com/Effect-TS/effect/issues`);
|
|
}
|
|
};
|
|
var random = (self2) => {
|
|
if (!randomHashCache.has(self2)) {
|
|
randomHashCache.set(self2, number2(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)));
|
|
}
|
|
return randomHashCache.get(self2);
|
|
};
|
|
var combine = (b) => (self2) => self2 * 53 ^ b;
|
|
var optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824;
|
|
var isHash = (u) => hasProperty(u, symbol);
|
|
var number2 = (n) => {
|
|
if (n !== n || n === Infinity) {
|
|
return 0;
|
|
}
|
|
let h = n | 0;
|
|
if (h !== n) {
|
|
h ^= n * 4294967295;
|
|
}
|
|
while (n > 4294967295) {
|
|
h ^= n /= 4294967295;
|
|
}
|
|
return optimize(h);
|
|
};
|
|
var string = (str) => {
|
|
let h = 5381, i = str.length;
|
|
while (i) {
|
|
h = h * 33 ^ str.charCodeAt(--i);
|
|
}
|
|
return optimize(h);
|
|
};
|
|
var structureKeys = (o, keys) => {
|
|
let h = 12289;
|
|
for (let i = 0;i < keys.length; i++) {
|
|
h ^= pipe(string(keys[i]), combine(hash(o[keys[i]])));
|
|
}
|
|
return optimize(h);
|
|
};
|
|
var structure = (o) => structureKeys(o, Object.keys(o));
|
|
var array2 = (arr) => {
|
|
let h = 6151;
|
|
for (let i = 0;i < arr.length; i++) {
|
|
h = pipe(h, combine(hash(arr[i])));
|
|
}
|
|
return optimize(h);
|
|
};
|
|
var cached = function() {
|
|
if (arguments.length === 1) {
|
|
const self2 = arguments[0];
|
|
return function(hash) {
|
|
Object.defineProperty(self2, symbol, {
|
|
value() {
|
|
return hash;
|
|
},
|
|
enumerable: false
|
|
});
|
|
return hash;
|
|
};
|
|
}
|
|
const self2 = arguments[0];
|
|
const hash = arguments[1];
|
|
Object.defineProperty(self2, symbol, {
|
|
value() {
|
|
return hash;
|
|
},
|
|
enumerable: false
|
|
});
|
|
return hash;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Equal.js
|
|
var symbol2 = /* @__PURE__ */ Symbol.for("effect/Equal");
|
|
function equals() {
|
|
if (arguments.length === 1) {
|
|
return (self2) => compareBoth(self2, arguments[0]);
|
|
}
|
|
return compareBoth(arguments[0], arguments[1]);
|
|
}
|
|
function compareBoth(self2, that) {
|
|
if (self2 === that) {
|
|
return true;
|
|
}
|
|
const selfType = typeof self2;
|
|
if (selfType !== typeof that) {
|
|
return false;
|
|
}
|
|
if (selfType === "object" || selfType === "function") {
|
|
if (self2 !== null && that !== null) {
|
|
if (isEqual(self2) && isEqual(that)) {
|
|
if (hash(self2) === hash(that) && self2[symbol2](that)) {
|
|
return true;
|
|
} else {
|
|
return structuralRegionState.enabled && structuralRegionState.tester ? structuralRegionState.tester(self2, that) : false;
|
|
}
|
|
} else if (self2 instanceof Date && that instanceof Date) {
|
|
const t1 = self2.getTime();
|
|
const t2 = that.getTime();
|
|
return t1 === t2 || Number.isNaN(t1) && Number.isNaN(t2);
|
|
} else if (self2 instanceof URL && that instanceof URL) {
|
|
return self2.href === that.href;
|
|
}
|
|
}
|
|
if (structuralRegionState.enabled) {
|
|
if (self2 === null || that === null) {
|
|
return false;
|
|
}
|
|
if (Array.isArray(self2) && Array.isArray(that)) {
|
|
return self2.length === that.length && self2.every((v, i) => compareBoth(v, that[i]));
|
|
}
|
|
if (Object.getPrototypeOf(self2) === Object.prototype && Object.getPrototypeOf(that) === Object.prototype) {
|
|
const keysSelf = Object.keys(self2);
|
|
const keysThat = Object.keys(that);
|
|
if (keysSelf.length === keysThat.length) {
|
|
for (const key of keysSelf) {
|
|
if (!((key in that) && compareBoth(self2[key], that[key]))) {
|
|
return structuralRegionState.tester ? structuralRegionState.tester(self2, that) : false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
}
|
|
return structuralRegionState.tester ? structuralRegionState.tester(self2, that) : false;
|
|
}
|
|
}
|
|
return structuralRegionState.enabled && structuralRegionState.tester ? structuralRegionState.tester(self2, that) : false;
|
|
}
|
|
var isEqual = (u) => hasProperty(u, symbol2);
|
|
var equivalence = () => equals;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Inspectable.js
|
|
var NodeInspectSymbol = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
|
|
var toJSON = (x) => {
|
|
try {
|
|
if (hasProperty(x, "toJSON") && isFunction2(x["toJSON"]) && x["toJSON"].length === 0) {
|
|
return x.toJSON();
|
|
} else if (Array.isArray(x)) {
|
|
return x.map(toJSON);
|
|
}
|
|
} catch {
|
|
return {};
|
|
}
|
|
return redact(x);
|
|
};
|
|
var CIRCULAR = "[Circular]";
|
|
function formatDate(date) {
|
|
try {
|
|
return date.toISOString();
|
|
} catch {
|
|
return "Invalid Date";
|
|
}
|
|
}
|
|
function safeToString(input) {
|
|
try {
|
|
const s = input.toString();
|
|
return typeof s === "string" ? s : String(s);
|
|
} catch {
|
|
return "[toString threw]";
|
|
}
|
|
}
|
|
function formatPropertyKey(name) {
|
|
return isString(name) ? JSON.stringify(name) : String(name);
|
|
}
|
|
function formatUnknown(input, options) {
|
|
const space = options?.space ?? 0;
|
|
const seen = new WeakSet;
|
|
const gap = !space ? "" : isNumber(space) ? " ".repeat(space) : space;
|
|
const ind = (d) => gap.repeat(d);
|
|
const wrap = (v, body) => {
|
|
const ctor = v?.constructor;
|
|
return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body;
|
|
};
|
|
const ownKeys = (o) => {
|
|
try {
|
|
return Reflect.ownKeys(o);
|
|
} catch {
|
|
return ["[ownKeys threw]"];
|
|
}
|
|
};
|
|
function go(v, d = 0) {
|
|
if (Array.isArray(v)) {
|
|
if (seen.has(v))
|
|
return CIRCULAR;
|
|
seen.add(v);
|
|
if (!gap || v.length <= 1)
|
|
return `[${v.map((x) => go(x, d)).join(",")}]`;
|
|
const inner = v.map((x) => go(x, d + 1)).join(`,
|
|
` + ind(d + 1));
|
|
return `[
|
|
${ind(d + 1)}${inner}
|
|
${ind(d)}]`;
|
|
}
|
|
if (isDate(v))
|
|
return formatDate(v);
|
|
if (!options?.ignoreToString && hasProperty(v, "toString") && isFunction2(v["toString"]) && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) {
|
|
const s = safeToString(v);
|
|
if (v instanceof Error && v.cause) {
|
|
return `${s} (cause: ${go(v.cause, d)})`;
|
|
}
|
|
return s;
|
|
}
|
|
if (isString(v))
|
|
return JSON.stringify(v);
|
|
if (isNumber(v) || v == null || isBoolean(v) || isSymbol(v))
|
|
return String(v);
|
|
if (isBigInt(v))
|
|
return String(v) + "n";
|
|
if (v instanceof Set || v instanceof Map) {
|
|
if (seen.has(v))
|
|
return CIRCULAR;
|
|
seen.add(v);
|
|
return `${v.constructor.name}(${go(Array.from(v), d)})`;
|
|
}
|
|
if (isObject2(v)) {
|
|
if (seen.has(v))
|
|
return CIRCULAR;
|
|
seen.add(v);
|
|
const keys = ownKeys(v);
|
|
if (!gap || keys.length <= 1) {
|
|
const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${go(v[k], d)}`).join(",")}}`;
|
|
return wrap(v, body);
|
|
}
|
|
const body = `{
|
|
${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${go(v[k], d + 1)}`).join(`,
|
|
`)}
|
|
${ind(d)}}`;
|
|
return wrap(v, body);
|
|
}
|
|
return String(v);
|
|
}
|
|
return go(input, 0);
|
|
}
|
|
var format2 = (x) => JSON.stringify(x, null, 2);
|
|
var BaseProto = {
|
|
toJSON() {
|
|
return toJSON(this);
|
|
},
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
},
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
}
|
|
};
|
|
var toStringUnknown = (u, whitespace = 2) => {
|
|
if (typeof u === "string") {
|
|
return u;
|
|
}
|
|
try {
|
|
return typeof u === "object" ? stringifyCircular(u, whitespace) : String(u);
|
|
} catch {
|
|
return String(u);
|
|
}
|
|
};
|
|
var stringifyCircular = (obj, whitespace) => {
|
|
let cache = [];
|
|
const retVal = JSON.stringify(obj, (_key, value) => typeof value === "object" && value !== null ? cache.includes(value) ? undefined : cache.push(value) && (redactableState.fiberRefs !== undefined && isRedactable(value) ? value[symbolRedactable](redactableState.fiberRefs) : value) : value, whitespace);
|
|
cache = undefined;
|
|
return retVal;
|
|
};
|
|
var symbolRedactable = /* @__PURE__ */ Symbol.for("effect/Inspectable/Redactable");
|
|
var isRedactable = (u) => typeof u === "object" && u !== null && (symbolRedactable in u);
|
|
var redactableState = /* @__PURE__ */ globalValue("effect/Inspectable/redactableState", () => ({
|
|
fiberRefs: undefined
|
|
}));
|
|
var withRedactableContext = (context, f) => {
|
|
const prev = redactableState.fiberRefs;
|
|
redactableState.fiberRefs = context;
|
|
try {
|
|
return f();
|
|
} finally {
|
|
redactableState.fiberRefs = prev;
|
|
}
|
|
};
|
|
var redact = (u) => {
|
|
if (isRedactable(u) && redactableState.fiberRefs !== undefined) {
|
|
return u[symbolRedactable](redactableState.fiberRefs);
|
|
}
|
|
return u;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Pipeable.js
|
|
var pipeArguments = (self2, args) => {
|
|
switch (args.length) {
|
|
case 0:
|
|
return self2;
|
|
case 1:
|
|
return args[0](self2);
|
|
case 2:
|
|
return args[1](args[0](self2));
|
|
case 3:
|
|
return args[2](args[1](args[0](self2)));
|
|
case 4:
|
|
return args[3](args[2](args[1](args[0](self2))));
|
|
case 5:
|
|
return args[4](args[3](args[2](args[1](args[0](self2)))));
|
|
case 6:
|
|
return args[5](args[4](args[3](args[2](args[1](args[0](self2))))));
|
|
case 7:
|
|
return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self2)))))));
|
|
case 8:
|
|
return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self2))))))));
|
|
case 9:
|
|
return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self2)))))))));
|
|
default: {
|
|
let ret = self2;
|
|
for (let i = 0, len = args.length;i < len; i++) {
|
|
ret = args[i](ret);
|
|
}
|
|
return ret;
|
|
}
|
|
}
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/opCodes/effect.js
|
|
var OP_ASYNC = "Async";
|
|
var OP_COMMIT = "Commit";
|
|
var OP_FAILURE = "Failure";
|
|
var OP_ON_FAILURE = "OnFailure";
|
|
var OP_ON_SUCCESS = "OnSuccess";
|
|
var OP_ON_SUCCESS_AND_FAILURE = "OnSuccessAndFailure";
|
|
var OP_SUCCESS = "Success";
|
|
var OP_SYNC = "Sync";
|
|
var OP_TAG = "Tag";
|
|
var OP_UPDATE_RUNTIME_FLAGS = "UpdateRuntimeFlags";
|
|
var OP_WHILE = "While";
|
|
var OP_ITERATOR = "Iterator";
|
|
var OP_WITH_RUNTIME = "WithRuntime";
|
|
var OP_YIELD = "Yield";
|
|
var OP_REVERT_FLAGS = "RevertFlags";
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/version.js
|
|
var moduleVersion = "3.22.1";
|
|
var getCurrentVersion = () => moduleVersion;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/effectable.js
|
|
var EffectTypeId = /* @__PURE__ */ Symbol.for("effect/Effect");
|
|
var StreamTypeId = /* @__PURE__ */ Symbol.for("effect/Stream");
|
|
var SinkTypeId = /* @__PURE__ */ Symbol.for("effect/Sink");
|
|
var ChannelTypeId = /* @__PURE__ */ Symbol.for("effect/Channel");
|
|
var effectVariance = {
|
|
_R: (_) => _,
|
|
_E: (_) => _,
|
|
_A: (_) => _,
|
|
_V: /* @__PURE__ */ getCurrentVersion()
|
|
};
|
|
var sinkVariance = {
|
|
_A: (_) => _,
|
|
_In: (_) => _,
|
|
_L: (_) => _,
|
|
_E: (_) => _,
|
|
_R: (_) => _
|
|
};
|
|
var channelVariance = {
|
|
_Env: (_) => _,
|
|
_InErr: (_) => _,
|
|
_InElem: (_) => _,
|
|
_InDone: (_) => _,
|
|
_OutErr: (_) => _,
|
|
_OutElem: (_) => _,
|
|
_OutDone: (_) => _
|
|
};
|
|
var EffectPrototype = {
|
|
[EffectTypeId]: effectVariance,
|
|
[StreamTypeId]: effectVariance,
|
|
[SinkTypeId]: sinkVariance,
|
|
[ChannelTypeId]: channelVariance,
|
|
[symbol2](that) {
|
|
return this === that;
|
|
},
|
|
[symbol]() {
|
|
return cached(this, random(this));
|
|
},
|
|
[Symbol.iterator]() {
|
|
return new SingleShotGen(new YieldWrap(this));
|
|
},
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var StructuralPrototype = {
|
|
[symbol]() {
|
|
return cached(this, structure(this));
|
|
},
|
|
[symbol2](that) {
|
|
const selfKeys = Object.keys(this);
|
|
const thatKeys = Object.keys(that);
|
|
if (selfKeys.length !== thatKeys.length) {
|
|
return false;
|
|
}
|
|
for (const key of selfKeys) {
|
|
if (!((key in that) && equals(this[key], that[key]))) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
};
|
|
var CommitPrototype = {
|
|
...EffectPrototype,
|
|
_op: OP_COMMIT
|
|
};
|
|
var StructuralCommitPrototype = {
|
|
...CommitPrototype,
|
|
...StructuralPrototype
|
|
};
|
|
var Base = /* @__PURE__ */ function() {
|
|
function Base() {}
|
|
Base.prototype = CommitPrototype;
|
|
return Base;
|
|
}();
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/option.js
|
|
var TypeId = /* @__PURE__ */ Symbol.for("effect/Option");
|
|
var CommonProto = {
|
|
...EffectPrototype,
|
|
[TypeId]: {
|
|
_A: (_) => _
|
|
},
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
},
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
}
|
|
};
|
|
var SomeProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(CommonProto), {
|
|
_tag: "Some",
|
|
_op: "Some",
|
|
[symbol2](that) {
|
|
return isOption(that) && isSome(that) && equals(this.value, that.value);
|
|
},
|
|
[symbol]() {
|
|
return cached(this, combine(hash(this._tag))(hash(this.value)));
|
|
},
|
|
toJSON() {
|
|
return {
|
|
_id: "Option",
|
|
_tag: this._tag,
|
|
value: toJSON(this.value)
|
|
};
|
|
}
|
|
});
|
|
var NoneHash = /* @__PURE__ */ hash("None");
|
|
var NoneProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(CommonProto), {
|
|
_tag: "None",
|
|
_op: "None",
|
|
[symbol2](that) {
|
|
return isOption(that) && isNone(that);
|
|
},
|
|
[symbol]() {
|
|
return NoneHash;
|
|
},
|
|
toJSON() {
|
|
return {
|
|
_id: "Option",
|
|
_tag: this._tag
|
|
};
|
|
}
|
|
});
|
|
var isOption = (input) => hasProperty(input, TypeId);
|
|
var isNone = (fa) => fa._tag === "None";
|
|
var isSome = (fa) => fa._tag === "Some";
|
|
var none = /* @__PURE__ */ Object.create(NoneProto);
|
|
var some = (value) => {
|
|
const a = Object.create(SomeProto);
|
|
a.value = value;
|
|
return a;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/either.js
|
|
var TypeId2 = /* @__PURE__ */ Symbol.for("effect/Either");
|
|
var CommonProto2 = {
|
|
...EffectPrototype,
|
|
[TypeId2]: {
|
|
_R: (_) => _
|
|
},
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
},
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
}
|
|
};
|
|
var RightProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(CommonProto2), {
|
|
_tag: "Right",
|
|
_op: "Right",
|
|
[symbol2](that) {
|
|
return isEither(that) && isRight(that) && equals(this.right, that.right);
|
|
},
|
|
[symbol]() {
|
|
return combine(hash(this._tag))(hash(this.right));
|
|
},
|
|
toJSON() {
|
|
return {
|
|
_id: "Either",
|
|
_tag: this._tag,
|
|
right: toJSON(this.right)
|
|
};
|
|
}
|
|
});
|
|
var LeftProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(CommonProto2), {
|
|
_tag: "Left",
|
|
_op: "Left",
|
|
[symbol2](that) {
|
|
return isEither(that) && isLeft(that) && equals(this.left, that.left);
|
|
},
|
|
[symbol]() {
|
|
return combine(hash(this._tag))(hash(this.left));
|
|
},
|
|
toJSON() {
|
|
return {
|
|
_id: "Either",
|
|
_tag: this._tag,
|
|
left: toJSON(this.left)
|
|
};
|
|
}
|
|
});
|
|
var isEither = (input) => hasProperty(input, TypeId2);
|
|
var isLeft = (ma) => ma._tag === "Left";
|
|
var isRight = (ma) => ma._tag === "Right";
|
|
var left = (left) => {
|
|
const a = Object.create(LeftProto);
|
|
a.left = left;
|
|
return a;
|
|
};
|
|
var right = (right) => {
|
|
const a = Object.create(RightProto);
|
|
a.right = right;
|
|
return a;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Either.js
|
|
var right2 = right;
|
|
var left2 = left;
|
|
var try_ = (evaluate) => {
|
|
if (isFunction2(evaluate)) {
|
|
try {
|
|
return right2(evaluate());
|
|
} catch (e) {
|
|
return left2(e);
|
|
}
|
|
} else {
|
|
try {
|
|
return right2(evaluate.try());
|
|
} catch (e) {
|
|
return left2(evaluate.catch(e));
|
|
}
|
|
}
|
|
};
|
|
var isEither2 = isEither;
|
|
var isLeft2 = isLeft;
|
|
var isRight2 = isRight;
|
|
var mapLeft = /* @__PURE__ */ dual(2, (self2, f) => isLeft2(self2) ? left2(f(self2.left)) : right2(self2.right));
|
|
var map = /* @__PURE__ */ dual(2, (self2, f) => isRight2(self2) ? right2(f(self2.right)) : left2(self2.left));
|
|
var match = /* @__PURE__ */ dual(2, (self2, {
|
|
onLeft,
|
|
onRight
|
|
}) => isLeft2(self2) ? onLeft(self2.left) : onRight(self2.right));
|
|
var merge = /* @__PURE__ */ match({
|
|
onLeft: identity,
|
|
onRight: identity
|
|
});
|
|
var getOrThrowWith = /* @__PURE__ */ dual(2, (self2, onLeft) => {
|
|
if (isRight2(self2)) {
|
|
return self2.right;
|
|
}
|
|
throw onLeft(self2.left);
|
|
});
|
|
var getOrThrow = /* @__PURE__ */ getOrThrowWith(() => new Error("getOrThrow called on a Left"));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/array.js
|
|
var isNonEmptyArray = (self2) => self2.length > 0;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Order.js
|
|
var make2 = (compare) => (self2, that) => self2 === that ? 0 : compare(self2, that);
|
|
var number3 = /* @__PURE__ */ make2((self2, that) => self2 < that ? -1 : 1);
|
|
var mapInput2 = /* @__PURE__ */ dual(2, (self2, f) => make2((b1, b2) => self2(f(b1), f(b2))));
|
|
var greaterThan = (O) => dual(2, (self2, that) => O(self2, that) === 1);
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Option.js
|
|
var none2 = () => none;
|
|
var some2 = some;
|
|
var isNone2 = isNone;
|
|
var isSome2 = isSome;
|
|
var match2 = /* @__PURE__ */ dual(2, (self2, {
|
|
onNone,
|
|
onSome
|
|
}) => isNone2(self2) ? onNone() : onSome(self2.value));
|
|
var getOrElse = /* @__PURE__ */ dual(2, (self2, onNone) => isNone2(self2) ? onNone() : self2.value);
|
|
var orElse = /* @__PURE__ */ dual(2, (self2, that) => isNone2(self2) ? that() : self2);
|
|
var orElseSome = /* @__PURE__ */ dual(2, (self2, onNone) => isNone2(self2) ? some2(onNone()) : self2);
|
|
var fromNullable = (nullableValue) => nullableValue == null ? none2() : some2(nullableValue);
|
|
var getOrUndefined = /* @__PURE__ */ getOrElse(constUndefined);
|
|
var liftThrowable = (f) => (...a) => {
|
|
try {
|
|
return some2(f(...a));
|
|
} catch {
|
|
return none2();
|
|
}
|
|
};
|
|
var map2 = /* @__PURE__ */ dual(2, (self2, f) => isNone2(self2) ? none2() : some2(f(self2.value)));
|
|
var flatMap = /* @__PURE__ */ dual(2, (self2, f) => isNone2(self2) ? none2() : f(self2.value));
|
|
var flatMapNullable = /* @__PURE__ */ dual(2, (self2, f) => isNone2(self2) ? none2() : fromNullable(f(self2.value)));
|
|
var containsWith = (isEquivalent) => dual(2, (self2, a) => isNone2(self2) ? false : isEquivalent(self2.value, a));
|
|
var _equivalence = /* @__PURE__ */ equivalence();
|
|
var contains = /* @__PURE__ */ containsWith(_equivalence);
|
|
var exists = /* @__PURE__ */ dual(2, (self2, refinement) => isNone2(self2) ? false : refinement(self2.value));
|
|
var mergeWith = (f) => (o1, o2) => {
|
|
if (isNone2(o1)) {
|
|
return o2;
|
|
} else if (isNone2(o2)) {
|
|
return o1;
|
|
}
|
|
return some2(f(o1.value, o2.value));
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Tuple.js
|
|
var make3 = (...elements) => elements;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Array.js
|
|
var allocate = (n) => new Array(n);
|
|
var makeBy = /* @__PURE__ */ dual(2, (n, f) => {
|
|
const max = Math.max(1, Math.floor(n));
|
|
const out = new Array(max);
|
|
for (let i = 0;i < max; i++) {
|
|
out[i] = f(i);
|
|
}
|
|
return out;
|
|
});
|
|
var fromIterable = (collection) => Array.isArray(collection) ? collection : Array.from(collection);
|
|
var ensure = (self2) => Array.isArray(self2) ? self2 : [self2];
|
|
var matchLeft = /* @__PURE__ */ dual(2, (self2, {
|
|
onEmpty,
|
|
onNonEmpty
|
|
}) => isNonEmptyReadonlyArray(self2) ? onNonEmpty(headNonEmpty(self2), tailNonEmpty(self2)) : onEmpty());
|
|
var prepend = /* @__PURE__ */ dual(2, (self2, head) => [head, ...self2]);
|
|
var append = /* @__PURE__ */ dual(2, (self2, last) => [...self2, last]);
|
|
var appendAll = /* @__PURE__ */ dual(2, (self2, that) => fromIterable(self2).concat(fromIterable(that)));
|
|
var isArray = Array.isArray;
|
|
var isEmptyArray = (self2) => self2.length === 0;
|
|
var isEmptyReadonlyArray = isEmptyArray;
|
|
var isNonEmptyArray2 = isNonEmptyArray;
|
|
var isNonEmptyReadonlyArray = isNonEmptyArray;
|
|
var isOutOfBounds = (i, as) => i < 0 || i >= as.length;
|
|
var clamp = (i, as) => Math.floor(Math.min(Math.max(0, i), as.length));
|
|
var get = /* @__PURE__ */ dual(2, (self2, index) => {
|
|
const i = Math.floor(index);
|
|
return isOutOfBounds(i, self2) ? none2() : some2(self2[i]);
|
|
});
|
|
var unsafeGet = /* @__PURE__ */ dual(2, (self2, index) => {
|
|
const i = Math.floor(index);
|
|
if (isOutOfBounds(i, self2)) {
|
|
throw new Error(`Index ${i} out of bounds`);
|
|
}
|
|
return self2[i];
|
|
});
|
|
var head = /* @__PURE__ */ get(0);
|
|
var headNonEmpty = /* @__PURE__ */ unsafeGet(0);
|
|
var last = (self2) => isNonEmptyReadonlyArray(self2) ? some2(lastNonEmpty(self2)) : none2();
|
|
var lastNonEmpty = (self2) => self2[self2.length - 1];
|
|
var tailNonEmpty = (self2) => self2.slice(1);
|
|
var spanIndex = (self2, predicate) => {
|
|
let i = 0;
|
|
for (const a of self2) {
|
|
if (!predicate(a, i)) {
|
|
break;
|
|
}
|
|
i++;
|
|
}
|
|
return i;
|
|
};
|
|
var span = /* @__PURE__ */ dual(2, (self2, predicate) => splitAt(self2, spanIndex(self2, predicate)));
|
|
var drop = /* @__PURE__ */ dual(2, (self2, n) => {
|
|
const input = fromIterable(self2);
|
|
return input.slice(clamp(n, input), input.length);
|
|
});
|
|
var reverse = (self2) => Array.from(self2).reverse();
|
|
var sort = /* @__PURE__ */ dual(2, (self2, O) => {
|
|
const out = Array.from(self2);
|
|
out.sort(O);
|
|
return out;
|
|
});
|
|
var zip = /* @__PURE__ */ dual(2, (self2, that) => zipWith(self2, that, make3));
|
|
var zipWith = /* @__PURE__ */ dual(3, (self2, that, f) => {
|
|
const as = fromIterable(self2);
|
|
const bs = fromIterable(that);
|
|
if (isNonEmptyReadonlyArray(as) && isNonEmptyReadonlyArray(bs)) {
|
|
const out = [f(headNonEmpty(as), headNonEmpty(bs))];
|
|
const len = Math.min(as.length, bs.length);
|
|
for (let i = 1;i < len; i++) {
|
|
out[i] = f(as[i], bs[i]);
|
|
}
|
|
return out;
|
|
}
|
|
return [];
|
|
});
|
|
var _equivalence2 = /* @__PURE__ */ equivalence();
|
|
var splitAt = /* @__PURE__ */ dual(2, (self2, n) => {
|
|
const input = Array.from(self2);
|
|
const _n = Math.floor(n);
|
|
if (isNonEmptyReadonlyArray(input)) {
|
|
if (_n >= 1) {
|
|
return splitNonEmptyAt(input, _n);
|
|
}
|
|
return [[], input];
|
|
}
|
|
return [input, []];
|
|
});
|
|
var splitNonEmptyAt = /* @__PURE__ */ dual(2, (self2, n) => {
|
|
const _n = Math.max(1, Math.floor(n));
|
|
return _n >= self2.length ? [copy(self2), []] : [prepend(self2.slice(1, _n), headNonEmpty(self2)), self2.slice(_n)];
|
|
});
|
|
var copy = (self2) => self2.slice();
|
|
var unionWith = /* @__PURE__ */ dual(3, (self2, that, isEquivalent) => {
|
|
const a = fromIterable(self2);
|
|
const b = fromIterable(that);
|
|
if (isNonEmptyReadonlyArray(a)) {
|
|
if (isNonEmptyReadonlyArray(b)) {
|
|
const dedupe = dedupeWith(isEquivalent);
|
|
return dedupe(appendAll(a, b));
|
|
}
|
|
return a;
|
|
}
|
|
return b;
|
|
});
|
|
var union = /* @__PURE__ */ dual(2, (self2, that) => unionWith(self2, that, _equivalence2));
|
|
var empty = () => [];
|
|
var of = (a) => [a];
|
|
var map3 = /* @__PURE__ */ dual(2, (self2, f) => self2.map(f));
|
|
var flatMap2 = /* @__PURE__ */ dual(2, (self2, f) => {
|
|
if (isEmptyReadonlyArray(self2)) {
|
|
return [];
|
|
}
|
|
const out = [];
|
|
for (let i = 0;i < self2.length; i++) {
|
|
const inner = f(self2[i], i);
|
|
for (let j = 0;j < inner.length; j++) {
|
|
out.push(inner[j]);
|
|
}
|
|
}
|
|
return out;
|
|
});
|
|
var flatten = /* @__PURE__ */ flatMap2(identity);
|
|
var filterMap = /* @__PURE__ */ dual(2, (self2, f) => {
|
|
const as = fromIterable(self2);
|
|
const out = [];
|
|
for (let i = 0;i < as.length; i++) {
|
|
const o = f(as[i], i);
|
|
if (isSome2(o)) {
|
|
out.push(o.value);
|
|
}
|
|
}
|
|
return out;
|
|
});
|
|
var filter = /* @__PURE__ */ dual(2, (self2, predicate) => {
|
|
const as = fromIterable(self2);
|
|
const out = [];
|
|
for (let i = 0;i < as.length; i++) {
|
|
if (predicate(as[i], i)) {
|
|
out.push(as[i]);
|
|
}
|
|
}
|
|
return out;
|
|
});
|
|
var reduce = /* @__PURE__ */ dual(3, (self2, b, f) => fromIterable(self2).reduce((b, a, i) => f(b, a, i), b));
|
|
var unfold = (b, f) => {
|
|
const out = [];
|
|
let next = b;
|
|
let o;
|
|
while (isSome2(o = f(next))) {
|
|
const [a, b] = o.value;
|
|
out.push(a);
|
|
next = b;
|
|
}
|
|
return out;
|
|
};
|
|
var getEquivalence = array;
|
|
var dedupeWith = /* @__PURE__ */ dual(2, (self2, isEquivalent) => {
|
|
const input = fromIterable(self2);
|
|
if (isNonEmptyReadonlyArray(input)) {
|
|
const out = [headNonEmpty(input)];
|
|
const rest = tailNonEmpty(input);
|
|
for (const r of rest) {
|
|
if (out.every((a) => !isEquivalent(r, a))) {
|
|
out.push(r);
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
return [];
|
|
});
|
|
var dedupe = (self2) => dedupeWith(self2, equivalence());
|
|
var join = /* @__PURE__ */ dual(2, (self2, sep) => fromIterable(self2).join(sep));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Brand.js
|
|
var RefinedConstructorsTypeId = /* @__PURE__ */ Symbol.for("effect/Brand/Refined");
|
|
var nominal = () => {
|
|
return Object.assign((args) => args, {
|
|
[RefinedConstructorsTypeId]: RefinedConstructorsTypeId,
|
|
option: (args) => some2(args),
|
|
either: (args) => right2(args),
|
|
is: (_args) => true
|
|
});
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/context.js
|
|
var TagTypeId = /* @__PURE__ */ Symbol.for("effect/Context/Tag");
|
|
var ReferenceTypeId = /* @__PURE__ */ Symbol.for("effect/Context/Reference");
|
|
var STMSymbolKey = "effect/STM";
|
|
var STMTypeId = /* @__PURE__ */ Symbol.for(STMSymbolKey);
|
|
var TagProto = {
|
|
...EffectPrototype,
|
|
_op: "Tag",
|
|
[STMTypeId]: effectVariance,
|
|
[TagTypeId]: {
|
|
_Service: (_) => _,
|
|
_Identifier: (_) => _
|
|
},
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
},
|
|
toJSON() {
|
|
return {
|
|
_id: "Tag",
|
|
key: this.key,
|
|
stack: this.stack
|
|
};
|
|
},
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
},
|
|
of(self2) {
|
|
return self2;
|
|
},
|
|
context(self2) {
|
|
return make4(this, self2);
|
|
}
|
|
};
|
|
var ReferenceProto = {
|
|
...TagProto,
|
|
[ReferenceTypeId]: ReferenceTypeId
|
|
};
|
|
var makeGenericTag = (key) => {
|
|
const limit = Error.stackTraceLimit;
|
|
Error.stackTraceLimit = 2;
|
|
const creationError = new Error;
|
|
Error.stackTraceLimit = limit;
|
|
const tag = Object.create(TagProto);
|
|
Object.defineProperty(tag, "stack", {
|
|
get() {
|
|
return creationError.stack;
|
|
}
|
|
});
|
|
tag.key = key;
|
|
return tag;
|
|
};
|
|
var Tag = (id) => () => {
|
|
const limit = Error.stackTraceLimit;
|
|
Error.stackTraceLimit = 2;
|
|
const creationError = new Error;
|
|
Error.stackTraceLimit = limit;
|
|
function TagClass() {}
|
|
Object.setPrototypeOf(TagClass, TagProto);
|
|
TagClass.key = id;
|
|
Object.defineProperty(TagClass, "stack", {
|
|
get() {
|
|
return creationError.stack;
|
|
}
|
|
});
|
|
return TagClass;
|
|
};
|
|
var Reference = () => (id, options) => {
|
|
const limit = Error.stackTraceLimit;
|
|
Error.stackTraceLimit = 2;
|
|
const creationError = new Error;
|
|
Error.stackTraceLimit = limit;
|
|
function ReferenceClass() {}
|
|
Object.setPrototypeOf(ReferenceClass, ReferenceProto);
|
|
ReferenceClass.key = id;
|
|
ReferenceClass.defaultValue = options.defaultValue;
|
|
Object.defineProperty(ReferenceClass, "stack", {
|
|
get() {
|
|
return creationError.stack;
|
|
}
|
|
});
|
|
return ReferenceClass;
|
|
};
|
|
var TypeId3 = /* @__PURE__ */ Symbol.for("effect/Context");
|
|
var ContextProto = {
|
|
[TypeId3]: {
|
|
_Services: (_) => _
|
|
},
|
|
[symbol2](that) {
|
|
if (isContext(that)) {
|
|
if (this.unsafeMap.size === that.unsafeMap.size) {
|
|
for (const k of this.unsafeMap.keys()) {
|
|
if (!that.unsafeMap.has(k) || !equals(this.unsafeMap.get(k), that.unsafeMap.get(k))) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
},
|
|
[symbol]() {
|
|
return cached(this, number2(this.unsafeMap.size));
|
|
},
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
},
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
},
|
|
toJSON() {
|
|
return {
|
|
_id: "Context",
|
|
services: Array.from(this.unsafeMap).map(toJSON)
|
|
};
|
|
},
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
}
|
|
};
|
|
var makeContext = (unsafeMap) => {
|
|
const context = Object.create(ContextProto);
|
|
context.unsafeMap = unsafeMap;
|
|
return context;
|
|
};
|
|
var serviceNotFoundError = (tag) => {
|
|
const error = new Error(`Service not found${tag.key ? `: ${String(tag.key)}` : ""}`);
|
|
if (tag.stack) {
|
|
const lines = tag.stack.split(`
|
|
`);
|
|
if (lines.length > 2) {
|
|
const afterAt = lines[2].match(/at (.*)/);
|
|
if (afterAt) {
|
|
error.message = error.message + ` (defined at ${afterAt[1]})`;
|
|
}
|
|
}
|
|
}
|
|
if (error.stack) {
|
|
const lines = error.stack.split(`
|
|
`);
|
|
lines.splice(1, 3);
|
|
error.stack = lines.join(`
|
|
`);
|
|
}
|
|
return error;
|
|
};
|
|
var isContext = (u) => hasProperty(u, TypeId3);
|
|
var isTag = (u) => hasProperty(u, TagTypeId);
|
|
var isReference = (u) => hasProperty(u, ReferenceTypeId);
|
|
var _empty = /* @__PURE__ */ makeContext(/* @__PURE__ */ new Map);
|
|
var empty2 = () => _empty;
|
|
var make4 = (tag, service) => makeContext(new Map([[tag.key, service]]));
|
|
var add = /* @__PURE__ */ dual(3, (self2, tag, service) => {
|
|
const map = new Map(self2.unsafeMap);
|
|
map.set(tag.key, service);
|
|
return makeContext(map);
|
|
});
|
|
var defaultValueCache = /* @__PURE__ */ globalValue("effect/Context/defaultValueCache", () => new Map);
|
|
var getDefaultValue = (tag) => {
|
|
if (defaultValueCache.has(tag.key)) {
|
|
return defaultValueCache.get(tag.key);
|
|
}
|
|
const value = tag.defaultValue();
|
|
defaultValueCache.set(tag.key, value);
|
|
return value;
|
|
};
|
|
var unsafeGetReference = (self2, tag) => {
|
|
return self2.unsafeMap.has(tag.key) ? self2.unsafeMap.get(tag.key) : getDefaultValue(tag);
|
|
};
|
|
var unsafeGet2 = /* @__PURE__ */ dual(2, (self2, tag) => {
|
|
if (!self2.unsafeMap.has(tag.key)) {
|
|
if (ReferenceTypeId in tag)
|
|
return getDefaultValue(tag);
|
|
throw serviceNotFoundError(tag);
|
|
}
|
|
return self2.unsafeMap.get(tag.key);
|
|
});
|
|
var get2 = unsafeGet2;
|
|
var getOption = /* @__PURE__ */ dual(2, (self2, tag) => {
|
|
if (!self2.unsafeMap.has(tag.key)) {
|
|
return isReference(tag) ? some(getDefaultValue(tag)) : none;
|
|
}
|
|
return some(self2.unsafeMap.get(tag.key));
|
|
});
|
|
var merge2 = /* @__PURE__ */ dual(2, (self2, that) => {
|
|
const map = new Map(self2.unsafeMap);
|
|
for (const [tag, s] of that.unsafeMap) {
|
|
map.set(tag, s);
|
|
}
|
|
return makeContext(map);
|
|
});
|
|
var mergeAll = (...ctxs) => {
|
|
const map = new Map;
|
|
for (let i = 0;i < ctxs.length; i++) {
|
|
ctxs[i].unsafeMap.forEach((value, key) => {
|
|
map.set(key, value);
|
|
});
|
|
}
|
|
return makeContext(map);
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Context.js
|
|
var GenericTag = makeGenericTag;
|
|
var isContext2 = isContext;
|
|
var isTag2 = isTag;
|
|
var empty3 = empty2;
|
|
var make5 = make4;
|
|
var add2 = add;
|
|
var get3 = get2;
|
|
var unsafeGet3 = unsafeGet2;
|
|
var getOption2 = getOption;
|
|
var merge3 = merge2;
|
|
var mergeAll2 = mergeAll;
|
|
var Tag2 = Tag;
|
|
var Reference2 = Reference;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Chunk.js
|
|
var TypeId4 = /* @__PURE__ */ Symbol.for("effect/Chunk");
|
|
function copy2(src, srcPos, dest, destPos, len) {
|
|
for (let i = srcPos;i < Math.min(src.length, srcPos + len); i++) {
|
|
dest[destPos + i - srcPos] = src[i];
|
|
}
|
|
return dest;
|
|
}
|
|
var emptyArray = [];
|
|
var getEquivalence2 = (isEquivalent) => make((self2, that) => self2.length === that.length && toReadonlyArray(self2).every((value, i) => isEquivalent(value, unsafeGet4(that, i))));
|
|
var _equivalence3 = /* @__PURE__ */ getEquivalence2(equals);
|
|
var ChunkProto = {
|
|
[TypeId4]: {
|
|
_A: (_) => _
|
|
},
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
},
|
|
toJSON() {
|
|
return {
|
|
_id: "Chunk",
|
|
values: toReadonlyArray(this).map(toJSON)
|
|
};
|
|
},
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
},
|
|
[symbol2](that) {
|
|
return isChunk(that) && _equivalence3(this, that);
|
|
},
|
|
[symbol]() {
|
|
return cached(this, array2(toReadonlyArray(this)));
|
|
},
|
|
[Symbol.iterator]() {
|
|
switch (this.backing._tag) {
|
|
case "IArray": {
|
|
return this.backing.array[Symbol.iterator]();
|
|
}
|
|
case "IEmpty": {
|
|
return emptyArray[Symbol.iterator]();
|
|
}
|
|
default: {
|
|
return toReadonlyArray(this)[Symbol.iterator]();
|
|
}
|
|
}
|
|
},
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var makeChunk = (backing) => {
|
|
const chunk = Object.create(ChunkProto);
|
|
chunk.backing = backing;
|
|
switch (backing._tag) {
|
|
case "IEmpty": {
|
|
chunk.length = 0;
|
|
chunk.depth = 0;
|
|
chunk.left = chunk;
|
|
chunk.right = chunk;
|
|
break;
|
|
}
|
|
case "IConcat": {
|
|
chunk.length = backing.left.length + backing.right.length;
|
|
chunk.depth = 1 + Math.max(backing.left.depth, backing.right.depth);
|
|
chunk.left = backing.left;
|
|
chunk.right = backing.right;
|
|
break;
|
|
}
|
|
case "IArray": {
|
|
chunk.length = backing.array.length;
|
|
chunk.depth = 0;
|
|
chunk.left = _empty2;
|
|
chunk.right = _empty2;
|
|
break;
|
|
}
|
|
case "ISingleton": {
|
|
chunk.length = 1;
|
|
chunk.depth = 0;
|
|
chunk.left = _empty2;
|
|
chunk.right = _empty2;
|
|
break;
|
|
}
|
|
case "ISlice": {
|
|
chunk.length = backing.length;
|
|
chunk.depth = backing.chunk.depth + 1;
|
|
chunk.left = _empty2;
|
|
chunk.right = _empty2;
|
|
break;
|
|
}
|
|
}
|
|
return chunk;
|
|
};
|
|
var isChunk = (u) => hasProperty(u, TypeId4);
|
|
var _empty2 = /* @__PURE__ */ makeChunk({
|
|
_tag: "IEmpty"
|
|
});
|
|
var empty4 = () => _empty2;
|
|
var make6 = (...as) => unsafeFromNonEmptyArray(as);
|
|
var of2 = (a) => makeChunk({
|
|
_tag: "ISingleton",
|
|
a
|
|
});
|
|
var fromIterable2 = (self2) => isChunk(self2) ? self2 : unsafeFromArray(fromIterable(self2));
|
|
var copyToArray = (self2, array, initial) => {
|
|
switch (self2.backing._tag) {
|
|
case "IArray": {
|
|
copy2(self2.backing.array, 0, array, initial, self2.length);
|
|
break;
|
|
}
|
|
case "IConcat": {
|
|
copyToArray(self2.left, array, initial);
|
|
copyToArray(self2.right, array, initial + self2.left.length);
|
|
break;
|
|
}
|
|
case "ISingleton": {
|
|
array[initial] = self2.backing.a;
|
|
break;
|
|
}
|
|
case "ISlice": {
|
|
let i = 0;
|
|
let j = initial;
|
|
while (i < self2.length) {
|
|
array[j] = unsafeGet4(self2, i);
|
|
i += 1;
|
|
j += 1;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
};
|
|
var toReadonlyArray_ = (self2) => {
|
|
switch (self2.backing._tag) {
|
|
case "IEmpty": {
|
|
return emptyArray;
|
|
}
|
|
case "IArray": {
|
|
return self2.backing.array;
|
|
}
|
|
default: {
|
|
const arr = new Array(self2.length);
|
|
copyToArray(self2, arr, 0);
|
|
self2.backing = {
|
|
_tag: "IArray",
|
|
array: arr
|
|
};
|
|
self2.left = _empty2;
|
|
self2.right = _empty2;
|
|
self2.depth = 0;
|
|
return arr;
|
|
}
|
|
}
|
|
};
|
|
var toReadonlyArray = toReadonlyArray_;
|
|
var reverseChunk = (self2) => {
|
|
switch (self2.backing._tag) {
|
|
case "IEmpty":
|
|
case "ISingleton":
|
|
return self2;
|
|
case "IArray": {
|
|
return makeChunk({
|
|
_tag: "IArray",
|
|
array: reverse(self2.backing.array)
|
|
});
|
|
}
|
|
case "IConcat": {
|
|
return makeChunk({
|
|
_tag: "IConcat",
|
|
left: reverse2(self2.backing.right),
|
|
right: reverse2(self2.backing.left)
|
|
});
|
|
}
|
|
case "ISlice":
|
|
return unsafeFromArray(reverse(toReadonlyArray(self2)));
|
|
}
|
|
};
|
|
var reverse2 = reverseChunk;
|
|
var get4 = /* @__PURE__ */ dual(2, (self2, index) => index < 0 || index >= self2.length ? none2() : some2(unsafeGet4(self2, index)));
|
|
var unsafeFromArray = (self2) => self2.length === 0 ? empty4() : self2.length === 1 ? of2(self2[0]) : makeChunk({
|
|
_tag: "IArray",
|
|
array: self2
|
|
});
|
|
var unsafeFromNonEmptyArray = (self2) => unsafeFromArray(self2);
|
|
var unsafeGet4 = /* @__PURE__ */ dual(2, (self2, index) => {
|
|
switch (self2.backing._tag) {
|
|
case "IEmpty": {
|
|
throw new Error(`Index out of bounds`);
|
|
}
|
|
case "ISingleton": {
|
|
if (index !== 0) {
|
|
throw new Error(`Index out of bounds`);
|
|
}
|
|
return self2.backing.a;
|
|
}
|
|
case "IArray": {
|
|
if (index >= self2.length || index < 0) {
|
|
throw new Error(`Index out of bounds`);
|
|
}
|
|
return self2.backing.array[index];
|
|
}
|
|
case "IConcat": {
|
|
return index < self2.left.length ? unsafeGet4(self2.left, index) : unsafeGet4(self2.right, index - self2.left.length);
|
|
}
|
|
case "ISlice": {
|
|
return unsafeGet4(self2.backing.chunk, index + self2.backing.offset);
|
|
}
|
|
}
|
|
});
|
|
var append2 = /* @__PURE__ */ dual(2, (self2, a) => appendAll2(self2, of2(a)));
|
|
var prepend2 = /* @__PURE__ */ dual(2, (self2, elem) => appendAll2(of2(elem), self2));
|
|
var drop2 = /* @__PURE__ */ dual(2, (self2, n) => {
|
|
if (n <= 0) {
|
|
return self2;
|
|
} else if (n >= self2.length) {
|
|
return _empty2;
|
|
} else {
|
|
switch (self2.backing._tag) {
|
|
case "ISlice": {
|
|
return makeChunk({
|
|
_tag: "ISlice",
|
|
chunk: self2.backing.chunk,
|
|
offset: self2.backing.offset + n,
|
|
length: self2.backing.length - n
|
|
});
|
|
}
|
|
case "IConcat": {
|
|
if (n > self2.left.length) {
|
|
return drop2(self2.right, n - self2.left.length);
|
|
}
|
|
return makeChunk({
|
|
_tag: "IConcat",
|
|
left: drop2(self2.left, n),
|
|
right: self2.right
|
|
});
|
|
}
|
|
default: {
|
|
return makeChunk({
|
|
_tag: "ISlice",
|
|
chunk: self2,
|
|
offset: n,
|
|
length: self2.length - n
|
|
});
|
|
}
|
|
}
|
|
}
|
|
});
|
|
var appendAll2 = /* @__PURE__ */ dual(2, (self2, that) => {
|
|
if (self2.backing._tag === "IEmpty") {
|
|
return that;
|
|
}
|
|
if (that.backing._tag === "IEmpty") {
|
|
return self2;
|
|
}
|
|
const diff = that.depth - self2.depth;
|
|
if (Math.abs(diff) <= 1) {
|
|
return makeChunk({
|
|
_tag: "IConcat",
|
|
left: self2,
|
|
right: that
|
|
});
|
|
} else if (diff < -1) {
|
|
if (self2.left.depth >= self2.right.depth) {
|
|
const nr = appendAll2(self2.right, that);
|
|
return makeChunk({
|
|
_tag: "IConcat",
|
|
left: self2.left,
|
|
right: nr
|
|
});
|
|
} else {
|
|
const nrr = appendAll2(self2.right.right, that);
|
|
if (nrr.depth === self2.depth - 3) {
|
|
const nr = makeChunk({
|
|
_tag: "IConcat",
|
|
left: self2.right.left,
|
|
right: nrr
|
|
});
|
|
return makeChunk({
|
|
_tag: "IConcat",
|
|
left: self2.left,
|
|
right: nr
|
|
});
|
|
} else {
|
|
const nl = makeChunk({
|
|
_tag: "IConcat",
|
|
left: self2.left,
|
|
right: self2.right.left
|
|
});
|
|
return makeChunk({
|
|
_tag: "IConcat",
|
|
left: nl,
|
|
right: nrr
|
|
});
|
|
}
|
|
}
|
|
} else {
|
|
if (that.right.depth >= that.left.depth) {
|
|
const nl = appendAll2(self2, that.left);
|
|
return makeChunk({
|
|
_tag: "IConcat",
|
|
left: nl,
|
|
right: that.right
|
|
});
|
|
} else {
|
|
const nll = appendAll2(self2, that.left.left);
|
|
if (nll.depth === that.depth - 3) {
|
|
const nl = makeChunk({
|
|
_tag: "IConcat",
|
|
left: nll,
|
|
right: that.left.right
|
|
});
|
|
return makeChunk({
|
|
_tag: "IConcat",
|
|
left: nl,
|
|
right: that.right
|
|
});
|
|
} else {
|
|
const nr = makeChunk({
|
|
_tag: "IConcat",
|
|
left: that.left.right,
|
|
right: that.right
|
|
});
|
|
return makeChunk({
|
|
_tag: "IConcat",
|
|
left: nll,
|
|
right: nr
|
|
});
|
|
}
|
|
}
|
|
}
|
|
});
|
|
var filter2 = /* @__PURE__ */ dual(2, (self2, predicate) => unsafeFromArray(filter(self2, predicate)));
|
|
var isEmpty = (self2) => self2.length === 0;
|
|
var isNonEmpty = (self2) => self2.length > 0;
|
|
var head2 = /* @__PURE__ */ get4(0);
|
|
var unsafeHead = (self2) => unsafeGet4(self2, 0);
|
|
var headNonEmpty2 = unsafeHead;
|
|
var map4 = /* @__PURE__ */ dual(2, (self2, f) => self2.backing._tag === "ISingleton" ? of2(f(self2.backing.a, 0)) : unsafeFromArray(pipe(toReadonlyArray(self2), map3((a, i) => f(a, i)))));
|
|
var tailNonEmpty2 = (self2) => drop2(self2, 1);
|
|
var reduce2 = reduce;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Duration.js
|
|
var TypeId5 = /* @__PURE__ */ Symbol.for("effect/Duration");
|
|
var bigint0 = /* @__PURE__ */ BigInt(0);
|
|
var bigint24 = /* @__PURE__ */ BigInt(24);
|
|
var bigint60 = /* @__PURE__ */ BigInt(60);
|
|
var bigint1e3 = /* @__PURE__ */ BigInt(1000);
|
|
var bigint1e6 = /* @__PURE__ */ BigInt(1e6);
|
|
var bigint1e9 = /* @__PURE__ */ BigInt(1e9);
|
|
var DURATION_REGEX = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/;
|
|
var decode = (input) => {
|
|
if (isDuration(input)) {
|
|
return input;
|
|
} else if (isNumber(input)) {
|
|
return millis(input);
|
|
} else if (isBigInt(input)) {
|
|
return nanos(input);
|
|
} else if (Array.isArray(input) && input.length === 2 && input.every(isNumber)) {
|
|
if (input[0] === -Infinity || input[1] === -Infinity || Number.isNaN(input[0]) || Number.isNaN(input[1])) {
|
|
return zero;
|
|
}
|
|
if (input[0] === Infinity || input[1] === Infinity) {
|
|
return infinity;
|
|
}
|
|
return nanos(BigInt(Math.round(input[0] * 1e9)) + BigInt(Math.round(input[1])));
|
|
} else if (isString(input)) {
|
|
const match = DURATION_REGEX.exec(input);
|
|
if (match) {
|
|
const [_, valueStr, unit] = match;
|
|
const value = Number(valueStr);
|
|
switch (unit) {
|
|
case "nano":
|
|
case "nanos":
|
|
return nanos(BigInt(valueStr));
|
|
case "micro":
|
|
case "micros":
|
|
return micros(BigInt(valueStr));
|
|
case "milli":
|
|
case "millis":
|
|
return millis(value);
|
|
case "second":
|
|
case "seconds":
|
|
return seconds(value);
|
|
case "minute":
|
|
case "minutes":
|
|
return minutes(value);
|
|
case "hour":
|
|
case "hours":
|
|
return hours(value);
|
|
case "day":
|
|
case "days":
|
|
return days(value);
|
|
case "week":
|
|
case "weeks":
|
|
return weeks(value);
|
|
}
|
|
}
|
|
}
|
|
throw new Error("Invalid DurationInput");
|
|
};
|
|
var zeroValue = {
|
|
_tag: "Millis",
|
|
millis: 0
|
|
};
|
|
var infinityValue = {
|
|
_tag: "Infinity"
|
|
};
|
|
var DurationProto = {
|
|
[TypeId5]: TypeId5,
|
|
[symbol]() {
|
|
return cached(this, structure(this.value));
|
|
},
|
|
[symbol2](that) {
|
|
return isDuration(that) && equals2(this, that);
|
|
},
|
|
toString() {
|
|
return `Duration(${format3(this)})`;
|
|
},
|
|
toJSON() {
|
|
switch (this.value._tag) {
|
|
case "Millis":
|
|
return {
|
|
_id: "Duration",
|
|
_tag: "Millis",
|
|
millis: this.value.millis
|
|
};
|
|
case "Nanos":
|
|
return {
|
|
_id: "Duration",
|
|
_tag: "Nanos",
|
|
hrtime: toHrTime(this)
|
|
};
|
|
case "Infinity":
|
|
return {
|
|
_id: "Duration",
|
|
_tag: "Infinity"
|
|
};
|
|
}
|
|
},
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
},
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var make7 = (input) => {
|
|
const duration = Object.create(DurationProto);
|
|
if (isNumber(input)) {
|
|
if (isNaN(input) || input <= 0) {
|
|
duration.value = zeroValue;
|
|
} else if (!Number.isFinite(input)) {
|
|
duration.value = infinityValue;
|
|
} else if (!Number.isInteger(input)) {
|
|
duration.value = {
|
|
_tag: "Nanos",
|
|
nanos: BigInt(Math.round(input * 1e6))
|
|
};
|
|
} else {
|
|
duration.value = {
|
|
_tag: "Millis",
|
|
millis: input
|
|
};
|
|
}
|
|
} else if (input <= bigint0) {
|
|
duration.value = zeroValue;
|
|
} else {
|
|
duration.value = {
|
|
_tag: "Nanos",
|
|
nanos: input
|
|
};
|
|
}
|
|
return duration;
|
|
};
|
|
var isDuration = (u) => hasProperty(u, TypeId5);
|
|
var isZero = (self2) => {
|
|
switch (self2.value._tag) {
|
|
case "Millis": {
|
|
return self2.value.millis === 0;
|
|
}
|
|
case "Nanos": {
|
|
return self2.value.nanos === bigint0;
|
|
}
|
|
case "Infinity": {
|
|
return false;
|
|
}
|
|
}
|
|
};
|
|
var zero = /* @__PURE__ */ make7(0);
|
|
var infinity = /* @__PURE__ */ make7(Infinity);
|
|
var nanos = (nanos) => make7(nanos);
|
|
var micros = (micros) => make7(micros * bigint1e3);
|
|
var millis = (millis) => make7(millis);
|
|
var seconds = (seconds) => make7(seconds * 1000);
|
|
var minutes = (minutes) => make7(minutes * 60000);
|
|
var hours = (hours) => make7(hours * 3600000);
|
|
var days = (days) => make7(days * 86400000);
|
|
var weeks = (weeks) => make7(weeks * 604800000);
|
|
var toMillis = (self2) => match3(self2, {
|
|
onMillis: (millis) => millis,
|
|
onNanos: (nanos) => Number(nanos) / 1e6
|
|
});
|
|
var unsafeToNanos = (self2) => {
|
|
const _self = decode(self2);
|
|
switch (_self.value._tag) {
|
|
case "Infinity":
|
|
throw new Error("Cannot convert infinite duration to nanos");
|
|
case "Nanos":
|
|
return _self.value.nanos;
|
|
case "Millis":
|
|
return BigInt(Math.round(_self.value.millis * 1e6));
|
|
}
|
|
};
|
|
var toHrTime = (self2) => {
|
|
const _self = decode(self2);
|
|
switch (_self.value._tag) {
|
|
case "Infinity":
|
|
return [Infinity, 0];
|
|
case "Nanos":
|
|
return [Number(_self.value.nanos / bigint1e9), Number(_self.value.nanos % bigint1e9)];
|
|
case "Millis":
|
|
return [Math.floor(_self.value.millis / 1000), Math.round(_self.value.millis % 1000 * 1e6)];
|
|
}
|
|
};
|
|
var match3 = /* @__PURE__ */ dual(2, (self2, options) => {
|
|
const _self = decode(self2);
|
|
switch (_self.value._tag) {
|
|
case "Nanos":
|
|
return options.onNanos(_self.value.nanos);
|
|
case "Infinity":
|
|
return options.onMillis(Infinity);
|
|
case "Millis":
|
|
return options.onMillis(_self.value.millis);
|
|
}
|
|
});
|
|
var matchWith = /* @__PURE__ */ dual(3, (self2, that, options) => {
|
|
const _self = decode(self2);
|
|
const _that = decode(that);
|
|
if (_self.value._tag === "Infinity" || _that.value._tag === "Infinity") {
|
|
return options.onMillis(toMillis(_self), toMillis(_that));
|
|
} else if (_self.value._tag === "Nanos" || _that.value._tag === "Nanos") {
|
|
const selfNanos = _self.value._tag === "Nanos" ? _self.value.nanos : BigInt(Math.round(_self.value.millis * 1e6));
|
|
const thatNanos = _that.value._tag === "Nanos" ? _that.value.nanos : BigInt(Math.round(_that.value.millis * 1e6));
|
|
return options.onNanos(selfNanos, thatNanos);
|
|
}
|
|
return options.onMillis(_self.value.millis, _that.value.millis);
|
|
});
|
|
var Equivalence = (self2, that) => matchWith(self2, that, {
|
|
onMillis: (self2, that) => self2 === that,
|
|
onNanos: (self2, that) => self2 === that
|
|
});
|
|
var lessThanOrEqualTo = /* @__PURE__ */ dual(2, (self2, that) => matchWith(self2, that, {
|
|
onMillis: (self2, that) => self2 <= that,
|
|
onNanos: (self2, that) => self2 <= that
|
|
}));
|
|
var greaterThanOrEqualTo = /* @__PURE__ */ dual(2, (self2, that) => matchWith(self2, that, {
|
|
onMillis: (self2, that) => self2 >= that,
|
|
onNanos: (self2, that) => self2 >= that
|
|
}));
|
|
var equals2 = /* @__PURE__ */ dual(2, (self2, that) => Equivalence(decode(self2), decode(that)));
|
|
var parts = (self2) => {
|
|
const duration = decode(self2);
|
|
if (duration.value._tag === "Infinity") {
|
|
return {
|
|
days: Infinity,
|
|
hours: Infinity,
|
|
minutes: Infinity,
|
|
seconds: Infinity,
|
|
millis: Infinity,
|
|
nanos: Infinity
|
|
};
|
|
}
|
|
const nanos = unsafeToNanos(duration);
|
|
const ms = nanos / bigint1e6;
|
|
const sec = ms / bigint1e3;
|
|
const min = sec / bigint60;
|
|
const hr = min / bigint60;
|
|
const days = hr / bigint24;
|
|
return {
|
|
days: Number(days),
|
|
hours: Number(hr % bigint24),
|
|
minutes: Number(min % bigint60),
|
|
seconds: Number(sec % bigint60),
|
|
millis: Number(ms % bigint1e3),
|
|
nanos: Number(nanos % bigint1e6)
|
|
};
|
|
};
|
|
var format3 = (self2) => {
|
|
const duration = decode(self2);
|
|
if (duration.value._tag === "Infinity") {
|
|
return "Infinity";
|
|
}
|
|
if (isZero(duration)) {
|
|
return "0";
|
|
}
|
|
const fragments = parts(duration);
|
|
const pieces = [];
|
|
if (fragments.days !== 0) {
|
|
pieces.push(`${fragments.days}d`);
|
|
}
|
|
if (fragments.hours !== 0) {
|
|
pieces.push(`${fragments.hours}h`);
|
|
}
|
|
if (fragments.minutes !== 0) {
|
|
pieces.push(`${fragments.minutes}m`);
|
|
}
|
|
if (fragments.seconds !== 0) {
|
|
pieces.push(`${fragments.seconds}s`);
|
|
}
|
|
if (fragments.millis !== 0) {
|
|
pieces.push(`${fragments.millis}ms`);
|
|
}
|
|
if (fragments.nanos !== 0) {
|
|
pieces.push(`${fragments.nanos}ns`);
|
|
}
|
|
return pieces.join(" ");
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/hashMap/config.js
|
|
var SIZE = 5;
|
|
var BUCKET_SIZE = /* @__PURE__ */ Math.pow(2, SIZE);
|
|
var MASK = BUCKET_SIZE - 1;
|
|
var MAX_INDEX_NODE = BUCKET_SIZE / 2;
|
|
var MIN_ARRAY_NODE = BUCKET_SIZE / 4;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/hashMap/bitwise.js
|
|
function popcount(x) {
|
|
x -= x >> 1 & 1431655765;
|
|
x = (x & 858993459) + (x >> 2 & 858993459);
|
|
x = x + (x >> 4) & 252645135;
|
|
x += x >> 8;
|
|
x += x >> 16;
|
|
return x & 127;
|
|
}
|
|
function hashFragment(shift, h) {
|
|
return h >>> shift & MASK;
|
|
}
|
|
function toBitmap(x) {
|
|
return 1 << x;
|
|
}
|
|
function fromBitmap(bitmap, bit) {
|
|
return popcount(bitmap & bit - 1);
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/stack.js
|
|
var make8 = (value, previous) => ({
|
|
value,
|
|
previous
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/hashMap/array.js
|
|
function arrayUpdate(mutate, at, v, arr) {
|
|
let out = arr;
|
|
if (!mutate) {
|
|
const len = arr.length;
|
|
out = new Array(len);
|
|
for (let i = 0;i < len; ++i)
|
|
out[i] = arr[i];
|
|
}
|
|
out[at] = v;
|
|
return out;
|
|
}
|
|
function arraySpliceOut(mutate, at, arr) {
|
|
const newLen = arr.length - 1;
|
|
let i = 0;
|
|
let g = 0;
|
|
let out = arr;
|
|
if (mutate) {
|
|
i = g = at;
|
|
} else {
|
|
out = new Array(newLen);
|
|
while (i < at)
|
|
out[g++] = arr[i++];
|
|
}
|
|
++i;
|
|
while (i <= newLen)
|
|
out[g++] = arr[i++];
|
|
if (mutate) {
|
|
out.length = newLen;
|
|
}
|
|
return out;
|
|
}
|
|
function arraySpliceIn(mutate, at, v, arr) {
|
|
const len = arr.length;
|
|
if (mutate) {
|
|
let i = len;
|
|
while (i >= at)
|
|
arr[i--] = arr[i];
|
|
arr[at] = v;
|
|
return arr;
|
|
}
|
|
let i = 0, g = 0;
|
|
const out = new Array(len + 1);
|
|
while (i < at)
|
|
out[g++] = arr[i++];
|
|
out[at] = v;
|
|
while (i < len)
|
|
out[++g] = arr[i++];
|
|
return out;
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/hashMap/node.js
|
|
class EmptyNode {
|
|
_tag = "EmptyNode";
|
|
modify(edit, _shift, f, hash, key, size) {
|
|
const v = f(none2());
|
|
if (isNone2(v))
|
|
return new EmptyNode;
|
|
++size.value;
|
|
return new LeafNode(edit, hash, key, v);
|
|
}
|
|
}
|
|
function isEmptyNode(a) {
|
|
return isTagged(a, "EmptyNode");
|
|
}
|
|
function isLeafNode(node) {
|
|
return isEmptyNode(node) || node._tag === "LeafNode" || node._tag === "CollisionNode";
|
|
}
|
|
function canEditNode(node, edit) {
|
|
return isEmptyNode(node) ? false : edit === node.edit;
|
|
}
|
|
|
|
class LeafNode {
|
|
edit;
|
|
hash;
|
|
key;
|
|
value;
|
|
_tag = "LeafNode";
|
|
constructor(edit, hash, key, value) {
|
|
this.edit = edit;
|
|
this.hash = hash;
|
|
this.key = key;
|
|
this.value = value;
|
|
}
|
|
modify(edit, shift, f, hash, key, size) {
|
|
if (equals(key, this.key)) {
|
|
const v = f(this.value);
|
|
if (v === this.value)
|
|
return this;
|
|
else if (isNone2(v)) {
|
|
--size.value;
|
|
return new EmptyNode;
|
|
}
|
|
if (canEditNode(this, edit)) {
|
|
this.value = v;
|
|
return this;
|
|
}
|
|
return new LeafNode(edit, hash, key, v);
|
|
}
|
|
const v = f(none2());
|
|
if (isNone2(v))
|
|
return this;
|
|
++size.value;
|
|
return mergeLeaves(edit, shift, this.hash, this, hash, new LeafNode(edit, hash, key, v));
|
|
}
|
|
}
|
|
|
|
class CollisionNode {
|
|
edit;
|
|
hash;
|
|
children;
|
|
_tag = "CollisionNode";
|
|
constructor(edit, hash, children) {
|
|
this.edit = edit;
|
|
this.hash = hash;
|
|
this.children = children;
|
|
}
|
|
modify(edit, shift, f, hash, key, size) {
|
|
if (hash === this.hash) {
|
|
const canEdit = canEditNode(this, edit);
|
|
const list = this.updateCollisionList(canEdit, edit, this.hash, this.children, f, key, size);
|
|
if (list === this.children)
|
|
return this;
|
|
return list.length > 1 ? new CollisionNode(edit, this.hash, list) : list[0];
|
|
}
|
|
const v = f(none2());
|
|
if (isNone2(v))
|
|
return this;
|
|
++size.value;
|
|
return mergeLeaves(edit, shift, this.hash, this, hash, new LeafNode(edit, hash, key, v));
|
|
}
|
|
updateCollisionList(mutate, edit, hash, list, f, key, size) {
|
|
const len = list.length;
|
|
for (let i = 0;i < len; ++i) {
|
|
const child = list[i];
|
|
if ("key" in child && equals(key, child.key)) {
|
|
const value = child.value;
|
|
const newValue = f(value);
|
|
if (newValue === value)
|
|
return list;
|
|
if (isNone2(newValue)) {
|
|
--size.value;
|
|
return arraySpliceOut(mutate, i, list);
|
|
}
|
|
return arrayUpdate(mutate, i, new LeafNode(edit, hash, key, newValue), list);
|
|
}
|
|
}
|
|
const newValue = f(none2());
|
|
if (isNone2(newValue))
|
|
return list;
|
|
++size.value;
|
|
return arrayUpdate(mutate, len, new LeafNode(edit, hash, key, newValue), list);
|
|
}
|
|
}
|
|
|
|
class IndexedNode {
|
|
edit;
|
|
mask;
|
|
children;
|
|
_tag = "IndexedNode";
|
|
constructor(edit, mask, children) {
|
|
this.edit = edit;
|
|
this.mask = mask;
|
|
this.children = children;
|
|
}
|
|
modify(edit, shift, f, hash, key, size) {
|
|
const mask = this.mask;
|
|
const children = this.children;
|
|
const frag = hashFragment(shift, hash);
|
|
const bit = toBitmap(frag);
|
|
const indx = fromBitmap(mask, bit);
|
|
const exists = mask & bit;
|
|
const canEdit = canEditNode(this, edit);
|
|
if (!exists) {
|
|
const _newChild = new EmptyNode().modify(edit, shift + SIZE, f, hash, key, size);
|
|
if (!_newChild)
|
|
return this;
|
|
return children.length >= MAX_INDEX_NODE ? expand(edit, frag, _newChild, mask, children) : new IndexedNode(edit, mask | bit, arraySpliceIn(canEdit, indx, _newChild, children));
|
|
}
|
|
const current = children[indx];
|
|
const child = current.modify(edit, shift + SIZE, f, hash, key, size);
|
|
if (current === child)
|
|
return this;
|
|
let bitmap = mask;
|
|
let newChildren;
|
|
if (isEmptyNode(child)) {
|
|
bitmap &= ~bit;
|
|
if (!bitmap)
|
|
return new EmptyNode;
|
|
if (children.length <= 2 && isLeafNode(children[indx ^ 1])) {
|
|
return children[indx ^ 1];
|
|
}
|
|
newChildren = arraySpliceOut(canEdit, indx, children);
|
|
} else {
|
|
newChildren = arrayUpdate(canEdit, indx, child, children);
|
|
}
|
|
if (canEdit) {
|
|
this.mask = bitmap;
|
|
this.children = newChildren;
|
|
return this;
|
|
}
|
|
return new IndexedNode(edit, bitmap, newChildren);
|
|
}
|
|
}
|
|
|
|
class ArrayNode {
|
|
edit;
|
|
size;
|
|
children;
|
|
_tag = "ArrayNode";
|
|
constructor(edit, size, children) {
|
|
this.edit = edit;
|
|
this.size = size;
|
|
this.children = children;
|
|
}
|
|
modify(edit, shift, f, hash, key, size) {
|
|
let count = this.size;
|
|
const children = this.children;
|
|
const frag = hashFragment(shift, hash);
|
|
const child = children[frag];
|
|
const newChild = (child || new EmptyNode).modify(edit, shift + SIZE, f, hash, key, size);
|
|
if (child === newChild)
|
|
return this;
|
|
const canEdit = canEditNode(this, edit);
|
|
let newChildren;
|
|
if (isEmptyNode(child) && !isEmptyNode(newChild)) {
|
|
++count;
|
|
newChildren = arrayUpdate(canEdit, frag, newChild, children);
|
|
} else if (!isEmptyNode(child) && isEmptyNode(newChild)) {
|
|
--count;
|
|
if (count <= MIN_ARRAY_NODE) {
|
|
return pack(edit, count, frag, children);
|
|
}
|
|
newChildren = arrayUpdate(canEdit, frag, new EmptyNode, children);
|
|
} else {
|
|
newChildren = arrayUpdate(canEdit, frag, newChild, children);
|
|
}
|
|
if (canEdit) {
|
|
this.size = count;
|
|
this.children = newChildren;
|
|
return this;
|
|
}
|
|
return new ArrayNode(edit, count, newChildren);
|
|
}
|
|
}
|
|
function pack(edit, count, removed, elements) {
|
|
const children = new Array(count - 1);
|
|
let g = 0;
|
|
let bitmap = 0;
|
|
for (let i = 0, len = elements.length;i < len; ++i) {
|
|
if (i !== removed) {
|
|
const elem = elements[i];
|
|
if (elem && !isEmptyNode(elem)) {
|
|
children[g++] = elem;
|
|
bitmap |= 1 << i;
|
|
}
|
|
}
|
|
}
|
|
return new IndexedNode(edit, bitmap, children);
|
|
}
|
|
function expand(edit, frag, child, bitmap, subNodes) {
|
|
const arr = [];
|
|
let bit = bitmap;
|
|
let count = 0;
|
|
for (let i = 0;bit; ++i) {
|
|
if (bit & 1)
|
|
arr[i] = subNodes[count++];
|
|
bit >>>= 1;
|
|
}
|
|
arr[frag] = child;
|
|
return new ArrayNode(edit, count + 1, arr);
|
|
}
|
|
function mergeLeavesInner(edit, shift, h1, n1, h2, n2) {
|
|
if (h1 === h2)
|
|
return new CollisionNode(edit, h1, [n2, n1]);
|
|
const subH1 = hashFragment(shift, h1);
|
|
const subH2 = hashFragment(shift, h2);
|
|
if (subH1 === subH2) {
|
|
return (child) => new IndexedNode(edit, toBitmap(subH1) | toBitmap(subH2), [child]);
|
|
} else {
|
|
const children = subH1 < subH2 ? [n1, n2] : [n2, n1];
|
|
return new IndexedNode(edit, toBitmap(subH1) | toBitmap(subH2), children);
|
|
}
|
|
}
|
|
function mergeLeaves(edit, shift, h1, n1, h2, n2) {
|
|
let stack = undefined;
|
|
let currentShift = shift;
|
|
while (true) {
|
|
const res = mergeLeavesInner(edit, currentShift, h1, n1, h2, n2);
|
|
if (typeof res === "function") {
|
|
stack = make8(res, stack);
|
|
currentShift = currentShift + SIZE;
|
|
} else {
|
|
let final = res;
|
|
while (stack != null) {
|
|
final = stack.value(final);
|
|
stack = stack.previous;
|
|
}
|
|
return final;
|
|
}
|
|
}
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/hashMap.js
|
|
var HashMapSymbolKey = "effect/HashMap";
|
|
var HashMapTypeId = /* @__PURE__ */ Symbol.for(HashMapSymbolKey);
|
|
var HashMapProto = {
|
|
[HashMapTypeId]: HashMapTypeId,
|
|
[Symbol.iterator]() {
|
|
return new HashMapIterator(this, (k, v) => [k, v]);
|
|
},
|
|
[symbol]() {
|
|
let hash2 = hash(HashMapSymbolKey);
|
|
for (const item of this) {
|
|
hash2 ^= pipe(hash(item[0]), combine(hash(item[1])));
|
|
}
|
|
return cached(this, hash2);
|
|
},
|
|
[symbol2](that) {
|
|
if (isHashMap(that)) {
|
|
if (that._size !== this._size) {
|
|
return false;
|
|
}
|
|
for (const item of this) {
|
|
const elem = pipe(that, getHash(item[0], hash(item[0])));
|
|
if (isNone2(elem)) {
|
|
return false;
|
|
} else {
|
|
if (!equals(item[1], elem.value)) {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
return false;
|
|
},
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
},
|
|
toJSON() {
|
|
return {
|
|
_id: "HashMap",
|
|
values: Array.from(this).map(toJSON)
|
|
};
|
|
},
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
},
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var makeImpl = (editable, edit, root, size) => {
|
|
const map = Object.create(HashMapProto);
|
|
map._editable = editable;
|
|
map._edit = edit;
|
|
map._root = root;
|
|
map._size = size;
|
|
return map;
|
|
};
|
|
|
|
class HashMapIterator {
|
|
map;
|
|
f;
|
|
v;
|
|
constructor(map, f) {
|
|
this.map = map;
|
|
this.f = f;
|
|
this.v = visitLazy(this.map._root, this.f, undefined);
|
|
}
|
|
next() {
|
|
if (isNone2(this.v)) {
|
|
return {
|
|
done: true,
|
|
value: undefined
|
|
};
|
|
}
|
|
const v0 = this.v.value;
|
|
this.v = applyCont(v0.cont);
|
|
return {
|
|
done: false,
|
|
value: v0.value
|
|
};
|
|
}
|
|
[Symbol.iterator]() {
|
|
return new HashMapIterator(this.map, this.f);
|
|
}
|
|
}
|
|
var applyCont = (cont) => cont ? visitLazyChildren(cont[0], cont[1], cont[2], cont[3], cont[4]) : none2();
|
|
var visitLazy = (node, f, cont = undefined) => {
|
|
switch (node._tag) {
|
|
case "LeafNode": {
|
|
if (isSome2(node.value)) {
|
|
return some2({
|
|
value: f(node.key, node.value.value),
|
|
cont
|
|
});
|
|
}
|
|
return applyCont(cont);
|
|
}
|
|
case "CollisionNode":
|
|
case "ArrayNode":
|
|
case "IndexedNode": {
|
|
const children = node.children;
|
|
return visitLazyChildren(children.length, children, 0, f, cont);
|
|
}
|
|
default: {
|
|
return applyCont(cont);
|
|
}
|
|
}
|
|
};
|
|
var visitLazyChildren = (len, children, i, f, cont) => {
|
|
while (i < len) {
|
|
const child = children[i++];
|
|
if (child && !isEmptyNode(child)) {
|
|
return visitLazy(child, f, [len, children, i, f, cont]);
|
|
}
|
|
}
|
|
return applyCont(cont);
|
|
};
|
|
var _empty3 = /* @__PURE__ */ makeImpl(false, 0, /* @__PURE__ */ new EmptyNode, 0);
|
|
var empty5 = () => _empty3;
|
|
var fromIterable3 = (entries) => {
|
|
const map = beginMutation(empty5());
|
|
for (const entry of entries) {
|
|
set(map, entry[0], entry[1]);
|
|
}
|
|
return endMutation(map);
|
|
};
|
|
var isHashMap = (u) => hasProperty(u, HashMapTypeId);
|
|
var isEmpty2 = (self2) => self2 && isEmptyNode(self2._root);
|
|
var get5 = /* @__PURE__ */ dual(2, (self2, key) => getHash(self2, key, hash(key)));
|
|
var getHash = /* @__PURE__ */ dual(3, (self2, key, hash) => {
|
|
let node = self2._root;
|
|
let shift = 0;
|
|
while (true) {
|
|
switch (node._tag) {
|
|
case "LeafNode": {
|
|
return equals(key, node.key) ? node.value : none2();
|
|
}
|
|
case "CollisionNode": {
|
|
if (hash === node.hash) {
|
|
const children = node.children;
|
|
for (let i = 0, len = children.length;i < len; ++i) {
|
|
const child = children[i];
|
|
if ("key" in child && equals(key, child.key)) {
|
|
return child.value;
|
|
}
|
|
}
|
|
}
|
|
return none2();
|
|
}
|
|
case "IndexedNode": {
|
|
const frag = hashFragment(shift, hash);
|
|
const bit = toBitmap(frag);
|
|
if (node.mask & bit) {
|
|
node = node.children[fromBitmap(node.mask, bit)];
|
|
shift += SIZE;
|
|
break;
|
|
}
|
|
return none2();
|
|
}
|
|
case "ArrayNode": {
|
|
node = node.children[hashFragment(shift, hash)];
|
|
if (node) {
|
|
shift += SIZE;
|
|
break;
|
|
}
|
|
return none2();
|
|
}
|
|
default:
|
|
return none2();
|
|
}
|
|
}
|
|
});
|
|
var has2 = /* @__PURE__ */ dual(2, (self2, key) => isSome2(getHash(self2, key, hash(key))));
|
|
var set = /* @__PURE__ */ dual(3, (self2, key, value) => modifyAt(self2, key, () => some2(value)));
|
|
var setTree = /* @__PURE__ */ dual(3, (self2, newRoot, newSize) => {
|
|
if (self2._editable) {
|
|
self2._root = newRoot;
|
|
self2._size = newSize;
|
|
return self2;
|
|
}
|
|
return newRoot === self2._root ? self2 : makeImpl(self2._editable, self2._edit, newRoot, newSize);
|
|
});
|
|
var keys = (self2) => new HashMapIterator(self2, (key) => key);
|
|
var size = (self2) => self2._size;
|
|
var beginMutation = (self2) => makeImpl(true, self2._edit + 1, self2._root, self2._size);
|
|
var endMutation = (self2) => {
|
|
self2._editable = false;
|
|
return self2;
|
|
};
|
|
var modifyAt = /* @__PURE__ */ dual(3, (self2, key, f) => modifyHash(self2, key, hash(key), f));
|
|
var modifyHash = /* @__PURE__ */ dual(4, (self2, key, hash, f) => {
|
|
const size = {
|
|
value: self2._size
|
|
};
|
|
const newRoot = self2._root.modify(self2._editable ? self2._edit : NaN, 0, f, hash, key, size);
|
|
return pipe(self2, setTree(newRoot, size.value));
|
|
});
|
|
var remove2 = /* @__PURE__ */ dual(2, (self2, key) => modifyAt(self2, key, none2));
|
|
var map5 = /* @__PURE__ */ dual(2, (self2, f) => reduce3(self2, empty5(), (map, value, key) => set(map, key, f(value, key))));
|
|
var forEach = /* @__PURE__ */ dual(2, (self2, f) => reduce3(self2, undefined, (_, value, key) => f(value, key)));
|
|
var reduce3 = /* @__PURE__ */ dual(3, (self2, zero, f) => {
|
|
const root = self2._root;
|
|
if (root._tag === "LeafNode") {
|
|
return isSome2(root.value) ? f(zero, root.value.value, root.key) : zero;
|
|
}
|
|
if (root._tag === "EmptyNode") {
|
|
return zero;
|
|
}
|
|
const toVisit = [root.children];
|
|
let children;
|
|
while (children = toVisit.pop()) {
|
|
for (let i = 0, len = children.length;i < len; ) {
|
|
const child = children[i++];
|
|
if (child && !isEmptyNode(child)) {
|
|
if (child._tag === "LeafNode") {
|
|
if (isSome2(child.value)) {
|
|
zero = f(zero, child.value.value, child.key);
|
|
}
|
|
} else {
|
|
toVisit.push(child.children);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return zero;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/hashSet.js
|
|
var HashSetSymbolKey = "effect/HashSet";
|
|
var HashSetTypeId = /* @__PURE__ */ Symbol.for(HashSetSymbolKey);
|
|
var HashSetProto = {
|
|
[HashSetTypeId]: HashSetTypeId,
|
|
[Symbol.iterator]() {
|
|
return keys(this._keyMap);
|
|
},
|
|
[symbol]() {
|
|
return cached(this, combine(hash(this._keyMap))(hash(HashSetSymbolKey)));
|
|
},
|
|
[symbol2](that) {
|
|
if (isHashSet(that)) {
|
|
return size(this._keyMap) === size(that._keyMap) && equals(this._keyMap, that._keyMap);
|
|
}
|
|
return false;
|
|
},
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
},
|
|
toJSON() {
|
|
return {
|
|
_id: "HashSet",
|
|
values: Array.from(this).map(toJSON)
|
|
};
|
|
},
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
},
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var makeImpl2 = (keyMap) => {
|
|
const set = Object.create(HashSetProto);
|
|
set._keyMap = keyMap;
|
|
return set;
|
|
};
|
|
var isHashSet = (u) => hasProperty(u, HashSetTypeId);
|
|
var _empty4 = /* @__PURE__ */ makeImpl2(/* @__PURE__ */ empty5());
|
|
var empty6 = () => _empty4;
|
|
var fromIterable4 = (elements) => {
|
|
const set = beginMutation2(empty6());
|
|
for (const value of elements) {
|
|
add3(set, value);
|
|
}
|
|
return endMutation2(set);
|
|
};
|
|
var make9 = (...elements) => {
|
|
const set = beginMutation2(empty6());
|
|
for (const value of elements) {
|
|
add3(set, value);
|
|
}
|
|
return endMutation2(set);
|
|
};
|
|
var has3 = /* @__PURE__ */ dual(2, (self2, value) => has2(self2._keyMap, value));
|
|
var size2 = (self2) => size(self2._keyMap);
|
|
var beginMutation2 = (self2) => makeImpl2(beginMutation(self2._keyMap));
|
|
var endMutation2 = (self2) => {
|
|
self2._keyMap._editable = false;
|
|
return self2;
|
|
};
|
|
var mutate = /* @__PURE__ */ dual(2, (self2, f) => {
|
|
const transient = beginMutation2(self2);
|
|
f(transient);
|
|
return endMutation2(transient);
|
|
});
|
|
var add3 = /* @__PURE__ */ dual(2, (self2, value) => self2._keyMap._editable ? (set(value, true)(self2._keyMap), self2) : makeImpl2(set(value, true)(self2._keyMap)));
|
|
var remove3 = /* @__PURE__ */ dual(2, (self2, value) => self2._keyMap._editable ? (remove2(value)(self2._keyMap), self2) : makeImpl2(remove2(value)(self2._keyMap)));
|
|
var difference2 = /* @__PURE__ */ dual(2, (self2, that) => mutate(self2, (set) => {
|
|
for (const value of that) {
|
|
remove3(set, value);
|
|
}
|
|
}));
|
|
var union2 = /* @__PURE__ */ dual(2, (self2, that) => mutate(empty6(), (set) => {
|
|
forEach2(self2, (value) => add3(set, value));
|
|
for (const value of that) {
|
|
add3(set, value);
|
|
}
|
|
}));
|
|
var forEach2 = /* @__PURE__ */ dual(2, (self2, f) => forEach(self2._keyMap, (_, k) => f(k)));
|
|
var reduce4 = /* @__PURE__ */ dual(3, (self2, zero, f) => reduce3(self2._keyMap, zero, (z, _, a) => f(z, a)));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/HashSet.js
|
|
var empty7 = empty6;
|
|
var fromIterable5 = fromIterable4;
|
|
var make10 = make9;
|
|
var has4 = has3;
|
|
var size3 = size2;
|
|
var add4 = add3;
|
|
var remove4 = remove3;
|
|
var difference3 = difference2;
|
|
var union3 = union2;
|
|
var reduce5 = reduce4;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/MutableRef.js
|
|
var TypeId6 = /* @__PURE__ */ Symbol.for("effect/MutableRef");
|
|
var MutableRefProto = {
|
|
[TypeId6]: TypeId6,
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
},
|
|
toJSON() {
|
|
return {
|
|
_id: "MutableRef",
|
|
current: toJSON(this.current)
|
|
};
|
|
},
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
},
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var make11 = (value) => {
|
|
const ref = Object.create(MutableRefProto);
|
|
ref.current = value;
|
|
return ref;
|
|
};
|
|
var compareAndSet = /* @__PURE__ */ dual(3, (self2, oldValue, newValue) => {
|
|
if (equals(oldValue, self2.current)) {
|
|
self2.current = newValue;
|
|
return true;
|
|
}
|
|
return false;
|
|
});
|
|
var get6 = (self2) => self2.current;
|
|
var set2 = /* @__PURE__ */ dual(2, (self2, value) => {
|
|
self2.current = value;
|
|
return self2;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/fiberId.js
|
|
var FiberIdSymbolKey = "effect/FiberId";
|
|
var FiberIdTypeId = /* @__PURE__ */ Symbol.for(FiberIdSymbolKey);
|
|
var OP_NONE = "None";
|
|
var OP_RUNTIME = "Runtime";
|
|
var OP_COMPOSITE = "Composite";
|
|
var emptyHash = /* @__PURE__ */ string(`${FiberIdSymbolKey}-${OP_NONE}`);
|
|
|
|
class None {
|
|
[FiberIdTypeId] = FiberIdTypeId;
|
|
_tag = OP_NONE;
|
|
id = -1;
|
|
startTimeMillis = -1;
|
|
[symbol]() {
|
|
return emptyHash;
|
|
}
|
|
[symbol2](that) {
|
|
return isFiberId(that) && that._tag === OP_NONE;
|
|
}
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_id: "FiberId",
|
|
_tag: this._tag
|
|
};
|
|
}
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
}
|
|
}
|
|
|
|
class Runtime {
|
|
id;
|
|
startTimeMillis;
|
|
[FiberIdTypeId] = FiberIdTypeId;
|
|
_tag = OP_RUNTIME;
|
|
constructor(id, startTimeMillis) {
|
|
this.id = id;
|
|
this.startTimeMillis = startTimeMillis;
|
|
}
|
|
[symbol]() {
|
|
return cached(this, string(`${FiberIdSymbolKey}-${this._tag}-${this.id}-${this.startTimeMillis}`));
|
|
}
|
|
[symbol2](that) {
|
|
return isFiberId(that) && that._tag === OP_RUNTIME && this.id === that.id && this.startTimeMillis === that.startTimeMillis;
|
|
}
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_id: "FiberId",
|
|
_tag: this._tag,
|
|
id: this.id,
|
|
startTimeMillis: this.startTimeMillis
|
|
};
|
|
}
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
}
|
|
}
|
|
|
|
class Composite {
|
|
left;
|
|
right;
|
|
[FiberIdTypeId] = FiberIdTypeId;
|
|
_tag = OP_COMPOSITE;
|
|
constructor(left, right) {
|
|
this.left = left;
|
|
this.right = right;
|
|
}
|
|
_hash;
|
|
[symbol]() {
|
|
return pipe(string(`${FiberIdSymbolKey}-${this._tag}`), combine(hash(this.left)), combine(hash(this.right)), cached(this));
|
|
}
|
|
[symbol2](that) {
|
|
return isFiberId(that) && that._tag === OP_COMPOSITE && equals(this.left, that.left) && equals(this.right, that.right);
|
|
}
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_id: "FiberId",
|
|
_tag: this._tag,
|
|
left: toJSON(this.left),
|
|
right: toJSON(this.right)
|
|
};
|
|
}
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
}
|
|
}
|
|
var none3 = /* @__PURE__ */ new None;
|
|
var isFiberId = (self2) => hasProperty(self2, FiberIdTypeId);
|
|
var combine2 = /* @__PURE__ */ dual(2, (self2, that) => {
|
|
if (self2._tag === OP_NONE) {
|
|
return that;
|
|
}
|
|
if (that._tag === OP_NONE) {
|
|
return self2;
|
|
}
|
|
return new Composite(self2, that);
|
|
});
|
|
var combineAll = (fiberIds) => {
|
|
return pipe(fiberIds, reduce5(none3, (a, b) => combine2(b)(a)));
|
|
};
|
|
var ids = (self2) => {
|
|
switch (self2._tag) {
|
|
case OP_NONE: {
|
|
return empty7();
|
|
}
|
|
case OP_RUNTIME: {
|
|
return make10(self2.id);
|
|
}
|
|
case OP_COMPOSITE: {
|
|
return pipe(ids(self2.left), union3(ids(self2.right)));
|
|
}
|
|
}
|
|
};
|
|
var _fiberCounter = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/Fiber/Id/_fiberCounter"), () => make11(0));
|
|
var threadName = (self2) => {
|
|
const identifiers = Array.from(ids(self2)).map((n) => `#${n}`).join(",");
|
|
return identifiers;
|
|
};
|
|
var unsafeMake = () => {
|
|
const id = get6(_fiberCounter);
|
|
pipe(_fiberCounter, set2(id + 1));
|
|
return new Runtime(id, Date.now());
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/FiberId.js
|
|
var none4 = none3;
|
|
var combine3 = combine2;
|
|
var combineAll2 = combineAll;
|
|
var ids2 = ids;
|
|
var threadName2 = threadName;
|
|
var unsafeMake2 = unsafeMake;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/HashMap.js
|
|
var empty8 = empty5;
|
|
var fromIterable6 = fromIterable3;
|
|
var isEmpty3 = isEmpty2;
|
|
var get7 = get5;
|
|
var set3 = set;
|
|
var keys2 = keys;
|
|
var modifyAt2 = modifyAt;
|
|
var map7 = map5;
|
|
var reduce6 = reduce3;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/List.js
|
|
var TypeId7 = /* @__PURE__ */ Symbol.for("effect/List");
|
|
var toArray2 = (self2) => fromIterable(self2);
|
|
var getEquivalence3 = (isEquivalent) => mapInput(getEquivalence(isEquivalent), toArray2);
|
|
var _equivalence4 = /* @__PURE__ */ getEquivalence3(equals);
|
|
var ConsProto = {
|
|
[TypeId7]: TypeId7,
|
|
_tag: "Cons",
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
},
|
|
toJSON() {
|
|
return {
|
|
_id: "List",
|
|
_tag: "Cons",
|
|
values: toArray2(this).map(toJSON)
|
|
};
|
|
},
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
},
|
|
[symbol2](that) {
|
|
return isList(that) && this._tag === that._tag && _equivalence4(this, that);
|
|
},
|
|
[symbol]() {
|
|
return cached(this, array2(toArray2(this)));
|
|
},
|
|
[Symbol.iterator]() {
|
|
let done = false;
|
|
let self2 = this;
|
|
return {
|
|
next() {
|
|
if (done) {
|
|
return this.return();
|
|
}
|
|
if (self2._tag === "Nil") {
|
|
done = true;
|
|
return this.return();
|
|
}
|
|
const value = self2.head;
|
|
self2 = self2.tail;
|
|
return {
|
|
done,
|
|
value
|
|
};
|
|
},
|
|
return(value) {
|
|
if (!done) {
|
|
done = true;
|
|
}
|
|
return {
|
|
done: true,
|
|
value
|
|
};
|
|
}
|
|
};
|
|
},
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var makeCons = (head, tail) => {
|
|
const cons = Object.create(ConsProto);
|
|
cons.head = head;
|
|
cons.tail = tail;
|
|
return cons;
|
|
};
|
|
var NilHash = /* @__PURE__ */ string("Nil");
|
|
var NilProto = {
|
|
[TypeId7]: TypeId7,
|
|
_tag: "Nil",
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
},
|
|
toJSON() {
|
|
return {
|
|
_id: "List",
|
|
_tag: "Nil"
|
|
};
|
|
},
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
},
|
|
[symbol]() {
|
|
return NilHash;
|
|
},
|
|
[symbol2](that) {
|
|
return isList(that) && this._tag === that._tag;
|
|
},
|
|
[Symbol.iterator]() {
|
|
return {
|
|
next() {
|
|
return {
|
|
done: true,
|
|
value: undefined
|
|
};
|
|
}
|
|
};
|
|
},
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var _Nil = /* @__PURE__ */ Object.create(NilProto);
|
|
var isList = (u) => hasProperty(u, TypeId7);
|
|
var isNil = (self2) => self2._tag === "Nil";
|
|
var isCons = (self2) => self2._tag === "Cons";
|
|
var nil = () => _Nil;
|
|
var cons = (head, tail) => makeCons(head, tail);
|
|
var empty9 = nil;
|
|
var of3 = (value) => makeCons(value, _Nil);
|
|
var appendAll3 = /* @__PURE__ */ dual(2, (self2, that) => prependAll(that, self2));
|
|
var prepend3 = /* @__PURE__ */ dual(2, (self2, element) => cons(element, self2));
|
|
var prependAll = /* @__PURE__ */ dual(2, (self2, prefix) => {
|
|
if (isNil(self2)) {
|
|
return prefix;
|
|
} else if (isNil(prefix)) {
|
|
return self2;
|
|
} else {
|
|
const result = makeCons(prefix.head, self2);
|
|
let curr = result;
|
|
let that = prefix.tail;
|
|
while (!isNil(that)) {
|
|
const temp = makeCons(that.head, self2);
|
|
curr.tail = temp;
|
|
curr = temp;
|
|
that = that.tail;
|
|
}
|
|
return result;
|
|
}
|
|
});
|
|
var reduce7 = /* @__PURE__ */ dual(3, (self2, zero, f) => {
|
|
let acc = zero;
|
|
let these = self2;
|
|
while (!isNil(these)) {
|
|
acc = f(acc, these.head);
|
|
these = these.tail;
|
|
}
|
|
return acc;
|
|
});
|
|
var reverse3 = (self2) => {
|
|
let result = empty9();
|
|
let these = self2;
|
|
while (!isNil(these)) {
|
|
result = prepend3(result, these.head);
|
|
these = these.tail;
|
|
}
|
|
return result;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/data.js
|
|
var ArrayProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(Array.prototype), {
|
|
[symbol]() {
|
|
return cached(this, array2(this));
|
|
},
|
|
[symbol2](that) {
|
|
if (Array.isArray(that) && this.length === that.length) {
|
|
return this.every((v, i) => equals(v, that[i]));
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
});
|
|
var Structural = /* @__PURE__ */ function() {
|
|
function Structural(args) {
|
|
if (args) {
|
|
Object.assign(this, args);
|
|
}
|
|
}
|
|
Structural.prototype = StructuralPrototype;
|
|
return Structural;
|
|
}();
|
|
var struct = (as) => Object.assign(Object.create(StructuralPrototype), as);
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/differ/contextPatch.js
|
|
var ContextPatchTypeId = /* @__PURE__ */ Symbol.for("effect/DifferContextPatch");
|
|
function variance(a) {
|
|
return a;
|
|
}
|
|
var PatchProto = {
|
|
...Structural.prototype,
|
|
[ContextPatchTypeId]: {
|
|
_Value: variance,
|
|
_Patch: variance
|
|
}
|
|
};
|
|
var EmptyProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(PatchProto), {
|
|
_tag: "Empty"
|
|
});
|
|
var _empty5 = /* @__PURE__ */ Object.create(EmptyProto);
|
|
var empty10 = () => _empty5;
|
|
var AndThenProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(PatchProto), {
|
|
_tag: "AndThen"
|
|
});
|
|
var makeAndThen = (first, second) => {
|
|
const o = Object.create(AndThenProto);
|
|
o.first = first;
|
|
o.second = second;
|
|
return o;
|
|
};
|
|
var AddServiceProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(PatchProto), {
|
|
_tag: "AddService"
|
|
});
|
|
var makeAddService = (key, service) => {
|
|
const o = Object.create(AddServiceProto);
|
|
o.key = key;
|
|
o.service = service;
|
|
return o;
|
|
};
|
|
var RemoveServiceProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(PatchProto), {
|
|
_tag: "RemoveService"
|
|
});
|
|
var makeRemoveService = (key) => {
|
|
const o = Object.create(RemoveServiceProto);
|
|
o.key = key;
|
|
return o;
|
|
};
|
|
var UpdateServiceProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(PatchProto), {
|
|
_tag: "UpdateService"
|
|
});
|
|
var makeUpdateService = (key, update) => {
|
|
const o = Object.create(UpdateServiceProto);
|
|
o.key = key;
|
|
o.update = update;
|
|
return o;
|
|
};
|
|
var diff = (oldValue, newValue) => {
|
|
const missingServices = new Map(oldValue.unsafeMap);
|
|
let patch = empty10();
|
|
for (const [tag, newService] of newValue.unsafeMap.entries()) {
|
|
if (missingServices.has(tag)) {
|
|
const old = missingServices.get(tag);
|
|
missingServices.delete(tag);
|
|
if (!equals(old, newService)) {
|
|
patch = combine4(makeUpdateService(tag, () => newService))(patch);
|
|
}
|
|
} else {
|
|
missingServices.delete(tag);
|
|
patch = combine4(makeAddService(tag, newService))(patch);
|
|
}
|
|
}
|
|
for (const [tag] of missingServices.entries()) {
|
|
patch = combine4(makeRemoveService(tag))(patch);
|
|
}
|
|
return patch;
|
|
};
|
|
var combine4 = /* @__PURE__ */ dual(2, (self2, that) => makeAndThen(self2, that));
|
|
var patch = /* @__PURE__ */ dual(2, (self2, context) => {
|
|
if (self2._tag === "Empty") {
|
|
return context;
|
|
}
|
|
let wasServiceUpdated = false;
|
|
let patches = of2(self2);
|
|
const updatedContext = new Map(context.unsafeMap);
|
|
while (isNonEmpty(patches)) {
|
|
const head = headNonEmpty2(patches);
|
|
const tail = tailNonEmpty2(patches);
|
|
switch (head._tag) {
|
|
case "Empty": {
|
|
patches = tail;
|
|
break;
|
|
}
|
|
case "AddService": {
|
|
updatedContext.set(head.key, head.service);
|
|
patches = tail;
|
|
break;
|
|
}
|
|
case "AndThen": {
|
|
patches = prepend2(prepend2(tail, head.second), head.first);
|
|
break;
|
|
}
|
|
case "RemoveService": {
|
|
updatedContext.delete(head.key);
|
|
patches = tail;
|
|
break;
|
|
}
|
|
case "UpdateService": {
|
|
updatedContext.set(head.key, head.update(updatedContext.get(head.key)));
|
|
wasServiceUpdated = true;
|
|
patches = tail;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (!wasServiceUpdated) {
|
|
return makeContext(updatedContext);
|
|
}
|
|
const map = new Map;
|
|
for (const [tag] of context.unsafeMap) {
|
|
if (updatedContext.has(tag)) {
|
|
map.set(tag, updatedContext.get(tag));
|
|
updatedContext.delete(tag);
|
|
}
|
|
}
|
|
for (const [tag, s] of updatedContext) {
|
|
map.set(tag, s);
|
|
}
|
|
return makeContext(map);
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/differ/hashSetPatch.js
|
|
var HashSetPatchTypeId = /* @__PURE__ */ Symbol.for("effect/DifferHashSetPatch");
|
|
function variance2(a) {
|
|
return a;
|
|
}
|
|
var PatchProto2 = {
|
|
...Structural.prototype,
|
|
[HashSetPatchTypeId]: {
|
|
_Value: variance2,
|
|
_Key: variance2,
|
|
_Patch: variance2
|
|
}
|
|
};
|
|
var EmptyProto2 = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(PatchProto2), {
|
|
_tag: "Empty"
|
|
});
|
|
var _empty6 = /* @__PURE__ */ Object.create(EmptyProto2);
|
|
var empty11 = () => _empty6;
|
|
var AndThenProto2 = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(PatchProto2), {
|
|
_tag: "AndThen"
|
|
});
|
|
var makeAndThen2 = (first, second) => {
|
|
const o = Object.create(AndThenProto2);
|
|
o.first = first;
|
|
o.second = second;
|
|
return o;
|
|
};
|
|
var AddProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(PatchProto2), {
|
|
_tag: "Add"
|
|
});
|
|
var makeAdd = (value) => {
|
|
const o = Object.create(AddProto);
|
|
o.value = value;
|
|
return o;
|
|
};
|
|
var RemoveProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(PatchProto2), {
|
|
_tag: "Remove"
|
|
});
|
|
var makeRemove = (value) => {
|
|
const o = Object.create(RemoveProto);
|
|
o.value = value;
|
|
return o;
|
|
};
|
|
var diff2 = (oldValue, newValue) => {
|
|
const [removed, patch] = reduce5([oldValue, empty11()], ([set, patch], value) => {
|
|
if (has4(value)(set)) {
|
|
return [remove4(value)(set), patch];
|
|
}
|
|
return [set, combine5(makeAdd(value))(patch)];
|
|
})(newValue);
|
|
return reduce5(patch, (patch, value) => combine5(makeRemove(value))(patch))(removed);
|
|
};
|
|
var combine5 = /* @__PURE__ */ dual(2, (self2, that) => makeAndThen2(self2, that));
|
|
var patch2 = /* @__PURE__ */ dual(2, (self2, oldValue) => {
|
|
if (self2._tag === "Empty") {
|
|
return oldValue;
|
|
}
|
|
let set = oldValue;
|
|
let patches = of2(self2);
|
|
while (isNonEmpty(patches)) {
|
|
const head = headNonEmpty2(patches);
|
|
const tail = tailNonEmpty2(patches);
|
|
switch (head._tag) {
|
|
case "Empty": {
|
|
patches = tail;
|
|
break;
|
|
}
|
|
case "AndThen": {
|
|
patches = prepend2(head.first)(prepend2(head.second)(tail));
|
|
break;
|
|
}
|
|
case "Add": {
|
|
set = add4(head.value)(set);
|
|
patches = tail;
|
|
break;
|
|
}
|
|
case "Remove": {
|
|
set = remove4(head.value)(set);
|
|
patches = tail;
|
|
}
|
|
}
|
|
}
|
|
return set;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/differ/readonlyArrayPatch.js
|
|
var ReadonlyArrayPatchTypeId = /* @__PURE__ */ Symbol.for("effect/DifferReadonlyArrayPatch");
|
|
function variance3(a) {
|
|
return a;
|
|
}
|
|
var PatchProto3 = {
|
|
...Structural.prototype,
|
|
[ReadonlyArrayPatchTypeId]: {
|
|
_Value: variance3,
|
|
_Patch: variance3
|
|
}
|
|
};
|
|
var EmptyProto3 = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(PatchProto3), {
|
|
_tag: "Empty"
|
|
});
|
|
var _empty7 = /* @__PURE__ */ Object.create(EmptyProto3);
|
|
var empty12 = () => _empty7;
|
|
var AndThenProto3 = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(PatchProto3), {
|
|
_tag: "AndThen"
|
|
});
|
|
var makeAndThen3 = (first, second) => {
|
|
const o = Object.create(AndThenProto3);
|
|
o.first = first;
|
|
o.second = second;
|
|
return o;
|
|
};
|
|
var AppendProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(PatchProto3), {
|
|
_tag: "Append"
|
|
});
|
|
var makeAppend = (values) => {
|
|
const o = Object.create(AppendProto);
|
|
o.values = values;
|
|
return o;
|
|
};
|
|
var SliceProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(PatchProto3), {
|
|
_tag: "Slice"
|
|
});
|
|
var makeSlice = (from, until) => {
|
|
const o = Object.create(SliceProto);
|
|
o.from = from;
|
|
o.until = until;
|
|
return o;
|
|
};
|
|
var UpdateProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(PatchProto3), {
|
|
_tag: "Update"
|
|
});
|
|
var makeUpdate = (index, patch) => {
|
|
const o = Object.create(UpdateProto);
|
|
o.index = index;
|
|
o.patch = patch;
|
|
return o;
|
|
};
|
|
var diff3 = (options) => {
|
|
let i = 0;
|
|
let patch = empty12();
|
|
while (i < options.oldValue.length && i < options.newValue.length) {
|
|
const oldElement = options.oldValue[i];
|
|
const newElement = options.newValue[i];
|
|
const valuePatch = options.differ.diff(oldElement, newElement);
|
|
if (!equals(valuePatch, options.differ.empty)) {
|
|
patch = combine6(patch, makeUpdate(i, valuePatch));
|
|
}
|
|
i = i + 1;
|
|
}
|
|
if (i < options.oldValue.length) {
|
|
patch = combine6(patch, makeSlice(0, i));
|
|
}
|
|
if (i < options.newValue.length) {
|
|
patch = combine6(patch, makeAppend(drop(i)(options.newValue)));
|
|
}
|
|
return patch;
|
|
};
|
|
var combine6 = /* @__PURE__ */ dual(2, (self2, that) => makeAndThen3(self2, that));
|
|
var patch3 = /* @__PURE__ */ dual(3, (self2, oldValue, differ) => {
|
|
if (self2._tag === "Empty") {
|
|
return oldValue;
|
|
}
|
|
let readonlyArray = oldValue.slice();
|
|
let patches = of(self2);
|
|
while (isNonEmptyArray2(patches)) {
|
|
const head = headNonEmpty(patches);
|
|
const tail = tailNonEmpty(patches);
|
|
switch (head._tag) {
|
|
case "Empty": {
|
|
patches = tail;
|
|
break;
|
|
}
|
|
case "AndThen": {
|
|
tail.unshift(head.first, head.second);
|
|
patches = tail;
|
|
break;
|
|
}
|
|
case "Append": {
|
|
for (const value of head.values) {
|
|
readonlyArray.push(value);
|
|
}
|
|
patches = tail;
|
|
break;
|
|
}
|
|
case "Slice": {
|
|
readonlyArray = readonlyArray.slice(head.from, head.until);
|
|
patches = tail;
|
|
break;
|
|
}
|
|
case "Update": {
|
|
readonlyArray[head.index] = differ.patch(head.patch, readonlyArray[head.index]);
|
|
patches = tail;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
return readonlyArray;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/differ.js
|
|
var DifferTypeId = /* @__PURE__ */ Symbol.for("effect/Differ");
|
|
var DifferProto = {
|
|
[DifferTypeId]: {
|
|
_P: identity,
|
|
_V: identity
|
|
},
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var make14 = (params) => {
|
|
const differ = Object.create(DifferProto);
|
|
differ.empty = params.empty;
|
|
differ.diff = params.diff;
|
|
differ.combine = params.combine;
|
|
differ.patch = params.patch;
|
|
return differ;
|
|
};
|
|
var environment = () => make14({
|
|
empty: empty10(),
|
|
combine: (first, second) => combine4(second)(first),
|
|
diff: (oldValue, newValue) => diff(oldValue, newValue),
|
|
patch: (patch2, oldValue) => patch(oldValue)(patch2)
|
|
});
|
|
var hashSet = () => make14({
|
|
empty: empty11(),
|
|
combine: (first, second) => combine5(second)(first),
|
|
diff: (oldValue, newValue) => diff2(oldValue, newValue),
|
|
patch: (patch, oldValue) => patch2(oldValue)(patch)
|
|
});
|
|
var readonlyArray = (differ) => make14({
|
|
empty: empty12(),
|
|
combine: (first, second) => combine6(first, second),
|
|
diff: (oldValue, newValue) => diff3({
|
|
oldValue,
|
|
newValue,
|
|
differ
|
|
}),
|
|
patch: (patch, oldValue) => patch3(patch, oldValue, differ)
|
|
});
|
|
var update = () => updateWith((_, a) => a);
|
|
var updateWith = (f) => make14({
|
|
empty: identity,
|
|
combine: (first, second) => {
|
|
if (first === identity) {
|
|
return second;
|
|
}
|
|
if (second === identity) {
|
|
return first;
|
|
}
|
|
return (a) => second(first(a));
|
|
},
|
|
diff: (oldValue, newValue) => {
|
|
if (equals(oldValue, newValue)) {
|
|
return identity;
|
|
}
|
|
return constant(newValue);
|
|
},
|
|
patch: (patch, oldValue) => f(oldValue, patch(oldValue))
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/runtimeFlagsPatch.js
|
|
var BIT_MASK = 255;
|
|
var BIT_SHIFT = 8;
|
|
var active = (patch) => patch & BIT_MASK;
|
|
var enabled = (patch) => patch >> BIT_SHIFT & BIT_MASK;
|
|
var make15 = (active, enabled) => (active & BIT_MASK) + ((enabled & active & BIT_MASK) << BIT_SHIFT);
|
|
var empty13 = /* @__PURE__ */ make15(0, 0);
|
|
var enable = (flag) => make15(flag, flag);
|
|
var disable = (flag) => make15(flag, 0);
|
|
var exclude = /* @__PURE__ */ dual(2, (self2, flag) => make15(active(self2) & ~flag, enabled(self2)));
|
|
var andThen = /* @__PURE__ */ dual(2, (self2, that) => self2 | that);
|
|
var invert = (n) => ~n >>> 0 & BIT_MASK;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/runtimeFlags.js
|
|
var None2 = 0;
|
|
var Interruption = 1 << 0;
|
|
var OpSupervision = 1 << 1;
|
|
var RuntimeMetrics = 1 << 2;
|
|
var WindDown = 1 << 4;
|
|
var CooperativeYielding = 1 << 5;
|
|
var cooperativeYielding = (self2) => isEnabled(self2, CooperativeYielding);
|
|
var disable2 = /* @__PURE__ */ dual(2, (self2, flag) => self2 & ~flag);
|
|
var enable2 = /* @__PURE__ */ dual(2, (self2, flag) => self2 | flag);
|
|
var interruptible = (self2) => interruption(self2) && !windDown(self2);
|
|
var interruption = (self2) => isEnabled(self2, Interruption);
|
|
var isEnabled = /* @__PURE__ */ dual(2, (self2, flag) => (self2 & flag) !== 0);
|
|
var make16 = (...flags) => flags.reduce((a, b) => a | b, 0);
|
|
var none5 = /* @__PURE__ */ make16(None2);
|
|
var runtimeMetrics = (self2) => isEnabled(self2, RuntimeMetrics);
|
|
var windDown = (self2) => isEnabled(self2, WindDown);
|
|
var diff4 = /* @__PURE__ */ dual(2, (self2, that) => make15(self2 ^ that, that));
|
|
var patch4 = /* @__PURE__ */ dual(2, (self2, patch) => self2 & (invert(active(patch)) | enabled(patch)) | active(patch) & enabled(patch));
|
|
var differ = /* @__PURE__ */ make14({
|
|
empty: empty13,
|
|
diff: (oldValue, newValue) => diff4(oldValue, newValue),
|
|
combine: (first, second) => andThen(second)(first),
|
|
patch: (_patch, oldValue) => patch4(oldValue, _patch)
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/RuntimeFlagsPatch.js
|
|
var enable3 = enable;
|
|
var disable3 = disable;
|
|
var exclude2 = exclude;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/blockedRequests.js
|
|
var par = (self2, that) => ({
|
|
_tag: "Par",
|
|
left: self2,
|
|
right: that
|
|
});
|
|
var seq = (self2, that) => ({
|
|
_tag: "Seq",
|
|
left: self2,
|
|
right: that
|
|
});
|
|
var flatten2 = (self2) => {
|
|
let current = of3(self2);
|
|
let updated = empty9();
|
|
while (true) {
|
|
const [parallel, sequential] = reduce7(current, [parallelCollectionEmpty(), empty9()], ([parallel, sequential], blockedRequest) => {
|
|
const [par, seq] = step(blockedRequest);
|
|
return [parallelCollectionCombine(parallel, par), appendAll3(sequential, seq)];
|
|
});
|
|
updated = merge4(updated, parallel);
|
|
if (isNil(sequential)) {
|
|
return reverse3(updated);
|
|
}
|
|
current = sequential;
|
|
}
|
|
throw new Error("BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues");
|
|
};
|
|
var step = (requests) => {
|
|
let current = requests;
|
|
let parallel = parallelCollectionEmpty();
|
|
let stack = empty9();
|
|
let sequential = empty9();
|
|
while (true) {
|
|
switch (current._tag) {
|
|
case "Empty": {
|
|
if (isNil(stack)) {
|
|
return [parallel, sequential];
|
|
}
|
|
current = stack.head;
|
|
stack = stack.tail;
|
|
break;
|
|
}
|
|
case "Par": {
|
|
stack = cons(current.right, stack);
|
|
current = current.left;
|
|
break;
|
|
}
|
|
case "Seq": {
|
|
const left = current.left;
|
|
const right = current.right;
|
|
switch (left._tag) {
|
|
case "Empty": {
|
|
current = right;
|
|
break;
|
|
}
|
|
case "Par": {
|
|
const l = left.left;
|
|
const r = left.right;
|
|
current = par(seq(l, right), seq(r, right));
|
|
break;
|
|
}
|
|
case "Seq": {
|
|
const l = left.left;
|
|
const r = left.right;
|
|
current = seq(l, seq(r, right));
|
|
break;
|
|
}
|
|
case "Single": {
|
|
current = left;
|
|
sequential = cons(right, sequential);
|
|
break;
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case "Single": {
|
|
parallel = parallelCollectionAdd(parallel, current);
|
|
if (isNil(stack)) {
|
|
return [parallel, sequential];
|
|
}
|
|
current = stack.head;
|
|
stack = stack.tail;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
throw new Error("BUG: BlockedRequests.step - please report an issue at https://github.com/Effect-TS/effect/issues");
|
|
};
|
|
var merge4 = (sequential, parallel) => {
|
|
if (isNil(sequential)) {
|
|
return of3(parallelCollectionToSequentialCollection(parallel));
|
|
}
|
|
if (parallelCollectionIsEmpty(parallel)) {
|
|
return sequential;
|
|
}
|
|
const seqHeadKeys = sequentialCollectionKeys(sequential.head);
|
|
const parKeys = parallelCollectionKeys(parallel);
|
|
if (seqHeadKeys.length === 1 && parKeys.length === 1 && equals(seqHeadKeys[0], parKeys[0])) {
|
|
return cons(sequentialCollectionCombine(sequential.head, parallelCollectionToSequentialCollection(parallel)), sequential.tail);
|
|
}
|
|
return cons(parallelCollectionToSequentialCollection(parallel), sequential);
|
|
};
|
|
var RequestBlockParallelTypeId = /* @__PURE__ */ Symbol.for("effect/RequestBlock/RequestBlockParallel");
|
|
var parallelVariance = {
|
|
_R: (_) => _
|
|
};
|
|
|
|
class ParallelImpl {
|
|
map;
|
|
[RequestBlockParallelTypeId] = parallelVariance;
|
|
constructor(map) {
|
|
this.map = map;
|
|
}
|
|
}
|
|
var parallelCollectionEmpty = () => new ParallelImpl(empty8());
|
|
var parallelCollectionAdd = (self2, blockedRequest) => new ParallelImpl(modifyAt2(self2.map, blockedRequest.dataSource, (_) => orElseSome(map2(_, append2(blockedRequest.blockedRequest)), () => of2(blockedRequest.blockedRequest))));
|
|
var parallelCollectionCombine = (self2, that) => new ParallelImpl(reduce6(self2.map, that.map, (map, value, key) => set3(map, key, match2(get7(map, key), {
|
|
onNone: () => value,
|
|
onSome: (other) => appendAll2(value, other)
|
|
}))));
|
|
var parallelCollectionIsEmpty = (self2) => isEmpty3(self2.map);
|
|
var parallelCollectionKeys = (self2) => Array.from(keys2(self2.map));
|
|
var parallelCollectionToSequentialCollection = (self2) => sequentialCollectionMake(map7(self2.map, (x) => of2(x)));
|
|
var SequentialCollectionTypeId = /* @__PURE__ */ Symbol.for("effect/RequestBlock/RequestBlockSequential");
|
|
var sequentialVariance = {
|
|
_R: (_) => _
|
|
};
|
|
|
|
class SequentialImpl {
|
|
map;
|
|
[SequentialCollectionTypeId] = sequentialVariance;
|
|
constructor(map) {
|
|
this.map = map;
|
|
}
|
|
}
|
|
var sequentialCollectionMake = (map) => new SequentialImpl(map);
|
|
var sequentialCollectionCombine = (self2, that) => new SequentialImpl(reduce6(that.map, self2.map, (map, value, key) => set3(map, key, match2(get7(map, key), {
|
|
onNone: () => empty4(),
|
|
onSome: (a) => appendAll2(a, value)
|
|
}))));
|
|
var sequentialCollectionKeys = (self2) => Array.from(keys2(self2.map));
|
|
var sequentialCollectionToChunk = (self2) => Array.from(self2.map);
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/opCodes/cause.js
|
|
var OP_DIE = "Die";
|
|
var OP_EMPTY = "Empty";
|
|
var OP_FAIL = "Fail";
|
|
var OP_INTERRUPT = "Interrupt";
|
|
var OP_PARALLEL = "Parallel";
|
|
var OP_SEQUENTIAL = "Sequential";
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/cause.js
|
|
var CauseSymbolKey = "effect/Cause";
|
|
var CauseTypeId = /* @__PURE__ */ Symbol.for(CauseSymbolKey);
|
|
var variance4 = {
|
|
_E: (_) => _
|
|
};
|
|
var proto = {
|
|
[CauseTypeId]: variance4,
|
|
[symbol]() {
|
|
return pipe(hash(CauseSymbolKey), combine(hash(flattenCause(this))), cached(this));
|
|
},
|
|
[symbol2](that) {
|
|
return isCause(that) && causeEquals(this, that);
|
|
},
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
},
|
|
toJSON() {
|
|
switch (this._tag) {
|
|
case "Empty":
|
|
return {
|
|
_id: "Cause",
|
|
_tag: this._tag
|
|
};
|
|
case "Die":
|
|
return {
|
|
_id: "Cause",
|
|
_tag: this._tag,
|
|
defect: toJSON(this.defect)
|
|
};
|
|
case "Interrupt":
|
|
return {
|
|
_id: "Cause",
|
|
_tag: this._tag,
|
|
fiberId: this.fiberId.toJSON()
|
|
};
|
|
case "Fail":
|
|
return {
|
|
_id: "Cause",
|
|
_tag: this._tag,
|
|
failure: toJSON(this.error)
|
|
};
|
|
case "Sequential":
|
|
case "Parallel":
|
|
return {
|
|
_id: "Cause",
|
|
_tag: this._tag,
|
|
left: toJSON(this.left),
|
|
right: toJSON(this.right)
|
|
};
|
|
}
|
|
},
|
|
toString() {
|
|
return pretty(this);
|
|
},
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
}
|
|
};
|
|
var empty14 = /* @__PURE__ */ (() => {
|
|
const o = /* @__PURE__ */ Object.create(proto);
|
|
o._tag = OP_EMPTY;
|
|
return o;
|
|
})();
|
|
var fail = (error) => {
|
|
const o = Object.create(proto);
|
|
o._tag = OP_FAIL;
|
|
o.error = error;
|
|
return o;
|
|
};
|
|
var die = (defect) => {
|
|
const o = Object.create(proto);
|
|
o._tag = OP_DIE;
|
|
o.defect = defect;
|
|
return o;
|
|
};
|
|
var interrupt = (fiberId) => {
|
|
const o = Object.create(proto);
|
|
o._tag = OP_INTERRUPT;
|
|
o.fiberId = fiberId;
|
|
return o;
|
|
};
|
|
var parallel = (left, right) => {
|
|
const o = Object.create(proto);
|
|
o._tag = OP_PARALLEL;
|
|
o.left = left;
|
|
o.right = right;
|
|
return o;
|
|
};
|
|
var sequential = (left, right) => {
|
|
const o = Object.create(proto);
|
|
o._tag = OP_SEQUENTIAL;
|
|
o.left = left;
|
|
o.right = right;
|
|
return o;
|
|
};
|
|
var isCause = (u) => hasProperty(u, CauseTypeId);
|
|
var isEmptyType = (self2) => self2._tag === OP_EMPTY;
|
|
var isFailType = (self2) => self2._tag === OP_FAIL;
|
|
var isDieType = (self2) => self2._tag === OP_DIE;
|
|
var isEmpty5 = (self2) => {
|
|
if (self2._tag === OP_EMPTY) {
|
|
return true;
|
|
}
|
|
return reduce8(self2, true, (acc, cause) => {
|
|
switch (cause._tag) {
|
|
case OP_EMPTY: {
|
|
return some2(acc);
|
|
}
|
|
case OP_DIE:
|
|
case OP_FAIL:
|
|
case OP_INTERRUPT: {
|
|
return some2(false);
|
|
}
|
|
default: {
|
|
return none2();
|
|
}
|
|
}
|
|
});
|
|
};
|
|
var isInterrupted = (self2) => isSome2(interruptOption(self2));
|
|
var isInterruptedOnly = (self2) => reduceWithContext(undefined, IsInterruptedOnlyCauseReducer)(self2);
|
|
var failures = (self2) => reverse2(reduce8(self2, empty4(), (list, cause) => cause._tag === OP_FAIL ? some2(pipe(list, prepend2(cause.error))) : none2()));
|
|
var defects = (self2) => reverse2(reduce8(self2, empty4(), (list, cause) => cause._tag === OP_DIE ? some2(pipe(list, prepend2(cause.defect))) : none2()));
|
|
var interruptors = (self2) => reduce8(self2, empty7(), (set, cause) => cause._tag === OP_INTERRUPT ? some2(pipe(set, add4(cause.fiberId))) : none2());
|
|
var failureOption = (self2) => find(self2, (cause) => cause._tag === OP_FAIL ? some2(cause.error) : none2());
|
|
var failureOrCause = (self2) => {
|
|
const option = failureOption(self2);
|
|
switch (option._tag) {
|
|
case "None": {
|
|
return right2(self2);
|
|
}
|
|
case "Some": {
|
|
return left2(option.value);
|
|
}
|
|
}
|
|
};
|
|
var flipCauseOption = (self2) => match4(self2, {
|
|
onEmpty: some2(empty14),
|
|
onFail: map2(fail),
|
|
onDie: (defect) => some2(die(defect)),
|
|
onInterrupt: (fiberId) => some2(interrupt(fiberId)),
|
|
onSequential: mergeWith(sequential),
|
|
onParallel: mergeWith(parallel)
|
|
});
|
|
var interruptOption = (self2) => find(self2, (cause) => cause._tag === OP_INTERRUPT ? some2(cause.fiberId) : none2());
|
|
var stripFailures = (self2) => match4(self2, {
|
|
onEmpty: empty14,
|
|
onFail: () => empty14,
|
|
onDie: die,
|
|
onInterrupt: interrupt,
|
|
onSequential: sequential,
|
|
onParallel: parallel
|
|
});
|
|
var electFailures = (self2) => match4(self2, {
|
|
onEmpty: empty14,
|
|
onFail: die,
|
|
onDie: die,
|
|
onInterrupt: interrupt,
|
|
onSequential: sequential,
|
|
onParallel: parallel
|
|
});
|
|
var map9 = /* @__PURE__ */ dual(2, (self2, f) => flatMap6(self2, (e) => fail(f(e))));
|
|
var flatMap6 = /* @__PURE__ */ dual(2, (self2, f) => match4(self2, {
|
|
onEmpty: empty14,
|
|
onFail: (error) => f(error),
|
|
onDie: (defect) => die(defect),
|
|
onInterrupt: (fiberId) => interrupt(fiberId),
|
|
onSequential: (left, right) => sequential(left, right),
|
|
onParallel: (left, right) => parallel(left, right)
|
|
}));
|
|
var causeEquals = (left, right) => {
|
|
let leftStack = of2(left);
|
|
let rightStack = of2(right);
|
|
while (isNonEmpty(leftStack) && isNonEmpty(rightStack)) {
|
|
const [leftParallel, leftSequential] = pipe(headNonEmpty2(leftStack), reduce8([empty7(), empty4()], ([parallel, sequential], cause) => {
|
|
const [par, seq] = evaluateCause(cause);
|
|
return some2([pipe(parallel, union3(par)), pipe(sequential, appendAll2(seq))]);
|
|
}));
|
|
const [rightParallel, rightSequential] = pipe(headNonEmpty2(rightStack), reduce8([empty7(), empty4()], ([parallel, sequential], cause) => {
|
|
const [par, seq] = evaluateCause(cause);
|
|
return some2([pipe(parallel, union3(par)), pipe(sequential, appendAll2(seq))]);
|
|
}));
|
|
if (!equals(leftParallel, rightParallel)) {
|
|
return false;
|
|
}
|
|
leftStack = leftSequential;
|
|
rightStack = rightSequential;
|
|
}
|
|
return true;
|
|
};
|
|
var flattenCause = (cause) => {
|
|
return flattenCauseLoop(of2(cause), empty4());
|
|
};
|
|
var flattenCauseLoop = (causes, flattened) => {
|
|
while (true) {
|
|
const [parallel, sequential] = pipe(causes, reduce([empty7(), empty4()], ([parallel, sequential], cause) => {
|
|
const [par, seq] = evaluateCause(cause);
|
|
return [pipe(parallel, union3(par)), pipe(sequential, appendAll2(seq))];
|
|
}));
|
|
const updated = size3(parallel) > 0 ? pipe(flattened, prepend2(parallel)) : flattened;
|
|
if (isEmpty(sequential)) {
|
|
return reverse2(updated);
|
|
}
|
|
causes = sequential;
|
|
flattened = updated;
|
|
}
|
|
throw new Error(getBugErrorMessage("Cause.flattenCauseLoop"));
|
|
};
|
|
var find = /* @__PURE__ */ dual(2, (self2, pf) => {
|
|
const stack = [self2];
|
|
while (stack.length > 0) {
|
|
const item = stack.pop();
|
|
const option = pf(item);
|
|
switch (option._tag) {
|
|
case "None": {
|
|
switch (item._tag) {
|
|
case OP_SEQUENTIAL:
|
|
case OP_PARALLEL: {
|
|
stack.push(item.right);
|
|
stack.push(item.left);
|
|
break;
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case "Some": {
|
|
return option;
|
|
}
|
|
}
|
|
}
|
|
return none2();
|
|
});
|
|
var evaluateCause = (self2) => {
|
|
let cause = self2;
|
|
const stack = [];
|
|
let _parallel = empty7();
|
|
let _sequential = empty4();
|
|
while (cause !== undefined) {
|
|
switch (cause._tag) {
|
|
case OP_EMPTY: {
|
|
if (stack.length === 0) {
|
|
return [_parallel, _sequential];
|
|
}
|
|
cause = stack.pop();
|
|
break;
|
|
}
|
|
case OP_FAIL: {
|
|
_parallel = add4(_parallel, make6(cause._tag, cause.error));
|
|
if (stack.length === 0) {
|
|
return [_parallel, _sequential];
|
|
}
|
|
cause = stack.pop();
|
|
break;
|
|
}
|
|
case OP_DIE: {
|
|
_parallel = add4(_parallel, make6(cause._tag, cause.defect));
|
|
if (stack.length === 0) {
|
|
return [_parallel, _sequential];
|
|
}
|
|
cause = stack.pop();
|
|
break;
|
|
}
|
|
case OP_INTERRUPT: {
|
|
_parallel = add4(_parallel, make6(cause._tag, cause.fiberId));
|
|
if (stack.length === 0) {
|
|
return [_parallel, _sequential];
|
|
}
|
|
cause = stack.pop();
|
|
break;
|
|
}
|
|
case OP_SEQUENTIAL: {
|
|
switch (cause.left._tag) {
|
|
case OP_EMPTY: {
|
|
cause = cause.right;
|
|
break;
|
|
}
|
|
case OP_SEQUENTIAL: {
|
|
cause = sequential(cause.left.left, sequential(cause.left.right, cause.right));
|
|
break;
|
|
}
|
|
case OP_PARALLEL: {
|
|
cause = parallel(sequential(cause.left.left, cause.right), sequential(cause.left.right, cause.right));
|
|
break;
|
|
}
|
|
default: {
|
|
_sequential = prepend2(_sequential, cause.right);
|
|
cause = cause.left;
|
|
break;
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case OP_PARALLEL: {
|
|
stack.push(cause.right);
|
|
cause = cause.left;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
throw new Error(getBugErrorMessage("Cause.evaluateCauseLoop"));
|
|
};
|
|
var IsInterruptedOnlyCauseReducer = {
|
|
emptyCase: constTrue,
|
|
failCase: constFalse,
|
|
dieCase: constFalse,
|
|
interruptCase: constTrue,
|
|
sequentialCase: (_, left, right) => left && right,
|
|
parallelCase: (_, left, right) => left && right
|
|
};
|
|
var OP_SEQUENTIAL_CASE = "SequentialCase";
|
|
var OP_PARALLEL_CASE = "ParallelCase";
|
|
var match4 = /* @__PURE__ */ dual(2, (self2, {
|
|
onDie,
|
|
onEmpty,
|
|
onFail,
|
|
onInterrupt,
|
|
onParallel,
|
|
onSequential
|
|
}) => {
|
|
return reduceWithContext(self2, undefined, {
|
|
emptyCase: () => onEmpty,
|
|
failCase: (_, error) => onFail(error),
|
|
dieCase: (_, defect) => onDie(defect),
|
|
interruptCase: (_, fiberId) => onInterrupt(fiberId),
|
|
sequentialCase: (_, left, right) => onSequential(left, right),
|
|
parallelCase: (_, left, right) => onParallel(left, right)
|
|
});
|
|
});
|
|
var reduce8 = /* @__PURE__ */ dual(3, (self2, zero, pf) => {
|
|
let accumulator = zero;
|
|
let cause = self2;
|
|
const causes = [];
|
|
while (cause !== undefined) {
|
|
const option = pf(accumulator, cause);
|
|
accumulator = isSome2(option) ? option.value : accumulator;
|
|
switch (cause._tag) {
|
|
case OP_SEQUENTIAL: {
|
|
causes.push(cause.right);
|
|
cause = cause.left;
|
|
break;
|
|
}
|
|
case OP_PARALLEL: {
|
|
causes.push(cause.right);
|
|
cause = cause.left;
|
|
break;
|
|
}
|
|
default: {
|
|
cause = undefined;
|
|
break;
|
|
}
|
|
}
|
|
if (cause === undefined && causes.length > 0) {
|
|
cause = causes.pop();
|
|
}
|
|
}
|
|
return accumulator;
|
|
});
|
|
var reduceWithContext = /* @__PURE__ */ dual(3, (self2, context, reducer) => {
|
|
const input = [self2];
|
|
const output = [];
|
|
while (input.length > 0) {
|
|
const cause = input.pop();
|
|
switch (cause._tag) {
|
|
case OP_EMPTY: {
|
|
output.push(right2(reducer.emptyCase(context)));
|
|
break;
|
|
}
|
|
case OP_FAIL: {
|
|
output.push(right2(reducer.failCase(context, cause.error)));
|
|
break;
|
|
}
|
|
case OP_DIE: {
|
|
output.push(right2(reducer.dieCase(context, cause.defect)));
|
|
break;
|
|
}
|
|
case OP_INTERRUPT: {
|
|
output.push(right2(reducer.interruptCase(context, cause.fiberId)));
|
|
break;
|
|
}
|
|
case OP_SEQUENTIAL: {
|
|
input.push(cause.right);
|
|
input.push(cause.left);
|
|
output.push(left2({
|
|
_tag: OP_SEQUENTIAL_CASE
|
|
}));
|
|
break;
|
|
}
|
|
case OP_PARALLEL: {
|
|
input.push(cause.right);
|
|
input.push(cause.left);
|
|
output.push(left2({
|
|
_tag: OP_PARALLEL_CASE
|
|
}));
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
const accumulator = [];
|
|
while (output.length > 0) {
|
|
const either = output.pop();
|
|
switch (either._tag) {
|
|
case "Left": {
|
|
switch (either.left._tag) {
|
|
case OP_SEQUENTIAL_CASE: {
|
|
const left = accumulator.pop();
|
|
const right = accumulator.pop();
|
|
const value = reducer.sequentialCase(context, left, right);
|
|
accumulator.push(value);
|
|
break;
|
|
}
|
|
case OP_PARALLEL_CASE: {
|
|
const left = accumulator.pop();
|
|
const right = accumulator.pop();
|
|
const value = reducer.parallelCase(context, left, right);
|
|
accumulator.push(value);
|
|
break;
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case "Right": {
|
|
accumulator.push(either.right);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (accumulator.length === 0) {
|
|
throw new Error("BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");
|
|
}
|
|
return accumulator.pop();
|
|
});
|
|
var pretty = (cause, options) => {
|
|
if (isInterruptedOnly(cause)) {
|
|
return "All fibers interrupted without errors.";
|
|
}
|
|
return prettyErrors(cause).map(function(e) {
|
|
if (options?.renderErrorCause !== true || e.cause === undefined) {
|
|
return e.stack;
|
|
}
|
|
return `${e.stack} {
|
|
${renderErrorCause(e.cause, " ")}
|
|
}`;
|
|
}).join(`
|
|
`);
|
|
};
|
|
var renderErrorCause = (cause, prefix) => {
|
|
const lines = cause.stack.split(`
|
|
`);
|
|
let stack = `${prefix}[cause]: ${lines[0]}`;
|
|
for (let i = 1, len = lines.length;i < len; i++) {
|
|
stack += `
|
|
${prefix}${lines[i]}`;
|
|
}
|
|
if (cause.cause) {
|
|
stack += ` {
|
|
${renderErrorCause(cause.cause, `${prefix} `)}
|
|
${prefix}}`;
|
|
}
|
|
return stack;
|
|
};
|
|
var makePrettyError = (originalError) => {
|
|
const originalErrorIsObject = typeof originalError === "object" && originalError !== null;
|
|
const prevLimit = Error.stackTraceLimit;
|
|
Error.stackTraceLimit = 1;
|
|
const error = new Error(prettyErrorMessage(originalError), originalErrorIsObject && "cause" in originalError && typeof originalError.cause !== "undefined" ? {
|
|
cause: makePrettyError(originalError.cause)
|
|
} : undefined);
|
|
Error.stackTraceLimit = prevLimit;
|
|
if (error.message === "") {
|
|
error.message = "An error has occurred";
|
|
}
|
|
Error.stackTraceLimit = prevLimit;
|
|
error.name = originalError instanceof Error ? originalError.name : "Error";
|
|
if (originalErrorIsObject) {
|
|
if (spanSymbol in originalError) {
|
|
error.span = originalError[spanSymbol];
|
|
}
|
|
Object.keys(originalError).forEach((key) => {
|
|
if (!(key in error)) {
|
|
error[key] = originalError[key];
|
|
}
|
|
});
|
|
}
|
|
error.stack = prettyErrorStack(`${error.name}: ${error.message}`, originalError instanceof Error && originalError.stack ? originalError.stack : "", error.span);
|
|
return error;
|
|
};
|
|
var prettyErrorMessage = (u) => {
|
|
if (typeof u === "string") {
|
|
return u;
|
|
}
|
|
if (typeof u === "object" && u !== null && u instanceof Error) {
|
|
return u.message;
|
|
}
|
|
try {
|
|
if (hasProperty(u, "toString") && isFunction2(u["toString"]) && u["toString"] !== Object.prototype.toString && u["toString"] !== globalThis.Array.prototype.toString) {
|
|
return u["toString"]();
|
|
}
|
|
} catch {}
|
|
return stringifyCircular(u);
|
|
};
|
|
var locationRegex = /\((.*)\)/g;
|
|
var spanToTrace = /* @__PURE__ */ globalValue("effect/Tracer/spanToTrace", () => new WeakMap);
|
|
var prettyErrorStack = (message, stack, span) => {
|
|
const out = [message];
|
|
const lines = stack.startsWith(message) ? stack.slice(message.length).split(`
|
|
`) : stack.split(`
|
|
`);
|
|
for (let i = 1;i < lines.length; i++) {
|
|
if (lines[i].includes(" at new BaseEffectError") || lines[i].includes(" at new YieldableError")) {
|
|
i++;
|
|
continue;
|
|
}
|
|
if (lines[i].includes("Generator.next")) {
|
|
break;
|
|
}
|
|
if (lines[i].includes("effect_internal_function")) {
|
|
break;
|
|
}
|
|
out.push(lines[i].replace(/at .*effect_instruction_i.*\((.*)\)/, "at $1").replace(/EffectPrimitive\.\w+/, "<anonymous>"));
|
|
}
|
|
if (span) {
|
|
let current = span;
|
|
let i = 0;
|
|
while (current && current._tag === "Span" && i < 10) {
|
|
const stackFn = spanToTrace.get(current);
|
|
if (typeof stackFn === "function") {
|
|
const stack = stackFn();
|
|
if (typeof stack === "string") {
|
|
const locationMatchAll = stack.matchAll(locationRegex);
|
|
let match = false;
|
|
for (const [, location2] of locationMatchAll) {
|
|
match = true;
|
|
out.push(` at ${current.name} (${location2})`);
|
|
}
|
|
if (!match) {
|
|
out.push(` at ${current.name} (${stack.replace(/^at /, "")})`);
|
|
}
|
|
} else {
|
|
out.push(` at ${current.name}`);
|
|
}
|
|
} else {
|
|
out.push(` at ${current.name}`);
|
|
}
|
|
current = getOrUndefined(current.parent);
|
|
i++;
|
|
}
|
|
}
|
|
return out.join(`
|
|
`);
|
|
};
|
|
var spanSymbol = /* @__PURE__ */ Symbol.for("effect/SpanAnnotation");
|
|
var prettyErrors = (cause) => reduceWithContext(cause, undefined, {
|
|
emptyCase: () => [],
|
|
dieCase: (_, unknownError) => {
|
|
return [makePrettyError(unknownError)];
|
|
},
|
|
failCase: (_, error) => {
|
|
return [makePrettyError(error)];
|
|
},
|
|
interruptCase: () => [],
|
|
parallelCase: (_, l, r) => [...l, ...r],
|
|
sequentialCase: (_, l, r) => [...l, ...r]
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/opCodes/deferred.js
|
|
var OP_STATE_PENDING = "Pending";
|
|
var OP_STATE_DONE = "Done";
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/deferred.js
|
|
var DeferredSymbolKey = "effect/Deferred";
|
|
var DeferredTypeId = /* @__PURE__ */ Symbol.for(DeferredSymbolKey);
|
|
var deferredVariance = {
|
|
_E: (_) => _,
|
|
_A: (_) => _
|
|
};
|
|
var pending = (joiners) => {
|
|
return {
|
|
_tag: OP_STATE_PENDING,
|
|
joiners
|
|
};
|
|
};
|
|
var done = (effect) => {
|
|
return {
|
|
_tag: OP_STATE_DONE,
|
|
effect
|
|
};
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/singleShotGen.js
|
|
class SingleShotGen2 {
|
|
self;
|
|
called = false;
|
|
constructor(self2) {
|
|
this.self = self2;
|
|
}
|
|
next(a) {
|
|
return this.called ? {
|
|
value: a,
|
|
done: true
|
|
} : (this.called = true, {
|
|
value: this.self,
|
|
done: false
|
|
});
|
|
}
|
|
return(a) {
|
|
return {
|
|
value: a,
|
|
done: true
|
|
};
|
|
}
|
|
throw(e) {
|
|
throw e;
|
|
}
|
|
[Symbol.iterator]() {
|
|
return new SingleShotGen2(this.self);
|
|
}
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/core.js
|
|
var blocked = (blockedRequests, _continue) => {
|
|
const effect = new EffectPrimitive("Blocked");
|
|
effect.effect_instruction_i0 = blockedRequests;
|
|
effect.effect_instruction_i1 = _continue;
|
|
return effect;
|
|
};
|
|
var runRequestBlock = (blockedRequests) => {
|
|
const effect = new EffectPrimitive("RunBlocked");
|
|
effect.effect_instruction_i0 = blockedRequests;
|
|
return effect;
|
|
};
|
|
var EffectTypeId2 = /* @__PURE__ */ Symbol.for("effect/Effect");
|
|
|
|
class RevertFlags {
|
|
patch;
|
|
op;
|
|
_op = OP_REVERT_FLAGS;
|
|
constructor(patch, op) {
|
|
this.patch = patch;
|
|
this.op = op;
|
|
}
|
|
}
|
|
|
|
class EffectPrimitive {
|
|
_op;
|
|
effect_instruction_i0 = undefined;
|
|
effect_instruction_i1 = undefined;
|
|
effect_instruction_i2 = undefined;
|
|
trace = undefined;
|
|
[EffectTypeId2] = effectVariance;
|
|
constructor(_op) {
|
|
this._op = _op;
|
|
}
|
|
[symbol2](that) {
|
|
return this === that;
|
|
}
|
|
[symbol]() {
|
|
return cached(this, random(this));
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_id: "Effect",
|
|
_op: this._op,
|
|
effect_instruction_i0: toJSON(this.effect_instruction_i0),
|
|
effect_instruction_i1: toJSON(this.effect_instruction_i1),
|
|
effect_instruction_i2: toJSON(this.effect_instruction_i2)
|
|
};
|
|
}
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
}
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
}
|
|
[Symbol.iterator]() {
|
|
return new SingleShotGen2(new YieldWrap(this));
|
|
}
|
|
}
|
|
|
|
class EffectPrimitiveFailure {
|
|
_op;
|
|
effect_instruction_i0 = undefined;
|
|
effect_instruction_i1 = undefined;
|
|
effect_instruction_i2 = undefined;
|
|
trace = undefined;
|
|
[EffectTypeId2] = effectVariance;
|
|
constructor(_op) {
|
|
this._op = _op;
|
|
this._tag = _op;
|
|
}
|
|
[symbol2](that) {
|
|
return exitIsExit(that) && that._op === "Failure" && equals(this.effect_instruction_i0, that.effect_instruction_i0);
|
|
}
|
|
[symbol]() {
|
|
return pipe(string(this._tag), combine(hash(this.effect_instruction_i0)), cached(this));
|
|
}
|
|
get cause() {
|
|
return this.effect_instruction_i0;
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_id: "Exit",
|
|
_tag: this._op,
|
|
cause: this.cause.toJSON()
|
|
};
|
|
}
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
}
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
}
|
|
[Symbol.iterator]() {
|
|
return new SingleShotGen2(new YieldWrap(this));
|
|
}
|
|
}
|
|
|
|
class EffectPrimitiveSuccess {
|
|
_op;
|
|
effect_instruction_i0 = undefined;
|
|
effect_instruction_i1 = undefined;
|
|
effect_instruction_i2 = undefined;
|
|
trace = undefined;
|
|
[EffectTypeId2] = effectVariance;
|
|
constructor(_op) {
|
|
this._op = _op;
|
|
this._tag = _op;
|
|
}
|
|
[symbol2](that) {
|
|
return exitIsExit(that) && that._op === "Success" && equals(this.effect_instruction_i0, that.effect_instruction_i0);
|
|
}
|
|
[symbol]() {
|
|
return pipe(string(this._tag), combine(hash(this.effect_instruction_i0)), cached(this));
|
|
}
|
|
get value() {
|
|
return this.effect_instruction_i0;
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_id: "Exit",
|
|
_tag: this._op,
|
|
value: toJSON(this.value)
|
|
};
|
|
}
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
}
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
}
|
|
[Symbol.iterator]() {
|
|
return new SingleShotGen2(new YieldWrap(this));
|
|
}
|
|
}
|
|
var isEffect = (u) => hasProperty(u, EffectTypeId2);
|
|
var withFiberRuntime = (withRuntime) => {
|
|
const effect = new EffectPrimitive(OP_WITH_RUNTIME);
|
|
effect.effect_instruction_i0 = withRuntime;
|
|
return effect;
|
|
};
|
|
var acquireUseRelease = /* @__PURE__ */ dual(3, (acquire, use, release) => uninterruptibleMask((restore) => flatMap7(acquire, (a) => flatMap7(exit(suspend(() => restore(use(a)))), (exit) => {
|
|
return suspend(() => release(a, exit)).pipe(matchCauseEffect({
|
|
onFailure: (cause) => {
|
|
switch (exit._tag) {
|
|
case OP_FAILURE:
|
|
return failCause(sequential(exit.effect_instruction_i0, cause));
|
|
case OP_SUCCESS:
|
|
return failCause(cause);
|
|
}
|
|
},
|
|
onSuccess: () => exit
|
|
}));
|
|
}))));
|
|
var as = /* @__PURE__ */ dual(2, (self2, value) => flatMap7(self2, () => succeed(value)));
|
|
var asVoid = (self2) => as(self2, undefined);
|
|
var custom2 = function() {
|
|
const wrapper = new EffectPrimitive(OP_COMMIT);
|
|
switch (arguments.length) {
|
|
case 2: {
|
|
wrapper.effect_instruction_i0 = arguments[0];
|
|
wrapper.commit = arguments[1];
|
|
break;
|
|
}
|
|
case 3: {
|
|
wrapper.effect_instruction_i0 = arguments[0];
|
|
wrapper.effect_instruction_i1 = arguments[1];
|
|
wrapper.commit = arguments[2];
|
|
break;
|
|
}
|
|
case 4: {
|
|
wrapper.effect_instruction_i0 = arguments[0];
|
|
wrapper.effect_instruction_i1 = arguments[1];
|
|
wrapper.effect_instruction_i2 = arguments[2];
|
|
wrapper.commit = arguments[3];
|
|
break;
|
|
}
|
|
default: {
|
|
throw new Error(getBugErrorMessage("you're not supposed to end up here"));
|
|
}
|
|
}
|
|
return wrapper;
|
|
};
|
|
var unsafeAsync = (register, blockingOn = none4) => {
|
|
const effect = new EffectPrimitive(OP_ASYNC);
|
|
let cancelerRef = undefined;
|
|
effect.effect_instruction_i0 = (resume) => {
|
|
cancelerRef = register(resume);
|
|
};
|
|
effect.effect_instruction_i1 = blockingOn;
|
|
return onInterrupt(effect, (_) => isEffect(cancelerRef) ? cancelerRef : void_);
|
|
};
|
|
var asyncInterrupt = (register, blockingOn = none4) => suspend(() => unsafeAsync(register, blockingOn));
|
|
var async_ = (resume, blockingOn = none4) => {
|
|
return custom2(resume, function() {
|
|
let backingResume = undefined;
|
|
let pendingEffect = undefined;
|
|
function proxyResume(effect) {
|
|
if (backingResume) {
|
|
backingResume(effect);
|
|
} else if (pendingEffect === undefined) {
|
|
pendingEffect = effect;
|
|
}
|
|
}
|
|
const effect = new EffectPrimitive(OP_ASYNC);
|
|
effect.effect_instruction_i0 = (resume) => {
|
|
backingResume = resume;
|
|
if (pendingEffect) {
|
|
resume(pendingEffect);
|
|
}
|
|
};
|
|
effect.effect_instruction_i1 = blockingOn;
|
|
let cancelerRef = undefined;
|
|
let controllerRef = undefined;
|
|
if (this.effect_instruction_i0.length !== 1) {
|
|
controllerRef = new AbortController;
|
|
cancelerRef = internalCall(() => this.effect_instruction_i0(proxyResume, controllerRef.signal));
|
|
} else {
|
|
cancelerRef = internalCall(() => this.effect_instruction_i0(proxyResume));
|
|
}
|
|
return cancelerRef || controllerRef ? onInterrupt(effect, (_) => {
|
|
if (controllerRef) {
|
|
controllerRef.abort();
|
|
}
|
|
return cancelerRef ?? void_;
|
|
}) : effect;
|
|
});
|
|
};
|
|
var catchAllCause = /* @__PURE__ */ dual(2, (self2, f) => {
|
|
const effect = new EffectPrimitive(OP_ON_FAILURE);
|
|
effect.effect_instruction_i0 = self2;
|
|
effect.effect_instruction_i1 = f;
|
|
return effect;
|
|
});
|
|
var catchAll = /* @__PURE__ */ dual(2, (self2, f) => matchEffect(self2, {
|
|
onFailure: f,
|
|
onSuccess: succeed
|
|
}));
|
|
var catchIf = /* @__PURE__ */ dual(3, (self2, predicate, f) => catchAllCause(self2, (cause) => {
|
|
const either = failureOrCause(cause);
|
|
switch (either._tag) {
|
|
case "Left":
|
|
return predicate(either.left) ? f(either.left) : failCause(cause);
|
|
case "Right":
|
|
return failCause(either.right);
|
|
}
|
|
}));
|
|
var originalSymbol = /* @__PURE__ */ Symbol.for("effect/OriginalAnnotation");
|
|
var capture = (obj, span) => {
|
|
if (isSome2(span)) {
|
|
return new Proxy(obj, {
|
|
has(target, p) {
|
|
return p === spanSymbol || p === originalSymbol || p in target;
|
|
},
|
|
get(target, p) {
|
|
if (p === spanSymbol) {
|
|
return span.value;
|
|
}
|
|
if (p === originalSymbol) {
|
|
return obj;
|
|
}
|
|
return target[p];
|
|
}
|
|
});
|
|
}
|
|
return obj;
|
|
};
|
|
var die2 = (defect) => isObject2(defect) && !(spanSymbol in defect) ? withFiberRuntime((fiber) => failCause(die(capture(defect, currentSpanFromFiber(fiber))))) : failCause(die(defect));
|
|
var dieMessage = (message) => failCauseSync(() => die(new RuntimeException(message)));
|
|
var either2 = (self2) => matchEffect(self2, {
|
|
onFailure: (e) => succeed(left2(e)),
|
|
onSuccess: (a) => succeed(right2(a))
|
|
});
|
|
var exit = (self2) => matchCause(self2, {
|
|
onFailure: exitFailCause,
|
|
onSuccess: exitSucceed
|
|
});
|
|
var fail2 = (error) => isObject2(error) && !(spanSymbol in error) ? withFiberRuntime((fiber) => failCause(fail(capture(error, currentSpanFromFiber(fiber))))) : failCause(fail(error));
|
|
var failSync = (evaluate) => flatMap7(sync(evaluate), fail2);
|
|
var failCause = (cause) => {
|
|
const effect = new EffectPrimitiveFailure(OP_FAILURE);
|
|
effect.effect_instruction_i0 = cause;
|
|
return effect;
|
|
};
|
|
var failCauseSync = (evaluate) => flatMap7(sync(evaluate), failCause);
|
|
var fiberId = /* @__PURE__ */ withFiberRuntime((state) => succeed(state.id()));
|
|
var fiberIdWith = (f) => withFiberRuntime((state) => f(state.id()));
|
|
var flatMap7 = /* @__PURE__ */ dual(2, (self2, f) => {
|
|
const effect = new EffectPrimitive(OP_ON_SUCCESS);
|
|
effect.effect_instruction_i0 = self2;
|
|
effect.effect_instruction_i1 = f;
|
|
return effect;
|
|
});
|
|
var step2 = (self2) => {
|
|
const effect = new EffectPrimitive("OnStep");
|
|
effect.effect_instruction_i0 = self2;
|
|
return effect;
|
|
};
|
|
var flatten3 = (self2) => flatMap7(self2, identity);
|
|
var matchCause = /* @__PURE__ */ dual(2, (self2, options) => matchCauseEffect(self2, {
|
|
onFailure: (cause) => succeed(options.onFailure(cause)),
|
|
onSuccess: (a) => succeed(options.onSuccess(a))
|
|
}));
|
|
var matchCauseEffect = /* @__PURE__ */ dual(2, (self2, options) => {
|
|
const effect = new EffectPrimitive(OP_ON_SUCCESS_AND_FAILURE);
|
|
effect.effect_instruction_i0 = self2;
|
|
effect.effect_instruction_i1 = options.onFailure;
|
|
effect.effect_instruction_i2 = options.onSuccess;
|
|
return effect;
|
|
});
|
|
var matchEffect = /* @__PURE__ */ dual(2, (self2, options) => matchCauseEffect(self2, {
|
|
onFailure: (cause) => {
|
|
const defects2 = defects(cause);
|
|
if (defects2.length > 0) {
|
|
return failCause(electFailures(cause));
|
|
}
|
|
const failures2 = failures(cause);
|
|
if (failures2.length > 0) {
|
|
return options.onFailure(unsafeHead(failures2));
|
|
}
|
|
return failCause(cause);
|
|
},
|
|
onSuccess: options.onSuccess
|
|
}));
|
|
var forEachSequential = /* @__PURE__ */ dual(2, (self2, f) => suspend(() => {
|
|
const arr = fromIterable(self2);
|
|
const ret = allocate(arr.length);
|
|
let i = 0;
|
|
return as(whileLoop({
|
|
while: () => i < arr.length,
|
|
body: () => f(arr[i], i),
|
|
step: (b) => {
|
|
ret[i++] = b;
|
|
}
|
|
}), ret);
|
|
}));
|
|
var forEachSequentialDiscard = /* @__PURE__ */ dual(2, (self2, f) => suspend(() => {
|
|
const arr = fromIterable(self2);
|
|
let i = 0;
|
|
return whileLoop({
|
|
while: () => i < arr.length,
|
|
body: () => f(arr[i], i),
|
|
step: () => {
|
|
i++;
|
|
}
|
|
});
|
|
}));
|
|
var interrupt2 = /* @__PURE__ */ flatMap7(fiberId, (fiberId) => interruptWith(fiberId));
|
|
var interruptWith = (fiberId) => failCause(interrupt(fiberId));
|
|
var interruptible2 = (self2) => {
|
|
const effect = new EffectPrimitive(OP_UPDATE_RUNTIME_FLAGS);
|
|
effect.effect_instruction_i0 = enable3(Interruption);
|
|
effect.effect_instruction_i1 = () => self2;
|
|
return effect;
|
|
};
|
|
var intoDeferred = /* @__PURE__ */ dual(2, (self2, deferred) => uninterruptibleMask((restore) => flatMap7(exit(restore(self2)), (exit) => deferredDone(deferred, exit))));
|
|
var map10 = /* @__PURE__ */ dual(2, (self2, f) => flatMap7(self2, (a) => sync(() => f(a))));
|
|
var mapBoth = /* @__PURE__ */ dual(2, (self2, options) => matchEffect(self2, {
|
|
onFailure: (e) => failSync(() => options.onFailure(e)),
|
|
onSuccess: (a) => sync(() => options.onSuccess(a))
|
|
}));
|
|
var mapError = /* @__PURE__ */ dual(2, (self2, f) => matchCauseEffect(self2, {
|
|
onFailure: (cause) => {
|
|
const either = failureOrCause(cause);
|
|
switch (either._tag) {
|
|
case "Left": {
|
|
return failSync(() => f(either.left));
|
|
}
|
|
case "Right": {
|
|
return failCause(either.right);
|
|
}
|
|
}
|
|
},
|
|
onSuccess: succeed
|
|
}));
|
|
var onError = /* @__PURE__ */ dual(2, (self2, cleanup) => onExit(self2, (exit) => exitIsSuccess(exit) ? void_ : cleanup(exit.effect_instruction_i0)));
|
|
var onExit = /* @__PURE__ */ dual(2, (self2, cleanup) => uninterruptibleMask((restore) => matchCauseEffect(restore(self2), {
|
|
onFailure: (cause1) => {
|
|
const result = exitFailCause(cause1);
|
|
return matchCauseEffect(cleanup(result), {
|
|
onFailure: (cause2) => exitFailCause(sequential(cause1, cause2)),
|
|
onSuccess: () => result
|
|
});
|
|
},
|
|
onSuccess: (success) => {
|
|
const result = exitSucceed(success);
|
|
return zipRight(cleanup(result), result);
|
|
}
|
|
})));
|
|
var onInterrupt = /* @__PURE__ */ dual(2, (self2, cleanup) => onExit(self2, exitMatch({
|
|
onFailure: (cause) => isInterruptedOnly(cause) ? asVoid(cleanup(interruptors(cause))) : void_,
|
|
onSuccess: () => void_
|
|
})));
|
|
var orDie = (self2) => orDieWith(self2, identity);
|
|
var orDieWith = /* @__PURE__ */ dual(2, (self2, f) => matchEffect(self2, {
|
|
onFailure: (e) => die2(f(e)),
|
|
onSuccess: succeed
|
|
}));
|
|
var succeed = (value) => {
|
|
const effect = new EffectPrimitiveSuccess(OP_SUCCESS);
|
|
effect.effect_instruction_i0 = value;
|
|
return effect;
|
|
};
|
|
var suspend = (evaluate) => {
|
|
const effect = new EffectPrimitive(OP_COMMIT);
|
|
effect.commit = evaluate;
|
|
return effect;
|
|
};
|
|
var sync = (thunk) => {
|
|
const effect = new EffectPrimitive(OP_SYNC);
|
|
effect.effect_instruction_i0 = thunk;
|
|
return effect;
|
|
};
|
|
var tap = /* @__PURE__ */ dual((args) => args.length === 3 || args.length === 2 && !(isObject2(args[1]) && ("onlyEffect" in args[1])), (self2, f) => flatMap7(self2, (a) => {
|
|
const b = typeof f === "function" ? f(a) : f;
|
|
if (isEffect(b)) {
|
|
return as(b, a);
|
|
} else if (isPromiseLike(b)) {
|
|
return unsafeAsync((resume) => {
|
|
b.then((_) => resume(succeed(a)), (e) => resume(fail2(new UnknownException(e, "An unknown error occurred in Effect.tap"))));
|
|
});
|
|
}
|
|
return succeed(a);
|
|
}));
|
|
var transplant = (f) => withFiberRuntime((state) => {
|
|
const scopeOverride = state.getFiberRef(currentForkScopeOverride);
|
|
const scope = pipe(scopeOverride, getOrElse(() => state.scope()));
|
|
return f(fiberRefLocally(currentForkScopeOverride, some2(scope)));
|
|
});
|
|
var uninterruptible = (self2) => {
|
|
const effect = new EffectPrimitive(OP_UPDATE_RUNTIME_FLAGS);
|
|
effect.effect_instruction_i0 = disable3(Interruption);
|
|
effect.effect_instruction_i1 = () => self2;
|
|
return effect;
|
|
};
|
|
var uninterruptibleMask = (f) => custom2(f, function() {
|
|
const effect = new EffectPrimitive(OP_UPDATE_RUNTIME_FLAGS);
|
|
effect.effect_instruction_i0 = disable3(Interruption);
|
|
effect.effect_instruction_i1 = (oldFlags) => interruption(oldFlags) ? internalCall(() => this.effect_instruction_i0(interruptible2)) : internalCall(() => this.effect_instruction_i0(uninterruptible));
|
|
return effect;
|
|
});
|
|
var void_ = /* @__PURE__ */ succeed(undefined);
|
|
var updateRuntimeFlags = (patch) => {
|
|
const effect = new EffectPrimitive(OP_UPDATE_RUNTIME_FLAGS);
|
|
effect.effect_instruction_i0 = patch;
|
|
effect.effect_instruction_i1 = undefined;
|
|
return effect;
|
|
};
|
|
var whenEffect = /* @__PURE__ */ dual(2, (self2, condition) => flatMap7(condition, (b) => {
|
|
if (b) {
|
|
return pipe(self2, map10(some2));
|
|
}
|
|
return succeed(none2());
|
|
}));
|
|
var whileLoop = (options) => {
|
|
const effect = new EffectPrimitive(OP_WHILE);
|
|
effect.effect_instruction_i0 = options.while;
|
|
effect.effect_instruction_i1 = options.body;
|
|
effect.effect_instruction_i2 = options.step;
|
|
return effect;
|
|
};
|
|
var fromIterator = (iterator) => suspend(() => {
|
|
const effect = new EffectPrimitive(OP_ITERATOR);
|
|
effect.effect_instruction_i0 = iterator();
|
|
return effect;
|
|
});
|
|
var gen = function() {
|
|
const f = arguments.length === 1 ? arguments[0] : arguments[1].bind(arguments[0]);
|
|
return fromIterator(() => f(pipe));
|
|
};
|
|
var fnUntraced = (body, ...pipeables) => Object.defineProperty(pipeables.length === 0 ? function(...args) {
|
|
return fromIterator(() => body.apply(this, args));
|
|
} : function(...args) {
|
|
let effect = fromIterator(() => body.apply(this, args));
|
|
for (const x of pipeables) {
|
|
effect = x(effect, ...args);
|
|
}
|
|
return effect;
|
|
}, "length", {
|
|
value: body.length,
|
|
configurable: true
|
|
});
|
|
var withRuntimeFlags = /* @__PURE__ */ dual(2, (self2, update) => {
|
|
const effect = new EffectPrimitive(OP_UPDATE_RUNTIME_FLAGS);
|
|
effect.effect_instruction_i0 = update;
|
|
effect.effect_instruction_i1 = () => self2;
|
|
return effect;
|
|
});
|
|
var yieldNow = (options) => {
|
|
const effect = new EffectPrimitive(OP_YIELD);
|
|
return typeof options?.priority !== "undefined" ? withSchedulingPriority(effect, options.priority) : effect;
|
|
};
|
|
var zip2 = /* @__PURE__ */ dual(2, (self2, that) => flatMap7(self2, (a) => map10(that, (b) => [a, b])));
|
|
var zipLeft = /* @__PURE__ */ dual(2, (self2, that) => flatMap7(self2, (a) => as(that, a)));
|
|
var zipRight = /* @__PURE__ */ dual(2, (self2, that) => flatMap7(self2, () => that));
|
|
var zipWith2 = /* @__PURE__ */ dual(3, (self2, that, f) => flatMap7(self2, (a) => map10(that, (b) => f(a, b))));
|
|
var never = /* @__PURE__ */ asyncInterrupt(() => {
|
|
const interval = setInterval(() => {}, 2 ** 31 - 1);
|
|
return sync(() => clearInterval(interval));
|
|
});
|
|
var interruptFiber = (self2) => flatMap7(fiberId, (fiberId) => pipe(self2, interruptAsFiber(fiberId)));
|
|
var interruptAsFiber = /* @__PURE__ */ dual(2, (self2, fiberId) => flatMap7(self2.interruptAsFork(fiberId), () => self2.await));
|
|
var logLevelAll = {
|
|
_tag: "All",
|
|
syslog: 0,
|
|
label: "ALL",
|
|
ordinal: Number.MIN_SAFE_INTEGER,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var logLevelFatal = {
|
|
_tag: "Fatal",
|
|
syslog: 2,
|
|
label: "FATAL",
|
|
ordinal: 50000,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var logLevelError = {
|
|
_tag: "Error",
|
|
syslog: 3,
|
|
label: "ERROR",
|
|
ordinal: 40000,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var logLevelWarning = {
|
|
_tag: "Warning",
|
|
syslog: 4,
|
|
label: "WARN",
|
|
ordinal: 30000,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var logLevelInfo = {
|
|
_tag: "Info",
|
|
syslog: 6,
|
|
label: "INFO",
|
|
ordinal: 20000,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var logLevelDebug = {
|
|
_tag: "Debug",
|
|
syslog: 7,
|
|
label: "DEBUG",
|
|
ordinal: 1e4,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var logLevelTrace = {
|
|
_tag: "Trace",
|
|
syslog: 7,
|
|
label: "TRACE",
|
|
ordinal: 0,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var logLevelNone = {
|
|
_tag: "None",
|
|
syslog: 7,
|
|
label: "OFF",
|
|
ordinal: Number.MAX_SAFE_INTEGER,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var FiberRefSymbolKey = "effect/FiberRef";
|
|
var FiberRefTypeId = /* @__PURE__ */ Symbol.for(FiberRefSymbolKey);
|
|
var fiberRefVariance = {
|
|
_A: (_) => _
|
|
};
|
|
var fiberRefGet = (self2) => withFiberRuntime((fiber) => exitSucceed(fiber.getFiberRef(self2)));
|
|
var fiberRefGetWith = /* @__PURE__ */ dual(2, (self2, f) => flatMap7(fiberRefGet(self2), f));
|
|
var fiberRefSet = /* @__PURE__ */ dual(2, (self2, value) => fiberRefModify(self2, () => [undefined, value]));
|
|
var fiberRefModify = /* @__PURE__ */ dual(2, (self2, f) => withFiberRuntime((state) => {
|
|
const [b, a] = f(state.getFiberRef(self2));
|
|
state.setFiberRef(self2, a);
|
|
return succeed(b);
|
|
}));
|
|
var fiberRefLocally = /* @__PURE__ */ dual(3, (use, self2, value) => acquireUseRelease(zipLeft(fiberRefGet(self2), fiberRefSet(self2, value)), () => use, (oldValue) => fiberRefSet(self2, oldValue)));
|
|
var fiberRefLocallyWith = /* @__PURE__ */ dual(3, (use, self2, f) => fiberRefGetWith(self2, (a) => fiberRefLocally(use, self2, f(a))));
|
|
var fiberRefUnsafeMake = (initial, options) => fiberRefUnsafeMakePatch(initial, {
|
|
differ: update(),
|
|
fork: options?.fork ?? identity,
|
|
join: options?.join
|
|
});
|
|
var fiberRefUnsafeMakeHashSet = (initial) => {
|
|
const differ2 = hashSet();
|
|
return fiberRefUnsafeMakePatch(initial, {
|
|
differ: differ2,
|
|
fork: differ2.empty
|
|
});
|
|
};
|
|
var fiberRefUnsafeMakeReadonlyArray = (initial) => {
|
|
const differ2 = readonlyArray(update());
|
|
return fiberRefUnsafeMakePatch(initial, {
|
|
differ: differ2,
|
|
fork: differ2.empty
|
|
});
|
|
};
|
|
var fiberRefUnsafeMakeContext = (initial) => {
|
|
const differ2 = environment();
|
|
return fiberRefUnsafeMakePatch(initial, {
|
|
differ: differ2,
|
|
fork: differ2.empty
|
|
});
|
|
};
|
|
var fiberRefUnsafeMakePatch = (initial, options) => {
|
|
const _fiberRef = {
|
|
...CommitPrototype,
|
|
[FiberRefTypeId]: fiberRefVariance,
|
|
initial,
|
|
commit() {
|
|
return fiberRefGet(this);
|
|
},
|
|
diff: (oldValue, newValue) => options.differ.diff(oldValue, newValue),
|
|
combine: (first, second) => options.differ.combine(first, second),
|
|
patch: (patch) => (oldValue) => options.differ.patch(patch, oldValue),
|
|
fork: options.fork,
|
|
join: options.join ?? ((_, n) => n)
|
|
};
|
|
return _fiberRef;
|
|
};
|
|
var fiberRefUnsafeMakeRuntimeFlags = (initial) => fiberRefUnsafeMakePatch(initial, {
|
|
differ,
|
|
fork: differ.empty
|
|
});
|
|
var currentContext = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/FiberRef/currentContext"), () => fiberRefUnsafeMakeContext(empty3()));
|
|
var currentSchedulingPriority = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/FiberRef/currentSchedulingPriority"), () => fiberRefUnsafeMake(0));
|
|
var currentMaxOpsBeforeYield = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/FiberRef/currentMaxOpsBeforeYield"), () => fiberRefUnsafeMake(2048));
|
|
var currentLogAnnotations = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/FiberRef/currentLogAnnotation"), () => fiberRefUnsafeMake(empty8()));
|
|
var currentLogLevel = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/FiberRef/currentLogLevel"), () => fiberRefUnsafeMake(logLevelInfo));
|
|
var currentLogSpan = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/FiberRef/currentLogSpan"), () => fiberRefUnsafeMake(empty9()));
|
|
var withSchedulingPriority = /* @__PURE__ */ dual(2, (self2, scheduler) => fiberRefLocally(self2, currentSchedulingPriority, scheduler));
|
|
var currentConcurrency = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/FiberRef/currentConcurrency"), () => fiberRefUnsafeMake("unbounded"));
|
|
var currentRequestBatching = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/FiberRef/currentRequestBatching"), () => fiberRefUnsafeMake(true));
|
|
var currentUnhandledErrorLogLevel = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/FiberRef/currentUnhandledErrorLogLevel"), () => fiberRefUnsafeMake(some2(logLevelDebug)));
|
|
var currentVersionMismatchErrorLogLevel = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/FiberRef/versionMismatchErrorLogLevel"), () => fiberRefUnsafeMake(some2(logLevelWarning)));
|
|
var currentMetricLabels = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/FiberRef/currentMetricLabels"), () => fiberRefUnsafeMakeReadonlyArray(empty()));
|
|
var currentForkScopeOverride = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/FiberRef/currentForkScopeOverride"), () => fiberRefUnsafeMake(none2(), {
|
|
fork: () => none2(),
|
|
join: (parent, _) => parent
|
|
}));
|
|
var currentInterruptedCause = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/FiberRef/currentInterruptedCause"), () => fiberRefUnsafeMake(empty14, {
|
|
fork: () => empty14,
|
|
join: (parent, _) => parent
|
|
}));
|
|
var ScopeTypeId = /* @__PURE__ */ Symbol.for("effect/Scope");
|
|
var CloseableScopeTypeId = /* @__PURE__ */ Symbol.for("effect/CloseableScope");
|
|
var scopeAddFinalizer = (self2, finalizer) => self2.addFinalizer(() => asVoid(finalizer));
|
|
var scopeAddFinalizerExit = (self2, finalizer) => self2.addFinalizer(finalizer);
|
|
var scopeClose = (self2, exit) => self2.close(exit);
|
|
var scopeFork = (self2, strategy) => self2.fork(strategy);
|
|
var causeSquash = (self2) => {
|
|
return causeSquashWith(identity)(self2);
|
|
};
|
|
var causeSquashWith = /* @__PURE__ */ dual(2, (self2, f) => {
|
|
const option = pipe(self2, failureOption, map2(f));
|
|
switch (option._tag) {
|
|
case "None": {
|
|
return pipe(defects(self2), head2, match2({
|
|
onNone: () => {
|
|
const interrupts = fromIterable(interruptors(self2)).flatMap((fiberId) => fromIterable(ids2(fiberId)).map((id) => `#${id}`));
|
|
return new InterruptedException(interrupts ? `Interrupted by fibers: ${interrupts.join(", ")}` : undefined);
|
|
},
|
|
onSome: identity
|
|
}));
|
|
}
|
|
case "Some": {
|
|
return option.value;
|
|
}
|
|
}
|
|
});
|
|
var YieldableError = /* @__PURE__ */ function() {
|
|
|
|
class YieldableError extends globalThis.Error {
|
|
commit() {
|
|
return fail2(this);
|
|
}
|
|
toJSON() {
|
|
const obj = {
|
|
...this
|
|
};
|
|
if (this.message)
|
|
obj.message = this.message;
|
|
if (this.cause)
|
|
obj.cause = this.cause;
|
|
return obj;
|
|
}
|
|
[NodeInspectSymbol]() {
|
|
if (this.toString !== globalThis.Error.prototype.toString) {
|
|
return this.stack ? `${this.toString()}
|
|
${this.stack.split(`
|
|
`).slice(1).join(`
|
|
`)}` : this.toString();
|
|
} else if ("Bun" in globalThis) {
|
|
return pretty(fail(this), {
|
|
renderErrorCause: true
|
|
});
|
|
}
|
|
return this;
|
|
}
|
|
}
|
|
Object.assign(YieldableError.prototype, StructuralCommitPrototype);
|
|
return YieldableError;
|
|
}();
|
|
var makeException = (proto, tag) => {
|
|
|
|
class Base extends YieldableError {
|
|
_tag = tag;
|
|
}
|
|
Object.assign(Base.prototype, proto);
|
|
Base.prototype.name = tag;
|
|
return Base;
|
|
};
|
|
var RuntimeExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/RuntimeException");
|
|
var RuntimeException = /* @__PURE__ */ makeException({
|
|
[RuntimeExceptionTypeId]: RuntimeExceptionTypeId
|
|
}, "RuntimeException");
|
|
var InterruptedExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/InterruptedException");
|
|
var InterruptedException = /* @__PURE__ */ makeException({
|
|
[InterruptedExceptionTypeId]: InterruptedExceptionTypeId
|
|
}, "InterruptedException");
|
|
var isInterruptedException = (u) => hasProperty(u, InterruptedExceptionTypeId);
|
|
var IllegalArgumentExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/IllegalArgument");
|
|
var IllegalArgumentException = /* @__PURE__ */ makeException({
|
|
[IllegalArgumentExceptionTypeId]: IllegalArgumentExceptionTypeId
|
|
}, "IllegalArgumentException");
|
|
var NoSuchElementExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/NoSuchElement");
|
|
var NoSuchElementException = /* @__PURE__ */ makeException({
|
|
[NoSuchElementExceptionTypeId]: NoSuchElementExceptionTypeId
|
|
}, "NoSuchElementException");
|
|
var InvalidPubSubCapacityExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException");
|
|
var InvalidPubSubCapacityException = /* @__PURE__ */ makeException({
|
|
[InvalidPubSubCapacityExceptionTypeId]: InvalidPubSubCapacityExceptionTypeId
|
|
}, "InvalidPubSubCapacityException");
|
|
var ExceededCapacityExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/ExceededCapacityException");
|
|
var ExceededCapacityException = /* @__PURE__ */ makeException({
|
|
[ExceededCapacityExceptionTypeId]: ExceededCapacityExceptionTypeId
|
|
}, "ExceededCapacityException");
|
|
var TimeoutExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/Timeout");
|
|
var TimeoutException = /* @__PURE__ */ makeException({
|
|
[TimeoutExceptionTypeId]: TimeoutExceptionTypeId
|
|
}, "TimeoutException");
|
|
var UnknownExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/UnknownException");
|
|
var UnknownException = /* @__PURE__ */ function() {
|
|
|
|
class UnknownException extends YieldableError {
|
|
_tag = "UnknownException";
|
|
error;
|
|
constructor(cause, message) {
|
|
super(message ?? "An unknown error occurred", {
|
|
cause
|
|
});
|
|
this.error = cause;
|
|
}
|
|
}
|
|
Object.assign(UnknownException.prototype, {
|
|
[UnknownExceptionTypeId]: UnknownExceptionTypeId,
|
|
name: "UnknownException"
|
|
});
|
|
return UnknownException;
|
|
}();
|
|
var exitIsExit = (u) => isEffect(u) && ("_tag" in u) && (u._tag === "Success" || u._tag === "Failure");
|
|
var exitIsFailure = (self2) => self2._tag === "Failure";
|
|
var exitIsSuccess = (self2) => self2._tag === "Success";
|
|
var exitAs = /* @__PURE__ */ dual(2, (self2, value) => {
|
|
switch (self2._tag) {
|
|
case OP_FAILURE: {
|
|
return exitFailCause(self2.effect_instruction_i0);
|
|
}
|
|
case OP_SUCCESS: {
|
|
return exitSucceed(value);
|
|
}
|
|
}
|
|
});
|
|
var exitAsVoid = (self2) => exitAs(self2, undefined);
|
|
var exitCollectAll = (exits, options) => exitCollectAllInternal(exits, options?.parallel ? parallel : sequential);
|
|
var exitDie = (defect) => exitFailCause(die(defect));
|
|
var exitFail = (error) => exitFailCause(fail(error));
|
|
var exitFailCause = (cause) => {
|
|
const effect = new EffectPrimitiveFailure(OP_FAILURE);
|
|
effect.effect_instruction_i0 = cause;
|
|
return effect;
|
|
};
|
|
var exitInterrupt = (fiberId) => exitFailCause(interrupt(fiberId));
|
|
var exitMap = /* @__PURE__ */ dual(2, (self2, f) => {
|
|
switch (self2._tag) {
|
|
case OP_FAILURE:
|
|
return exitFailCause(self2.effect_instruction_i0);
|
|
case OP_SUCCESS:
|
|
return exitSucceed(f(self2.effect_instruction_i0));
|
|
}
|
|
});
|
|
var exitMapBoth = /* @__PURE__ */ dual(2, (self2, {
|
|
onFailure,
|
|
onSuccess
|
|
}) => {
|
|
switch (self2._tag) {
|
|
case OP_FAILURE:
|
|
return exitFailCause(pipe(self2.effect_instruction_i0, map9(onFailure)));
|
|
case OP_SUCCESS:
|
|
return exitSucceed(onSuccess(self2.effect_instruction_i0));
|
|
}
|
|
});
|
|
var exitMatch = /* @__PURE__ */ dual(2, (self2, {
|
|
onFailure,
|
|
onSuccess
|
|
}) => {
|
|
switch (self2._tag) {
|
|
case OP_FAILURE:
|
|
return onFailure(self2.effect_instruction_i0);
|
|
case OP_SUCCESS:
|
|
return onSuccess(self2.effect_instruction_i0);
|
|
}
|
|
});
|
|
var exitMatchEffect = /* @__PURE__ */ dual(2, (self2, {
|
|
onFailure,
|
|
onSuccess
|
|
}) => {
|
|
switch (self2._tag) {
|
|
case OP_FAILURE:
|
|
return onFailure(self2.effect_instruction_i0);
|
|
case OP_SUCCESS:
|
|
return onSuccess(self2.effect_instruction_i0);
|
|
}
|
|
});
|
|
var exitSucceed = (value) => {
|
|
const effect = new EffectPrimitiveSuccess(OP_SUCCESS);
|
|
effect.effect_instruction_i0 = value;
|
|
return effect;
|
|
};
|
|
var exitVoid = /* @__PURE__ */ exitSucceed(undefined);
|
|
var exitZip = /* @__PURE__ */ dual(2, (self2, that) => exitZipWith(self2, that, {
|
|
onSuccess: (a, a2) => [a, a2],
|
|
onFailure: sequential
|
|
}));
|
|
var exitZipRight = /* @__PURE__ */ dual(2, (self2, that) => exitZipWith(self2, that, {
|
|
onSuccess: (_, a2) => a2,
|
|
onFailure: sequential
|
|
}));
|
|
var exitZipWith = /* @__PURE__ */ dual(3, (self2, that, {
|
|
onFailure,
|
|
onSuccess
|
|
}) => {
|
|
switch (self2._tag) {
|
|
case OP_FAILURE: {
|
|
switch (that._tag) {
|
|
case OP_SUCCESS:
|
|
return exitFailCause(self2.effect_instruction_i0);
|
|
case OP_FAILURE: {
|
|
return exitFailCause(onFailure(self2.effect_instruction_i0, that.effect_instruction_i0));
|
|
}
|
|
}
|
|
}
|
|
case OP_SUCCESS: {
|
|
switch (that._tag) {
|
|
case OP_SUCCESS:
|
|
return exitSucceed(onSuccess(self2.effect_instruction_i0, that.effect_instruction_i0));
|
|
case OP_FAILURE:
|
|
return exitFailCause(that.effect_instruction_i0);
|
|
}
|
|
}
|
|
}
|
|
});
|
|
var exitCollectAllInternal = (exits, combineCauses) => {
|
|
const list = fromIterable2(exits);
|
|
if (!isNonEmpty(list)) {
|
|
return none2();
|
|
}
|
|
return pipe(tailNonEmpty2(list), reduce(pipe(headNonEmpty2(list), exitMap(of2)), (accumulator, current) => pipe(accumulator, exitZipWith(current, {
|
|
onSuccess: (list, value) => pipe(list, prepend2(value)),
|
|
onFailure: combineCauses
|
|
}))), exitMap(reverse2), exitMap((chunk) => toReadonlyArray(chunk)), some2);
|
|
};
|
|
var deferredUnsafeMake = (fiberId) => {
|
|
const _deferred = {
|
|
...CommitPrototype,
|
|
[DeferredTypeId]: deferredVariance,
|
|
state: make11(pending([])),
|
|
commit() {
|
|
return deferredAwait(this);
|
|
},
|
|
blockingOn: fiberId
|
|
};
|
|
return _deferred;
|
|
};
|
|
var deferredMake = () => flatMap7(fiberId, (id) => deferredMakeAs(id));
|
|
var deferredMakeAs = (fiberId) => sync(() => deferredUnsafeMake(fiberId));
|
|
var deferredAwait = (self2) => asyncInterrupt((resume) => {
|
|
const state = get6(self2.state);
|
|
switch (state._tag) {
|
|
case OP_STATE_DONE: {
|
|
return resume(state.effect);
|
|
}
|
|
case OP_STATE_PENDING: {
|
|
state.joiners.push(resume);
|
|
return deferredInterruptJoiner(self2, resume);
|
|
}
|
|
}
|
|
}, self2.blockingOn);
|
|
var deferredCompleteWith = /* @__PURE__ */ dual(2, (self2, effect) => sync(() => {
|
|
const state = get6(self2.state);
|
|
switch (state._tag) {
|
|
case OP_STATE_DONE: {
|
|
return false;
|
|
}
|
|
case OP_STATE_PENDING: {
|
|
set2(self2.state, done(effect));
|
|
for (let i = 0, len = state.joiners.length;i < len; i++) {
|
|
state.joiners[i](effect);
|
|
}
|
|
return true;
|
|
}
|
|
}
|
|
}));
|
|
var deferredDone = /* @__PURE__ */ dual(2, (self2, exit) => deferredCompleteWith(self2, exit));
|
|
var deferredFailCause = /* @__PURE__ */ dual(2, (self2, cause) => deferredCompleteWith(self2, failCause(cause)));
|
|
var deferredInterruptWith = /* @__PURE__ */ dual(2, (self2, fiberId) => deferredCompleteWith(self2, interruptWith(fiberId)));
|
|
var deferredIsDone = (self2) => sync(() => get6(self2.state)._tag === OP_STATE_DONE);
|
|
var deferredSucceed = /* @__PURE__ */ dual(2, (self2, value) => deferredCompleteWith(self2, succeed(value)));
|
|
var deferredUnsafeDone = (self2, effect) => {
|
|
const state = get6(self2.state);
|
|
if (state._tag === OP_STATE_PENDING) {
|
|
set2(self2.state, done(effect));
|
|
for (let i = 0, len = state.joiners.length;i < len; i++) {
|
|
state.joiners[i](effect);
|
|
}
|
|
}
|
|
};
|
|
var deferredInterruptJoiner = (self2, joiner) => sync(() => {
|
|
const state = get6(self2.state);
|
|
if (state._tag === OP_STATE_PENDING) {
|
|
const index = state.joiners.indexOf(joiner);
|
|
if (index >= 0) {
|
|
state.joiners.splice(index, 1);
|
|
}
|
|
}
|
|
});
|
|
var constContext = /* @__PURE__ */ withFiberRuntime((fiber) => exitSucceed(fiber.currentContext));
|
|
var context = () => constContext;
|
|
var contextWithEffect = (f) => flatMap7(context(), f);
|
|
var provideContext = /* @__PURE__ */ dual(2, (self2, context) => fiberRefLocally(currentContext, context)(self2));
|
|
var provideSomeContext = /* @__PURE__ */ dual(2, (self2, context) => fiberRefLocallyWith(currentContext, (parent) => merge3(parent, context))(self2));
|
|
var mapInputContext = /* @__PURE__ */ dual(2, (self2, f) => contextWithEffect((context) => provideContext(self2, f(context))));
|
|
var currentSpanFromFiber = (fiber) => {
|
|
const span = fiber.currentSpan;
|
|
return span !== undefined && span._tag === "Span" ? some2(span) : none2();
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Data.js
|
|
var struct2 = struct;
|
|
var tagged = (tag) => (args) => {
|
|
const value = args === undefined ? Object.create(StructuralPrototype) : struct2(args);
|
|
value._tag = tag;
|
|
return value;
|
|
};
|
|
var Error2 = /* @__PURE__ */ function() {
|
|
const plainArgsSymbol = /* @__PURE__ */ Symbol.for("effect/Data/Error/plainArgs");
|
|
const O = {
|
|
BaseEffectError: class extends YieldableError {
|
|
constructor(args) {
|
|
super(args?.message, args?.cause ? {
|
|
cause: args.cause
|
|
} : undefined);
|
|
if (args) {
|
|
Object.assign(this, args);
|
|
Object.defineProperty(this, plainArgsSymbol, {
|
|
value: args,
|
|
enumerable: false
|
|
});
|
|
}
|
|
}
|
|
toJSON() {
|
|
return {
|
|
...this[plainArgsSymbol],
|
|
...this
|
|
};
|
|
}
|
|
}
|
|
};
|
|
return O.BaseEffectError;
|
|
}();
|
|
var TaggedError = (tag) => {
|
|
const O = {
|
|
BaseEffectError: class extends Error2 {
|
|
_tag = tag;
|
|
}
|
|
};
|
|
O.BaseEffectError.prototype.name = tag;
|
|
return O.BaseEffectError;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Cause.js
|
|
var fail3 = fail;
|
|
var die3 = die;
|
|
var interrupt3 = interrupt;
|
|
var isFailType2 = isFailType;
|
|
var isInterrupted2 = isInterrupted;
|
|
var interruptors2 = interruptors;
|
|
var failureOrCause2 = failureOrCause;
|
|
var flipCauseOption2 = flipCauseOption;
|
|
var map11 = map9;
|
|
var squash = causeSquash;
|
|
var pretty2 = pretty;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Deferred.js
|
|
var make18 = deferredMake;
|
|
var _await = deferredAwait;
|
|
var failCause2 = deferredFailCause;
|
|
var isDone = deferredIsDone;
|
|
var succeed2 = deferredSucceed;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/clock.js
|
|
var ClockSymbolKey = "effect/Clock";
|
|
var ClockTypeId = /* @__PURE__ */ Symbol.for(ClockSymbolKey);
|
|
var clockTag = /* @__PURE__ */ GenericTag("effect/Clock");
|
|
var MAX_TIMER_MILLIS = 2 ** 31 - 1;
|
|
var globalClockScheduler = {
|
|
unsafeSchedule(task, duration) {
|
|
const millis = toMillis(duration);
|
|
if (millis > MAX_TIMER_MILLIS) {
|
|
return constFalse;
|
|
}
|
|
let completed = false;
|
|
const handle = setTimeout(() => {
|
|
completed = true;
|
|
task();
|
|
}, millis);
|
|
return () => {
|
|
clearTimeout(handle);
|
|
return !completed;
|
|
};
|
|
}
|
|
};
|
|
var performanceNowNanos = /* @__PURE__ */ function() {
|
|
const bigint1e6 = /* @__PURE__ */ BigInt(1e6);
|
|
if (typeof performance === "undefined" || typeof performance.now !== "function") {
|
|
return () => BigInt(Date.now()) * bigint1e6;
|
|
}
|
|
let origin;
|
|
return () => {
|
|
if (origin === undefined) {
|
|
origin = BigInt(Date.now()) * bigint1e6 - BigInt(Math.round(performance.now() * 1e6));
|
|
}
|
|
return origin + BigInt(Math.round(performance.now() * 1e6));
|
|
};
|
|
}();
|
|
var processOrPerformanceNow = /* @__PURE__ */ function() {
|
|
const processHrtime = typeof process === "object" && "hrtime" in process && typeof process.hrtime.bigint === "function" ? process.hrtime : undefined;
|
|
if (!processHrtime) {
|
|
return performanceNowNanos;
|
|
}
|
|
const origin = /* @__PURE__ */ performanceNowNanos() - /* @__PURE__ */ processHrtime.bigint();
|
|
return () => origin + processHrtime.bigint();
|
|
}();
|
|
|
|
class ClockImpl {
|
|
[ClockTypeId] = ClockTypeId;
|
|
unsafeCurrentTimeMillis() {
|
|
return Date.now();
|
|
}
|
|
unsafeCurrentTimeNanos() {
|
|
return processOrPerformanceNow();
|
|
}
|
|
currentTimeMillis = /* @__PURE__ */ sync(() => this.unsafeCurrentTimeMillis());
|
|
currentTimeNanos = /* @__PURE__ */ sync(() => this.unsafeCurrentTimeNanos());
|
|
scheduler() {
|
|
return succeed(globalClockScheduler);
|
|
}
|
|
sleep(duration) {
|
|
return async_((resume) => {
|
|
const canceler = globalClockScheduler.unsafeSchedule(() => resume(void_), duration);
|
|
return asVoid(sync(canceler));
|
|
});
|
|
}
|
|
}
|
|
var make19 = () => new ClockImpl;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Number.js
|
|
var Order = number3;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/RegExp.js
|
|
var escape2 = (string) => string.replace(/[/\\^$*+?.()|[\]{}]/g, "\\$&");
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/opCodes/configError.js
|
|
var OP_AND = "And";
|
|
var OP_OR = "Or";
|
|
var OP_INVALID_DATA = "InvalidData";
|
|
var OP_MISSING_DATA = "MissingData";
|
|
var OP_SOURCE_UNAVAILABLE = "SourceUnavailable";
|
|
var OP_UNSUPPORTED = "Unsupported";
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/configError.js
|
|
var ConfigErrorSymbolKey = "effect/ConfigError";
|
|
var ConfigErrorTypeId = /* @__PURE__ */ Symbol.for(ConfigErrorSymbolKey);
|
|
var proto2 = {
|
|
_tag: "ConfigError",
|
|
[ConfigErrorTypeId]: ConfigErrorTypeId
|
|
};
|
|
var And = (self2, that) => {
|
|
const error = Object.create(proto2);
|
|
error._op = OP_AND;
|
|
error.left = self2;
|
|
error.right = that;
|
|
Object.defineProperty(error, "toString", {
|
|
enumerable: false,
|
|
value() {
|
|
return `${this.left} and ${this.right}`;
|
|
}
|
|
});
|
|
Object.defineProperty(error, "message", {
|
|
enumerable: false,
|
|
get() {
|
|
return this.toString();
|
|
}
|
|
});
|
|
return error;
|
|
};
|
|
var Or = (self2, that) => {
|
|
const error = Object.create(proto2);
|
|
error._op = OP_OR;
|
|
error.left = self2;
|
|
error.right = that;
|
|
Object.defineProperty(error, "toString", {
|
|
enumerable: false,
|
|
value() {
|
|
return `${this.left} or ${this.right}`;
|
|
}
|
|
});
|
|
Object.defineProperty(error, "message", {
|
|
enumerable: false,
|
|
get() {
|
|
return this.toString();
|
|
}
|
|
});
|
|
return error;
|
|
};
|
|
var InvalidData = (path, message, options = {
|
|
pathDelim: "."
|
|
}) => {
|
|
const error = Object.create(proto2);
|
|
error._op = OP_INVALID_DATA;
|
|
error.path = path;
|
|
error.message = message;
|
|
Object.defineProperty(error, "toString", {
|
|
enumerable: false,
|
|
value() {
|
|
const path = pipe(this.path, join(options.pathDelim));
|
|
return `(Invalid data at ${path}: "${this.message}")`;
|
|
}
|
|
});
|
|
return error;
|
|
};
|
|
var MissingData = (path, message, options = {
|
|
pathDelim: "."
|
|
}) => {
|
|
const error = Object.create(proto2);
|
|
error._op = OP_MISSING_DATA;
|
|
error.path = path;
|
|
error.message = message;
|
|
Object.defineProperty(error, "toString", {
|
|
enumerable: false,
|
|
value() {
|
|
const path = pipe(this.path, join(options.pathDelim));
|
|
return `(Missing data at ${path}: "${this.message}")`;
|
|
}
|
|
});
|
|
return error;
|
|
};
|
|
var SourceUnavailable = (path, message, cause, options = {
|
|
pathDelim: "."
|
|
}) => {
|
|
const error = Object.create(proto2);
|
|
error._op = OP_SOURCE_UNAVAILABLE;
|
|
error.path = path;
|
|
error.message = message;
|
|
error.cause = cause;
|
|
Object.defineProperty(error, "toString", {
|
|
enumerable: false,
|
|
value() {
|
|
const path = pipe(this.path, join(options.pathDelim));
|
|
return `(Source unavailable at ${path}: "${this.message}")`;
|
|
}
|
|
});
|
|
return error;
|
|
};
|
|
var Unsupported = (path, message, options = {
|
|
pathDelim: "."
|
|
}) => {
|
|
const error = Object.create(proto2);
|
|
error._op = OP_UNSUPPORTED;
|
|
error.path = path;
|
|
error.message = message;
|
|
Object.defineProperty(error, "toString", {
|
|
enumerable: false,
|
|
value() {
|
|
const path = pipe(this.path, join(options.pathDelim));
|
|
return `(Unsupported operation at ${path}: "${this.message}")`;
|
|
}
|
|
});
|
|
return error;
|
|
};
|
|
var prefixed = /* @__PURE__ */ dual(2, (self2, prefix) => {
|
|
switch (self2._op) {
|
|
case OP_AND: {
|
|
return And(prefixed(self2.left, prefix), prefixed(self2.right, prefix));
|
|
}
|
|
case OP_OR: {
|
|
return Or(prefixed(self2.left, prefix), prefixed(self2.right, prefix));
|
|
}
|
|
case OP_INVALID_DATA: {
|
|
return InvalidData([...prefix, ...self2.path], self2.message);
|
|
}
|
|
case OP_MISSING_DATA: {
|
|
return MissingData([...prefix, ...self2.path], self2.message);
|
|
}
|
|
case OP_SOURCE_UNAVAILABLE: {
|
|
return SourceUnavailable([...prefix, ...self2.path], self2.message, self2.cause);
|
|
}
|
|
case OP_UNSUPPORTED: {
|
|
return Unsupported([...prefix, ...self2.path], self2.message);
|
|
}
|
|
}
|
|
});
|
|
var reduceWithContext2 = /* @__PURE__ */ dual(3, (self2, context, reducer) => {
|
|
const input = [self2];
|
|
const output = [];
|
|
while (input.length > 0) {
|
|
const error = input.pop();
|
|
switch (error._op) {
|
|
case OP_AND: {
|
|
input.push(error.right);
|
|
input.push(error.left);
|
|
output.push(left2({
|
|
_op: "AndCase"
|
|
}));
|
|
break;
|
|
}
|
|
case OP_OR: {
|
|
input.push(error.right);
|
|
input.push(error.left);
|
|
output.push(left2({
|
|
_op: "OrCase"
|
|
}));
|
|
break;
|
|
}
|
|
case OP_INVALID_DATA: {
|
|
output.push(right2(reducer.invalidDataCase(context, error.path, error.message)));
|
|
break;
|
|
}
|
|
case OP_MISSING_DATA: {
|
|
output.push(right2(reducer.missingDataCase(context, error.path, error.message)));
|
|
break;
|
|
}
|
|
case OP_SOURCE_UNAVAILABLE: {
|
|
output.push(right2(reducer.sourceUnavailableCase(context, error.path, error.message, error.cause)));
|
|
break;
|
|
}
|
|
case OP_UNSUPPORTED: {
|
|
output.push(right2(reducer.unsupportedCase(context, error.path, error.message)));
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
const accumulator = [];
|
|
while (output.length > 0) {
|
|
const either = output.pop();
|
|
switch (either._op) {
|
|
case "Left": {
|
|
switch (either.left._op) {
|
|
case "AndCase": {
|
|
const left = accumulator.pop();
|
|
const right = accumulator.pop();
|
|
const value = reducer.andCase(context, left, right);
|
|
accumulator.push(value);
|
|
break;
|
|
}
|
|
case "OrCase": {
|
|
const left = accumulator.pop();
|
|
const right = accumulator.pop();
|
|
const value = reducer.orCase(context, left, right);
|
|
accumulator.push(value);
|
|
break;
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case "Right": {
|
|
accumulator.push(either.right);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (accumulator.length === 0) {
|
|
throw new Error("BUG: ConfigError.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");
|
|
}
|
|
return accumulator.pop();
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/configProvider/pathPatch.js
|
|
var empty15 = {
|
|
_tag: "Empty"
|
|
};
|
|
var patch5 = /* @__PURE__ */ dual(2, (path, patch) => {
|
|
let input = of3(patch);
|
|
let output = path;
|
|
while (isCons(input)) {
|
|
const patch = input.head;
|
|
switch (patch._tag) {
|
|
case "Empty": {
|
|
input = input.tail;
|
|
break;
|
|
}
|
|
case "AndThen": {
|
|
input = cons(patch.first, cons(patch.second, input.tail));
|
|
break;
|
|
}
|
|
case "MapName": {
|
|
output = map3(output, patch.f);
|
|
input = input.tail;
|
|
break;
|
|
}
|
|
case "Nested": {
|
|
output = prepend(output, patch.name);
|
|
input = input.tail;
|
|
break;
|
|
}
|
|
case "Unnested": {
|
|
const containsName = pipe(head(output), contains(patch.name));
|
|
if (containsName) {
|
|
output = tailNonEmpty(output);
|
|
input = input.tail;
|
|
} else {
|
|
return left2(MissingData(output, `Expected ${patch.name} to be in path in ConfigProvider#unnested`));
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
return right2(output);
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/opCodes/config.js
|
|
var OP_CONSTANT = "Constant";
|
|
var OP_FAIL2 = "Fail";
|
|
var OP_FALLBACK = "Fallback";
|
|
var OP_DESCRIBED = "Described";
|
|
var OP_LAZY = "Lazy";
|
|
var OP_MAP_OR_FAIL = "MapOrFail";
|
|
var OP_NESTED = "Nested";
|
|
var OP_PRIMITIVE = "Primitive";
|
|
var OP_REDACTED = "Redacted";
|
|
var OP_SEQUENCE = "Sequence";
|
|
var OP_HASHMAP = "HashMap";
|
|
var OP_ZIP_WITH = "ZipWith";
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/configProvider.js
|
|
var concat = (l, r) => [...l, ...r];
|
|
var ConfigProviderSymbolKey = "effect/ConfigProvider";
|
|
var ConfigProviderTypeId = /* @__PURE__ */ Symbol.for(ConfigProviderSymbolKey);
|
|
var configProviderTag = /* @__PURE__ */ GenericTag("effect/ConfigProvider");
|
|
var FlatConfigProviderSymbolKey = "effect/ConfigProviderFlat";
|
|
var FlatConfigProviderTypeId = /* @__PURE__ */ Symbol.for(FlatConfigProviderSymbolKey);
|
|
var make21 = (options) => ({
|
|
[ConfigProviderTypeId]: ConfigProviderTypeId,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
},
|
|
...options
|
|
});
|
|
var makeFlat = (options) => ({
|
|
[FlatConfigProviderTypeId]: FlatConfigProviderTypeId,
|
|
patch: options.patch,
|
|
load: (path, config, split = true) => options.load(path, config, split),
|
|
enumerateChildren: options.enumerateChildren
|
|
});
|
|
var fromFlat = (flat) => make21({
|
|
load: (config) => flatMap7(fromFlatLoop(flat, empty(), config, false), (chunk) => match2(head(chunk), {
|
|
onNone: () => fail2(MissingData(empty(), `Expected a single value having structure: ${config}`)),
|
|
onSome: succeed
|
|
})),
|
|
flattened: flat
|
|
});
|
|
var fromEnv = (options) => {
|
|
const {
|
|
pathDelim,
|
|
seqDelim
|
|
} = Object.assign({}, {
|
|
pathDelim: "_",
|
|
seqDelim: ","
|
|
}, options);
|
|
const makePathString = (path) => pipe(path, join(pathDelim));
|
|
const unmakePathString = (pathString) => pathString.split(pathDelim);
|
|
const getEnv = () => typeof process !== "undefined" && ("env" in process) && typeof process.env === "object" ? process.env : {};
|
|
const load = (path, primitive, split = true) => {
|
|
const pathString = makePathString(path);
|
|
const current = getEnv();
|
|
const valueOpt = pathString in current ? some2(current[pathString]) : none2();
|
|
return pipe(valueOpt, mapError(() => MissingData(path, `Expected ${pathString} to exist in the process context`)), flatMap7((value) => parsePrimitive(value, path, primitive, seqDelim, split)));
|
|
};
|
|
const enumerateChildren = (path) => sync(() => {
|
|
const current = getEnv();
|
|
const keys = Object.keys(current);
|
|
const keyPaths = keys.map((value) => unmakePathString(value.toUpperCase()));
|
|
const filteredKeyPaths = keyPaths.filter((keyPath) => {
|
|
for (let i = 0;i < path.length; i++) {
|
|
const pathComponent = pipe(path, unsafeGet(i));
|
|
const currentElement = keyPath[i];
|
|
if (currentElement === undefined || pathComponent !== currentElement) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}).flatMap((keyPath) => keyPath.slice(path.length, path.length + 1));
|
|
return fromIterable5(filteredKeyPaths);
|
|
});
|
|
return fromFlat(makeFlat({
|
|
load,
|
|
enumerateChildren,
|
|
patch: empty15
|
|
}));
|
|
};
|
|
var extend = (leftDef, rightDef, left, right) => {
|
|
const leftPad = unfold(left.length, (index) => index >= right.length ? none2() : some2([leftDef(index), index + 1]));
|
|
const rightPad = unfold(right.length, (index) => index >= left.length ? none2() : some2([rightDef(index), index + 1]));
|
|
const leftExtension = concat(left, leftPad);
|
|
const rightExtension = concat(right, rightPad);
|
|
return [leftExtension, rightExtension];
|
|
};
|
|
var appendConfigPath = (path, config) => {
|
|
let op = config;
|
|
if (op._tag === "Nested") {
|
|
const out = path.slice();
|
|
while (op._tag === "Nested") {
|
|
out.push(op.name);
|
|
op = op.config;
|
|
}
|
|
return out;
|
|
}
|
|
return path;
|
|
};
|
|
var RedactedConfigErrorReducer = {
|
|
andCase: (_, left, right) => And(left, right),
|
|
orCase: (_, left, right) => Or(left, right),
|
|
invalidDataCase: (_, path) => InvalidData(path, "<redacted>"),
|
|
missingDataCase: (_, path) => MissingData(path, "<redacted>"),
|
|
sourceUnavailableCase: (_, path, _message, cause) => SourceUnavailable(path, "<redacted>", cause),
|
|
unsupportedCase: (_, path) => Unsupported(path, "<redacted>")
|
|
};
|
|
var redactConfigError = (error) => reduceWithContext2(error, undefined, RedactedConfigErrorReducer);
|
|
var fromFlatLoop = (flat, prefix, config, split) => {
|
|
const op = config;
|
|
switch (op._tag) {
|
|
case OP_CONSTANT: {
|
|
return succeed(of(op.value));
|
|
}
|
|
case OP_DESCRIBED: {
|
|
return suspend(() => fromFlatLoop(flat, prefix, op.config, split));
|
|
}
|
|
case OP_FAIL2: {
|
|
return fail2(MissingData(prefix, op.message));
|
|
}
|
|
case OP_FALLBACK: {
|
|
return pipe(suspend(() => fromFlatLoop(flat, prefix, op.first, split)), catchAll((error1) => {
|
|
if (op.condition(error1)) {
|
|
return pipe(fromFlatLoop(flat, prefix, op.second, split), catchAll((error2) => fail2(Or(error1, error2))));
|
|
}
|
|
return fail2(error1);
|
|
}));
|
|
}
|
|
case OP_LAZY: {
|
|
return suspend(() => fromFlatLoop(flat, prefix, op.config(), split));
|
|
}
|
|
case OP_MAP_OR_FAIL: {
|
|
return suspend(() => pipe(fromFlatLoop(flat, prefix, op.original, split), flatMap7(forEachSequential((a) => pipe(op.mapOrFail(a), mapError(prefixed(appendConfigPath(prefix, op.original))))))));
|
|
}
|
|
case OP_NESTED: {
|
|
return suspend(() => fromFlatLoop(flat, concat(prefix, of(op.name)), op.config, split));
|
|
}
|
|
case OP_PRIMITIVE: {
|
|
return pipe(patch5(prefix, flat.patch), flatMap7((prefix) => pipe(flat.load(prefix, op, split), flatMap7((values) => {
|
|
if (values.length === 0) {
|
|
const name = pipe(last(prefix), getOrElse(() => "<n/a>"));
|
|
return fail2(MissingData([], `Expected ${op.description} with name ${name}`));
|
|
}
|
|
return succeed(values);
|
|
}))));
|
|
}
|
|
case OP_REDACTED: {
|
|
return suspend(() => pipe(fromFlatLoop(flat, prefix, op.original, split), mapError(redactConfigError), map10(map3(op.redact))));
|
|
}
|
|
case OP_SEQUENCE: {
|
|
return pipe(patch5(prefix, flat.patch), flatMap7((patchedPrefix) => pipe(flat.enumerateChildren(patchedPrefix), flatMap7(indicesFrom), flatMap7((indices) => {
|
|
if (indices.length === 0) {
|
|
return suspend(() => map10(fromFlatLoop(flat, prefix, op.config, true), of));
|
|
}
|
|
return pipe(forEachSequential(indices, (index) => fromFlatLoop(flat, append(prefix, `[${index}]`), op.config, true)), map10((chunkChunk) => {
|
|
const flattened = flatten(chunkChunk);
|
|
if (flattened.length === 0) {
|
|
return of(empty());
|
|
}
|
|
return of(flattened);
|
|
}));
|
|
}))));
|
|
}
|
|
case OP_HASHMAP: {
|
|
return suspend(() => pipe(patch5(prefix, flat.patch), flatMap7((prefix) => pipe(flat.enumerateChildren(prefix), flatMap7((keys) => {
|
|
return pipe(keys, forEachSequential((key) => fromFlatLoop(flat, concat(prefix, of(key)), op.valueConfig, split)), map10((matrix) => {
|
|
if (matrix.length === 0) {
|
|
return of(empty8());
|
|
}
|
|
return pipe(transpose(matrix), map3((values) => fromIterable6(zip(fromIterable(keys), values))));
|
|
}));
|
|
})))));
|
|
}
|
|
case OP_ZIP_WITH: {
|
|
return suspend(() => pipe(fromFlatLoop(flat, prefix, op.left, split), either2, flatMap7((left) => pipe(fromFlatLoop(flat, prefix, op.right, split), either2, flatMap7((right) => {
|
|
if (isLeft2(left) && isLeft2(right)) {
|
|
return fail2(And(left.left, right.left));
|
|
}
|
|
if (isLeft2(left) && isRight2(right)) {
|
|
return fail2(left.left);
|
|
}
|
|
if (isRight2(left) && isLeft2(right)) {
|
|
return fail2(right.left);
|
|
}
|
|
if (isRight2(left) && isRight2(right)) {
|
|
const path = pipe(prefix, join("."));
|
|
const fail = fromFlatLoopFail(prefix, path);
|
|
const [lefts, rights] = extend(fail, fail, pipe(left.right, map3(right2)), pipe(right.right, map3(right2)));
|
|
return pipe(lefts, zip(rights), forEachSequential(([left, right]) => pipe(zip2(left, right), map10(([left, right]) => op.zip(left, right)))));
|
|
}
|
|
throw new Error("BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/effect/issues");
|
|
})))));
|
|
}
|
|
}
|
|
};
|
|
var fromFlatLoopFail = (prefix, path) => (index) => left2(MissingData(prefix, `The element at index ${index} in a sequence at path "${path}" was missing`));
|
|
var splitPathString = (text, delim) => {
|
|
const split = text.split(new RegExp(`\\s*${escape2(delim)}\\s*`));
|
|
return split;
|
|
};
|
|
var parsePrimitive = (text, path, primitive, delimiter, split) => {
|
|
if (!split) {
|
|
return pipe(primitive.parse(text), mapBoth({
|
|
onFailure: prefixed(path),
|
|
onSuccess: of
|
|
}));
|
|
}
|
|
return pipe(splitPathString(text, delimiter), forEachSequential((char) => primitive.parse(char.trim())), mapError(prefixed(path)));
|
|
};
|
|
var transpose = (array) => {
|
|
return Object.keys(array[0]).map((column) => array.map((row) => row[column]));
|
|
};
|
|
var indicesFrom = (quotedIndices) => pipe(forEachSequential(quotedIndices, parseQuotedIndex), mapBoth({
|
|
onFailure: () => empty(),
|
|
onSuccess: sort(Order)
|
|
}), either2, map10(merge));
|
|
var QUOTED_INDEX_REGEX = /^(\[(\d+)\])$/;
|
|
var parseQuotedIndex = (str) => {
|
|
const match = str.match(QUOTED_INDEX_REGEX);
|
|
if (match !== null) {
|
|
const matchedIndex = match[2];
|
|
return pipe(matchedIndex !== undefined && matchedIndex.length > 0 ? some2(matchedIndex) : none2(), flatMap(parseInteger));
|
|
}
|
|
return none2();
|
|
};
|
|
var parseInteger = (str) => {
|
|
const parsedIndex = Number.parseInt(str);
|
|
return Number.isNaN(parsedIndex) ? none2() : some2(parsedIndex);
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/defaultServices/console.js
|
|
var TypeId8 = /* @__PURE__ */ Symbol.for("effect/Console");
|
|
var consoleTag = /* @__PURE__ */ GenericTag("effect/Console");
|
|
var defaultConsole = {
|
|
[TypeId8]: TypeId8,
|
|
assert(condition, ...args) {
|
|
return sync(() => {
|
|
console.assert(condition, ...args);
|
|
});
|
|
},
|
|
clear: /* @__PURE__ */ sync(() => {
|
|
console.clear();
|
|
}),
|
|
count(label) {
|
|
return sync(() => {
|
|
console.count(label);
|
|
});
|
|
},
|
|
countReset(label) {
|
|
return sync(() => {
|
|
console.countReset(label);
|
|
});
|
|
},
|
|
debug(...args) {
|
|
return sync(() => {
|
|
console.debug(...args);
|
|
});
|
|
},
|
|
dir(item, options) {
|
|
return sync(() => {
|
|
console.dir(item, options);
|
|
});
|
|
},
|
|
dirxml(...args) {
|
|
return sync(() => {
|
|
console.dirxml(...args);
|
|
});
|
|
},
|
|
error(...args) {
|
|
return sync(() => {
|
|
console.error(...args);
|
|
});
|
|
},
|
|
group(options) {
|
|
return options?.collapsed ? sync(() => console.groupCollapsed(options?.label)) : sync(() => console.group(options?.label));
|
|
},
|
|
groupEnd: /* @__PURE__ */ sync(() => {
|
|
console.groupEnd();
|
|
}),
|
|
info(...args) {
|
|
return sync(() => {
|
|
console.info(...args);
|
|
});
|
|
},
|
|
log(...args) {
|
|
return sync(() => {
|
|
console.log(...args);
|
|
});
|
|
},
|
|
table(tabularData, properties) {
|
|
return sync(() => {
|
|
console.table(tabularData, properties);
|
|
});
|
|
},
|
|
time(label) {
|
|
return sync(() => console.time(label));
|
|
},
|
|
timeEnd(label) {
|
|
return sync(() => console.timeEnd(label));
|
|
},
|
|
timeLog(label, ...args) {
|
|
return sync(() => {
|
|
console.timeLog(label, ...args);
|
|
});
|
|
},
|
|
trace(...args) {
|
|
return sync(() => {
|
|
console.trace(...args);
|
|
});
|
|
},
|
|
warn(...args) {
|
|
return sync(() => {
|
|
console.warn(...args);
|
|
});
|
|
},
|
|
unsafe: console
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/random.js
|
|
var RandomSymbolKey = "effect/Random";
|
|
var RandomTypeId = /* @__PURE__ */ Symbol.for(RandomSymbolKey);
|
|
var randomTag = /* @__PURE__ */ GenericTag("effect/Random");
|
|
|
|
class RandomImpl {
|
|
seed;
|
|
[RandomTypeId] = RandomTypeId;
|
|
PRNG;
|
|
constructor(seed) {
|
|
this.seed = seed;
|
|
this.PRNG = new PCGRandom(seed);
|
|
}
|
|
get next() {
|
|
return sync(() => this.PRNG.number());
|
|
}
|
|
get nextBoolean() {
|
|
return map10(this.next, (n) => n > 0.5);
|
|
}
|
|
get nextInt() {
|
|
return sync(() => this.PRNG.integer(Number.MAX_SAFE_INTEGER));
|
|
}
|
|
nextRange(min, max) {
|
|
return map10(this.next, (n) => (max - min) * n + min);
|
|
}
|
|
nextIntBetween(min, max) {
|
|
return sync(() => this.PRNG.integer(max - min) + min);
|
|
}
|
|
shuffle(elements) {
|
|
return shuffleWith(elements, (n) => this.nextIntBetween(0, n));
|
|
}
|
|
}
|
|
var shuffleWith = (elements, nextIntBounded) => {
|
|
return suspend(() => pipe(sync(() => Array.from(elements)), flatMap7((buffer) => {
|
|
const numbers = [];
|
|
for (let i = buffer.length;i >= 2; i = i - 1) {
|
|
numbers.push(i);
|
|
}
|
|
return pipe(numbers, forEachSequentialDiscard((n) => pipe(nextIntBounded(n), map10((k) => swap(buffer, n - 1, k)))), as(fromIterable2(buffer)));
|
|
})));
|
|
};
|
|
var swap = (buffer, index1, index2) => {
|
|
const tmp = buffer[index1];
|
|
buffer[index1] = buffer[index2];
|
|
buffer[index2] = tmp;
|
|
return buffer;
|
|
};
|
|
var make22 = (seed) => new RandomImpl(hash(seed));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/tracer.js
|
|
var TracerTypeId = /* @__PURE__ */ Symbol.for("effect/Tracer");
|
|
var make23 = (options) => ({
|
|
[TracerTypeId]: TracerTypeId,
|
|
...options
|
|
});
|
|
var tracerTag = /* @__PURE__ */ GenericTag("effect/Tracer");
|
|
var spanTag = /* @__PURE__ */ GenericTag("effect/ParentSpan");
|
|
var randomHexString = /* @__PURE__ */ function() {
|
|
const characters = "abcdef0123456789";
|
|
const charactersLength = characters.length;
|
|
return function(length) {
|
|
let result = "";
|
|
for (let i = 0;i < length; i++) {
|
|
result += characters.charAt(Math.floor(Math.random() * charactersLength));
|
|
}
|
|
return result;
|
|
};
|
|
}();
|
|
|
|
class NativeSpan {
|
|
name;
|
|
parent;
|
|
context;
|
|
startTime;
|
|
kind;
|
|
_tag = "Span";
|
|
spanId;
|
|
traceId = "native";
|
|
sampled = true;
|
|
status;
|
|
attributes;
|
|
events = [];
|
|
links;
|
|
constructor(name, parent, context, links, startTime, kind) {
|
|
this.name = name;
|
|
this.parent = parent;
|
|
this.context = context;
|
|
this.startTime = startTime;
|
|
this.kind = kind;
|
|
this.status = {
|
|
_tag: "Started",
|
|
startTime
|
|
};
|
|
this.attributes = new Map;
|
|
this.traceId = parent._tag === "Some" ? parent.value.traceId : randomHexString(32);
|
|
this.spanId = randomHexString(16);
|
|
this.links = Array.from(links);
|
|
}
|
|
end(endTime, exit) {
|
|
this.status = {
|
|
_tag: "Ended",
|
|
endTime,
|
|
exit,
|
|
startTime: this.status.startTime
|
|
};
|
|
}
|
|
attribute(key, value) {
|
|
this.attributes.set(key, value);
|
|
}
|
|
event(name, startTime, attributes) {
|
|
this.events.push([name, startTime, attributes ?? {}]);
|
|
}
|
|
addLinks(links) {
|
|
this.links.push(...links);
|
|
}
|
|
}
|
|
var nativeTracer = /* @__PURE__ */ make23({
|
|
span: (name, parent, context, links, startTime, kind) => new NativeSpan(name, parent, context, links, startTime, kind),
|
|
context: (f) => f()
|
|
});
|
|
var DisablePropagation = /* @__PURE__ */ Reference2()("effect/Tracer/DisablePropagation", {
|
|
defaultValue: constFalse
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/defaultServices.js
|
|
var liveServices = /* @__PURE__ */ pipe(/* @__PURE__ */ empty3(), /* @__PURE__ */ add2(clockTag, /* @__PURE__ */ make19()), /* @__PURE__ */ add2(consoleTag, defaultConsole), /* @__PURE__ */ add2(randomTag, /* @__PURE__ */ make22(/* @__PURE__ */ Math.random())), /* @__PURE__ */ add2(configProviderTag, /* @__PURE__ */ fromEnv()), /* @__PURE__ */ add2(tracerTag, nativeTracer));
|
|
var currentServices = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/DefaultServices/currentServices"), () => fiberRefUnsafeMakeContext(liveServices));
|
|
var sleep = (duration) => {
|
|
const decodedDuration = decode(duration);
|
|
return clockWith((clock) => clock.sleep(decodedDuration));
|
|
};
|
|
var defaultServicesWith = (f) => withFiberRuntime((fiber) => f(fiber.currentDefaultServices));
|
|
var clockWith = (f) => defaultServicesWith((services) => f(services.unsafeMap.get(clockTag.key)));
|
|
var currentTimeMillis = /* @__PURE__ */ clockWith((clock) => clock.currentTimeMillis);
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Effectable.js
|
|
var EffectPrototype2 = EffectPrototype;
|
|
var Base2 = Base;
|
|
class Class extends Base2 {
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/executionStrategy.js
|
|
var OP_SEQUENTIAL2 = "Sequential";
|
|
var OP_PARALLEL2 = "Parallel";
|
|
var OP_PARALLEL_N = "ParallelN";
|
|
var sequential2 = {
|
|
_tag: OP_SEQUENTIAL2
|
|
};
|
|
var parallel2 = {
|
|
_tag: OP_PARALLEL2
|
|
};
|
|
var parallelN = (parallelism) => ({
|
|
_tag: OP_PARALLEL_N,
|
|
parallelism
|
|
});
|
|
var isSequential = (self2) => self2._tag === OP_SEQUENTIAL2;
|
|
var isParallel = (self2) => self2._tag === OP_PARALLEL2;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/ExecutionStrategy.js
|
|
var sequential3 = sequential2;
|
|
var parallel3 = parallel2;
|
|
var parallelN2 = parallelN;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/fiberRefs.js
|
|
function unsafeMake3(fiberRefLocals) {
|
|
return new FiberRefsImpl(fiberRefLocals);
|
|
}
|
|
function empty16() {
|
|
return unsafeMake3(new Map);
|
|
}
|
|
var FiberRefsSym = /* @__PURE__ */ Symbol.for("effect/FiberRefs");
|
|
|
|
class FiberRefsImpl {
|
|
locals;
|
|
[FiberRefsSym] = FiberRefsSym;
|
|
constructor(locals) {
|
|
this.locals = locals;
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
}
|
|
var findAncestor = (_ref, _parentStack, _childStack, _childModified = false) => {
|
|
const ref = _ref;
|
|
let parentStack = _parentStack;
|
|
let childStack = _childStack;
|
|
let childModified = _childModified;
|
|
let ret = undefined;
|
|
while (ret === undefined) {
|
|
if (isNonEmptyReadonlyArray(parentStack) && isNonEmptyReadonlyArray(childStack)) {
|
|
const parentFiberId = headNonEmpty(parentStack)[0];
|
|
const parentAncestors = tailNonEmpty(parentStack);
|
|
const childFiberId = headNonEmpty(childStack)[0];
|
|
const childRefValue = headNonEmpty(childStack)[1];
|
|
const childAncestors = tailNonEmpty(childStack);
|
|
if (parentFiberId.startTimeMillis < childFiberId.startTimeMillis) {
|
|
childStack = childAncestors;
|
|
childModified = true;
|
|
} else if (parentFiberId.startTimeMillis > childFiberId.startTimeMillis) {
|
|
parentStack = parentAncestors;
|
|
} else {
|
|
if (parentFiberId.id < childFiberId.id) {
|
|
childStack = childAncestors;
|
|
childModified = true;
|
|
} else if (parentFiberId.id > childFiberId.id) {
|
|
parentStack = parentAncestors;
|
|
} else {
|
|
ret = [childRefValue, childModified];
|
|
}
|
|
}
|
|
} else {
|
|
ret = [ref.initial, true];
|
|
}
|
|
}
|
|
return ret;
|
|
};
|
|
var joinAs = /* @__PURE__ */ dual(3, (self2, fiberId, that) => {
|
|
const parentFiberRefs = new Map(self2.locals);
|
|
that.locals.forEach((childStack, fiberRef) => {
|
|
const childValue = childStack[0][1];
|
|
if (!childStack[0][0][symbol2](fiberId)) {
|
|
if (!parentFiberRefs.has(fiberRef)) {
|
|
if (equals(childValue, fiberRef.initial)) {
|
|
return;
|
|
}
|
|
parentFiberRefs.set(fiberRef, [[fiberId, fiberRef.join(fiberRef.initial, childValue)]]);
|
|
return;
|
|
}
|
|
const parentStack = parentFiberRefs.get(fiberRef);
|
|
const [ancestor, wasModified] = findAncestor(fiberRef, parentStack, childStack);
|
|
if (wasModified) {
|
|
const patch = fiberRef.diff(ancestor, childValue);
|
|
const oldValue = parentStack[0][1];
|
|
const newValue = fiberRef.join(oldValue, fiberRef.patch(patch)(oldValue));
|
|
if (!equals(oldValue, newValue)) {
|
|
let newStack;
|
|
const parentFiberId = parentStack[0][0];
|
|
if (parentFiberId[symbol2](fiberId)) {
|
|
newStack = [[parentFiberId, newValue], ...parentStack.slice(1)];
|
|
} else {
|
|
newStack = [[fiberId, newValue], ...parentStack];
|
|
}
|
|
parentFiberRefs.set(fiberRef, newStack);
|
|
}
|
|
}
|
|
}
|
|
});
|
|
return new FiberRefsImpl(parentFiberRefs);
|
|
});
|
|
var forkAs = /* @__PURE__ */ dual(2, (self2, childId) => {
|
|
const map = new Map;
|
|
unsafeForkAs(self2, map, childId);
|
|
return new FiberRefsImpl(map);
|
|
});
|
|
var unsafeForkAs = (self2, map, fiberId) => {
|
|
self2.locals.forEach((stack, fiberRef) => {
|
|
const oldValue = stack[0][1];
|
|
const newValue = fiberRef.patch(fiberRef.fork)(oldValue);
|
|
if (equals(oldValue, newValue)) {
|
|
map.set(fiberRef, stack);
|
|
} else {
|
|
map.set(fiberRef, [[fiberId, newValue], ...stack]);
|
|
}
|
|
});
|
|
};
|
|
var delete_ = /* @__PURE__ */ dual(2, (self2, fiberRef) => {
|
|
const locals = new Map(self2.locals);
|
|
locals.delete(fiberRef);
|
|
return new FiberRefsImpl(locals);
|
|
});
|
|
var get8 = /* @__PURE__ */ dual(2, (self2, fiberRef) => {
|
|
if (!self2.locals.has(fiberRef)) {
|
|
return none2();
|
|
}
|
|
return some2(headNonEmpty(self2.locals.get(fiberRef))[1]);
|
|
});
|
|
var getOrDefault = /* @__PURE__ */ dual(2, (self2, fiberRef) => pipe(get8(self2, fiberRef), getOrElse(() => fiberRef.initial)));
|
|
var updateAs = /* @__PURE__ */ dual(2, (self2, {
|
|
fiberId,
|
|
fiberRef,
|
|
value
|
|
}) => {
|
|
if (self2.locals.size === 0) {
|
|
return new FiberRefsImpl(new Map([[fiberRef, [[fiberId, value]]]]));
|
|
}
|
|
const locals = new Map(self2.locals);
|
|
unsafeUpdateAs(locals, fiberId, fiberRef, value);
|
|
return new FiberRefsImpl(locals);
|
|
});
|
|
var unsafeUpdateAs = (locals, fiberId, fiberRef, value) => {
|
|
const oldStack = locals.get(fiberRef) ?? [];
|
|
let newStack;
|
|
if (isNonEmptyReadonlyArray(oldStack)) {
|
|
const [currentId, currentValue] = headNonEmpty(oldStack);
|
|
if (currentId[symbol2](fiberId)) {
|
|
if (equals(currentValue, value)) {
|
|
return;
|
|
} else {
|
|
newStack = [[fiberId, value], ...oldStack.slice(1)];
|
|
}
|
|
} else {
|
|
newStack = [[fiberId, value], ...oldStack];
|
|
}
|
|
} else {
|
|
newStack = [[fiberId, value]];
|
|
}
|
|
locals.set(fiberRef, newStack);
|
|
};
|
|
var updateManyAs = /* @__PURE__ */ dual(2, (self2, {
|
|
entries,
|
|
forkAs
|
|
}) => {
|
|
if (self2.locals.size === 0) {
|
|
return new FiberRefsImpl(new Map(entries));
|
|
}
|
|
const locals = new Map(self2.locals);
|
|
if (forkAs !== undefined) {
|
|
unsafeForkAs(self2, locals, forkAs);
|
|
}
|
|
entries.forEach(([fiberRef, values]) => {
|
|
if (values.length === 1) {
|
|
unsafeUpdateAs(locals, values[0][0], fiberRef, values[0][1]);
|
|
} else {
|
|
values.forEach(([fiberId, value]) => {
|
|
unsafeUpdateAs(locals, fiberId, fiberRef, value);
|
|
});
|
|
}
|
|
});
|
|
return new FiberRefsImpl(locals);
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/FiberRefs.js
|
|
var getOrDefault2 = getOrDefault;
|
|
var updateManyAs2 = updateManyAs;
|
|
var empty17 = empty16;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/fiberRefs/patch.js
|
|
var OP_EMPTY2 = "Empty";
|
|
var OP_ADD = "Add";
|
|
var OP_REMOVE = "Remove";
|
|
var OP_UPDATE = "Update";
|
|
var OP_AND_THEN = "AndThen";
|
|
var empty18 = {
|
|
_tag: OP_EMPTY2
|
|
};
|
|
var diff5 = (oldValue, newValue) => {
|
|
const missingLocals = new Map(oldValue.locals);
|
|
let patch = empty18;
|
|
for (const [fiberRef, pairs] of newValue.locals.entries()) {
|
|
const newValue = headNonEmpty(pairs)[1];
|
|
const old = missingLocals.get(fiberRef);
|
|
if (old !== undefined) {
|
|
const oldValue = headNonEmpty(old)[1];
|
|
if (!equals(oldValue, newValue)) {
|
|
patch = combine7({
|
|
_tag: OP_UPDATE,
|
|
fiberRef,
|
|
patch: fiberRef.diff(oldValue, newValue)
|
|
})(patch);
|
|
}
|
|
} else {
|
|
patch = combine7({
|
|
_tag: OP_ADD,
|
|
fiberRef,
|
|
value: newValue
|
|
})(patch);
|
|
}
|
|
missingLocals.delete(fiberRef);
|
|
}
|
|
for (const [fiberRef] of missingLocals.entries()) {
|
|
patch = combine7({
|
|
_tag: OP_REMOVE,
|
|
fiberRef
|
|
})(patch);
|
|
}
|
|
return patch;
|
|
};
|
|
var combine7 = /* @__PURE__ */ dual(2, (self2, that) => ({
|
|
_tag: OP_AND_THEN,
|
|
first: self2,
|
|
second: that
|
|
}));
|
|
var patch6 = /* @__PURE__ */ dual(3, (self2, fiberId, oldValue) => {
|
|
let fiberRefs = oldValue;
|
|
let patches = of(self2);
|
|
while (isNonEmptyReadonlyArray(patches)) {
|
|
const head = headNonEmpty(patches);
|
|
const tail = tailNonEmpty(patches);
|
|
switch (head._tag) {
|
|
case OP_EMPTY2: {
|
|
patches = tail;
|
|
break;
|
|
}
|
|
case OP_ADD: {
|
|
fiberRefs = updateAs(fiberRefs, {
|
|
fiberId,
|
|
fiberRef: head.fiberRef,
|
|
value: head.value
|
|
});
|
|
patches = tail;
|
|
break;
|
|
}
|
|
case OP_REMOVE: {
|
|
fiberRefs = delete_(fiberRefs, head.fiberRef);
|
|
patches = tail;
|
|
break;
|
|
}
|
|
case OP_UPDATE: {
|
|
const value = getOrDefault(fiberRefs, head.fiberRef);
|
|
fiberRefs = updateAs(fiberRefs, {
|
|
fiberId,
|
|
fiberRef: head.fiberRef,
|
|
value: head.fiberRef.patch(head.patch)(value)
|
|
});
|
|
patches = tail;
|
|
break;
|
|
}
|
|
case OP_AND_THEN: {
|
|
patches = prepend(head.first)(prepend(head.second)(tail));
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
return fiberRefs;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/FiberRefsPatch.js
|
|
var diff6 = diff5;
|
|
var patch7 = patch6;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/fiberStatus.js
|
|
var FiberStatusSymbolKey = "effect/FiberStatus";
|
|
var FiberStatusTypeId = /* @__PURE__ */ Symbol.for(FiberStatusSymbolKey);
|
|
var OP_DONE = "Done";
|
|
var OP_RUNNING = "Running";
|
|
var OP_SUSPENDED = "Suspended";
|
|
var DoneHash = /* @__PURE__ */ string(`${FiberStatusSymbolKey}-${OP_DONE}`);
|
|
|
|
class Done {
|
|
[FiberStatusTypeId] = FiberStatusTypeId;
|
|
_tag = OP_DONE;
|
|
[symbol]() {
|
|
return DoneHash;
|
|
}
|
|
[symbol2](that) {
|
|
return isFiberStatus(that) && that._tag === OP_DONE;
|
|
}
|
|
}
|
|
|
|
class Running {
|
|
runtimeFlags;
|
|
[FiberStatusTypeId] = FiberStatusTypeId;
|
|
_tag = OP_RUNNING;
|
|
constructor(runtimeFlags) {
|
|
this.runtimeFlags = runtimeFlags;
|
|
}
|
|
[symbol]() {
|
|
return pipe(hash(FiberStatusSymbolKey), combine(hash(this._tag)), combine(hash(this.runtimeFlags)), cached(this));
|
|
}
|
|
[symbol2](that) {
|
|
return isFiberStatus(that) && that._tag === OP_RUNNING && this.runtimeFlags === that.runtimeFlags;
|
|
}
|
|
}
|
|
|
|
class Suspended {
|
|
runtimeFlags;
|
|
blockingOn;
|
|
[FiberStatusTypeId] = FiberStatusTypeId;
|
|
_tag = OP_SUSPENDED;
|
|
constructor(runtimeFlags, blockingOn) {
|
|
this.runtimeFlags = runtimeFlags;
|
|
this.blockingOn = blockingOn;
|
|
}
|
|
[symbol]() {
|
|
return pipe(hash(FiberStatusSymbolKey), combine(hash(this._tag)), combine(hash(this.runtimeFlags)), combine(hash(this.blockingOn)), cached(this));
|
|
}
|
|
[symbol2](that) {
|
|
return isFiberStatus(that) && that._tag === OP_SUSPENDED && this.runtimeFlags === that.runtimeFlags && equals(this.blockingOn, that.blockingOn);
|
|
}
|
|
}
|
|
var done2 = /* @__PURE__ */ new Done;
|
|
var running = (runtimeFlags) => new Running(runtimeFlags);
|
|
var suspended = (runtimeFlags, blockingOn) => new Suspended(runtimeFlags, blockingOn);
|
|
var isFiberStatus = (u) => hasProperty(u, FiberStatusTypeId);
|
|
var isDone2 = (self2) => self2._tag === OP_DONE;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/FiberStatus.js
|
|
var done3 = done2;
|
|
var running2 = running;
|
|
var suspended2 = suspended;
|
|
var isDone3 = isDone2;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/LogLevel.js
|
|
var All = logLevelAll;
|
|
var Fatal = logLevelFatal;
|
|
var Error3 = logLevelError;
|
|
var Warning = logLevelWarning;
|
|
var Info = logLevelInfo;
|
|
var Debug = logLevelDebug;
|
|
var Trace = logLevelTrace;
|
|
var None3 = logLevelNone;
|
|
var Order2 = /* @__PURE__ */ pipe(Order, /* @__PURE__ */ mapInput2((level) => level.ordinal));
|
|
var greaterThan2 = /* @__PURE__ */ greaterThan(Order2);
|
|
var fromLiteral = (literal) => {
|
|
switch (literal) {
|
|
case "All":
|
|
return All;
|
|
case "Debug":
|
|
return Debug;
|
|
case "Error":
|
|
return Error3;
|
|
case "Fatal":
|
|
return Fatal;
|
|
case "Info":
|
|
return Info;
|
|
case "Trace":
|
|
return Trace;
|
|
case "None":
|
|
return None3;
|
|
case "Warning":
|
|
return Warning;
|
|
}
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Micro.js
|
|
var TypeId9 = /* @__PURE__ */ Symbol.for("effect/Micro");
|
|
var MicroExitTypeId = /* @__PURE__ */ Symbol.for("effect/Micro/MicroExit");
|
|
var MicroCauseTypeId = /* @__PURE__ */ Symbol.for("effect/Micro/MicroCause");
|
|
var microCauseVariance = {
|
|
_E: identity
|
|
};
|
|
|
|
class MicroCauseImpl extends globalThis.Error {
|
|
_tag;
|
|
traces;
|
|
[MicroCauseTypeId];
|
|
constructor(_tag, originalError, traces) {
|
|
const causeName = `MicroCause.${_tag}`;
|
|
let name;
|
|
let message;
|
|
let stack;
|
|
if (originalError instanceof globalThis.Error) {
|
|
name = `(${causeName}) ${originalError.name}`;
|
|
message = originalError.message;
|
|
const messageLines = message.split(`
|
|
`).length;
|
|
stack = originalError.stack ? `(${causeName}) ${originalError.stack.split(`
|
|
`).slice(0, messageLines + 3).join(`
|
|
`)}` : `${name}: ${message}`;
|
|
} else {
|
|
name = causeName;
|
|
message = toStringUnknown(originalError, 0);
|
|
stack = `${name}: ${message}`;
|
|
}
|
|
if (traces.length > 0) {
|
|
stack += `
|
|
${traces.join(`
|
|
`)}`;
|
|
}
|
|
super(message);
|
|
this._tag = _tag;
|
|
this.traces = traces;
|
|
this[MicroCauseTypeId] = microCauseVariance;
|
|
this.name = name;
|
|
this.stack = stack;
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
toString() {
|
|
return this.stack;
|
|
}
|
|
[NodeInspectSymbol]() {
|
|
return this.stack;
|
|
}
|
|
}
|
|
class Die extends MicroCauseImpl {
|
|
defect;
|
|
constructor(defect, traces = []) {
|
|
super("Die", defect, traces);
|
|
this.defect = defect;
|
|
}
|
|
}
|
|
var causeDie = (defect, traces = []) => new Die(defect, traces);
|
|
|
|
class Interrupt extends MicroCauseImpl {
|
|
constructor(traces = []) {
|
|
super("Interrupt", "interrupted", traces);
|
|
}
|
|
}
|
|
var causeInterrupt = (traces = []) => new Interrupt(traces);
|
|
var causeIsInterrupt = (self2) => self2._tag === "Interrupt";
|
|
var MicroFiberTypeId = /* @__PURE__ */ Symbol.for("effect/Micro/MicroFiber");
|
|
var fiberVariance = {
|
|
_A: identity,
|
|
_E: identity
|
|
};
|
|
|
|
class MicroFiberImpl {
|
|
context;
|
|
interruptible;
|
|
[MicroFiberTypeId];
|
|
_stack = [];
|
|
_observers = [];
|
|
_exit;
|
|
_children;
|
|
currentOpCount = 0;
|
|
constructor(context, interruptible = true) {
|
|
this.context = context;
|
|
this.interruptible = interruptible;
|
|
this[MicroFiberTypeId] = fiberVariance;
|
|
}
|
|
getRef(ref) {
|
|
return unsafeGetReference(this.context, ref);
|
|
}
|
|
addObserver(cb) {
|
|
if (this._exit) {
|
|
cb(this._exit);
|
|
return constVoid;
|
|
}
|
|
this._observers.push(cb);
|
|
return () => {
|
|
const index = this._observers.indexOf(cb);
|
|
if (index >= 0) {
|
|
this._observers.splice(index, 1);
|
|
}
|
|
};
|
|
}
|
|
_interrupted = false;
|
|
unsafeInterrupt() {
|
|
if (this._exit) {
|
|
return;
|
|
}
|
|
this._interrupted = true;
|
|
if (this.interruptible) {
|
|
this.evaluate(exitInterrupt2);
|
|
}
|
|
}
|
|
unsafePoll() {
|
|
return this._exit;
|
|
}
|
|
evaluate(effect) {
|
|
if (this._exit) {
|
|
return;
|
|
} else if (this._yielded !== undefined) {
|
|
const yielded = this._yielded;
|
|
this._yielded = undefined;
|
|
yielded();
|
|
}
|
|
const exit = this.runLoop(effect);
|
|
if (exit === Yield) {
|
|
return;
|
|
}
|
|
const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this);
|
|
if (interruptChildren !== undefined) {
|
|
return this.evaluate(flatMap8(interruptChildren, () => exit));
|
|
}
|
|
this._exit = exit;
|
|
for (let i = 0;i < this._observers.length; i++) {
|
|
this._observers[i](exit);
|
|
}
|
|
this._observers.length = 0;
|
|
}
|
|
runLoop(effect) {
|
|
let yielding = false;
|
|
let current = effect;
|
|
this.currentOpCount = 0;
|
|
try {
|
|
while (true) {
|
|
this.currentOpCount++;
|
|
if (!yielding && this.getRef(CurrentScheduler).shouldYield(this)) {
|
|
yielding = true;
|
|
const prev = current;
|
|
current = flatMap8(yieldNow2, () => prev);
|
|
}
|
|
current = current[evaluate](this);
|
|
if (current === Yield) {
|
|
const yielded = this._yielded;
|
|
if (MicroExitTypeId in yielded) {
|
|
this._yielded = undefined;
|
|
return yielded;
|
|
}
|
|
return Yield;
|
|
}
|
|
}
|
|
} catch (error) {
|
|
if (!hasProperty(current, evaluate)) {
|
|
return exitDie2(`MicroFiber.runLoop: Not a valid effect: ${String(current)}`);
|
|
}
|
|
return exitDie2(error);
|
|
}
|
|
}
|
|
getCont(symbol) {
|
|
while (true) {
|
|
const op = this._stack.pop();
|
|
if (!op)
|
|
return;
|
|
const cont = op[ensureCont] && op[ensureCont](this);
|
|
if (cont)
|
|
return {
|
|
[symbol]: cont
|
|
};
|
|
if (op[symbol])
|
|
return op;
|
|
}
|
|
}
|
|
_yielded = undefined;
|
|
yieldWith(value) {
|
|
this._yielded = value;
|
|
return Yield;
|
|
}
|
|
children() {
|
|
return this._children ??= new Set;
|
|
}
|
|
}
|
|
var fiberMiddleware = /* @__PURE__ */ globalValue("effect/Micro/fiberMiddleware", () => ({
|
|
interruptChildren: undefined
|
|
}));
|
|
var identifier = /* @__PURE__ */ Symbol.for("effect/Micro/identifier");
|
|
var args = /* @__PURE__ */ Symbol.for("effect/Micro/args");
|
|
var evaluate = /* @__PURE__ */ Symbol.for("effect/Micro/evaluate");
|
|
var successCont = /* @__PURE__ */ Symbol.for("effect/Micro/successCont");
|
|
var failureCont = /* @__PURE__ */ Symbol.for("effect/Micro/failureCont");
|
|
var ensureCont = /* @__PURE__ */ Symbol.for("effect/Micro/ensureCont");
|
|
var Yield = /* @__PURE__ */ Symbol.for("effect/Micro/Yield");
|
|
var microVariance = {
|
|
_A: identity,
|
|
_E: identity,
|
|
_R: identity
|
|
};
|
|
var MicroProto = {
|
|
...EffectPrototype2,
|
|
_op: "Micro",
|
|
[TypeId9]: microVariance,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
},
|
|
[Symbol.iterator]() {
|
|
return new SingleShotGen(new YieldWrap(this));
|
|
},
|
|
toJSON() {
|
|
return {
|
|
_id: "Micro",
|
|
op: this[identifier],
|
|
...args in this ? {
|
|
args: this[args]
|
|
} : undefined
|
|
};
|
|
},
|
|
toString() {
|
|
return format2(this);
|
|
},
|
|
[NodeInspectSymbol]() {
|
|
return format2(this);
|
|
}
|
|
};
|
|
function defaultEvaluate(_fiber) {
|
|
return exitDie2(`Micro.evaluate: Not implemented`);
|
|
}
|
|
var makePrimitiveProto = (options) => ({
|
|
...MicroProto,
|
|
[identifier]: options.op,
|
|
[evaluate]: options.eval ?? defaultEvaluate,
|
|
[successCont]: options.contA,
|
|
[failureCont]: options.contE,
|
|
[ensureCont]: options.ensure
|
|
});
|
|
var makePrimitive = (options) => {
|
|
const Proto = makePrimitiveProto(options);
|
|
return function() {
|
|
const self2 = Object.create(Proto);
|
|
self2[args] = options.single === false ? arguments : arguments[0];
|
|
return self2;
|
|
};
|
|
};
|
|
var makeExit = (options) => {
|
|
const Proto = {
|
|
...makePrimitiveProto(options),
|
|
[MicroExitTypeId]: MicroExitTypeId,
|
|
_tag: options.op,
|
|
get [options.prop]() {
|
|
return this[args];
|
|
},
|
|
toJSON() {
|
|
return {
|
|
_id: "MicroExit",
|
|
_tag: options.op,
|
|
[options.prop]: this[args]
|
|
};
|
|
},
|
|
[symbol2](that) {
|
|
return isMicroExit(that) && that._tag === options.op && equals(this[args], that[args]);
|
|
},
|
|
[symbol]() {
|
|
return cached(this, combine(string(options.op))(hash(this[args])));
|
|
}
|
|
};
|
|
return function(value) {
|
|
const self2 = Object.create(Proto);
|
|
self2[args] = value;
|
|
self2[successCont] = undefined;
|
|
self2[failureCont] = undefined;
|
|
self2[ensureCont] = undefined;
|
|
return self2;
|
|
};
|
|
};
|
|
var succeed3 = /* @__PURE__ */ makeExit({
|
|
op: "Success",
|
|
prop: "value",
|
|
eval(fiber) {
|
|
const cont = fiber.getCont(successCont);
|
|
return cont ? cont[successCont](this[args], fiber) : fiber.yieldWith(this);
|
|
}
|
|
});
|
|
var failCause3 = /* @__PURE__ */ makeExit({
|
|
op: "Failure",
|
|
prop: "cause",
|
|
eval(fiber) {
|
|
let cont = fiber.getCont(failureCont);
|
|
while (causeIsInterrupt(this[args]) && cont && fiber.interruptible) {
|
|
cont = fiber.getCont(failureCont);
|
|
}
|
|
return cont ? cont[failureCont](this[args], fiber) : fiber.yieldWith(this);
|
|
}
|
|
});
|
|
var yieldNowWith = /* @__PURE__ */ makePrimitive({
|
|
op: "Yield",
|
|
eval(fiber) {
|
|
let resumed = false;
|
|
fiber.getRef(CurrentScheduler).scheduleTask(() => {
|
|
if (resumed)
|
|
return;
|
|
fiber.evaluate(exitVoid2);
|
|
}, this[args] ?? 0);
|
|
return fiber.yieldWith(() => {
|
|
resumed = true;
|
|
});
|
|
}
|
|
});
|
|
var yieldNow2 = /* @__PURE__ */ yieldNowWith(0);
|
|
var void_2 = /* @__PURE__ */ succeed3(undefined);
|
|
var withMicroFiber = /* @__PURE__ */ makePrimitive({
|
|
op: "WithMicroFiber",
|
|
eval(fiber) {
|
|
return this[args](fiber);
|
|
}
|
|
});
|
|
var flatMap8 = /* @__PURE__ */ dual(2, (self2, f) => {
|
|
const onSuccess = Object.create(OnSuccessProto);
|
|
onSuccess[args] = self2;
|
|
onSuccess[successCont] = f;
|
|
return onSuccess;
|
|
});
|
|
var OnSuccessProto = /* @__PURE__ */ makePrimitiveProto({
|
|
op: "OnSuccess",
|
|
eval(fiber) {
|
|
fiber._stack.push(this);
|
|
return this[args];
|
|
}
|
|
});
|
|
var isMicroExit = (u) => hasProperty(u, MicroExitTypeId);
|
|
var exitSucceed2 = succeed3;
|
|
var exitFailCause2 = failCause3;
|
|
var exitInterrupt2 = /* @__PURE__ */ exitFailCause2(/* @__PURE__ */ causeInterrupt());
|
|
var exitDie2 = (defect) => exitFailCause2(causeDie(defect));
|
|
var exitVoid2 = /* @__PURE__ */ exitSucceed2(undefined);
|
|
var setImmediate = "setImmediate" in globalThis ? globalThis.setImmediate : (f) => setTimeout(f, 0);
|
|
|
|
class MicroSchedulerDefault {
|
|
tasks = [];
|
|
running = false;
|
|
scheduleTask(task, _priority) {
|
|
this.tasks.push(task);
|
|
if (!this.running) {
|
|
this.running = true;
|
|
setImmediate(this.afterScheduled);
|
|
}
|
|
}
|
|
afterScheduled = () => {
|
|
this.running = false;
|
|
this.runTasks();
|
|
};
|
|
runTasks() {
|
|
const tasks = this.tasks;
|
|
this.tasks = [];
|
|
for (let i = 0, len = tasks.length;i < len; i++) {
|
|
tasks[i]();
|
|
}
|
|
}
|
|
shouldYield(fiber) {
|
|
return fiber.currentOpCount >= fiber.getRef(MaxOpsBeforeYield);
|
|
}
|
|
flush() {
|
|
while (this.tasks.length > 0) {
|
|
this.runTasks();
|
|
}
|
|
}
|
|
}
|
|
var updateContext = /* @__PURE__ */ dual(2, (self2, f) => withMicroFiber((fiber) => {
|
|
const prev = fiber.context;
|
|
fiber.context = f(prev);
|
|
return onExit2(self2, () => {
|
|
fiber.context = prev;
|
|
return void_2;
|
|
});
|
|
}));
|
|
var provideContext2 = /* @__PURE__ */ dual(2, (self2, provided) => updateContext(self2, merge3(provided)));
|
|
class MaxOpsBeforeYield extends (/* @__PURE__ */ Reference2()("effect/Micro/currentMaxOpsBeforeYield", {
|
|
defaultValue: () => 2048
|
|
})) {
|
|
}
|
|
class CurrentScheduler extends (/* @__PURE__ */ Reference2()("effect/Micro/currentScheduler", {
|
|
defaultValue: () => new MicroSchedulerDefault
|
|
})) {
|
|
}
|
|
var matchCauseEffect2 = /* @__PURE__ */ dual(2, (self2, options) => {
|
|
const primitive = Object.create(OnSuccessAndFailureProto);
|
|
primitive[args] = self2;
|
|
primitive[successCont] = options.onSuccess;
|
|
primitive[failureCont] = options.onFailure;
|
|
return primitive;
|
|
});
|
|
var OnSuccessAndFailureProto = /* @__PURE__ */ makePrimitiveProto({
|
|
op: "OnSuccessAndFailure",
|
|
eval(fiber) {
|
|
fiber._stack.push(this);
|
|
return this[args];
|
|
}
|
|
});
|
|
var onExit2 = /* @__PURE__ */ dual(2, (self2, f) => uninterruptibleMask2((restore) => matchCauseEffect2(restore(self2), {
|
|
onFailure: (cause) => flatMap8(f(exitFailCause2(cause)), () => failCause3(cause)),
|
|
onSuccess: (a) => flatMap8(f(exitSucceed2(a)), () => succeed3(a))
|
|
})));
|
|
var setInterruptible = /* @__PURE__ */ makePrimitive({
|
|
op: "SetInterruptible",
|
|
ensure(fiber) {
|
|
fiber.interruptible = this[args];
|
|
if (fiber._interrupted && fiber.interruptible) {
|
|
return () => exitInterrupt2;
|
|
}
|
|
}
|
|
});
|
|
var interruptible3 = (self2) => withMicroFiber((fiber) => {
|
|
if (fiber.interruptible)
|
|
return self2;
|
|
fiber.interruptible = true;
|
|
fiber._stack.push(setInterruptible(false));
|
|
if (fiber._interrupted)
|
|
return exitInterrupt2;
|
|
return self2;
|
|
});
|
|
var uninterruptibleMask2 = (f) => withMicroFiber((fiber) => {
|
|
if (!fiber.interruptible)
|
|
return f(identity);
|
|
fiber.interruptible = false;
|
|
fiber._stack.push(setInterruptible(true));
|
|
return f(interruptible3);
|
|
});
|
|
var runFork = (effect, options) => {
|
|
const fiber = new MicroFiberImpl(CurrentScheduler.context(options?.scheduler ?? new MicroSchedulerDefault));
|
|
fiber.evaluate(effect);
|
|
if (options?.signal) {
|
|
if (options.signal.aborted) {
|
|
fiber.unsafeInterrupt();
|
|
} else {
|
|
const abort = () => fiber.unsafeInterrupt();
|
|
options.signal.addEventListener("abort", abort, {
|
|
once: true
|
|
});
|
|
fiber.addObserver(() => options.signal.removeEventListener("abort", abort));
|
|
}
|
|
}
|
|
return fiber;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Readable.js
|
|
var TypeId10 = /* @__PURE__ */ Symbol.for("effect/Readable");
|
|
var Proto = {
|
|
[TypeId10]: TypeId10,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/ref.js
|
|
var RefTypeId = /* @__PURE__ */ Symbol.for("effect/Ref");
|
|
var refVariance = {
|
|
_A: (_) => _
|
|
};
|
|
|
|
class RefImpl extends Class {
|
|
ref;
|
|
commit() {
|
|
return this.get;
|
|
}
|
|
[RefTypeId] = refVariance;
|
|
[TypeId10] = TypeId10;
|
|
constructor(ref) {
|
|
super();
|
|
this.ref = ref;
|
|
this.get = sync(() => get6(this.ref));
|
|
}
|
|
get;
|
|
modify(f) {
|
|
return sync(() => {
|
|
const current = get6(this.ref);
|
|
const [b, a] = f(current);
|
|
if (current !== a) {
|
|
set2(a)(this.ref);
|
|
}
|
|
return b;
|
|
});
|
|
}
|
|
}
|
|
var unsafeMake4 = (value) => new RefImpl(make11(value));
|
|
var make24 = (value) => sync(() => unsafeMake4(value));
|
|
var get9 = (self2) => self2.get;
|
|
var set4 = /* @__PURE__ */ dual(2, (self2, value) => self2.modify(() => [undefined, value]));
|
|
var modify3 = /* @__PURE__ */ dual(2, (self2, f) => self2.modify(f));
|
|
var update2 = /* @__PURE__ */ dual(2, (self2, f) => self2.modify((a) => [undefined, f(a)]));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Ref.js
|
|
var make25 = make24;
|
|
var get10 = get9;
|
|
var modify4 = modify3;
|
|
var set5 = set4;
|
|
var update3 = update2;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Scheduler.js
|
|
class SchedulerRunner {
|
|
scheduleDrain;
|
|
running = false;
|
|
tasks = /* @__PURE__ */ new PriorityBuckets;
|
|
constructor(scheduleDrain) {
|
|
this.scheduleDrain = scheduleDrain;
|
|
}
|
|
starveInternal = (depth) => {
|
|
const tasks = this.tasks.buckets;
|
|
this.tasks.buckets = [];
|
|
for (const [_, toRun] of tasks) {
|
|
for (let i = 0;i < toRun.length; i++) {
|
|
toRun[i]();
|
|
}
|
|
}
|
|
if (this.tasks.buckets.length === 0) {
|
|
this.running = false;
|
|
} else {
|
|
this.starve(depth);
|
|
}
|
|
};
|
|
starve(depth = 0) {
|
|
this.scheduleDrain(depth, this.starveInternal);
|
|
}
|
|
scheduleTask(task, priority) {
|
|
this.tasks.scheduleTask(task, priority);
|
|
if (!this.running) {
|
|
this.running = true;
|
|
this.starve();
|
|
}
|
|
}
|
|
static cached(scheduleDrain) {
|
|
const fallback = new SchedulerRunner(scheduleDrain);
|
|
const runners = new WeakMap;
|
|
return (fiber) => {
|
|
if (fiber === undefined) {
|
|
return fallback;
|
|
}
|
|
let runner = runners.get(fiber);
|
|
if (runner === undefined) {
|
|
runner = new SchedulerRunner(scheduleDrain);
|
|
runners.set(fiber, runner);
|
|
}
|
|
return runner;
|
|
};
|
|
}
|
|
}
|
|
|
|
class PriorityBuckets {
|
|
buckets = [];
|
|
scheduleTask(task, priority) {
|
|
const length = this.buckets.length;
|
|
let bucket = undefined;
|
|
let index = 0;
|
|
for (;index < length; index++) {
|
|
if (this.buckets[index][0] <= priority) {
|
|
bucket = this.buckets[index];
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
if (bucket && bucket[0] === priority) {
|
|
bucket[1].push(task);
|
|
} else if (index === length) {
|
|
this.buckets.push([priority, [task]]);
|
|
} else {
|
|
this.buckets.splice(index, 0, [priority, [task]]);
|
|
}
|
|
}
|
|
}
|
|
|
|
class MixedScheduler {
|
|
maxNextTickBeforeTimer;
|
|
getRunner = /* @__PURE__ */ SchedulerRunner.cached((depth, drain) => {
|
|
if (depth >= this.maxNextTickBeforeTimer) {
|
|
setTimeout(() => drain(0), 0);
|
|
} else {
|
|
Promise.resolve(undefined).then(() => drain(depth + 1));
|
|
}
|
|
});
|
|
constructor(maxNextTickBeforeTimer) {
|
|
this.maxNextTickBeforeTimer = maxNextTickBeforeTimer;
|
|
}
|
|
shouldYield(fiber) {
|
|
return fiber.currentOpCount > fiber.getFiberRef(currentMaxOpsBeforeYield) ? fiber.getFiberRef(currentSchedulingPriority) : false;
|
|
}
|
|
scheduleTask(task, priority, fiber) {
|
|
this.getRunner(fiber).scheduleTask(task, priority);
|
|
}
|
|
}
|
|
var defaultScheduler = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/Scheduler/defaultScheduler"), () => new MixedScheduler(2048));
|
|
|
|
class SyncScheduler {
|
|
tasks = /* @__PURE__ */ new PriorityBuckets;
|
|
deferred = false;
|
|
scheduleTask(task, priority, fiber) {
|
|
if (this.deferred) {
|
|
defaultScheduler.scheduleTask(task, priority, fiber);
|
|
} else {
|
|
this.tasks.scheduleTask(task, priority);
|
|
}
|
|
}
|
|
shouldYield(fiber) {
|
|
return fiber.currentOpCount > fiber.getFiberRef(currentMaxOpsBeforeYield) ? fiber.getFiberRef(currentSchedulingPriority) : false;
|
|
}
|
|
flush() {
|
|
while (this.tasks.buckets.length > 0) {
|
|
const tasks = this.tasks.buckets;
|
|
this.tasks.buckets = [];
|
|
for (const [_, toRun] of tasks) {
|
|
for (let i = 0;i < toRun.length; i++) {
|
|
toRun[i]();
|
|
}
|
|
}
|
|
}
|
|
this.deferred = true;
|
|
}
|
|
}
|
|
var currentScheduler = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/FiberRef/currentScheduler"), () => fiberRefUnsafeMake(defaultScheduler));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/completedRequestMap.js
|
|
var currentRequestMap = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/FiberRef/currentRequestMap"), () => fiberRefUnsafeMake(new Map));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/concurrency.js
|
|
var match7 = (concurrency, sequential, unbounded, bounded) => {
|
|
switch (concurrency) {
|
|
case undefined:
|
|
return sequential();
|
|
case "unbounded":
|
|
return unbounded();
|
|
case "inherit":
|
|
return fiberRefGetWith(currentConcurrency, (concurrency) => concurrency === "unbounded" ? unbounded() : concurrency > 1 ? bounded(concurrency) : sequential());
|
|
default:
|
|
return concurrency > 1 ? bounded(concurrency) : sequential();
|
|
}
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Clock.js
|
|
var sleep2 = sleep;
|
|
var currentTimeMillis2 = currentTimeMillis;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/logSpan.js
|
|
var formatLabel = (key) => key.replace(/[\s="]/g, "_");
|
|
var render = (now) => (self2) => {
|
|
const label = formatLabel(self2.label);
|
|
return `${label}=${now - self2.startTime}ms`;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/metric/label.js
|
|
var MetricLabelSymbolKey = "effect/MetricLabel";
|
|
var MetricLabelTypeId = /* @__PURE__ */ Symbol.for(MetricLabelSymbolKey);
|
|
|
|
class MetricLabelImpl {
|
|
key;
|
|
value;
|
|
[MetricLabelTypeId] = MetricLabelTypeId;
|
|
_hash;
|
|
constructor(key, value) {
|
|
this.key = key;
|
|
this.value = value;
|
|
this._hash = string(MetricLabelSymbolKey + this.key + this.value);
|
|
}
|
|
[symbol]() {
|
|
return this._hash;
|
|
}
|
|
[symbol2](that) {
|
|
return isMetricLabel(that) && this.key === that.key && this.value === that.value;
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
}
|
|
var make26 = (key, value) => {
|
|
return new MetricLabelImpl(key, value);
|
|
};
|
|
var isMetricLabel = (u) => hasProperty(u, MetricLabelTypeId);
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/core-effect.js
|
|
var asSome = (self2) => map10(self2, some2);
|
|
var try_2 = (arg) => {
|
|
let evaluate;
|
|
let onFailure = undefined;
|
|
if (typeof arg === "function") {
|
|
evaluate = arg;
|
|
} else {
|
|
evaluate = arg.try;
|
|
onFailure = arg.catch;
|
|
}
|
|
return suspend(() => {
|
|
try {
|
|
return succeed(internalCall(evaluate));
|
|
} catch (error) {
|
|
return fail2(onFailure ? internalCall(() => onFailure(error)) : new UnknownException(error, "An unknown error occurred in Effect.try"));
|
|
}
|
|
});
|
|
};
|
|
var catchTag = /* @__PURE__ */ dual((args) => isEffect(args[0]), (self2, ...args) => {
|
|
const f = args[args.length - 1];
|
|
let predicate;
|
|
if (args.length === 2) {
|
|
predicate = isTagged(args[0]);
|
|
} else {
|
|
predicate = (e) => {
|
|
const tag = hasProperty(e, "_tag") ? e["_tag"] : undefined;
|
|
if (!tag)
|
|
return false;
|
|
for (let i = 0;i < args.length - 1; i++) {
|
|
if (args[i] === tag)
|
|
return true;
|
|
}
|
|
return false;
|
|
};
|
|
}
|
|
return catchIf(self2, predicate, f);
|
|
});
|
|
var diffFiberRefs = (self2) => summarized(self2, fiberRefs2, diff5);
|
|
var match8 = /* @__PURE__ */ dual(2, (self2, options) => matchEffect(self2, {
|
|
onFailure: (e) => succeed(options.onFailure(e)),
|
|
onSuccess: (a) => succeed(options.onSuccess(a))
|
|
}));
|
|
var fiberRefs2 = /* @__PURE__ */ withFiberRuntime((state) => succeed(state.getFiberRefs()));
|
|
var ignore = (self2) => match8(self2, {
|
|
onFailure: constVoid,
|
|
onSuccess: constVoid
|
|
});
|
|
var mapErrorCause = /* @__PURE__ */ dual(2, (self2, f) => matchCauseEffect(self2, {
|
|
onFailure: (c) => failCauseSync(() => f(c)),
|
|
onSuccess: succeed
|
|
}));
|
|
var negate = (self2) => map10(self2, (b) => !b);
|
|
var patchFiberRefs = (patch) => updateFiberRefs((fiberId, fiberRefs) => pipe(patch, patch6(fiberId, fiberRefs)));
|
|
var promise = (evaluate) => evaluate.length >= 1 ? async_((resolve, signal) => {
|
|
try {
|
|
evaluate(signal).then((a) => resolve(succeed(a)), (e) => resolve(die2(e)));
|
|
} catch (e) {
|
|
resolve(die2(e));
|
|
}
|
|
}) : async_((resolve) => {
|
|
try {
|
|
evaluate().then((a) => resolve(succeed(a)), (e) => resolve(die2(e)));
|
|
} catch (e) {
|
|
resolve(die2(e));
|
|
}
|
|
});
|
|
var provideService = /* @__PURE__ */ dual(3, (self2, tag, service) => contextWithEffect((env) => provideContext(self2, add2(env, tag, service))));
|
|
var provideServiceEffect = /* @__PURE__ */ dual(3, (self2, tag, effect) => contextWithEffect((env) => flatMap7(effect, (service) => provideContext(self2, pipe(env, add2(tag, service))))));
|
|
var sleep3 = sleep2;
|
|
var succeedNone = /* @__PURE__ */ succeed(/* @__PURE__ */ none2());
|
|
var summarized = /* @__PURE__ */ dual(3, (self2, summary, f) => flatMap7(summary, (start) => flatMap7(self2, (value) => map10(summary, (end) => [f(start, end), value]))));
|
|
var tapErrorCause = /* @__PURE__ */ dual(2, (self2, f) => matchCauseEffect(self2, {
|
|
onFailure: (cause) => zipRight(f(cause), failCause(cause)),
|
|
onSuccess: succeed
|
|
}));
|
|
var tryPromise = (arg) => {
|
|
let evaluate;
|
|
let catcher = undefined;
|
|
if (typeof arg === "function") {
|
|
evaluate = arg;
|
|
} else {
|
|
evaluate = arg.try;
|
|
catcher = arg.catch;
|
|
}
|
|
const fail = (e) => catcher ? failSync(() => catcher(e)) : fail2(new UnknownException(e, "An unknown error occurred in Effect.tryPromise"));
|
|
if (evaluate.length >= 1) {
|
|
return async_((resolve, signal) => {
|
|
try {
|
|
evaluate(signal).then((a) => resolve(succeed(a)), (e) => resolve(fail(e)));
|
|
} catch (e) {
|
|
resolve(fail(e));
|
|
}
|
|
});
|
|
}
|
|
return async_((resolve) => {
|
|
try {
|
|
evaluate().then((a) => resolve(succeed(a)), (e) => resolve(fail(e)));
|
|
} catch (e) {
|
|
resolve(fail(e));
|
|
}
|
|
});
|
|
};
|
|
var tryMap = /* @__PURE__ */ dual(2, (self2, options) => flatMap7(self2, (a) => try_2({
|
|
try: () => options.try(a),
|
|
catch: options.catch
|
|
})));
|
|
var updateFiberRefs = (f) => withFiberRuntime((state) => {
|
|
state.setFiberRefs(f(state.id(), state.getFiberRefs()));
|
|
return void_;
|
|
});
|
|
var when = /* @__PURE__ */ dual(2, (self2, condition) => suspend(() => condition() ? map10(self2, some2) : succeed(none2())));
|
|
var serviceOption = (tag) => map10(context(), getOption2(tag));
|
|
var filterDisablePropagation = /* @__PURE__ */ flatMap((span) => get3(span.context, DisablePropagation) ? span._tag === "Span" ? filterDisablePropagation(span.parent) : none2() : some2(span));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Exit.js
|
|
var isFailure2 = exitIsFailure;
|
|
var isSuccess = exitIsSuccess;
|
|
var all2 = exitCollectAll;
|
|
var die4 = exitDie;
|
|
var fail4 = exitFail;
|
|
var failCause4 = exitFailCause;
|
|
var map12 = exitMap;
|
|
var mapBoth2 = exitMapBoth;
|
|
var match9 = exitMatch;
|
|
var succeed4 = exitSucceed;
|
|
var void_3 = exitVoid;
|
|
var zip3 = exitZip;
|
|
var zipRight2 = exitZipRight;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/fiberMessage.js
|
|
var OP_INTERRUPT_SIGNAL = "InterruptSignal";
|
|
var OP_STATEFUL = "Stateful";
|
|
var OP_RESUME = "Resume";
|
|
var OP_YIELD_NOW = "YieldNow";
|
|
var interruptSignal = (cause) => ({
|
|
_tag: OP_INTERRUPT_SIGNAL,
|
|
cause
|
|
});
|
|
var stateful = (onFiber) => ({
|
|
_tag: OP_STATEFUL,
|
|
onFiber
|
|
});
|
|
var resume = (effect) => ({
|
|
_tag: OP_RESUME,
|
|
effect
|
|
});
|
|
var yieldNow3 = () => ({
|
|
_tag: OP_YIELD_NOW
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/fiberScope.js
|
|
var FiberScopeSymbolKey = "effect/FiberScope";
|
|
var FiberScopeTypeId = /* @__PURE__ */ Symbol.for(FiberScopeSymbolKey);
|
|
|
|
class Global {
|
|
[FiberScopeTypeId] = FiberScopeTypeId;
|
|
fiberId = none4;
|
|
roots = /* @__PURE__ */ new Set;
|
|
add(_runtimeFlags, child) {
|
|
this.roots.add(child);
|
|
child.addObserver(() => {
|
|
this.roots.delete(child);
|
|
});
|
|
}
|
|
}
|
|
|
|
class Local {
|
|
fiberId;
|
|
parent;
|
|
[FiberScopeTypeId] = FiberScopeTypeId;
|
|
constructor(fiberId, parent) {
|
|
this.fiberId = fiberId;
|
|
this.parent = parent;
|
|
}
|
|
add(_runtimeFlags, child) {
|
|
this.parent.tell(stateful((parentFiber) => {
|
|
parentFiber.addChild(child);
|
|
child.addObserver(() => {
|
|
parentFiber.removeChild(child);
|
|
});
|
|
}));
|
|
}
|
|
}
|
|
var unsafeMake5 = (fiber) => {
|
|
return new Local(fiber.id(), fiber);
|
|
};
|
|
var globalScope = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/FiberScope/Global"), () => new Global);
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/fiber.js
|
|
var FiberSymbolKey = "effect/Fiber";
|
|
var FiberTypeId = /* @__PURE__ */ Symbol.for(FiberSymbolKey);
|
|
var fiberVariance2 = {
|
|
_E: (_) => _,
|
|
_A: (_) => _
|
|
};
|
|
var fiberProto = {
|
|
[FiberTypeId]: fiberVariance2,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var RuntimeFiberSymbolKey = "effect/Fiber";
|
|
var RuntimeFiberTypeId = /* @__PURE__ */ Symbol.for(RuntimeFiberSymbolKey);
|
|
var _await2 = (self2) => self2.await;
|
|
var inheritAll = (self2) => self2.inheritAll;
|
|
var join2 = (self2) => zipLeft(flatten3(self2.await), self2.inheritAll);
|
|
var _never = {
|
|
...CommitPrototype,
|
|
commit() {
|
|
return join2(this);
|
|
},
|
|
...fiberProto,
|
|
id: () => none4,
|
|
await: never,
|
|
children: /* @__PURE__ */ succeed([]),
|
|
inheritAll: never,
|
|
poll: /* @__PURE__ */ succeed(/* @__PURE__ */ none2()),
|
|
interruptAsFork: () => never
|
|
};
|
|
var currentFiberURI = "effect/FiberCurrent";
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/logger.js
|
|
var LoggerSymbolKey = "effect/Logger";
|
|
var LoggerTypeId = /* @__PURE__ */ Symbol.for(LoggerSymbolKey);
|
|
var loggerVariance = {
|
|
_Message: (_) => _,
|
|
_Output: (_) => _
|
|
};
|
|
var makeLogger = (log) => ({
|
|
[LoggerTypeId]: loggerVariance,
|
|
log,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
});
|
|
var none6 = {
|
|
[LoggerTypeId]: loggerVariance,
|
|
log: constVoid,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var textOnly = /^[^\s"=]*$/;
|
|
var format4 = (quoteValue, whitespace) => ({
|
|
annotations,
|
|
cause,
|
|
date,
|
|
fiberId,
|
|
logLevel,
|
|
message,
|
|
spans
|
|
}) => {
|
|
const formatValue = (value) => value.match(textOnly) ? value : quoteValue(value);
|
|
const format = (label, value) => `${formatLabel(label)}=${formatValue(value)}`;
|
|
const append = (label, value) => " " + format(label, value);
|
|
let out = format("timestamp", date.toISOString());
|
|
out += append("level", logLevel.label);
|
|
out += append("fiber", threadName(fiberId));
|
|
const messages = ensure(message);
|
|
for (let i = 0;i < messages.length; i++) {
|
|
out += append("message", toStringUnknown(messages[i], whitespace));
|
|
}
|
|
if (!isEmptyType(cause)) {
|
|
out += append("cause", pretty(cause, {
|
|
renderErrorCause: true
|
|
}));
|
|
}
|
|
for (const span of spans) {
|
|
out += " " + render(date.getTime())(span);
|
|
}
|
|
for (const [label, value] of annotations) {
|
|
out += append(label, toStringUnknown(value, whitespace));
|
|
}
|
|
return out;
|
|
};
|
|
var escapeDoubleQuotes = (s) => `"${s.replace(/\\([\s\S])|(")/g, "\\$1$2")}"`;
|
|
var stringLogger = /* @__PURE__ */ makeLogger(/* @__PURE__ */ format4(escapeDoubleQuotes));
|
|
var colors = {
|
|
bold: "1",
|
|
red: "31",
|
|
green: "32",
|
|
yellow: "33",
|
|
blue: "34",
|
|
cyan: "36",
|
|
white: "37",
|
|
gray: "90",
|
|
black: "30",
|
|
bgBrightRed: "101"
|
|
};
|
|
var logLevelColors = {
|
|
None: [],
|
|
All: [],
|
|
Trace: [colors.gray],
|
|
Debug: [colors.blue],
|
|
Info: [colors.green],
|
|
Warning: [colors.yellow],
|
|
Error: [colors.red],
|
|
Fatal: [colors.bgBrightRed, colors.black]
|
|
};
|
|
var hasProcessStdout = typeof process === "object" && process !== null && typeof process.stdout === "object" && process.stdout !== null;
|
|
var processStdoutIsTTY = hasProcessStdout && process.stdout.isTTY === true;
|
|
var hasProcessStdoutOrDeno = hasProcessStdout || "Deno" in globalThis;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/metric/boundaries.js
|
|
var MetricBoundariesSymbolKey = "effect/MetricBoundaries";
|
|
var MetricBoundariesTypeId = /* @__PURE__ */ Symbol.for(MetricBoundariesSymbolKey);
|
|
|
|
class MetricBoundariesImpl {
|
|
values;
|
|
[MetricBoundariesTypeId] = MetricBoundariesTypeId;
|
|
constructor(values) {
|
|
this.values = values;
|
|
this._hash = pipe(string(MetricBoundariesSymbolKey), combine(array2(this.values)));
|
|
}
|
|
_hash;
|
|
[symbol]() {
|
|
return this._hash;
|
|
}
|
|
[symbol2](u) {
|
|
return isMetricBoundaries(u) && equals(this.values, u.values);
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
}
|
|
var isMetricBoundaries = (u) => hasProperty(u, MetricBoundariesTypeId);
|
|
var fromIterable7 = (iterable) => {
|
|
const values = pipe(iterable, appendAll(of2(Number.POSITIVE_INFINITY)), dedupe);
|
|
return new MetricBoundariesImpl(values);
|
|
};
|
|
var exponential = (options) => pipe(makeBy(options.count - 1, (i) => options.start * Math.pow(options.factor, i)), unsafeFromArray, fromIterable7);
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/metric/keyType.js
|
|
var MetricKeyTypeSymbolKey = "effect/MetricKeyType";
|
|
var MetricKeyTypeTypeId = /* @__PURE__ */ Symbol.for(MetricKeyTypeSymbolKey);
|
|
var CounterKeyTypeSymbolKey = "effect/MetricKeyType/Counter";
|
|
var CounterKeyTypeTypeId = /* @__PURE__ */ Symbol.for(CounterKeyTypeSymbolKey);
|
|
var FrequencyKeyTypeSymbolKey = "effect/MetricKeyType/Frequency";
|
|
var FrequencyKeyTypeTypeId = /* @__PURE__ */ Symbol.for(FrequencyKeyTypeSymbolKey);
|
|
var GaugeKeyTypeSymbolKey = "effect/MetricKeyType/Gauge";
|
|
var GaugeKeyTypeTypeId = /* @__PURE__ */ Symbol.for(GaugeKeyTypeSymbolKey);
|
|
var HistogramKeyTypeSymbolKey = "effect/MetricKeyType/Histogram";
|
|
var HistogramKeyTypeTypeId = /* @__PURE__ */ Symbol.for(HistogramKeyTypeSymbolKey);
|
|
var SummaryKeyTypeSymbolKey = "effect/MetricKeyType/Summary";
|
|
var SummaryKeyTypeTypeId = /* @__PURE__ */ Symbol.for(SummaryKeyTypeSymbolKey);
|
|
var metricKeyTypeVariance = {
|
|
_In: (_) => _,
|
|
_Out: (_) => _
|
|
};
|
|
|
|
class CounterKeyType {
|
|
incremental;
|
|
bigint;
|
|
[MetricKeyTypeTypeId] = metricKeyTypeVariance;
|
|
[CounterKeyTypeTypeId] = CounterKeyTypeTypeId;
|
|
constructor(incremental, bigint) {
|
|
this.incremental = incremental;
|
|
this.bigint = bigint;
|
|
this._hash = string(CounterKeyTypeSymbolKey);
|
|
}
|
|
_hash;
|
|
[symbol]() {
|
|
return this._hash;
|
|
}
|
|
[symbol2](that) {
|
|
return isCounterKey(that);
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
}
|
|
class HistogramKeyType {
|
|
boundaries;
|
|
[MetricKeyTypeTypeId] = metricKeyTypeVariance;
|
|
[HistogramKeyTypeTypeId] = HistogramKeyTypeTypeId;
|
|
constructor(boundaries) {
|
|
this.boundaries = boundaries;
|
|
this._hash = pipe(string(HistogramKeyTypeSymbolKey), combine(hash(this.boundaries)));
|
|
}
|
|
_hash;
|
|
[symbol]() {
|
|
return this._hash;
|
|
}
|
|
[symbol2](that) {
|
|
return isHistogramKey(that) && equals(this.boundaries, that.boundaries);
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
}
|
|
var counter = (options) => new CounterKeyType(options?.incremental ?? false, options?.bigint ?? false);
|
|
var histogram = (boundaries) => {
|
|
return new HistogramKeyType(boundaries);
|
|
};
|
|
var isCounterKey = (u) => hasProperty(u, CounterKeyTypeTypeId);
|
|
var isFrequencyKey = (u) => hasProperty(u, FrequencyKeyTypeTypeId);
|
|
var isGaugeKey = (u) => hasProperty(u, GaugeKeyTypeTypeId);
|
|
var isHistogramKey = (u) => hasProperty(u, HistogramKeyTypeTypeId);
|
|
var isSummaryKey = (u) => hasProperty(u, SummaryKeyTypeTypeId);
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/metric/key.js
|
|
var MetricKeySymbolKey = "effect/MetricKey";
|
|
var MetricKeyTypeId = /* @__PURE__ */ Symbol.for(MetricKeySymbolKey);
|
|
var metricKeyVariance = {
|
|
_Type: (_) => _
|
|
};
|
|
var arrayEquivilence = /* @__PURE__ */ getEquivalence(equals);
|
|
|
|
class MetricKeyImpl {
|
|
name;
|
|
keyType;
|
|
description;
|
|
tags;
|
|
[MetricKeyTypeId] = metricKeyVariance;
|
|
constructor(name, keyType, description, tags = []) {
|
|
this.name = name;
|
|
this.keyType = keyType;
|
|
this.description = description;
|
|
this.tags = tags;
|
|
this._hash = pipe(string(this.name + this.description), combine(hash(this.keyType)), combine(array2(this.tags)));
|
|
}
|
|
_hash;
|
|
[symbol]() {
|
|
return this._hash;
|
|
}
|
|
[symbol2](u) {
|
|
return isMetricKey(u) && this.name === u.name && equals(this.keyType, u.keyType) && equals(this.description, u.description) && arrayEquivilence(this.tags, u.tags);
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
}
|
|
var isMetricKey = (u) => hasProperty(u, MetricKeyTypeId);
|
|
var counter2 = (name, options) => new MetricKeyImpl(name, counter(options), fromNullable(options?.description));
|
|
var histogram2 = (name, boundaries, description) => new MetricKeyImpl(name, histogram(boundaries), fromNullable(description));
|
|
var taggedWithLabels = /* @__PURE__ */ dual(2, (self2, extraTags) => extraTags.length === 0 ? self2 : new MetricKeyImpl(self2.name, self2.keyType, self2.description, union(self2.tags, extraTags)));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/MutableHashMap.js
|
|
var TypeId11 = /* @__PURE__ */ Symbol.for("effect/MutableHashMap");
|
|
var MutableHashMapProto = {
|
|
[TypeId11]: TypeId11,
|
|
[Symbol.iterator]() {
|
|
return new MutableHashMapIterator(this);
|
|
},
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
},
|
|
toJSON() {
|
|
return {
|
|
_id: "MutableHashMap",
|
|
values: Array.from(this).map(toJSON)
|
|
};
|
|
},
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
},
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
|
|
class MutableHashMapIterator {
|
|
self;
|
|
referentialIterator;
|
|
bucketIterator;
|
|
constructor(self2) {
|
|
this.self = self2;
|
|
this.referentialIterator = self2.referential[Symbol.iterator]();
|
|
}
|
|
next() {
|
|
if (this.bucketIterator !== undefined) {
|
|
return this.bucketIterator.next();
|
|
}
|
|
const result = this.referentialIterator.next();
|
|
if (result.done) {
|
|
this.bucketIterator = new BucketIterator(this.self.buckets.values());
|
|
return this.next();
|
|
}
|
|
return result;
|
|
}
|
|
[Symbol.iterator]() {
|
|
return new MutableHashMapIterator(this.self);
|
|
}
|
|
}
|
|
|
|
class BucketIterator {
|
|
backing;
|
|
constructor(backing) {
|
|
this.backing = backing;
|
|
}
|
|
currentBucket;
|
|
next() {
|
|
if (this.currentBucket === undefined) {
|
|
const result = this.backing.next();
|
|
if (result.done) {
|
|
return result;
|
|
}
|
|
this.currentBucket = result.value[Symbol.iterator]();
|
|
}
|
|
const result = this.currentBucket.next();
|
|
if (result.done) {
|
|
this.currentBucket = undefined;
|
|
return this.next();
|
|
}
|
|
return result;
|
|
}
|
|
}
|
|
var empty19 = () => {
|
|
const self2 = Object.create(MutableHashMapProto);
|
|
self2.referential = new Map;
|
|
self2.buckets = new Map;
|
|
self2.bucketsSize = 0;
|
|
return self2;
|
|
};
|
|
var get11 = /* @__PURE__ */ dual(2, (self2, key) => {
|
|
if (isEqual(key) === false) {
|
|
return self2.referential.has(key) ? some2(self2.referential.get(key)) : none2();
|
|
}
|
|
const hash = key[symbol]();
|
|
const bucket = self2.buckets.get(hash);
|
|
if (bucket === undefined) {
|
|
return none2();
|
|
}
|
|
return getFromBucket(self2, bucket, key);
|
|
});
|
|
var getFromBucket = (self2, bucket, key, remove = false) => {
|
|
for (let i = 0, len = bucket.length;i < len; i++) {
|
|
if (key[symbol2](bucket[i][0])) {
|
|
const value = bucket[i][1];
|
|
if (remove) {
|
|
bucket.splice(i, 1);
|
|
self2.bucketsSize--;
|
|
}
|
|
return some2(value);
|
|
}
|
|
}
|
|
return none2();
|
|
};
|
|
var has5 = /* @__PURE__ */ dual(2, (self2, key) => isSome2(get11(self2, key)));
|
|
var set6 = /* @__PURE__ */ dual(3, (self2, key, value) => {
|
|
if (isEqual(key) === false) {
|
|
self2.referential.set(key, value);
|
|
return self2;
|
|
}
|
|
const hash = key[symbol]();
|
|
const bucket = self2.buckets.get(hash);
|
|
if (bucket === undefined) {
|
|
self2.buckets.set(hash, [[key, value]]);
|
|
self2.bucketsSize++;
|
|
return self2;
|
|
}
|
|
removeFromBucket(self2, bucket, key);
|
|
bucket.push([key, value]);
|
|
self2.bucketsSize++;
|
|
return self2;
|
|
});
|
|
var removeFromBucket = (self2, bucket, key) => {
|
|
for (let i = 0, len = bucket.length;i < len; i++) {
|
|
if (key[symbol2](bucket[i][0])) {
|
|
bucket.splice(i, 1);
|
|
self2.bucketsSize--;
|
|
return;
|
|
}
|
|
}
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/metric/state.js
|
|
var MetricStateSymbolKey = "effect/MetricState";
|
|
var MetricStateTypeId = /* @__PURE__ */ Symbol.for(MetricStateSymbolKey);
|
|
var CounterStateSymbolKey = "effect/MetricState/Counter";
|
|
var CounterStateTypeId = /* @__PURE__ */ Symbol.for(CounterStateSymbolKey);
|
|
var FrequencyStateSymbolKey = "effect/MetricState/Frequency";
|
|
var FrequencyStateTypeId = /* @__PURE__ */ Symbol.for(FrequencyStateSymbolKey);
|
|
var GaugeStateSymbolKey = "effect/MetricState/Gauge";
|
|
var GaugeStateTypeId = /* @__PURE__ */ Symbol.for(GaugeStateSymbolKey);
|
|
var HistogramStateSymbolKey = "effect/MetricState/Histogram";
|
|
var HistogramStateTypeId = /* @__PURE__ */ Symbol.for(HistogramStateSymbolKey);
|
|
var SummaryStateSymbolKey = "effect/MetricState/Summary";
|
|
var SummaryStateTypeId = /* @__PURE__ */ Symbol.for(SummaryStateSymbolKey);
|
|
var metricStateVariance = {
|
|
_A: (_) => _
|
|
};
|
|
|
|
class CounterState {
|
|
count;
|
|
[MetricStateTypeId] = metricStateVariance;
|
|
[CounterStateTypeId] = CounterStateTypeId;
|
|
constructor(count) {
|
|
this.count = count;
|
|
}
|
|
[symbol]() {
|
|
return pipe(hash(CounterStateSymbolKey), combine(hash(this.count)), cached(this));
|
|
}
|
|
[symbol2](that) {
|
|
return isCounterState(that) && this.count === that.count;
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
}
|
|
var arrayEquals = /* @__PURE__ */ getEquivalence(equals);
|
|
|
|
class FrequencyState {
|
|
occurrences;
|
|
[MetricStateTypeId] = metricStateVariance;
|
|
[FrequencyStateTypeId] = FrequencyStateTypeId;
|
|
constructor(occurrences) {
|
|
this.occurrences = occurrences;
|
|
}
|
|
_hash;
|
|
[symbol]() {
|
|
return pipe(string(FrequencyStateSymbolKey), combine(array2(fromIterable(this.occurrences.entries()))), cached(this));
|
|
}
|
|
[symbol2](that) {
|
|
return isFrequencyState(that) && arrayEquals(fromIterable(this.occurrences.entries()), fromIterable(that.occurrences.entries()));
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
}
|
|
|
|
class GaugeState {
|
|
value;
|
|
[MetricStateTypeId] = metricStateVariance;
|
|
[GaugeStateTypeId] = GaugeStateTypeId;
|
|
constructor(value) {
|
|
this.value = value;
|
|
}
|
|
[symbol]() {
|
|
return pipe(hash(GaugeStateSymbolKey), combine(hash(this.value)), cached(this));
|
|
}
|
|
[symbol2](u) {
|
|
return isGaugeState(u) && this.value === u.value;
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
}
|
|
|
|
class HistogramState {
|
|
buckets;
|
|
count;
|
|
min;
|
|
max;
|
|
sum;
|
|
[MetricStateTypeId] = metricStateVariance;
|
|
[HistogramStateTypeId] = HistogramStateTypeId;
|
|
constructor(buckets, count, min, max, sum) {
|
|
this.buckets = buckets;
|
|
this.count = count;
|
|
this.min = min;
|
|
this.max = max;
|
|
this.sum = sum;
|
|
}
|
|
[symbol]() {
|
|
return pipe(hash(HistogramStateSymbolKey), combine(hash(this.buckets)), combine(hash(this.count)), combine(hash(this.min)), combine(hash(this.max)), combine(hash(this.sum)), cached(this));
|
|
}
|
|
[symbol2](that) {
|
|
return isHistogramState(that) && equals(this.buckets, that.buckets) && this.count === that.count && this.min === that.min && this.max === that.max && this.sum === that.sum;
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
}
|
|
|
|
class SummaryState {
|
|
error;
|
|
quantiles;
|
|
count;
|
|
min;
|
|
max;
|
|
sum;
|
|
[MetricStateTypeId] = metricStateVariance;
|
|
[SummaryStateTypeId] = SummaryStateTypeId;
|
|
constructor(error, quantiles, count, min, max, sum) {
|
|
this.error = error;
|
|
this.quantiles = quantiles;
|
|
this.count = count;
|
|
this.min = min;
|
|
this.max = max;
|
|
this.sum = sum;
|
|
}
|
|
[symbol]() {
|
|
return pipe(hash(SummaryStateSymbolKey), combine(hash(this.error)), combine(hash(this.quantiles)), combine(hash(this.count)), combine(hash(this.min)), combine(hash(this.max)), combine(hash(this.sum)), cached(this));
|
|
}
|
|
[symbol2](that) {
|
|
return isSummaryState(that) && this.error === that.error && equals(this.quantiles, that.quantiles) && this.count === that.count && this.min === that.min && this.max === that.max && this.sum === that.sum;
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
}
|
|
var counter3 = (count) => new CounterState(count);
|
|
var frequency2 = (occurrences) => {
|
|
return new FrequencyState(occurrences);
|
|
};
|
|
var gauge2 = (count) => new GaugeState(count);
|
|
var histogram3 = (options) => new HistogramState(options.buckets, options.count, options.min, options.max, options.sum);
|
|
var summary2 = (options) => new SummaryState(options.error, options.quantiles, options.count, options.min, options.max, options.sum);
|
|
var isCounterState = (u) => hasProperty(u, CounterStateTypeId);
|
|
var isFrequencyState = (u) => hasProperty(u, FrequencyStateTypeId);
|
|
var isGaugeState = (u) => hasProperty(u, GaugeStateTypeId);
|
|
var isHistogramState = (u) => hasProperty(u, HistogramStateTypeId);
|
|
var isSummaryState = (u) => hasProperty(u, SummaryStateTypeId);
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/metric/hook.js
|
|
var MetricHookSymbolKey = "effect/MetricHook";
|
|
var MetricHookTypeId = /* @__PURE__ */ Symbol.for(MetricHookSymbolKey);
|
|
var metricHookVariance = {
|
|
_In: (_) => _,
|
|
_Out: (_) => _
|
|
};
|
|
var make27 = (options) => ({
|
|
[MetricHookTypeId]: metricHookVariance,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
},
|
|
...options
|
|
});
|
|
var bigint02 = /* @__PURE__ */ BigInt(0);
|
|
var counter4 = (key) => {
|
|
let sum = key.keyType.bigint ? bigint02 : 0;
|
|
const canUpdate = key.keyType.incremental ? key.keyType.bigint ? (value) => value >= bigint02 : (value) => value >= 0 : (_value) => true;
|
|
const update = (value) => {
|
|
if (canUpdate(value)) {
|
|
sum = sum + value;
|
|
}
|
|
};
|
|
return make27({
|
|
get: () => counter3(sum),
|
|
update,
|
|
modify: update
|
|
});
|
|
};
|
|
var frequency3 = (key) => {
|
|
const values = new Map;
|
|
for (const word of key.keyType.preregisteredWords) {
|
|
values.set(word, 0);
|
|
}
|
|
const update = (word) => {
|
|
const slotCount = values.get(word) ?? 0;
|
|
values.set(word, slotCount + 1);
|
|
};
|
|
return make27({
|
|
get: () => frequency2(values),
|
|
update,
|
|
modify: update
|
|
});
|
|
};
|
|
var gauge3 = (_key, startAt) => {
|
|
let value = startAt;
|
|
return make27({
|
|
get: () => gauge2(value),
|
|
update: (v) => {
|
|
value = v;
|
|
},
|
|
modify: (v) => {
|
|
value = value + v;
|
|
}
|
|
});
|
|
};
|
|
var histogram4 = (key) => {
|
|
const bounds = key.keyType.boundaries.values;
|
|
const size = bounds.length;
|
|
const values = new Uint32Array(size + 1);
|
|
const boundaries = new Float64Array(size);
|
|
let count = 0;
|
|
let sum = 0;
|
|
let min = Number.MAX_VALUE;
|
|
let max = Number.MIN_VALUE;
|
|
pipe(bounds, sort(Order), map3((n, i) => {
|
|
boundaries[i] = n;
|
|
}));
|
|
const update = (value) => {
|
|
let from = 0;
|
|
let to = size;
|
|
while (from !== to) {
|
|
const mid = Math.floor(from + (to - from) / 2);
|
|
const boundary = boundaries[mid];
|
|
if (value <= boundary) {
|
|
to = mid;
|
|
} else {
|
|
from = mid;
|
|
}
|
|
if (to === from + 1) {
|
|
if (value <= boundaries[from]) {
|
|
to = from;
|
|
} else {
|
|
from = to;
|
|
}
|
|
}
|
|
}
|
|
values[from] = values[from] + 1;
|
|
count = count + 1;
|
|
sum = sum + value;
|
|
if (value < min) {
|
|
min = value;
|
|
}
|
|
if (value > max) {
|
|
max = value;
|
|
}
|
|
};
|
|
const getBuckets = () => {
|
|
const builder = allocate(size);
|
|
let cumulated = 0;
|
|
for (let i = 0;i < size; i++) {
|
|
const boundary = boundaries[i];
|
|
const value = values[i];
|
|
cumulated = cumulated + value;
|
|
builder[i] = [boundary, cumulated];
|
|
}
|
|
return builder;
|
|
};
|
|
return make27({
|
|
get: () => histogram3({
|
|
buckets: getBuckets(),
|
|
count,
|
|
min,
|
|
max,
|
|
sum
|
|
}),
|
|
update,
|
|
modify: update
|
|
});
|
|
};
|
|
var summary3 = (key) => {
|
|
const {
|
|
error,
|
|
maxAge,
|
|
maxSize,
|
|
quantiles
|
|
} = key.keyType;
|
|
const sortedQuantiles = pipe(quantiles, sort(Order));
|
|
const values = allocate(maxSize);
|
|
let head = 0;
|
|
let count = 0;
|
|
let sum = 0;
|
|
let min = 0;
|
|
let max = 0;
|
|
const snapshot = (now) => {
|
|
const builder = [];
|
|
let i = 0;
|
|
while (i !== maxSize - 1) {
|
|
const item = values[i];
|
|
if (item != null) {
|
|
const [t, v] = item;
|
|
const age = millis(now - t);
|
|
if (greaterThanOrEqualTo(age, zero) && lessThanOrEqualTo(age, maxAge)) {
|
|
builder.push(v);
|
|
}
|
|
}
|
|
i = i + 1;
|
|
}
|
|
return calculateQuantiles(error, sortedQuantiles, sort(builder, Order));
|
|
};
|
|
const observe = (value, timestamp) => {
|
|
if (maxSize > 0) {
|
|
head = head + 1;
|
|
const target = head % maxSize;
|
|
values[target] = [timestamp, value];
|
|
}
|
|
min = count === 0 ? value : Math.min(min, value);
|
|
max = count === 0 ? value : Math.max(max, value);
|
|
count = count + 1;
|
|
sum = sum + value;
|
|
};
|
|
return make27({
|
|
get: () => summary2({
|
|
error,
|
|
quantiles: snapshot(Date.now()),
|
|
count,
|
|
min,
|
|
max,
|
|
sum
|
|
}),
|
|
update: ([value, timestamp]) => observe(value, timestamp),
|
|
modify: ([value, timestamp]) => observe(value, timestamp)
|
|
});
|
|
};
|
|
var calculateQuantiles = (error, sortedQuantiles, sortedSamples) => {
|
|
const sampleCount = sortedSamples.length;
|
|
if (!isNonEmptyReadonlyArray(sortedQuantiles)) {
|
|
return empty();
|
|
}
|
|
const head = sortedQuantiles[0];
|
|
const tail = sortedQuantiles.slice(1);
|
|
const resolvedHead = resolveQuantile(error, sampleCount, none2(), 0, head, sortedSamples);
|
|
const resolved = of(resolvedHead);
|
|
tail.forEach((quantile) => {
|
|
resolved.push(resolveQuantile(error, sampleCount, resolvedHead.value, resolvedHead.consumed, quantile, resolvedHead.rest));
|
|
});
|
|
return map3(resolved, (rq) => [rq.quantile, rq.value]);
|
|
};
|
|
var resolveQuantile = (error, sampleCount, current, consumed, quantile, rest) => {
|
|
let error_1 = error;
|
|
let sampleCount_1 = sampleCount;
|
|
let current_1 = current;
|
|
let consumed_1 = consumed;
|
|
let quantile_1 = quantile;
|
|
let rest_1 = rest;
|
|
let error_2 = error;
|
|
let sampleCount_2 = sampleCount;
|
|
let current_2 = current;
|
|
let consumed_2 = consumed;
|
|
let quantile_2 = quantile;
|
|
let rest_2 = rest;
|
|
while (true) {
|
|
if (!isNonEmptyReadonlyArray(rest_1)) {
|
|
return {
|
|
quantile: quantile_1,
|
|
value: none2(),
|
|
consumed: consumed_1,
|
|
rest: []
|
|
};
|
|
}
|
|
if (quantile_1 === 1) {
|
|
return {
|
|
quantile: quantile_1,
|
|
value: some2(lastNonEmpty(rest_1)),
|
|
consumed: consumed_1 + rest_1.length,
|
|
rest: []
|
|
};
|
|
}
|
|
const headValue = headNonEmpty(rest_1);
|
|
const sameHead = span(rest_1, (n) => n === headValue);
|
|
const desired = quantile_1 * sampleCount_1;
|
|
const allowedError = error_1 / 2 * desired;
|
|
const candConsumed = consumed_1 + sameHead[0].length;
|
|
const candError = Math.abs(candConsumed - desired);
|
|
if (candConsumed < desired - allowedError) {
|
|
error_2 = error_1;
|
|
sampleCount_2 = sampleCount_1;
|
|
current_2 = head(rest_1);
|
|
consumed_2 = candConsumed;
|
|
quantile_2 = quantile_1;
|
|
rest_2 = sameHead[1];
|
|
error_1 = error_2;
|
|
sampleCount_1 = sampleCount_2;
|
|
current_1 = current_2;
|
|
consumed_1 = consumed_2;
|
|
quantile_1 = quantile_2;
|
|
rest_1 = rest_2;
|
|
continue;
|
|
}
|
|
if (candConsumed > desired + allowedError) {
|
|
const valueToReturn = isNone2(current_1) ? some2(headValue) : current_1;
|
|
return {
|
|
quantile: quantile_1,
|
|
value: valueToReturn,
|
|
consumed: consumed_1,
|
|
rest: rest_1
|
|
};
|
|
}
|
|
switch (current_1._tag) {
|
|
case "None": {
|
|
error_2 = error_1;
|
|
sampleCount_2 = sampleCount_1;
|
|
current_2 = head(rest_1);
|
|
consumed_2 = candConsumed;
|
|
quantile_2 = quantile_1;
|
|
rest_2 = sameHead[1];
|
|
error_1 = error_2;
|
|
sampleCount_1 = sampleCount_2;
|
|
current_1 = current_2;
|
|
consumed_1 = consumed_2;
|
|
quantile_1 = quantile_2;
|
|
rest_1 = rest_2;
|
|
continue;
|
|
}
|
|
case "Some": {
|
|
const prevError = Math.abs(desired - current_1.value);
|
|
if (candError < prevError) {
|
|
error_2 = error_1;
|
|
sampleCount_2 = sampleCount_1;
|
|
current_2 = head(rest_1);
|
|
consumed_2 = candConsumed;
|
|
quantile_2 = quantile_1;
|
|
rest_2 = sameHead[1];
|
|
error_1 = error_2;
|
|
sampleCount_1 = sampleCount_2;
|
|
current_1 = current_2;
|
|
consumed_1 = consumed_2;
|
|
quantile_1 = quantile_2;
|
|
rest_1 = rest_2;
|
|
continue;
|
|
}
|
|
return {
|
|
quantile: quantile_1,
|
|
value: some2(current_1.value),
|
|
consumed: consumed_1,
|
|
rest: rest_1
|
|
};
|
|
}
|
|
}
|
|
}
|
|
throw new Error("BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/effect/issues");
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/metric/pair.js
|
|
var MetricPairSymbolKey = "effect/MetricPair";
|
|
var MetricPairTypeId = /* @__PURE__ */ Symbol.for(MetricPairSymbolKey);
|
|
var metricPairVariance = {
|
|
_Type: (_) => _
|
|
};
|
|
var unsafeMake6 = (metricKey, metricState) => {
|
|
return {
|
|
[MetricPairTypeId]: metricPairVariance,
|
|
metricKey,
|
|
metricState,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/metric/registry.js
|
|
var MetricRegistrySymbolKey = "effect/MetricRegistry";
|
|
var MetricRegistryTypeId = /* @__PURE__ */ Symbol.for(MetricRegistrySymbolKey);
|
|
|
|
class MetricRegistryImpl {
|
|
[MetricRegistryTypeId] = MetricRegistryTypeId;
|
|
map = /* @__PURE__ */ empty19();
|
|
snapshot() {
|
|
const result = [];
|
|
for (const [key, hook] of this.map) {
|
|
result.push(unsafeMake6(key, hook.get()));
|
|
}
|
|
return result;
|
|
}
|
|
get(key) {
|
|
const hook = pipe(this.map, get11(key), getOrUndefined);
|
|
if (hook == null) {
|
|
if (isCounterKey(key.keyType)) {
|
|
return this.getCounter(key);
|
|
}
|
|
if (isGaugeKey(key.keyType)) {
|
|
return this.getGauge(key);
|
|
}
|
|
if (isFrequencyKey(key.keyType)) {
|
|
return this.getFrequency(key);
|
|
}
|
|
if (isHistogramKey(key.keyType)) {
|
|
return this.getHistogram(key);
|
|
}
|
|
if (isSummaryKey(key.keyType)) {
|
|
return this.getSummary(key);
|
|
}
|
|
throw new Error("BUG: MetricRegistry.get - unknown MetricKeyType - please report an issue at https://github.com/Effect-TS/effect/issues");
|
|
} else {
|
|
return hook;
|
|
}
|
|
}
|
|
getCounter(key) {
|
|
let value = pipe(this.map, get11(key), getOrUndefined);
|
|
if (value == null) {
|
|
const counter = counter4(key);
|
|
if (!pipe(this.map, has5(key))) {
|
|
pipe(this.map, set6(key, counter));
|
|
}
|
|
value = counter;
|
|
}
|
|
return value;
|
|
}
|
|
getFrequency(key) {
|
|
let value = pipe(this.map, get11(key), getOrUndefined);
|
|
if (value == null) {
|
|
const frequency = frequency3(key);
|
|
if (!pipe(this.map, has5(key))) {
|
|
pipe(this.map, set6(key, frequency));
|
|
}
|
|
value = frequency;
|
|
}
|
|
return value;
|
|
}
|
|
getGauge(key) {
|
|
let value = pipe(this.map, get11(key), getOrUndefined);
|
|
if (value == null) {
|
|
const gauge = gauge3(key, key.keyType.bigint ? BigInt(0) : 0);
|
|
if (!pipe(this.map, has5(key))) {
|
|
pipe(this.map, set6(key, gauge));
|
|
}
|
|
value = gauge;
|
|
}
|
|
return value;
|
|
}
|
|
getHistogram(key) {
|
|
let value = pipe(this.map, get11(key), getOrUndefined);
|
|
if (value == null) {
|
|
const histogram = histogram4(key);
|
|
if (!pipe(this.map, has5(key))) {
|
|
pipe(this.map, set6(key, histogram));
|
|
}
|
|
value = histogram;
|
|
}
|
|
return value;
|
|
}
|
|
getSummary(key) {
|
|
let value = pipe(this.map, get11(key), getOrUndefined);
|
|
if (value == null) {
|
|
const summary = summary3(key);
|
|
if (!pipe(this.map, has5(key))) {
|
|
pipe(this.map, set6(key, summary));
|
|
}
|
|
value = summary;
|
|
}
|
|
return value;
|
|
}
|
|
}
|
|
var make28 = () => {
|
|
return new MetricRegistryImpl;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/metric.js
|
|
var MetricSymbolKey = "effect/Metric";
|
|
var MetricTypeId = /* @__PURE__ */ Symbol.for(MetricSymbolKey);
|
|
var metricVariance = {
|
|
_Type: (_) => _,
|
|
_In: (_) => _,
|
|
_Out: (_) => _
|
|
};
|
|
var globalMetricRegistry = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/Metric/globalMetricRegistry"), () => make28());
|
|
var make29 = function(keyType, unsafeUpdate, unsafeValue, unsafeModify) {
|
|
const metric = Object.assign((effect) => tap(effect, (a) => update4(metric, a)), {
|
|
[MetricTypeId]: metricVariance,
|
|
keyType,
|
|
unsafeUpdate,
|
|
unsafeValue,
|
|
unsafeModify,
|
|
register() {
|
|
this.unsafeValue([]);
|
|
return this;
|
|
},
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
});
|
|
return metric;
|
|
};
|
|
var counter5 = (name, options) => fromMetricKey(counter2(name, options));
|
|
var fromMetricKey = (key) => {
|
|
let untaggedHook;
|
|
const hookCache = new WeakMap;
|
|
const hook = (extraTags) => {
|
|
if (extraTags.length === 0) {
|
|
if (untaggedHook !== undefined) {
|
|
return untaggedHook;
|
|
}
|
|
untaggedHook = globalMetricRegistry.get(key);
|
|
return untaggedHook;
|
|
}
|
|
let hook = hookCache.get(extraTags);
|
|
if (hook !== undefined) {
|
|
return hook;
|
|
}
|
|
hook = globalMetricRegistry.get(taggedWithLabels(key, extraTags));
|
|
hookCache.set(extraTags, hook);
|
|
return hook;
|
|
};
|
|
return make29(key.keyType, (input, extraTags) => hook(extraTags).update(input), (extraTags) => hook(extraTags).get(), (input, extraTags) => hook(extraTags).modify(input));
|
|
};
|
|
var histogram5 = (name, boundaries, description) => fromMetricKey(histogram2(name, boundaries, description));
|
|
var tagged2 = /* @__PURE__ */ dual(3, (self2, key, value) => taggedWithLabels2(self2, [make26(key, value)]));
|
|
var taggedWithLabels2 = /* @__PURE__ */ dual(2, (self2, extraTags) => {
|
|
return make29(self2.keyType, (input, extraTags1) => self2.unsafeUpdate(input, union(extraTags, extraTags1)), (extraTags1) => self2.unsafeValue(union(extraTags, extraTags1)), (input, extraTags1) => self2.unsafeModify(input, union(extraTags, extraTags1)));
|
|
});
|
|
var update4 = /* @__PURE__ */ dual(2, (self2, input) => fiberRefGetWith(currentMetricLabels, (tags) => sync(() => self2.unsafeUpdate(input, tags))));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/request.js
|
|
var RequestSymbolKey = "effect/Request";
|
|
var RequestTypeId = /* @__PURE__ */ Symbol.for(RequestSymbolKey);
|
|
var requestVariance = {
|
|
_E: (_) => _,
|
|
_A: (_) => _
|
|
};
|
|
var RequestPrototype = {
|
|
...StructuralPrototype,
|
|
[RequestTypeId]: requestVariance
|
|
};
|
|
var complete = /* @__PURE__ */ dual(2, (self2, result) => fiberRefGetWith(currentRequestMap, (map) => sync(() => {
|
|
if (map.has(self2)) {
|
|
const entry = map.get(self2);
|
|
if (!entry.state.completed) {
|
|
entry.state.completed = true;
|
|
deferredUnsafeDone(entry.result, result);
|
|
}
|
|
}
|
|
})));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/supervisor.js
|
|
var SupervisorSymbolKey = "effect/Supervisor";
|
|
var SupervisorTypeId = /* @__PURE__ */ Symbol.for(SupervisorSymbolKey);
|
|
var supervisorVariance = {
|
|
_T: (_) => _
|
|
};
|
|
|
|
class ProxySupervisor {
|
|
underlying;
|
|
value0;
|
|
[SupervisorTypeId] = supervisorVariance;
|
|
constructor(underlying, value0) {
|
|
this.underlying = underlying;
|
|
this.value0 = value0;
|
|
}
|
|
get value() {
|
|
return this.value0;
|
|
}
|
|
onStart(context, effect, parent, fiber) {
|
|
this.underlying.onStart(context, effect, parent, fiber);
|
|
}
|
|
onEnd(value, fiber) {
|
|
this.underlying.onEnd(value, fiber);
|
|
}
|
|
onEffect(fiber, effect) {
|
|
this.underlying.onEffect(fiber, effect);
|
|
}
|
|
onSuspend(fiber) {
|
|
this.underlying.onSuspend(fiber);
|
|
}
|
|
onResume(fiber) {
|
|
this.underlying.onResume(fiber);
|
|
}
|
|
map(f) {
|
|
return new ProxySupervisor(this, pipe(this.value, map10(f)));
|
|
}
|
|
zip(right) {
|
|
return new Zip(this, right);
|
|
}
|
|
}
|
|
|
|
class Zip {
|
|
left;
|
|
right;
|
|
_tag = "Zip";
|
|
[SupervisorTypeId] = supervisorVariance;
|
|
constructor(left, right) {
|
|
this.left = left;
|
|
this.right = right;
|
|
}
|
|
get value() {
|
|
return zip2(this.left.value, this.right.value);
|
|
}
|
|
onStart(context, effect, parent, fiber) {
|
|
this.left.onStart(context, effect, parent, fiber);
|
|
this.right.onStart(context, effect, parent, fiber);
|
|
}
|
|
onEnd(value, fiber) {
|
|
this.left.onEnd(value, fiber);
|
|
this.right.onEnd(value, fiber);
|
|
}
|
|
onEffect(fiber, effect) {
|
|
this.left.onEffect(fiber, effect);
|
|
this.right.onEffect(fiber, effect);
|
|
}
|
|
onSuspend(fiber) {
|
|
this.left.onSuspend(fiber);
|
|
this.right.onSuspend(fiber);
|
|
}
|
|
onResume(fiber) {
|
|
this.left.onResume(fiber);
|
|
this.right.onResume(fiber);
|
|
}
|
|
map(f) {
|
|
return new ProxySupervisor(this, pipe(this.value, map10(f)));
|
|
}
|
|
zip(right) {
|
|
return new Zip(this, right);
|
|
}
|
|
}
|
|
var isZip = (self2) => hasProperty(self2, SupervisorTypeId) && isTagged(self2, "Zip");
|
|
class Const {
|
|
effect;
|
|
[SupervisorTypeId] = supervisorVariance;
|
|
constructor(effect) {
|
|
this.effect = effect;
|
|
}
|
|
get value() {
|
|
return this.effect;
|
|
}
|
|
onStart(_context, _effect, _parent, _fiber) {}
|
|
onEnd(_value, _fiber) {}
|
|
onEffect(_fiber, _effect) {}
|
|
onSuspend(_fiber) {}
|
|
onResume(_fiber) {}
|
|
map(f) {
|
|
return new ProxySupervisor(this, pipe(this.value, map10(f)));
|
|
}
|
|
zip(right) {
|
|
return new Zip(this, right);
|
|
}
|
|
onRun(execution, _fiber) {
|
|
return execution();
|
|
}
|
|
}
|
|
var fromEffect = (effect) => {
|
|
return new Const(effect);
|
|
};
|
|
var none7 = /* @__PURE__ */ globalValue("effect/Supervisor/none", () => fromEffect(void_));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Differ.js
|
|
var make30 = make14;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/supervisor/patch.js
|
|
var OP_EMPTY3 = "Empty";
|
|
var OP_ADD_SUPERVISOR = "AddSupervisor";
|
|
var OP_REMOVE_SUPERVISOR = "RemoveSupervisor";
|
|
var OP_AND_THEN2 = "AndThen";
|
|
var empty20 = {
|
|
_tag: OP_EMPTY3
|
|
};
|
|
var combine8 = (self2, that) => {
|
|
return {
|
|
_tag: OP_AND_THEN2,
|
|
first: self2,
|
|
second: that
|
|
};
|
|
};
|
|
var patch8 = (self2, supervisor) => {
|
|
return patchLoop(supervisor, of2(self2));
|
|
};
|
|
var patchLoop = (_supervisor, _patches) => {
|
|
let supervisor = _supervisor;
|
|
let patches = _patches;
|
|
while (isNonEmpty(patches)) {
|
|
const head = headNonEmpty2(patches);
|
|
switch (head._tag) {
|
|
case OP_EMPTY3: {
|
|
patches = tailNonEmpty2(patches);
|
|
break;
|
|
}
|
|
case OP_ADD_SUPERVISOR: {
|
|
supervisor = supervisor.zip(head.supervisor);
|
|
patches = tailNonEmpty2(patches);
|
|
break;
|
|
}
|
|
case OP_REMOVE_SUPERVISOR: {
|
|
supervisor = removeSupervisor(supervisor, head.supervisor);
|
|
patches = tailNonEmpty2(patches);
|
|
break;
|
|
}
|
|
case OP_AND_THEN2: {
|
|
patches = prepend2(head.first)(prepend2(head.second)(tailNonEmpty2(patches)));
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
return supervisor;
|
|
};
|
|
var removeSupervisor = (self2, that) => {
|
|
if (equals(self2, that)) {
|
|
return none7;
|
|
} else {
|
|
if (isZip(self2)) {
|
|
return removeSupervisor(self2.left, that).zip(removeSupervisor(self2.right, that));
|
|
} else {
|
|
return self2;
|
|
}
|
|
}
|
|
};
|
|
var toSet2 = (self2) => {
|
|
if (equals(self2, none7)) {
|
|
return empty7();
|
|
} else {
|
|
if (isZip(self2)) {
|
|
return pipe(toSet2(self2.left), union3(toSet2(self2.right)));
|
|
} else {
|
|
return make10(self2);
|
|
}
|
|
}
|
|
};
|
|
var diff7 = (oldValue, newValue) => {
|
|
if (equals(oldValue, newValue)) {
|
|
return empty20;
|
|
}
|
|
const oldSupervisors = toSet2(oldValue);
|
|
const newSupervisors = toSet2(newValue);
|
|
const added = pipe(newSupervisors, difference3(oldSupervisors), reduce5(empty20, (patch, supervisor) => combine8(patch, {
|
|
_tag: OP_ADD_SUPERVISOR,
|
|
supervisor
|
|
})));
|
|
const removed = pipe(oldSupervisors, difference3(newSupervisors), reduce5(empty20, (patch, supervisor) => combine8(patch, {
|
|
_tag: OP_REMOVE_SUPERVISOR,
|
|
supervisor
|
|
})));
|
|
return combine8(added, removed);
|
|
};
|
|
var differ2 = /* @__PURE__ */ make30({
|
|
empty: empty20,
|
|
patch: patch8,
|
|
combine: combine8,
|
|
diff: diff7
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/fiberRuntime.js
|
|
var fiberStarted = /* @__PURE__ */ counter5("effect_fiber_started", {
|
|
incremental: true
|
|
});
|
|
var fiberActive = /* @__PURE__ */ counter5("effect_fiber_active");
|
|
var fiberSuccesses = /* @__PURE__ */ counter5("effect_fiber_successes", {
|
|
incremental: true
|
|
});
|
|
var fiberFailures = /* @__PURE__ */ counter5("effect_fiber_failures", {
|
|
incremental: true
|
|
});
|
|
var fiberLifetimes = /* @__PURE__ */ tagged2(/* @__PURE__ */ histogram5("effect_fiber_lifetimes", /* @__PURE__ */ exponential({
|
|
start: 0.5,
|
|
factor: 2,
|
|
count: 35
|
|
})), "time_unit", "milliseconds");
|
|
var EvaluationSignalContinue = "Continue";
|
|
var EvaluationSignalDone = "Done";
|
|
var EvaluationSignalYieldNow = "Yield";
|
|
var runtimeFiberVariance = {
|
|
_E: (_) => _,
|
|
_A: (_) => _
|
|
};
|
|
var absurd = (_) => {
|
|
throw new Error(`BUG: FiberRuntime - ${toStringUnknown(_)} - please report an issue at https://github.com/Effect-TS/effect/issues`);
|
|
};
|
|
var YieldedOp = /* @__PURE__ */ Symbol.for("effect/internal/fiberRuntime/YieldedOp");
|
|
var yieldedOpChannel = /* @__PURE__ */ globalValue("effect/internal/fiberRuntime/yieldedOpChannel", () => ({
|
|
currentOp: null
|
|
}));
|
|
var contOpSuccess = {
|
|
[OP_ON_SUCCESS]: (_, cont, value) => {
|
|
return internalCall(() => cont.effect_instruction_i1(value));
|
|
},
|
|
["OnStep"]: (_, _cont, value) => {
|
|
return exitSucceed(exitSucceed(value));
|
|
},
|
|
[OP_ON_SUCCESS_AND_FAILURE]: (_, cont, value) => {
|
|
return internalCall(() => cont.effect_instruction_i2(value));
|
|
},
|
|
[OP_REVERT_FLAGS]: (self2, cont, value) => {
|
|
self2.patchRuntimeFlags(self2.currentRuntimeFlags, cont.patch);
|
|
if (interruptible(self2.currentRuntimeFlags) && self2.isInterrupted()) {
|
|
return exitFailCause(self2.getInterruptedCause());
|
|
} else {
|
|
return exitSucceed(value);
|
|
}
|
|
},
|
|
[OP_WHILE]: (self2, cont, value) => {
|
|
internalCall(() => cont.effect_instruction_i2(value));
|
|
if (internalCall(() => cont.effect_instruction_i0())) {
|
|
self2.pushStack(cont);
|
|
return internalCall(() => cont.effect_instruction_i1());
|
|
} else {
|
|
return void_;
|
|
}
|
|
},
|
|
[OP_ITERATOR]: (self2, cont, value) => {
|
|
while (true) {
|
|
const state = internalCall(() => cont.effect_instruction_i0.next(value));
|
|
if (state.done) {
|
|
return exitSucceed(state.value);
|
|
}
|
|
const primitive = yieldWrapGet(state.value);
|
|
if (!exitIsExit(primitive)) {
|
|
self2.pushStack(cont);
|
|
return primitive;
|
|
} else if (primitive._tag === "Failure") {
|
|
return primitive;
|
|
}
|
|
value = primitive.value;
|
|
}
|
|
}
|
|
};
|
|
var drainQueueWhileRunningTable = {
|
|
[OP_INTERRUPT_SIGNAL]: (self2, runtimeFlags, cur, message) => {
|
|
self2.processNewInterruptSignal(message.cause);
|
|
return interruptible(runtimeFlags) ? exitFailCause(message.cause) : cur;
|
|
},
|
|
[OP_RESUME]: (_self, _runtimeFlags, _cur, _message) => {
|
|
throw new Error("It is illegal to have multiple concurrent run loops in a single fiber");
|
|
},
|
|
[OP_STATEFUL]: (self2, runtimeFlags, cur, message) => {
|
|
message.onFiber(self2, running2(runtimeFlags));
|
|
return cur;
|
|
},
|
|
[OP_YIELD_NOW]: (_self, _runtimeFlags, cur, _message) => {
|
|
return flatMap7(yieldNow(), () => cur);
|
|
}
|
|
};
|
|
var runBlockedRequests = (self2) => forEachSequentialDiscard(flatten2(self2), (requestsByRequestResolver) => forEachConcurrentDiscard(sequentialCollectionToChunk(requestsByRequestResolver), ([dataSource, sequential]) => {
|
|
const map = new Map;
|
|
const arr = [];
|
|
for (const block of sequential) {
|
|
arr.push(toReadonlyArray(block));
|
|
for (const entry of block) {
|
|
map.set(entry.request, entry);
|
|
}
|
|
}
|
|
const flat = arr.flat();
|
|
return fiberRefLocally(invokeWithInterrupt(dataSource.runAll(arr), flat, () => flat.forEach((entry) => {
|
|
entry.listeners.interrupted = true;
|
|
})), currentRequestMap, map);
|
|
}, false, false));
|
|
var _version = /* @__PURE__ */ getCurrentVersion();
|
|
|
|
class FiberRuntime extends Class {
|
|
[FiberTypeId] = fiberVariance2;
|
|
[RuntimeFiberTypeId] = runtimeFiberVariance;
|
|
_fiberRefs;
|
|
_fiberId;
|
|
_queue = /* @__PURE__ */ new Array;
|
|
_children = null;
|
|
_observers = /* @__PURE__ */ new Array;
|
|
_running = false;
|
|
_stack = [];
|
|
_asyncInterruptor = null;
|
|
_asyncBlockingOn = null;
|
|
_exitValue = null;
|
|
_steps = [];
|
|
_isYielding = false;
|
|
currentRuntimeFlags;
|
|
currentOpCount = 0;
|
|
currentSupervisor;
|
|
currentScheduler;
|
|
currentTracer;
|
|
currentSpan;
|
|
currentContext;
|
|
currentDefaultServices;
|
|
constructor(fiberId, fiberRefs0, runtimeFlags0) {
|
|
super();
|
|
this.currentRuntimeFlags = runtimeFlags0;
|
|
this._fiberId = fiberId;
|
|
this._fiberRefs = fiberRefs0;
|
|
if (runtimeMetrics(runtimeFlags0)) {
|
|
const tags = this.getFiberRef(currentMetricLabels);
|
|
fiberStarted.unsafeUpdate(1, tags);
|
|
fiberActive.unsafeUpdate(1, tags);
|
|
}
|
|
this.refreshRefCache();
|
|
}
|
|
commit() {
|
|
return join2(this);
|
|
}
|
|
id() {
|
|
return this._fiberId;
|
|
}
|
|
resume(effect) {
|
|
this.tell(resume(effect));
|
|
}
|
|
get status() {
|
|
return this.ask((_, status) => status);
|
|
}
|
|
get runtimeFlags() {
|
|
return this.ask((state, status) => {
|
|
if (isDone3(status)) {
|
|
return state.currentRuntimeFlags;
|
|
}
|
|
return status.runtimeFlags;
|
|
});
|
|
}
|
|
scope() {
|
|
return unsafeMake5(this);
|
|
}
|
|
get children() {
|
|
return this.ask((fiber) => Array.from(fiber.getChildren()));
|
|
}
|
|
getChildren() {
|
|
if (this._children === null) {
|
|
this._children = new Set;
|
|
}
|
|
return this._children;
|
|
}
|
|
getInterruptedCause() {
|
|
return this.getFiberRef(currentInterruptedCause);
|
|
}
|
|
fiberRefs() {
|
|
return this.ask((fiber) => fiber.getFiberRefs());
|
|
}
|
|
ask(f) {
|
|
return suspend(() => {
|
|
const deferred = deferredUnsafeMake(this._fiberId);
|
|
this.tell(stateful((fiber, status) => {
|
|
deferredUnsafeDone(deferred, sync(() => f(fiber, status)));
|
|
}));
|
|
return deferredAwait(deferred);
|
|
});
|
|
}
|
|
tell(message) {
|
|
this._queue.push(message);
|
|
if (!this._running) {
|
|
this._running = true;
|
|
this.drainQueueLaterOnExecutor();
|
|
}
|
|
}
|
|
get await() {
|
|
return async_((resume) => {
|
|
const cb = (exit) => resume(succeed(exit));
|
|
if (this._exitValue !== null) {
|
|
cb(this._exitValue);
|
|
return;
|
|
}
|
|
this.tell(stateful((fiber, _) => {
|
|
if (fiber._exitValue !== null) {
|
|
cb(this._exitValue);
|
|
} else {
|
|
fiber.addObserver(cb);
|
|
}
|
|
}));
|
|
return sync(() => this.tell(stateful((fiber, _) => {
|
|
fiber.removeObserver(cb);
|
|
})));
|
|
}, this.id());
|
|
}
|
|
get inheritAll() {
|
|
return withFiberRuntime((parentFiber, parentStatus) => {
|
|
const parentFiberId = parentFiber.id();
|
|
const parentFiberRefs = parentFiber.getFiberRefs();
|
|
const parentRuntimeFlags = parentStatus.runtimeFlags;
|
|
const childFiberRefs = this.getFiberRefs();
|
|
const updatedFiberRefs = joinAs(parentFiberRefs, parentFiberId, childFiberRefs);
|
|
parentFiber.setFiberRefs(updatedFiberRefs);
|
|
const updatedRuntimeFlags = parentFiber.getFiberRef(currentRuntimeFlags);
|
|
const patch = pipe(diff4(parentRuntimeFlags, updatedRuntimeFlags), exclude2(Interruption), exclude2(WindDown));
|
|
return updateRuntimeFlags(patch);
|
|
});
|
|
}
|
|
get poll() {
|
|
return sync(() => fromNullable(this._exitValue));
|
|
}
|
|
unsafePoll() {
|
|
return this._exitValue;
|
|
}
|
|
interruptAsFork(fiberId) {
|
|
return sync(() => this.tell(interruptSignal(interrupt(fiberId))));
|
|
}
|
|
unsafeInterruptAsFork(fiberId) {
|
|
this.tell(interruptSignal(interrupt(fiberId)));
|
|
}
|
|
addObserver(observer) {
|
|
if (this._exitValue !== null) {
|
|
observer(this._exitValue);
|
|
} else {
|
|
this._observers.push(observer);
|
|
}
|
|
}
|
|
removeObserver(observer) {
|
|
this._observers = this._observers.filter((o) => o !== observer);
|
|
}
|
|
getFiberRefs() {
|
|
this.setFiberRef(currentRuntimeFlags, this.currentRuntimeFlags);
|
|
return this._fiberRefs;
|
|
}
|
|
unsafeDeleteFiberRef(fiberRef) {
|
|
this._fiberRefs = delete_(this._fiberRefs, fiberRef);
|
|
}
|
|
getFiberRef(fiberRef) {
|
|
if (this._fiberRefs.locals.has(fiberRef)) {
|
|
return this._fiberRefs.locals.get(fiberRef)[0][1];
|
|
}
|
|
return fiberRef.initial;
|
|
}
|
|
setFiberRef(fiberRef, value) {
|
|
this._fiberRefs = updateAs(this._fiberRefs, {
|
|
fiberId: this._fiberId,
|
|
fiberRef,
|
|
value
|
|
});
|
|
this.refreshRefCache();
|
|
}
|
|
refreshRefCache() {
|
|
this.currentDefaultServices = this.getFiberRef(currentServices);
|
|
this.currentTracer = this.currentDefaultServices.unsafeMap.get(tracerTag.key);
|
|
this.currentSupervisor = this.getFiberRef(currentSupervisor);
|
|
this.currentScheduler = this.getFiberRef(currentScheduler);
|
|
this.currentContext = this.getFiberRef(currentContext);
|
|
this.currentSpan = this.currentContext.unsafeMap.get(spanTag.key);
|
|
}
|
|
setFiberRefs(fiberRefs) {
|
|
this._fiberRefs = fiberRefs;
|
|
this.refreshRefCache();
|
|
}
|
|
addChild(child) {
|
|
this.getChildren().add(child);
|
|
}
|
|
removeChild(child) {
|
|
this.getChildren().delete(child);
|
|
}
|
|
transferChildren(scope) {
|
|
const children = this._children;
|
|
this._children = null;
|
|
if (children !== null && children.size > 0) {
|
|
for (const child of children) {
|
|
if (child._exitValue === null) {
|
|
scope.add(this.currentRuntimeFlags, child);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
drainQueueOnCurrentThread() {
|
|
let recurse = true;
|
|
while (recurse) {
|
|
let evaluationSignal = EvaluationSignalContinue;
|
|
const prev = globalThis[currentFiberURI];
|
|
globalThis[currentFiberURI] = this;
|
|
try {
|
|
while (evaluationSignal === EvaluationSignalContinue) {
|
|
evaluationSignal = this._queue.length === 0 ? EvaluationSignalDone : this.evaluateMessageWhileSuspended(this._queue.splice(0, 1)[0]);
|
|
}
|
|
} finally {
|
|
this._running = false;
|
|
globalThis[currentFiberURI] = prev;
|
|
}
|
|
if (this._queue.length > 0 && !this._running) {
|
|
this._running = true;
|
|
if (evaluationSignal === EvaluationSignalYieldNow) {
|
|
this.drainQueueLaterOnExecutor();
|
|
recurse = false;
|
|
} else {
|
|
recurse = true;
|
|
}
|
|
} else {
|
|
recurse = false;
|
|
}
|
|
}
|
|
}
|
|
drainQueueLaterOnExecutor() {
|
|
this.currentScheduler.scheduleTask(this.run, this.getFiberRef(currentSchedulingPriority), this);
|
|
}
|
|
drainQueueWhileRunning(runtimeFlags, cur0) {
|
|
let cur = cur0;
|
|
while (this._queue.length > 0) {
|
|
const message = this._queue.splice(0, 1)[0];
|
|
cur = drainQueueWhileRunningTable[message._tag](this, runtimeFlags, cur, message);
|
|
}
|
|
return cur;
|
|
}
|
|
isInterrupted() {
|
|
return !isEmpty5(this.getFiberRef(currentInterruptedCause));
|
|
}
|
|
addInterruptedCause(cause) {
|
|
const oldSC = this.getFiberRef(currentInterruptedCause);
|
|
this.setFiberRef(currentInterruptedCause, sequential(oldSC, cause));
|
|
}
|
|
processNewInterruptSignal(cause) {
|
|
this.addInterruptedCause(cause);
|
|
this.sendInterruptSignalToAllChildren();
|
|
}
|
|
sendInterruptSignalToAllChildren() {
|
|
if (this._children === null || this._children.size === 0) {
|
|
return false;
|
|
}
|
|
let told = false;
|
|
for (const child of this._children) {
|
|
child.tell(interruptSignal(interrupt(this.id())));
|
|
told = true;
|
|
}
|
|
return told;
|
|
}
|
|
interruptAllChildren() {
|
|
if (this.sendInterruptSignalToAllChildren()) {
|
|
const it = this._children.values();
|
|
this._children = null;
|
|
let isDone = false;
|
|
const body = () => {
|
|
const next = it.next();
|
|
if (!next.done) {
|
|
return asVoid(next.value.await);
|
|
} else {
|
|
return sync(() => {
|
|
isDone = true;
|
|
});
|
|
}
|
|
};
|
|
return whileLoop({
|
|
while: () => !isDone,
|
|
body,
|
|
step: () => {}
|
|
});
|
|
}
|
|
return null;
|
|
}
|
|
reportExitValue(exit) {
|
|
if (runtimeMetrics(this.currentRuntimeFlags)) {
|
|
const tags = this.getFiberRef(currentMetricLabels);
|
|
const startTimeMillis = this.id().startTimeMillis;
|
|
const endTimeMillis = Date.now();
|
|
fiberLifetimes.unsafeUpdate(endTimeMillis - startTimeMillis, tags);
|
|
fiberActive.unsafeUpdate(-1, tags);
|
|
switch (exit._tag) {
|
|
case OP_SUCCESS: {
|
|
fiberSuccesses.unsafeUpdate(1, tags);
|
|
break;
|
|
}
|
|
case OP_FAILURE: {
|
|
fiberFailures.unsafeUpdate(1, tags);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (exit._tag === "Failure") {
|
|
const level = this.getFiberRef(currentUnhandledErrorLogLevel);
|
|
if (!isInterruptedOnly(exit.cause) && level._tag === "Some") {
|
|
this.log("Fiber terminated with an unhandled error", exit.cause, level);
|
|
}
|
|
}
|
|
}
|
|
setExitValue(exit) {
|
|
this._exitValue = exit;
|
|
this.reportExitValue(exit);
|
|
for (let i = this._observers.length - 1;i >= 0; i--) {
|
|
this._observers[i](exit);
|
|
}
|
|
this._observers = [];
|
|
}
|
|
getLoggers() {
|
|
return this.getFiberRef(currentLoggers);
|
|
}
|
|
log(message, cause, overrideLogLevel) {
|
|
const logLevel = isSome2(overrideLogLevel) ? overrideLogLevel.value : this.getFiberRef(currentLogLevel);
|
|
const minimumLogLevel = this.getFiberRef(currentMinimumLogLevel);
|
|
if (greaterThan2(minimumLogLevel, logLevel)) {
|
|
return;
|
|
}
|
|
const spans = this.getFiberRef(currentLogSpan);
|
|
const annotations = this.getFiberRef(currentLogAnnotations);
|
|
const loggers = this.getLoggers();
|
|
const contextMap = this.getFiberRefs();
|
|
if (size3(loggers) > 0) {
|
|
const clockService = get3(this.getFiberRef(currentServices), clockTag);
|
|
const date = new Date(clockService.unsafeCurrentTimeMillis());
|
|
withRedactableContext(contextMap, () => {
|
|
for (const logger of loggers) {
|
|
logger.log({
|
|
fiberId: this.id(),
|
|
logLevel,
|
|
message,
|
|
cause,
|
|
context: contextMap,
|
|
spans,
|
|
annotations,
|
|
date
|
|
});
|
|
}
|
|
});
|
|
}
|
|
}
|
|
evaluateMessageWhileSuspended(message) {
|
|
switch (message._tag) {
|
|
case OP_YIELD_NOW: {
|
|
return EvaluationSignalYieldNow;
|
|
}
|
|
case OP_INTERRUPT_SIGNAL: {
|
|
this.processNewInterruptSignal(message.cause);
|
|
if (this._asyncInterruptor !== null) {
|
|
this._asyncInterruptor(exitFailCause(message.cause));
|
|
this._asyncInterruptor = null;
|
|
}
|
|
return EvaluationSignalContinue;
|
|
}
|
|
case OP_RESUME: {
|
|
this._asyncInterruptor = null;
|
|
this._asyncBlockingOn = null;
|
|
this.evaluateEffect(message.effect);
|
|
return EvaluationSignalContinue;
|
|
}
|
|
case OP_STATEFUL: {
|
|
message.onFiber(this, this._exitValue !== null ? done3 : suspended2(this.currentRuntimeFlags, this._asyncBlockingOn));
|
|
return EvaluationSignalContinue;
|
|
}
|
|
default: {
|
|
return absurd(message);
|
|
}
|
|
}
|
|
}
|
|
evaluateEffect(effect0) {
|
|
this.currentSupervisor.onResume(this);
|
|
try {
|
|
let effect = interruptible(this.currentRuntimeFlags) && this.isInterrupted() ? exitFailCause(this.getInterruptedCause()) : effect0;
|
|
while (effect !== null) {
|
|
const eff = effect;
|
|
const exit = this.runLoop(eff);
|
|
if (exit === YieldedOp) {
|
|
const op = yieldedOpChannel.currentOp;
|
|
yieldedOpChannel.currentOp = null;
|
|
if (op._op === OP_YIELD) {
|
|
if (cooperativeYielding(this.currentRuntimeFlags)) {
|
|
this.tell(yieldNow3());
|
|
this.tell(resume(exitVoid));
|
|
effect = null;
|
|
} else {
|
|
effect = exitVoid;
|
|
}
|
|
} else if (op._op === OP_ASYNC) {
|
|
effect = null;
|
|
}
|
|
} else {
|
|
this.currentRuntimeFlags = pipe(this.currentRuntimeFlags, enable2(WindDown));
|
|
const interruption = this.interruptAllChildren();
|
|
if (interruption !== null) {
|
|
effect = flatMap7(interruption, () => exit);
|
|
} else {
|
|
if (this._queue.length === 0) {
|
|
this.setExitValue(exit);
|
|
} else {
|
|
this.tell(resume(exit));
|
|
}
|
|
effect = null;
|
|
}
|
|
}
|
|
}
|
|
} finally {
|
|
this.currentSupervisor.onSuspend(this);
|
|
}
|
|
}
|
|
start(effect) {
|
|
if (!this._running) {
|
|
this._running = true;
|
|
const prev = globalThis[currentFiberURI];
|
|
globalThis[currentFiberURI] = this;
|
|
try {
|
|
this.evaluateEffect(effect);
|
|
} finally {
|
|
this._running = false;
|
|
globalThis[currentFiberURI] = prev;
|
|
if (this._queue.length > 0) {
|
|
this.drainQueueLaterOnExecutor();
|
|
}
|
|
}
|
|
} else {
|
|
this.tell(resume(effect));
|
|
}
|
|
}
|
|
startFork(effect) {
|
|
this.tell(resume(effect));
|
|
}
|
|
patchRuntimeFlags(oldRuntimeFlags, patch) {
|
|
const newRuntimeFlags = patch4(oldRuntimeFlags, patch);
|
|
globalThis[currentFiberURI] = this;
|
|
this.currentRuntimeFlags = newRuntimeFlags;
|
|
return newRuntimeFlags;
|
|
}
|
|
initiateAsync(runtimeFlags, asyncRegister) {
|
|
let alreadyCalled = false;
|
|
const callback = (effect) => {
|
|
if (!alreadyCalled) {
|
|
alreadyCalled = true;
|
|
this.tell(resume(effect));
|
|
}
|
|
};
|
|
if (interruptible(runtimeFlags)) {
|
|
this._asyncInterruptor = callback;
|
|
}
|
|
try {
|
|
asyncRegister(callback);
|
|
} catch (e) {
|
|
callback(failCause(die(e)));
|
|
}
|
|
}
|
|
pushStack(cont) {
|
|
this._stack.push(cont);
|
|
if (cont._op === "OnStep") {
|
|
this._steps.push({
|
|
refs: this.getFiberRefs(),
|
|
flags: this.currentRuntimeFlags
|
|
});
|
|
}
|
|
}
|
|
popStack() {
|
|
const item = this._stack.pop();
|
|
if (item) {
|
|
if (item._op === "OnStep") {
|
|
this._steps.pop();
|
|
}
|
|
return item;
|
|
}
|
|
return;
|
|
}
|
|
getNextSuccessCont() {
|
|
let frame = this.popStack();
|
|
while (frame) {
|
|
if (frame._op !== OP_ON_FAILURE) {
|
|
return frame;
|
|
}
|
|
frame = this.popStack();
|
|
}
|
|
}
|
|
getNextFailCont() {
|
|
let frame = this.popStack();
|
|
while (frame) {
|
|
if (frame._op !== OP_ON_SUCCESS && frame._op !== OP_WHILE && frame._op !== OP_ITERATOR) {
|
|
return frame;
|
|
}
|
|
frame = this.popStack();
|
|
}
|
|
}
|
|
[OP_TAG](op) {
|
|
return sync(() => unsafeGet3(this.currentContext, op));
|
|
}
|
|
["Left"](op) {
|
|
return fail2(op.left);
|
|
}
|
|
["None"](_) {
|
|
return fail2(new NoSuchElementException);
|
|
}
|
|
["Right"](op) {
|
|
return exitSucceed(op.right);
|
|
}
|
|
["Some"](op) {
|
|
return exitSucceed(op.value);
|
|
}
|
|
["Micro"](op) {
|
|
return unsafeAsync((microResume) => {
|
|
let resume = microResume;
|
|
const fiber = runFork(provideContext2(op, this.currentContext));
|
|
fiber.addObserver((exit) => {
|
|
if (exit._tag === "Success") {
|
|
return resume(exitSucceed(exit.value));
|
|
}
|
|
switch (exit.cause._tag) {
|
|
case "Interrupt": {
|
|
return resume(exitFailCause(interrupt(none4)));
|
|
}
|
|
case "Fail": {
|
|
return resume(fail2(exit.cause.error));
|
|
}
|
|
case "Die": {
|
|
return resume(die2(exit.cause.defect));
|
|
}
|
|
}
|
|
});
|
|
return unsafeAsync((abortResume) => {
|
|
resume = (_) => {
|
|
abortResume(void_);
|
|
};
|
|
fiber.unsafeInterrupt();
|
|
});
|
|
});
|
|
}
|
|
[OP_SYNC](op) {
|
|
const value = internalCall(() => op.effect_instruction_i0());
|
|
const cont = this.getNextSuccessCont();
|
|
if (cont !== undefined) {
|
|
if (!(cont._op in contOpSuccess)) {
|
|
absurd(cont);
|
|
}
|
|
return contOpSuccess[cont._op](this, cont, value);
|
|
} else {
|
|
yieldedOpChannel.currentOp = exitSucceed(value);
|
|
return YieldedOp;
|
|
}
|
|
}
|
|
[OP_SUCCESS](op) {
|
|
const oldCur = op;
|
|
const cont = this.getNextSuccessCont();
|
|
if (cont !== undefined) {
|
|
if (!(cont._op in contOpSuccess)) {
|
|
absurd(cont);
|
|
}
|
|
return contOpSuccess[cont._op](this, cont, oldCur.effect_instruction_i0);
|
|
} else {
|
|
yieldedOpChannel.currentOp = oldCur;
|
|
return YieldedOp;
|
|
}
|
|
}
|
|
[OP_FAILURE](op) {
|
|
const cause = op.effect_instruction_i0;
|
|
const cont = this.getNextFailCont();
|
|
if (cont !== undefined) {
|
|
switch (cont._op) {
|
|
case OP_ON_FAILURE:
|
|
case OP_ON_SUCCESS_AND_FAILURE: {
|
|
if (!(interruptible(this.currentRuntimeFlags) && this.isInterrupted())) {
|
|
return internalCall(() => cont.effect_instruction_i1(cause));
|
|
} else {
|
|
return exitFailCause(stripFailures(cause));
|
|
}
|
|
}
|
|
case "OnStep": {
|
|
if (!(interruptible(this.currentRuntimeFlags) && this.isInterrupted())) {
|
|
return exitSucceed(exitFailCause(cause));
|
|
} else {
|
|
return exitFailCause(stripFailures(cause));
|
|
}
|
|
}
|
|
case OP_REVERT_FLAGS: {
|
|
this.patchRuntimeFlags(this.currentRuntimeFlags, cont.patch);
|
|
if (interruptible(this.currentRuntimeFlags) && this.isInterrupted()) {
|
|
return exitFailCause(sequential(cause, this.getInterruptedCause()));
|
|
} else {
|
|
return exitFailCause(cause);
|
|
}
|
|
}
|
|
default: {
|
|
absurd(cont);
|
|
}
|
|
}
|
|
} else {
|
|
yieldedOpChannel.currentOp = exitFailCause(cause);
|
|
return YieldedOp;
|
|
}
|
|
}
|
|
[OP_WITH_RUNTIME](op) {
|
|
return internalCall(() => op.effect_instruction_i0(this, running2(this.currentRuntimeFlags)));
|
|
}
|
|
["Blocked"](op) {
|
|
const refs = this.getFiberRefs();
|
|
const flags = this.currentRuntimeFlags;
|
|
if (this._steps.length > 0) {
|
|
const frames = [];
|
|
const snap = this._steps[this._steps.length - 1];
|
|
let frame = this.popStack();
|
|
while (frame && frame._op !== "OnStep") {
|
|
frames.push(frame);
|
|
frame = this.popStack();
|
|
}
|
|
this.setFiberRefs(snap.refs);
|
|
this.currentRuntimeFlags = snap.flags;
|
|
const patchRefs = diff6(snap.refs, refs);
|
|
const patchFlags = diff4(snap.flags, flags);
|
|
return exitSucceed(blocked(op.effect_instruction_i0, withFiberRuntime((newFiber) => {
|
|
while (frames.length > 0) {
|
|
newFiber.pushStack(frames.pop());
|
|
}
|
|
newFiber.setFiberRefs(patch7(newFiber.id(), newFiber.getFiberRefs())(patchRefs));
|
|
newFiber.currentRuntimeFlags = patch4(patchFlags)(newFiber.currentRuntimeFlags);
|
|
return op.effect_instruction_i1;
|
|
})));
|
|
}
|
|
return uninterruptibleMask((restore) => flatMap7(forkDaemon(runRequestBlock(op.effect_instruction_i0)), () => restore(op.effect_instruction_i1)));
|
|
}
|
|
["RunBlocked"](op) {
|
|
return runBlockedRequests(op.effect_instruction_i0);
|
|
}
|
|
[OP_UPDATE_RUNTIME_FLAGS](op) {
|
|
const updateFlags = op.effect_instruction_i0;
|
|
const oldRuntimeFlags = this.currentRuntimeFlags;
|
|
const newRuntimeFlags = patch4(oldRuntimeFlags, updateFlags);
|
|
if (interruptible(newRuntimeFlags) && this.isInterrupted()) {
|
|
return exitFailCause(this.getInterruptedCause());
|
|
} else {
|
|
this.patchRuntimeFlags(this.currentRuntimeFlags, updateFlags);
|
|
if (op.effect_instruction_i1) {
|
|
const revertFlags = diff4(newRuntimeFlags, oldRuntimeFlags);
|
|
this.pushStack(new RevertFlags(revertFlags, op));
|
|
return internalCall(() => op.effect_instruction_i1(oldRuntimeFlags));
|
|
} else {
|
|
return exitVoid;
|
|
}
|
|
}
|
|
}
|
|
[OP_ON_SUCCESS](op) {
|
|
this.pushStack(op);
|
|
return op.effect_instruction_i0;
|
|
}
|
|
["OnStep"](op) {
|
|
this.pushStack(op);
|
|
return op.effect_instruction_i0;
|
|
}
|
|
[OP_ON_FAILURE](op) {
|
|
this.pushStack(op);
|
|
return op.effect_instruction_i0;
|
|
}
|
|
[OP_ON_SUCCESS_AND_FAILURE](op) {
|
|
this.pushStack(op);
|
|
return op.effect_instruction_i0;
|
|
}
|
|
[OP_ASYNC](op) {
|
|
this._asyncBlockingOn = op.effect_instruction_i1;
|
|
this.initiateAsync(this.currentRuntimeFlags, op.effect_instruction_i0);
|
|
yieldedOpChannel.currentOp = op;
|
|
return YieldedOp;
|
|
}
|
|
[OP_YIELD](op) {
|
|
this._isYielding = false;
|
|
yieldedOpChannel.currentOp = op;
|
|
return YieldedOp;
|
|
}
|
|
[OP_WHILE](op) {
|
|
const check = op.effect_instruction_i0;
|
|
const body = op.effect_instruction_i1;
|
|
if (check()) {
|
|
this.pushStack(op);
|
|
return body();
|
|
} else {
|
|
return exitVoid;
|
|
}
|
|
}
|
|
[OP_ITERATOR](op) {
|
|
return contOpSuccess[OP_ITERATOR](this, op, undefined);
|
|
}
|
|
[OP_COMMIT](op) {
|
|
return internalCall(() => op.commit());
|
|
}
|
|
runLoop(effect0) {
|
|
let cur = effect0;
|
|
this.currentOpCount = 0;
|
|
while (true) {
|
|
if ((this.currentRuntimeFlags & OpSupervision) !== 0) {
|
|
this.currentSupervisor.onEffect(this, cur);
|
|
}
|
|
if (this._queue.length > 0) {
|
|
cur = this.drainQueueWhileRunning(this.currentRuntimeFlags, cur);
|
|
}
|
|
if (!this._isYielding) {
|
|
this.currentOpCount += 1;
|
|
const shouldYield = this.currentScheduler.shouldYield(this);
|
|
if (shouldYield !== false) {
|
|
this._isYielding = true;
|
|
this.currentOpCount = 0;
|
|
const oldCur = cur;
|
|
cur = flatMap7(yieldNow({
|
|
priority: shouldYield
|
|
}), () => oldCur);
|
|
}
|
|
}
|
|
try {
|
|
cur = this.currentTracer.context(() => {
|
|
if (_version !== cur[EffectTypeId2]._V) {
|
|
const level = this.getFiberRef(currentVersionMismatchErrorLogLevel);
|
|
if (level._tag === "Some") {
|
|
const effectVersion = cur[EffectTypeId2]._V;
|
|
this.log(`Executing an Effect versioned ${effectVersion} with a Runtime of version ${getCurrentVersion()}, you may want to dedupe the effect dependencies, you can use the language service plugin to detect this at compile time: https://github.com/Effect-TS/language-service`, empty14, level);
|
|
}
|
|
}
|
|
return this[cur._op](cur);
|
|
}, this);
|
|
if (cur === YieldedOp) {
|
|
const op = yieldedOpChannel.currentOp;
|
|
if (op._op === OP_YIELD || op._op === OP_ASYNC) {
|
|
return YieldedOp;
|
|
}
|
|
yieldedOpChannel.currentOp = null;
|
|
return op._op === OP_SUCCESS || op._op === OP_FAILURE ? op : exitFailCause(die(op));
|
|
}
|
|
} catch (e) {
|
|
if (cur !== YieldedOp && !hasProperty(cur, "_op") || !(cur._op in this)) {
|
|
cur = dieMessage(`Not a valid effect: ${toStringUnknown(cur)}`);
|
|
} else if (isInterruptedException(e)) {
|
|
cur = exitFailCause(sequential(die(e), interrupt(none4)));
|
|
} else {
|
|
cur = die2(e);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
run = () => {
|
|
this.drainQueueOnCurrentThread();
|
|
};
|
|
}
|
|
var currentMinimumLogLevel = /* @__PURE__ */ globalValue("effect/FiberRef/currentMinimumLogLevel", () => fiberRefUnsafeMake(fromLiteral("Info")));
|
|
var loggerWithConsoleLog = (self2) => makeLogger((opts) => {
|
|
const services = getOrDefault2(opts.context, currentServices);
|
|
get3(services, consoleTag).unsafe.log(self2.log(opts));
|
|
});
|
|
var defaultLogger = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/Logger/defaultLogger"), () => loggerWithConsoleLog(stringLogger));
|
|
var tracerLogger = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/Logger/tracerLogger"), () => makeLogger(({
|
|
annotations,
|
|
cause,
|
|
context,
|
|
fiberId,
|
|
logLevel,
|
|
message
|
|
}) => {
|
|
const span = filterDisablePropagation(getOption2(getOrDefault(context, currentContext), spanTag));
|
|
if (span._tag === "None" || span.value._tag === "ExternalSpan") {
|
|
return;
|
|
}
|
|
const clockService = unsafeGet3(getOrDefault(context, currentServices), clockTag);
|
|
const attributes = {};
|
|
for (const [key, value] of annotations) {
|
|
attributes[key] = value;
|
|
}
|
|
attributes["effect.fiberId"] = threadName2(fiberId);
|
|
attributes["effect.logLevel"] = logLevel.label;
|
|
if (cause !== null && cause._tag !== "Empty") {
|
|
attributes["effect.cause"] = pretty(cause, {
|
|
renderErrorCause: true
|
|
});
|
|
}
|
|
span.value.event(toStringUnknown(Array.isArray(message) && message.length === 1 ? message[0] : message), clockService.unsafeCurrentTimeNanos(), attributes);
|
|
}));
|
|
var currentLoggers = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/FiberRef/currentLoggers"), () => fiberRefUnsafeMakeHashSet(make10(defaultLogger, tracerLogger)));
|
|
var acquireRelease = /* @__PURE__ */ dual((args) => isEffect(args[0]), (acquire, release) => uninterruptible(tap(acquire, (a) => addFinalizer((exit) => release(a, exit)))));
|
|
var addFinalizer = (finalizer) => withFiberRuntime((runtime) => {
|
|
const acquireRefs = runtime.getFiberRefs();
|
|
const acquireFlags = disable2(runtime.currentRuntimeFlags, Interruption);
|
|
return flatMap7(scope, (scope) => scopeAddFinalizerExit(scope, (exit) => withFiberRuntime((runtimeFinalizer) => {
|
|
const preRefs = runtimeFinalizer.getFiberRefs();
|
|
const preFlags = runtimeFinalizer.currentRuntimeFlags;
|
|
const patchRefs = diff6(preRefs, acquireRefs);
|
|
const patchFlags = diff4(preFlags, acquireFlags);
|
|
const inverseRefs = diff6(acquireRefs, preRefs);
|
|
runtimeFinalizer.setFiberRefs(patch7(patchRefs, runtimeFinalizer.id(), acquireRefs));
|
|
return ensuring(withRuntimeFlags(finalizer(exit), patchFlags), sync(() => {
|
|
runtimeFinalizer.setFiberRefs(patch7(inverseRefs, runtimeFinalizer.id(), runtimeFinalizer.getFiberRefs()));
|
|
}));
|
|
})));
|
|
});
|
|
var allResolveInput = (input) => {
|
|
if (Array.isArray(input) || isIterable(input)) {
|
|
return [input, none2()];
|
|
}
|
|
const keys = Object.keys(input);
|
|
const size = keys.length;
|
|
return [keys.map((k) => input[k]), some2((values) => {
|
|
const res = {};
|
|
for (let i = 0;i < size; i++) {
|
|
res[keys[i]] = values[i];
|
|
}
|
|
return res;
|
|
})];
|
|
};
|
|
var allValidate = (effects, reconcile, options) => {
|
|
const eitherEffects = [];
|
|
for (const effect of effects) {
|
|
eitherEffects.push(either2(effect));
|
|
}
|
|
return flatMap7(forEach3(eitherEffects, identity, {
|
|
concurrency: options?.concurrency,
|
|
batching: options?.batching,
|
|
concurrentFinalizers: options?.concurrentFinalizers
|
|
}), (eithers) => {
|
|
const none = none2();
|
|
const size = eithers.length;
|
|
const errors = new Array(size);
|
|
const successes = new Array(size);
|
|
let errored = false;
|
|
for (let i = 0;i < size; i++) {
|
|
const either = eithers[i];
|
|
if (either._tag === "Left") {
|
|
errors[i] = some2(either.left);
|
|
errored = true;
|
|
} else {
|
|
successes[i] = either.right;
|
|
errors[i] = none;
|
|
}
|
|
}
|
|
if (errored) {
|
|
return reconcile._tag === "Some" ? fail2(reconcile.value(errors)) : fail2(errors);
|
|
} else if (options?.discard) {
|
|
return void_;
|
|
}
|
|
return reconcile._tag === "Some" ? succeed(reconcile.value(successes)) : succeed(successes);
|
|
});
|
|
};
|
|
var allEither = (effects, reconcile, options) => {
|
|
const eitherEffects = [];
|
|
for (const effect of effects) {
|
|
eitherEffects.push(either2(effect));
|
|
}
|
|
if (options?.discard) {
|
|
return forEach3(eitherEffects, identity, {
|
|
concurrency: options?.concurrency,
|
|
batching: options?.batching,
|
|
discard: true,
|
|
concurrentFinalizers: options?.concurrentFinalizers
|
|
});
|
|
}
|
|
return map10(forEach3(eitherEffects, identity, {
|
|
concurrency: options?.concurrency,
|
|
batching: options?.batching,
|
|
concurrentFinalizers: options?.concurrentFinalizers
|
|
}), (eithers) => reconcile._tag === "Some" ? reconcile.value(eithers) : eithers);
|
|
};
|
|
var all3 = (arg, options) => {
|
|
const [effects, reconcile] = allResolveInput(arg);
|
|
if (options?.mode === "validate") {
|
|
return allValidate(effects, reconcile, options);
|
|
} else if (options?.mode === "either") {
|
|
return allEither(effects, reconcile, options);
|
|
}
|
|
return options?.discard !== true && reconcile._tag === "Some" ? map10(forEach3(effects, identity, options), reconcile.value) : forEach3(effects, identity, options);
|
|
};
|
|
var forEach3 = /* @__PURE__ */ dual((args) => isIterable(args[0]), (self2, f, options) => withFiberRuntime((r) => {
|
|
const isRequestBatchingEnabled = options?.batching === true || options?.batching === "inherit" && r.getFiberRef(currentRequestBatching);
|
|
if (options?.discard) {
|
|
return match7(options.concurrency, () => finalizersMaskInternal(sequential3, options?.concurrentFinalizers)((restore) => isRequestBatchingEnabled ? forEachConcurrentDiscard(self2, (a, i) => restore(f(a, i)), true, false, 1) : forEachSequentialDiscard(self2, (a, i) => restore(f(a, i)))), () => finalizersMaskInternal(parallel3, options?.concurrentFinalizers)((restore) => forEachConcurrentDiscard(self2, (a, i) => restore(f(a, i)), isRequestBatchingEnabled, false)), (n) => finalizersMaskInternal(parallelN2(n), options?.concurrentFinalizers)((restore) => forEachConcurrentDiscard(self2, (a, i) => restore(f(a, i)), isRequestBatchingEnabled, false, n)));
|
|
}
|
|
return match7(options?.concurrency, () => finalizersMaskInternal(sequential3, options?.concurrentFinalizers)((restore) => isRequestBatchingEnabled ? forEachParN(self2, 1, (a, i) => restore(f(a, i)), true) : forEachSequential(self2, (a, i) => restore(f(a, i)))), () => finalizersMaskInternal(parallel3, options?.concurrentFinalizers)((restore) => forEachParUnbounded(self2, (a, i) => restore(f(a, i)), isRequestBatchingEnabled)), (n) => finalizersMaskInternal(parallelN2(n), options?.concurrentFinalizers)((restore) => forEachParN(self2, n, (a, i) => restore(f(a, i)), isRequestBatchingEnabled)));
|
|
}));
|
|
var forEachParUnbounded = (self2, f, batching) => suspend(() => {
|
|
const as = fromIterable(self2);
|
|
const array = new Array(as.length);
|
|
const fn = (a, i) => flatMap7(f(a, i), (b) => sync(() => array[i] = b));
|
|
return zipRight(forEachConcurrentDiscard(as, fn, batching, false), succeed(array));
|
|
});
|
|
var forEachConcurrentDiscard = (self2, f, batching, processAll, n) => uninterruptibleMask((restore) => transplant((graft) => withFiberRuntime((parent) => {
|
|
let todos = Array.from(self2).reverse();
|
|
let target = todos.length;
|
|
if (target === 0) {
|
|
return void_;
|
|
}
|
|
let counter = 0;
|
|
let interrupted = false;
|
|
const fibersCount = n ? Math.min(todos.length, n) : todos.length;
|
|
const fibers = new Set;
|
|
const results = new Array;
|
|
const interruptAll = () => fibers.forEach((fiber) => {
|
|
fiber.currentScheduler.scheduleTask(() => {
|
|
fiber.unsafeInterruptAsFork(parent.id());
|
|
}, 0, fiber);
|
|
});
|
|
const startOrder = new Array;
|
|
const joinOrder = new Array;
|
|
const residual = new Array;
|
|
const collectExits = () => {
|
|
const exits = results.filter(({
|
|
exit
|
|
}) => exit._tag === "Failure").sort((a, b) => a.index < b.index ? -1 : a.index === b.index ? 0 : 1).map(({
|
|
exit
|
|
}) => exit);
|
|
if (exits.length === 0) {
|
|
exits.push(exitVoid);
|
|
}
|
|
return exits;
|
|
};
|
|
const runFiber = (eff, interruptImmediately = false) => {
|
|
const runnable = uninterruptible(graft(eff));
|
|
const fiber = unsafeForkUnstarted(runnable, parent, parent.currentRuntimeFlags, globalScope);
|
|
parent.currentScheduler.scheduleTask(() => {
|
|
if (interruptImmediately) {
|
|
fiber.unsafeInterruptAsFork(parent.id());
|
|
}
|
|
fiber.resume(runnable);
|
|
}, 0, fiber);
|
|
return fiber;
|
|
};
|
|
const onInterruptSignal = () => {
|
|
if (!processAll) {
|
|
target -= todos.length;
|
|
todos = [];
|
|
}
|
|
interrupted = true;
|
|
interruptAll();
|
|
};
|
|
const stepOrExit = batching ? step2 : exit;
|
|
const processingFiber = runFiber(async_((resume) => {
|
|
const pushResult = (res, index) => {
|
|
if (res._op === "Blocked") {
|
|
residual.push(res);
|
|
} else {
|
|
results.push({
|
|
index,
|
|
exit: res
|
|
});
|
|
if (res._op === "Failure" && !interrupted) {
|
|
onInterruptSignal();
|
|
}
|
|
}
|
|
};
|
|
const next = () => {
|
|
if (todos.length > 0) {
|
|
const a = todos.pop();
|
|
let index = counter++;
|
|
const returnNextElement = () => {
|
|
const a = todos.pop();
|
|
index = counter++;
|
|
return flatMap7(yieldNow(), () => flatMap7(stepOrExit(restore(f(a, index))), onRes));
|
|
};
|
|
const onRes = (res) => {
|
|
if (todos.length > 0) {
|
|
pushResult(res, index);
|
|
if (todos.length > 0) {
|
|
return returnNextElement();
|
|
}
|
|
}
|
|
return succeed(res);
|
|
};
|
|
const todo = flatMap7(stepOrExit(restore(f(a, index))), onRes);
|
|
const fiber = runFiber(todo);
|
|
startOrder.push(fiber);
|
|
fibers.add(fiber);
|
|
if (interrupted) {
|
|
fiber.currentScheduler.scheduleTask(() => {
|
|
fiber.unsafeInterruptAsFork(parent.id());
|
|
}, 0, fiber);
|
|
}
|
|
fiber.addObserver((wrapped) => {
|
|
let exit;
|
|
if (wrapped._op === "Failure") {
|
|
exit = wrapped;
|
|
} else {
|
|
exit = wrapped.effect_instruction_i0;
|
|
}
|
|
joinOrder.push(fiber);
|
|
fibers.delete(fiber);
|
|
pushResult(exit, index);
|
|
if (results.length === target) {
|
|
resume(succeed(getOrElse(exitCollectAll(collectExits(), {
|
|
parallel: true
|
|
}), () => exitVoid)));
|
|
} else if (residual.length + results.length === target) {
|
|
const exits = collectExits();
|
|
const requests = residual.map((blocked) => blocked.effect_instruction_i0).reduce(par);
|
|
resume(succeed(blocked(requests, forEachConcurrentDiscard([getOrElse(exitCollectAll(exits, {
|
|
parallel: true
|
|
}), () => exitVoid), ...residual.map((blocked) => blocked.effect_instruction_i1)], (i) => i, batching, true, n))));
|
|
} else {
|
|
next();
|
|
}
|
|
});
|
|
}
|
|
};
|
|
for (let i = 0;i < fibersCount; i++) {
|
|
next();
|
|
}
|
|
}));
|
|
return asVoid(onExit(flatten3(restore(join2(processingFiber))), exitMatch({
|
|
onFailure: (cause) => {
|
|
onInterruptSignal();
|
|
const target = residual.length + 1;
|
|
const concurrency = Math.min(typeof n === "number" ? n : residual.length, residual.length);
|
|
const toPop = Array.from(residual);
|
|
return async_((cb) => {
|
|
const exits = [];
|
|
let count = 0;
|
|
let index = 0;
|
|
const check = (index, hitNext) => (exit) => {
|
|
exits[index] = exit;
|
|
count++;
|
|
if (count === target) {
|
|
cb(exitSucceed(exitFailCause(cause)));
|
|
}
|
|
if (toPop.length > 0 && hitNext) {
|
|
next();
|
|
}
|
|
};
|
|
const next = () => {
|
|
runFiber(toPop.pop(), true).addObserver(check(index, true));
|
|
index++;
|
|
};
|
|
processingFiber.addObserver(check(index, false));
|
|
index++;
|
|
for (let i = 0;i < concurrency; i++) {
|
|
next();
|
|
}
|
|
});
|
|
},
|
|
onSuccess: () => forEachSequential(joinOrder, (f) => f.inheritAll)
|
|
})));
|
|
})));
|
|
var forEachParN = (self2, n, f, batching) => suspend(() => {
|
|
const as = fromIterable(self2);
|
|
const array = new Array(as.length);
|
|
const fn = (a, i) => map10(f(a, i), (b) => array[i] = b);
|
|
return zipRight(forEachConcurrentDiscard(as, fn, batching, false, n), succeed(array));
|
|
});
|
|
var forkDaemon = (self2) => forkWithScopeOverride(self2, globalScope);
|
|
var unsafeFork = (effect, parentFiber, parentRuntimeFlags, overrideScope = null) => {
|
|
const childFiber = unsafeMakeChildFiber(effect, parentFiber, parentRuntimeFlags, overrideScope);
|
|
childFiber.resume(effect);
|
|
return childFiber;
|
|
};
|
|
var unsafeForkUnstarted = (effect, parentFiber, parentRuntimeFlags, overrideScope = null) => {
|
|
const childFiber = unsafeMakeChildFiber(effect, parentFiber, parentRuntimeFlags, overrideScope);
|
|
return childFiber;
|
|
};
|
|
var unsafeMakeChildFiber = (effect, parentFiber, parentRuntimeFlags, overrideScope = null) => {
|
|
const childId = unsafeMake2();
|
|
const parentFiberRefs = parentFiber.getFiberRefs();
|
|
const childFiberRefs = forkAs(parentFiberRefs, childId);
|
|
const childFiber = new FiberRuntime(childId, childFiberRefs, parentRuntimeFlags);
|
|
const childContext = getOrDefault(childFiberRefs, currentContext);
|
|
const supervisor = childFiber.currentSupervisor;
|
|
supervisor.onStart(childContext, effect, some2(parentFiber), childFiber);
|
|
childFiber.addObserver((exit) => supervisor.onEnd(exit, childFiber));
|
|
const parentScope = overrideScope !== null ? overrideScope : pipe(parentFiber.getFiberRef(currentForkScopeOverride), getOrElse(() => parentFiber.scope()));
|
|
parentScope.add(parentRuntimeFlags, childFiber);
|
|
return childFiber;
|
|
};
|
|
var forkWithScopeOverride = (self2, scopeOverride) => withFiberRuntime((parentFiber, parentStatus) => succeed(unsafeFork(self2, parentFiber, parentStatus.runtimeFlags, scopeOverride)));
|
|
var parallelFinalizers = (self2) => contextWithEffect((context) => match2(getOption2(context, scopeTag), {
|
|
onNone: () => self2,
|
|
onSome: (scope) => {
|
|
switch (scope.strategy._tag) {
|
|
case "Parallel":
|
|
return self2;
|
|
case "Sequential":
|
|
case "ParallelN":
|
|
return flatMap7(scopeFork(scope, parallel3), (inner) => scopeExtend(self2, inner));
|
|
}
|
|
}
|
|
}));
|
|
var parallelNFinalizers = (parallelism) => (self2) => contextWithEffect((context) => match2(getOption2(context, scopeTag), {
|
|
onNone: () => self2,
|
|
onSome: (scope) => {
|
|
if (scope.strategy._tag === "ParallelN" && scope.strategy.parallelism === parallelism) {
|
|
return self2;
|
|
}
|
|
return flatMap7(scopeFork(scope, parallelN2(parallelism)), (inner) => scopeExtend(self2, inner));
|
|
}
|
|
}));
|
|
var finalizersMaskInternal = (strategy, concurrentFinalizers) => (self2) => contextWithEffect((context) => match2(getOption2(context, scopeTag), {
|
|
onNone: () => self2(identity),
|
|
onSome: (scope) => {
|
|
if (concurrentFinalizers === true) {
|
|
const patch = strategy._tag === "Parallel" ? parallelFinalizers : strategy._tag === "Sequential" ? sequentialFinalizers : parallelNFinalizers(strategy.parallelism);
|
|
switch (scope.strategy._tag) {
|
|
case "Parallel":
|
|
return patch(self2(parallelFinalizers));
|
|
case "Sequential":
|
|
return patch(self2(sequentialFinalizers));
|
|
case "ParallelN":
|
|
return patch(self2(parallelNFinalizers(scope.strategy.parallelism)));
|
|
}
|
|
} else {
|
|
return self2(identity);
|
|
}
|
|
}
|
|
}));
|
|
var scopeWith = (f) => flatMap7(scopeTag, f);
|
|
var scopedWith = (f) => flatMap7(scopeMake(), (scope) => onExit(f(scope), (exit) => scope.close(exit)));
|
|
var scopedEffect = (effect) => flatMap7(scopeMake(), (scope) => scopeUse(effect, scope));
|
|
var sequentialFinalizers = (self2) => contextWithEffect((context) => match2(getOption2(context, scopeTag), {
|
|
onNone: () => self2,
|
|
onSome: (scope) => {
|
|
switch (scope.strategy._tag) {
|
|
case "Sequential":
|
|
return self2;
|
|
case "Parallel":
|
|
case "ParallelN":
|
|
return flatMap7(scopeFork(scope, sequential3), (inner) => scopeExtend(self2, inner));
|
|
}
|
|
}
|
|
}));
|
|
var zipOptions = /* @__PURE__ */ dual((args) => isEffect(args[1]), (self2, that, options) => zipWithOptions(self2, that, (a, b) => [a, b], options));
|
|
var zipLeftOptions = /* @__PURE__ */ dual((args) => isEffect(args[1]), (self2, that, options) => {
|
|
if (options?.concurrent !== true && (options?.batching === undefined || options.batching === false)) {
|
|
return zipLeft(self2, that);
|
|
}
|
|
return zipWithOptions(self2, that, (a, _) => a, options);
|
|
});
|
|
var zipRightOptions = /* @__PURE__ */ dual((args) => isEffect(args[1]), (self2, that, options) => {
|
|
if (options?.concurrent !== true && (options?.batching === undefined || options.batching === false)) {
|
|
return zipRight(self2, that);
|
|
}
|
|
return zipWithOptions(self2, that, (_, b) => b, options);
|
|
});
|
|
var zipWithOptions = /* @__PURE__ */ dual((args) => isEffect(args[1]), (self2, that, f, options) => map10(all3([self2, that], {
|
|
concurrency: options?.concurrent ? 2 : 1,
|
|
batching: options?.batching,
|
|
concurrentFinalizers: options?.concurrentFinalizers
|
|
}), ([a, a2]) => f(a, a2)));
|
|
var scopeTag = /* @__PURE__ */ GenericTag("effect/Scope");
|
|
var scope = scopeTag;
|
|
var scopeUnsafeAddFinalizer = (scope, fin) => {
|
|
if (scope.state._tag === "Open") {
|
|
scope.state.finalizers.set({}, fin);
|
|
}
|
|
};
|
|
var ScopeImplProto = {
|
|
[ScopeTypeId]: ScopeTypeId,
|
|
[CloseableScopeTypeId]: CloseableScopeTypeId,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
},
|
|
fork(strategy) {
|
|
return sync(() => {
|
|
const newScope = scopeUnsafeMake(strategy);
|
|
if (this.state._tag === "Closed") {
|
|
newScope.state = this.state;
|
|
return newScope;
|
|
}
|
|
const key = {};
|
|
const fin = (exit) => newScope.close(exit);
|
|
this.state.finalizers.set(key, fin);
|
|
scopeUnsafeAddFinalizer(newScope, (_) => sync(() => {
|
|
if (this.state._tag === "Open") {
|
|
this.state.finalizers.delete(key);
|
|
}
|
|
}));
|
|
return newScope;
|
|
});
|
|
},
|
|
close(exit2) {
|
|
return suspend(() => {
|
|
if (this.state._tag === "Closed") {
|
|
return void_;
|
|
}
|
|
const finalizers = Array.from(this.state.finalizers.values()).reverse();
|
|
this.state = {
|
|
_tag: "Closed",
|
|
exit: exit2
|
|
};
|
|
if (finalizers.length === 0) {
|
|
return void_;
|
|
}
|
|
return isSequential(this.strategy) ? pipe(forEachSequential(finalizers, (fin) => exit(fin(exit2))), flatMap7((results) => pipe(exitCollectAll(results), map2(exitAsVoid), getOrElse(() => exitVoid)))) : isParallel(this.strategy) ? pipe(forEachParUnbounded(finalizers, (fin) => exit(fin(exit2)), false), flatMap7((results) => pipe(exitCollectAll(results, {
|
|
parallel: true
|
|
}), map2(exitAsVoid), getOrElse(() => exitVoid)))) : pipe(forEachParN(finalizers, this.strategy.parallelism, (fin) => exit(fin(exit2)), false), flatMap7((results) => pipe(exitCollectAll(results, {
|
|
parallel: true
|
|
}), map2(exitAsVoid), getOrElse(() => exitVoid))));
|
|
});
|
|
},
|
|
addFinalizer(fin) {
|
|
return suspend(() => {
|
|
if (this.state._tag === "Closed") {
|
|
return fin(this.state.exit);
|
|
}
|
|
this.state.finalizers.set({}, fin);
|
|
return void_;
|
|
});
|
|
}
|
|
};
|
|
var scopeUnsafeMake = (strategy = sequential2) => {
|
|
const scope = Object.create(ScopeImplProto);
|
|
scope.strategy = strategy;
|
|
scope.state = {
|
|
_tag: "Open",
|
|
finalizers: new Map
|
|
};
|
|
return scope;
|
|
};
|
|
var scopeMake = (strategy = sequential2) => sync(() => scopeUnsafeMake(strategy));
|
|
var scopeExtend = /* @__PURE__ */ dual(2, (effect, scope) => mapInputContext(effect, merge3(make5(scopeTag, scope))));
|
|
var scopeUse = /* @__PURE__ */ dual(2, (effect, scope) => pipe(effect, scopeExtend(scope), onExit((exit) => scope.close(exit))));
|
|
var fiberRefUnsafeMakeSupervisor = (initial) => fiberRefUnsafeMakePatch(initial, {
|
|
differ: differ2,
|
|
fork: empty20
|
|
});
|
|
var currentRuntimeFlags = /* @__PURE__ */ fiberRefUnsafeMakeRuntimeFlags(none5);
|
|
var currentSupervisor = /* @__PURE__ */ fiberRefUnsafeMakeSupervisor(none7);
|
|
var raceWith = /* @__PURE__ */ dual(3, (self2, other, options) => raceFibersWith(self2, other, {
|
|
onSelfWin: (winner, loser) => flatMap7(winner.await, (exit) => {
|
|
switch (exit._tag) {
|
|
case OP_SUCCESS: {
|
|
return flatMap7(winner.inheritAll, () => options.onSelfDone(exit, loser));
|
|
}
|
|
case OP_FAILURE: {
|
|
return options.onSelfDone(exit, loser);
|
|
}
|
|
}
|
|
}),
|
|
onOtherWin: (winner, loser) => flatMap7(winner.await, (exit) => {
|
|
switch (exit._tag) {
|
|
case OP_SUCCESS: {
|
|
return flatMap7(winner.inheritAll, () => options.onOtherDone(exit, loser));
|
|
}
|
|
case OP_FAILURE: {
|
|
return options.onOtherDone(exit, loser);
|
|
}
|
|
}
|
|
})
|
|
}));
|
|
var race = /* @__PURE__ */ dual(2, (self2, that) => fiberIdWith((parentFiberId) => raceWith(self2, that, {
|
|
onSelfDone: (exit, right) => exitMatchEffect(exit, {
|
|
onFailure: (cause) => pipe(join2(right), mapErrorCause((cause2) => parallel(cause, cause2))),
|
|
onSuccess: (value) => pipe(right, interruptAsFiber(parentFiberId), as(value))
|
|
}),
|
|
onOtherDone: (exit, left) => exitMatchEffect(exit, {
|
|
onFailure: (cause) => pipe(join2(left), mapErrorCause((cause2) => parallel(cause2, cause))),
|
|
onSuccess: (value) => pipe(left, interruptAsFiber(parentFiberId), as(value))
|
|
})
|
|
})));
|
|
var raceFibersWith = /* @__PURE__ */ dual(3, (self2, other, options) => withFiberRuntime((parentFiber, parentStatus) => {
|
|
const parentRuntimeFlags = parentStatus.runtimeFlags;
|
|
const raceIndicator = make11(true);
|
|
const leftFiber = unsafeMakeChildFiber(self2, parentFiber, parentRuntimeFlags, options.selfScope);
|
|
const rightFiber = unsafeMakeChildFiber(other, parentFiber, parentRuntimeFlags, options.otherScope);
|
|
return async_((cb) => {
|
|
leftFiber.addObserver(() => completeRace(leftFiber, rightFiber, options.onSelfWin, raceIndicator, cb));
|
|
rightFiber.addObserver(() => completeRace(rightFiber, leftFiber, options.onOtherWin, raceIndicator, cb));
|
|
leftFiber.startFork(self2);
|
|
rightFiber.startFork(other);
|
|
}, combine3(leftFiber.id(), rightFiber.id()));
|
|
}));
|
|
var completeRace = (winner, loser, cont, ab, cb) => {
|
|
if (compareAndSet(true, false)(ab)) {
|
|
cb(cont(winner, loser));
|
|
}
|
|
};
|
|
var ensuring = /* @__PURE__ */ dual(2, (self2, finalizer) => uninterruptibleMask((restore) => matchCauseEffect(restore(self2), {
|
|
onFailure: (cause1) => matchCauseEffect(finalizer, {
|
|
onFailure: (cause2) => failCause(sequential(cause1, cause2)),
|
|
onSuccess: () => failCause(cause1)
|
|
}),
|
|
onSuccess: (a) => as(finalizer, a)
|
|
})));
|
|
var invokeWithInterrupt = (self2, entries, onInterrupt) => fiberIdWith((id) => ensuring(flatMap7(forkDaemon(interruptible2(self2)), (processing) => async_((cb) => {
|
|
const counts = entries.map((_) => _.listeners.count);
|
|
const checkDone = () => {
|
|
if (counts.every((count) => count === 0)) {
|
|
if (entries.every((_) => {
|
|
if (_.result.state.current._tag === "Pending") {
|
|
return true;
|
|
} else if (_.result.state.current._tag === "Done" && exitIsExit(_.result.state.current.effect) && _.result.state.current.effect._tag === "Failure" && isInterrupted(_.result.state.current.effect.cause)) {
|
|
return true;
|
|
} else {
|
|
return false;
|
|
}
|
|
})) {
|
|
cleanup.forEach((f) => f());
|
|
onInterrupt?.();
|
|
cb(interruptFiber(processing));
|
|
}
|
|
}
|
|
};
|
|
processing.addObserver((exit) => {
|
|
cleanup.forEach((f) => f());
|
|
cb(exit);
|
|
});
|
|
const cleanup = entries.map((r, i) => {
|
|
const observer = (count) => {
|
|
counts[i] = count;
|
|
checkDone();
|
|
};
|
|
r.listeners.addObserver(observer);
|
|
return () => r.listeners.removeObserver(observer);
|
|
});
|
|
checkDone();
|
|
return sync(() => {
|
|
cleanup.forEach((f) => f());
|
|
});
|
|
})), suspend(() => {
|
|
const residual = entries.flatMap((entry) => {
|
|
if (!entry.state.completed) {
|
|
return [entry];
|
|
}
|
|
return [];
|
|
});
|
|
return forEachSequentialDiscard(residual, (entry) => complete(entry.request, exitInterrupt(id)));
|
|
})));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/schedule/interval.js
|
|
var IntervalSymbolKey = "effect/ScheduleInterval";
|
|
var IntervalTypeId = /* @__PURE__ */ Symbol.for(IntervalSymbolKey);
|
|
var empty22 = {
|
|
[IntervalTypeId]: IntervalTypeId,
|
|
startMillis: 0,
|
|
endMillis: 0
|
|
};
|
|
var make31 = (startMillis, endMillis) => {
|
|
if (startMillis > endMillis) {
|
|
return empty22;
|
|
}
|
|
return {
|
|
[IntervalTypeId]: IntervalTypeId,
|
|
startMillis,
|
|
endMillis
|
|
};
|
|
};
|
|
var lessThan2 = /* @__PURE__ */ dual(2, (self2, that) => min2(self2, that) === self2);
|
|
var min2 = /* @__PURE__ */ dual(2, (self2, that) => {
|
|
if (self2.endMillis <= that.startMillis)
|
|
return self2;
|
|
if (that.endMillis <= self2.startMillis)
|
|
return that;
|
|
if (self2.startMillis < that.startMillis)
|
|
return self2;
|
|
if (that.startMillis < self2.startMillis)
|
|
return that;
|
|
if (self2.endMillis <= that.endMillis)
|
|
return self2;
|
|
return that;
|
|
});
|
|
var isEmpty6 = (self2) => {
|
|
return self2.startMillis >= self2.endMillis;
|
|
};
|
|
var intersect2 = /* @__PURE__ */ dual(2, (self2, that) => {
|
|
const start = Math.max(self2.startMillis, that.startMillis);
|
|
const end = Math.min(self2.endMillis, that.endMillis);
|
|
return make31(start, end);
|
|
});
|
|
var after = (startMilliseconds) => {
|
|
return make31(startMilliseconds, Number.POSITIVE_INFINITY);
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/ScheduleInterval.js
|
|
var empty23 = empty22;
|
|
var lessThan3 = lessThan2;
|
|
var isEmpty7 = isEmpty6;
|
|
var intersect3 = intersect2;
|
|
var after2 = after;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/schedule/intervals.js
|
|
var IntervalsSymbolKey = "effect/ScheduleIntervals";
|
|
var IntervalsTypeId = /* @__PURE__ */ Symbol.for(IntervalsSymbolKey);
|
|
var make33 = (intervals) => {
|
|
return {
|
|
[IntervalsTypeId]: IntervalsTypeId,
|
|
intervals
|
|
};
|
|
};
|
|
var intersect4 = /* @__PURE__ */ dual(2, (self2, that) => intersectLoop(self2.intervals, that.intervals, empty4()));
|
|
var intersectLoop = (_left, _right, _acc) => {
|
|
let left = _left;
|
|
let right = _right;
|
|
let acc = _acc;
|
|
while (isNonEmpty(left) && isNonEmpty(right)) {
|
|
const interval = pipe(headNonEmpty2(left), intersect3(headNonEmpty2(right)));
|
|
const intervals = isEmpty7(interval) ? acc : pipe(acc, prepend2(interval));
|
|
if (pipe(headNonEmpty2(left), lessThan3(headNonEmpty2(right)))) {
|
|
left = tailNonEmpty2(left);
|
|
} else {
|
|
right = tailNonEmpty2(right);
|
|
}
|
|
acc = intervals;
|
|
}
|
|
return make33(reverse2(acc));
|
|
};
|
|
var start = (self2) => {
|
|
return pipe(self2.intervals, head2, getOrElse(() => empty23)).startMillis;
|
|
};
|
|
var end = (self2) => {
|
|
return pipe(self2.intervals, head2, getOrElse(() => empty23)).endMillis;
|
|
};
|
|
var lessThan4 = /* @__PURE__ */ dual(2, (self2, that) => start(self2) < start(that));
|
|
var isNonEmpty3 = (self2) => {
|
|
return isNonEmpty(self2.intervals);
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/ScheduleIntervals.js
|
|
var make34 = make33;
|
|
var intersect5 = intersect4;
|
|
var start2 = start;
|
|
var end2 = end;
|
|
var lessThan5 = lessThan4;
|
|
var isNonEmpty4 = isNonEmpty3;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/schedule/decision.js
|
|
var OP_CONTINUE = "Continue";
|
|
var OP_DONE2 = "Done";
|
|
var _continue = (intervals) => {
|
|
return {
|
|
_tag: OP_CONTINUE,
|
|
intervals
|
|
};
|
|
};
|
|
var continueWith = (interval) => {
|
|
return {
|
|
_tag: OP_CONTINUE,
|
|
intervals: make34(of2(interval))
|
|
};
|
|
};
|
|
var done4 = {
|
|
_tag: OP_DONE2
|
|
};
|
|
var isContinue = (self2) => {
|
|
return self2._tag === OP_CONTINUE;
|
|
};
|
|
var isDone4 = (self2) => {
|
|
return self2._tag === OP_DONE2;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/ScheduleDecision.js
|
|
var _continue2 = _continue;
|
|
var continueWith2 = continueWith;
|
|
var done5 = done4;
|
|
var isContinue2 = isContinue;
|
|
var isDone5 = isDone4;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Scope.js
|
|
var addFinalizer2 = scopeAddFinalizer;
|
|
var addFinalizerExit = scopeAddFinalizerExit;
|
|
var close = scopeClose;
|
|
var extend2 = scopeExtend;
|
|
var fork = scopeFork;
|
|
var make35 = scopeMake;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/effect/circular.js
|
|
class Semaphore {
|
|
permits;
|
|
waiters = /* @__PURE__ */ new Set;
|
|
taken = 0;
|
|
constructor(permits) {
|
|
this.permits = permits;
|
|
}
|
|
get free() {
|
|
return this.permits - this.taken;
|
|
}
|
|
take = (n) => asyncInterrupt((resume) => {
|
|
if (this.free < n) {
|
|
const observer = () => {
|
|
if (this.free < n)
|
|
return;
|
|
this.waiters.delete(observer);
|
|
resume(suspend(() => {
|
|
if (this.free < n)
|
|
return this.take(n);
|
|
this.taken += n;
|
|
return succeed(n);
|
|
}));
|
|
};
|
|
this.waiters.add(observer);
|
|
return sync(() => {
|
|
this.waiters.delete(observer);
|
|
});
|
|
}
|
|
resume(suspend(() => {
|
|
if (this.free < n)
|
|
return this.take(n);
|
|
this.taken += n;
|
|
return succeed(n);
|
|
}));
|
|
});
|
|
updateTakenUnsafe(fiber, f) {
|
|
this.taken = f(this.taken);
|
|
if (this.waiters.size > 0) {
|
|
fiber.getFiberRef(currentScheduler).scheduleTask(() => {
|
|
const iter = this.waiters.values();
|
|
let item = iter.next();
|
|
while (item.done === false && this.free > 0) {
|
|
item.value();
|
|
item = iter.next();
|
|
}
|
|
}, fiber.getFiberRef(currentSchedulingPriority), fiber);
|
|
}
|
|
return succeed(this.free);
|
|
}
|
|
updateTaken(f) {
|
|
return withFiberRuntime((fiber) => this.updateTakenUnsafe(fiber, f));
|
|
}
|
|
resize = (permits) => asVoid(withFiberRuntime((fiber) => {
|
|
this.permits = permits;
|
|
if (this.free < 0) {
|
|
return void_;
|
|
}
|
|
return this.updateTakenUnsafe(fiber, (taken) => taken);
|
|
}));
|
|
release = (n) => this.updateTaken((taken) => taken - n);
|
|
releaseAll = /* @__PURE__ */ this.updateTaken((_) => 0);
|
|
withPermits = (n) => (self2) => uninterruptibleMask((restore) => flatMap7(restore(this.take(n)), (permits) => ensuring(restore(self2), this.release(permits))));
|
|
withPermitsIfAvailable = (n) => (self2) => uninterruptibleMask((restore) => suspend(() => {
|
|
if (this.free < n) {
|
|
return succeedNone;
|
|
}
|
|
this.taken += n;
|
|
return ensuring(restore(asSome(self2)), this.release(n));
|
|
}));
|
|
}
|
|
var unsafeMakeSemaphore = (permits) => new Semaphore(permits);
|
|
var makeSemaphore = (permits) => sync(() => unsafeMakeSemaphore(permits));
|
|
var forkIn = /* @__PURE__ */ dual(2, (self2, scope) => withFiberRuntime((parent, parentStatus) => {
|
|
const scopeImpl = scope;
|
|
const fiber = unsafeFork(self2, parent, parentStatus.runtimeFlags, globalScope);
|
|
if (scopeImpl.state._tag === "Open") {
|
|
const finalizer = () => fiberIdWith((fiberId) => equals(fiberId, fiber.id()) ? void_ : asVoid(interruptFiber(fiber)));
|
|
const key = {};
|
|
scopeImpl.state.finalizers.set(key, finalizer);
|
|
fiber.addObserver(() => {
|
|
if (scopeImpl.state._tag === "Closed")
|
|
return;
|
|
scopeImpl.state.finalizers.delete(key);
|
|
});
|
|
} else {
|
|
fiber.unsafeInterruptAsFork(parent.id());
|
|
}
|
|
return succeed(fiber);
|
|
}));
|
|
var forkScoped = (self2) => scopeWith((scope) => forkIn(self2, scope));
|
|
var SynchronizedSymbolKey = "effect/Ref/SynchronizedRef";
|
|
var SynchronizedTypeId = /* @__PURE__ */ Symbol.for(SynchronizedSymbolKey);
|
|
var synchronizedVariance = {
|
|
_A: (_) => _
|
|
};
|
|
|
|
class SynchronizedImpl extends Class {
|
|
ref;
|
|
withLock;
|
|
[SynchronizedTypeId] = synchronizedVariance;
|
|
[RefTypeId] = refVariance;
|
|
[TypeId10] = TypeId10;
|
|
constructor(ref, withLock) {
|
|
super();
|
|
this.ref = ref;
|
|
this.withLock = withLock;
|
|
this.get = get9(this.ref);
|
|
}
|
|
get;
|
|
commit() {
|
|
return this.get;
|
|
}
|
|
modify(f) {
|
|
return this.modifyEffect((a) => succeed(f(a)));
|
|
}
|
|
modifyEffect(f) {
|
|
return this.withLock(pipe(flatMap7(get9(this.ref), f), flatMap7(([b, a]) => as(set4(this.ref, a), b))));
|
|
}
|
|
}
|
|
var makeSynchronized = (value) => sync(() => unsafeMakeSynchronized(value));
|
|
var unsafeMakeSynchronized = (value) => {
|
|
const ref = unsafeMake4(value);
|
|
const sem = unsafeMakeSemaphore(1);
|
|
return new SynchronizedImpl(ref, sem.withPermits(1));
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/managedRuntime/circular.js
|
|
var TypeId12 = /* @__PURE__ */ Symbol.for("effect/ManagedRuntime");
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/opCodes/layer.js
|
|
var OP_FRESH = "Fresh";
|
|
var OP_FROM_EFFECT = "FromEffect";
|
|
var OP_MERGE_ALL = "MergeAll";
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Fiber.js
|
|
var _await3 = _await2;
|
|
var inheritAll2 = inheritAll;
|
|
var interrupt4 = interruptFiber;
|
|
var interruptAs = interruptAsFiber;
|
|
var join3 = join2;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/runtime.js
|
|
var makeDual = (f) => function() {
|
|
if (arguments.length === 1) {
|
|
const runtime = arguments[0];
|
|
return (effect, ...args) => f(runtime, effect, ...args);
|
|
}
|
|
return f.apply(this, arguments);
|
|
};
|
|
var unsafeFork2 = /* @__PURE__ */ makeDual((runtime, self2, options) => {
|
|
const fiberId = unsafeMake2();
|
|
const fiberRefUpdates = [[currentContext, [[fiberId, runtime.context]]]];
|
|
if (options?.scheduler) {
|
|
fiberRefUpdates.push([currentScheduler, [[fiberId, options.scheduler]]]);
|
|
}
|
|
let fiberRefs = updateManyAs2(runtime.fiberRefs, {
|
|
entries: fiberRefUpdates,
|
|
forkAs: fiberId
|
|
});
|
|
if (options?.updateRefs) {
|
|
fiberRefs = options.updateRefs(fiberRefs, fiberId);
|
|
}
|
|
const fiberRuntime = new FiberRuntime(fiberId, fiberRefs, runtime.runtimeFlags);
|
|
let effect = self2;
|
|
if (options?.scope) {
|
|
effect = flatMap7(fork(options.scope, sequential2), (closeableScope) => zipRight(scopeAddFinalizer(closeableScope, fiberIdWith((id) => equals(id, fiberRuntime.id()) ? void_ : interruptAsFiber(fiberRuntime, id))), onExit(self2, (exit) => close(closeableScope, exit))));
|
|
}
|
|
const supervisor = fiberRuntime.currentSupervisor;
|
|
if (supervisor !== none7) {
|
|
supervisor.onStart(runtime.context, effect, none2(), fiberRuntime);
|
|
fiberRuntime.addObserver((exit) => supervisor.onEnd(exit, fiberRuntime));
|
|
}
|
|
globalScope.add(runtime.runtimeFlags, fiberRuntime);
|
|
if (options?.immediate === false) {
|
|
fiberRuntime.resume(effect);
|
|
} else {
|
|
fiberRuntime.start(effect);
|
|
}
|
|
return fiberRuntime;
|
|
});
|
|
var unsafeRunSync = /* @__PURE__ */ makeDual((runtime, effect) => {
|
|
const result = unsafeRunSyncExit(runtime)(effect);
|
|
if (result._tag === "Failure") {
|
|
throw fiberFailure(result.effect_instruction_i0);
|
|
}
|
|
return result.effect_instruction_i0;
|
|
});
|
|
|
|
class AsyncFiberExceptionImpl extends Error {
|
|
fiber;
|
|
_tag = "AsyncFiberException";
|
|
constructor(fiber) {
|
|
super(`Fiber #${fiber.id().id} cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work`);
|
|
this.fiber = fiber;
|
|
this.name = this._tag;
|
|
this.stack = this.message;
|
|
}
|
|
}
|
|
var asyncFiberException = (fiber) => {
|
|
const limit = Error.stackTraceLimit;
|
|
Error.stackTraceLimit = 0;
|
|
const error = new AsyncFiberExceptionImpl(fiber);
|
|
Error.stackTraceLimit = limit;
|
|
return error;
|
|
};
|
|
var FiberFailureId = /* @__PURE__ */ Symbol.for("effect/Runtime/FiberFailure");
|
|
var FiberFailureCauseId = /* @__PURE__ */ Symbol.for("effect/Runtime/FiberFailure/Cause");
|
|
|
|
class FiberFailureImpl extends Error {
|
|
[FiberFailureId];
|
|
[FiberFailureCauseId];
|
|
constructor(cause) {
|
|
const head = prettyErrors(cause)[0];
|
|
super(head?.message || "An error has occurred");
|
|
this[FiberFailureId] = FiberFailureId;
|
|
this[FiberFailureCauseId] = cause;
|
|
this.name = head ? `(FiberFailure) ${head.name}` : "FiberFailure";
|
|
if (head?.stack) {
|
|
this.stack = head.stack;
|
|
}
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_id: "FiberFailure",
|
|
cause: this[FiberFailureCauseId].toJSON()
|
|
};
|
|
}
|
|
toString() {
|
|
return "(FiberFailure) " + pretty(this[FiberFailureCauseId], {
|
|
renderErrorCause: true
|
|
});
|
|
}
|
|
[NodeInspectSymbol]() {
|
|
return this.toString();
|
|
}
|
|
}
|
|
var fiberFailure = (cause) => {
|
|
const limit = Error.stackTraceLimit;
|
|
Error.stackTraceLimit = 0;
|
|
const error = new FiberFailureImpl(cause);
|
|
Error.stackTraceLimit = limit;
|
|
return error;
|
|
};
|
|
var fastPath = (effect) => {
|
|
const op = effect;
|
|
switch (op._op) {
|
|
case "Failure":
|
|
case "Success": {
|
|
return op;
|
|
}
|
|
case "Left": {
|
|
return exitFail(op.left);
|
|
}
|
|
case "Right": {
|
|
return exitSucceed(op.right);
|
|
}
|
|
case "Some": {
|
|
return exitSucceed(op.value);
|
|
}
|
|
case "None": {
|
|
return exitFail(new NoSuchElementException);
|
|
}
|
|
}
|
|
};
|
|
var unsafeRunSyncExit = /* @__PURE__ */ makeDual((runtime, effect) => {
|
|
const op = fastPath(effect);
|
|
if (op) {
|
|
return op;
|
|
}
|
|
const scheduler = new SyncScheduler;
|
|
const fiberRuntime = unsafeFork2(runtime)(effect, {
|
|
scheduler
|
|
});
|
|
scheduler.flush();
|
|
const result = fiberRuntime.unsafePoll();
|
|
if (result) {
|
|
return result;
|
|
}
|
|
return exitDie(capture(asyncFiberException(fiberRuntime), currentSpanFromFiber(fiberRuntime)));
|
|
});
|
|
var unsafeRunPromise = /* @__PURE__ */ makeDual((runtime, effect, options) => unsafeRunPromiseExit(runtime, effect, options).then((result) => {
|
|
switch (result._tag) {
|
|
case OP_SUCCESS: {
|
|
return result.effect_instruction_i0;
|
|
}
|
|
case OP_FAILURE: {
|
|
throw fiberFailure(result.effect_instruction_i0);
|
|
}
|
|
}
|
|
}));
|
|
var unsafeRunPromiseExit = /* @__PURE__ */ makeDual((runtime, effect, options) => new Promise((resolve) => {
|
|
const op = fastPath(effect);
|
|
if (op) {
|
|
resolve(op);
|
|
}
|
|
const fiber = unsafeFork2(runtime)(effect);
|
|
fiber.addObserver((exit) => {
|
|
resolve(exit);
|
|
});
|
|
if (options?.signal !== undefined) {
|
|
if (options.signal.aborted) {
|
|
fiber.unsafeInterruptAsFork(fiber.id());
|
|
} else {
|
|
options.signal.addEventListener("abort", () => {
|
|
fiber.unsafeInterruptAsFork(fiber.id());
|
|
}, {
|
|
once: true
|
|
});
|
|
}
|
|
}
|
|
}));
|
|
|
|
class RuntimeImpl {
|
|
context;
|
|
runtimeFlags;
|
|
fiberRefs;
|
|
constructor(context, runtimeFlags, fiberRefs) {
|
|
this.context = context;
|
|
this.runtimeFlags = runtimeFlags;
|
|
this.fiberRefs = fiberRefs;
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
}
|
|
var make36 = (options) => new RuntimeImpl(options.context, options.runtimeFlags, options.fiberRefs);
|
|
var runtime2 = () => withFiberRuntime((state, status) => succeed(new RuntimeImpl(state.getFiberRef(currentContext), status.runtimeFlags, state.getFiberRefs())));
|
|
var defaultRuntimeFlags = /* @__PURE__ */ make16(Interruption, CooperativeYielding, RuntimeMetrics);
|
|
var defaultRuntime = /* @__PURE__ */ make36({
|
|
context: /* @__PURE__ */ empty3(),
|
|
runtimeFlags: defaultRuntimeFlags,
|
|
fiberRefs: /* @__PURE__ */ empty17()
|
|
});
|
|
var unsafeForkEffect = /* @__PURE__ */ unsafeFork2(defaultRuntime);
|
|
var unsafeRunPromiseEffect = /* @__PURE__ */ unsafeRunPromise(defaultRuntime);
|
|
var unsafeRunSyncEffect = /* @__PURE__ */ unsafeRunSync(defaultRuntime);
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/synchronizedRef.js
|
|
var modifyEffect = /* @__PURE__ */ dual(2, (self2, f) => self2.modifyEffect(f));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/layer.js
|
|
var LayerSymbolKey = "effect/Layer";
|
|
var LayerTypeId = /* @__PURE__ */ Symbol.for(LayerSymbolKey);
|
|
var layerVariance = {
|
|
_RIn: (_) => _,
|
|
_E: (_) => _,
|
|
_ROut: (_) => _
|
|
};
|
|
var proto3 = {
|
|
[LayerTypeId]: layerVariance,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var MemoMapTypeIdKey = "effect/Layer/MemoMap";
|
|
var MemoMapTypeId = /* @__PURE__ */ Symbol.for(MemoMapTypeIdKey);
|
|
var CurrentMemoMap = /* @__PURE__ */ Reference2()("effect/Layer/CurrentMemoMap", {
|
|
defaultValue: () => unsafeMakeMemoMap()
|
|
});
|
|
var isLayer = (u) => hasProperty(u, LayerTypeId);
|
|
var isFresh = (self2) => {
|
|
return self2._op_layer === OP_FRESH;
|
|
};
|
|
|
|
class MemoMapImpl {
|
|
ref;
|
|
[MemoMapTypeId];
|
|
constructor(ref) {
|
|
this.ref = ref;
|
|
this[MemoMapTypeId] = MemoMapTypeId;
|
|
}
|
|
getOrElseMemoize(layer, scope) {
|
|
return pipe(modifyEffect(this.ref, (map) => {
|
|
const inMap = map.get(layer);
|
|
if (inMap !== undefined) {
|
|
const [acquire, release] = inMap;
|
|
const cached = pipe(acquire, flatMap7(([patch, b]) => pipe(patchFiberRefs(patch), as(b))), onExit(exitMatch({
|
|
onFailure: () => void_,
|
|
onSuccess: () => scopeAddFinalizerExit(scope, release)
|
|
})));
|
|
return succeed([cached, map]);
|
|
}
|
|
return pipe(make24(0), flatMap7((observers) => pipe(deferredMake(), flatMap7((deferred) => pipe(make24(() => void_), map10((finalizerRef) => {
|
|
const resource = uninterruptibleMask((restore) => pipe(scopeMake(), flatMap7((innerScope) => pipe(restore(flatMap7(makeBuilder(layer, innerScope, true), (f) => diffFiberRefs(f(this)))), exit, flatMap7((exit) => {
|
|
switch (exit._tag) {
|
|
case OP_FAILURE: {
|
|
return pipe(deferredFailCause(deferred, exit.effect_instruction_i0), zipRight(scopeClose(innerScope, exit)), zipRight(failCause(exit.effect_instruction_i0)));
|
|
}
|
|
case OP_SUCCESS: {
|
|
return pipe(set4(finalizerRef, (exit) => pipe(scopeClose(innerScope, exit), whenEffect(modify3(observers, (n) => [n === 1, n - 1])), asVoid)), zipRight(update2(observers, (n) => n + 1)), zipRight(scopeAddFinalizerExit(scope, (exit) => pipe(sync(() => map.delete(layer)), zipRight(get9(finalizerRef)), flatMap7((finalizer) => finalizer(exit))))), zipRight(deferredSucceed(deferred, exit.effect_instruction_i0)), as(exit.effect_instruction_i0[1]));
|
|
}
|
|
}
|
|
})))));
|
|
const memoized = [pipe(deferredAwait(deferred), onExit(exitMatchEffect({
|
|
onFailure: () => void_,
|
|
onSuccess: () => update2(observers, (n) => n + 1)
|
|
}))), (exit) => pipe(get9(finalizerRef), flatMap7((finalizer) => finalizer(exit)))];
|
|
return [resource, isFresh(layer) ? map : map.set(layer, memoized)];
|
|
}))))));
|
|
}), flatten3);
|
|
}
|
|
}
|
|
var makeMemoMap = /* @__PURE__ */ suspend(() => map10(makeSynchronized(new Map), (ref) => new MemoMapImpl(ref)));
|
|
var unsafeMakeMemoMap = () => new MemoMapImpl(unsafeMakeSynchronized(new Map));
|
|
var buildWithScope = /* @__PURE__ */ dual(2, (self2, scope) => flatMap7(makeMemoMap, (memoMap) => buildWithMemoMap(self2, memoMap, scope)));
|
|
var buildWithMemoMap = /* @__PURE__ */ dual(3, (self2, memoMap, scope) => flatMap7(makeBuilder(self2, scope), (run) => provideService(run(memoMap), CurrentMemoMap, memoMap)));
|
|
var makeBuilder = (self2, scope, inMemoMap = false) => {
|
|
const op = self2;
|
|
switch (op._op_layer) {
|
|
case "Locally": {
|
|
return sync(() => (memoMap) => op.f(memoMap.getOrElseMemoize(op.self, scope)));
|
|
}
|
|
case "ExtendScope": {
|
|
return sync(() => (memoMap) => scopeWith((scope) => memoMap.getOrElseMemoize(op.layer, scope)));
|
|
}
|
|
case "Fold": {
|
|
return sync(() => (memoMap) => pipe(memoMap.getOrElseMemoize(op.layer, scope), matchCauseEffect({
|
|
onFailure: (cause) => memoMap.getOrElseMemoize(op.failureK(cause), scope),
|
|
onSuccess: (value) => memoMap.getOrElseMemoize(op.successK(value), scope)
|
|
})));
|
|
}
|
|
case "Fresh": {
|
|
return sync(() => (_) => pipe(op.layer, buildWithScope(scope)));
|
|
}
|
|
case "FromEffect": {
|
|
return inMemoMap ? sync(() => (_) => op.effect) : sync(() => (memoMap) => memoMap.getOrElseMemoize(self2, scope));
|
|
}
|
|
case "Provide": {
|
|
return sync(() => (memoMap) => pipe(memoMap.getOrElseMemoize(op.first, scope), flatMap7((env) => pipe(memoMap.getOrElseMemoize(op.second, scope), provideContext(env)))));
|
|
}
|
|
case "Scoped": {
|
|
return inMemoMap ? sync(() => (_) => scopeExtend(op.effect, scope)) : sync(() => (memoMap) => memoMap.getOrElseMemoize(self2, scope));
|
|
}
|
|
case "Suspend": {
|
|
return sync(() => (memoMap) => memoMap.getOrElseMemoize(op.evaluate(), scope));
|
|
}
|
|
case "ProvideMerge": {
|
|
return sync(() => (memoMap) => pipe(memoMap.getOrElseMemoize(op.first, scope), zipWith2(memoMap.getOrElseMemoize(op.second, scope), op.zipK)));
|
|
}
|
|
case "ZipWith": {
|
|
return gen(function* () {
|
|
const parallelScope = yield* scopeFork(scope, parallel2);
|
|
const firstScope = yield* scopeFork(parallelScope, sequential2);
|
|
const secondScope = yield* scopeFork(parallelScope, sequential2);
|
|
return (memoMap) => pipe(memoMap.getOrElseMemoize(op.first, firstScope), zipWithOptions(memoMap.getOrElseMemoize(op.second, secondScope), op.zipK, {
|
|
concurrent: true
|
|
}));
|
|
});
|
|
}
|
|
case "MergeAll": {
|
|
const layers = op.layers;
|
|
return map10(scopeFork(scope, parallel2), (parallelScope) => (memoMap) => {
|
|
const contexts = new Array(layers.length);
|
|
return map10(forEachConcurrentDiscard(layers, fnUntraced(function* (layer, i) {
|
|
const scope = yield* scopeFork(parallelScope, sequential2);
|
|
const context = yield* memoMap.getOrElseMemoize(layer, scope);
|
|
contexts[i] = context;
|
|
}), false, false), () => mergeAll2(...contexts));
|
|
});
|
|
}
|
|
}
|
|
};
|
|
var fromEffect3 = /* @__PURE__ */ dual(2, (a, b) => {
|
|
const tagFirst = isTag2(a);
|
|
const tag = tagFirst ? a : b;
|
|
const effect = tagFirst ? b : a;
|
|
return fromEffectContext(map10(effect, (service) => make5(tag, service)));
|
|
});
|
|
function fromEffectContext(effect) {
|
|
const fromEffect = Object.create(proto3);
|
|
fromEffect._op_layer = OP_FROM_EFFECT;
|
|
fromEffect.effect = effect;
|
|
return fromEffect;
|
|
}
|
|
var mergeAll3 = (...layers) => {
|
|
const mergeAll = Object.create(proto3);
|
|
mergeAll._op_layer = OP_MERGE_ALL;
|
|
mergeAll.layers = layers;
|
|
return mergeAll;
|
|
};
|
|
var succeed6 = /* @__PURE__ */ dual(2, (a, b) => {
|
|
const tagFirst = isTag2(a);
|
|
const tag = tagFirst ? a : b;
|
|
const resource = tagFirst ? b : a;
|
|
return fromEffectContext(succeed(make5(tag, resource)));
|
|
});
|
|
var provideSomeLayer = /* @__PURE__ */ dual(2, (self2, layer) => scopedWith((scope) => flatMap7(buildWithScope(layer, scope), (context) => provideSomeContext(self2, context))));
|
|
var provideSomeRuntime = /* @__PURE__ */ dual(2, (self2, rt) => {
|
|
const patchRefs = diff6(defaultRuntime.fiberRefs, rt.fiberRefs);
|
|
const patchFlags = diff4(defaultRuntime.runtimeFlags, rt.runtimeFlags);
|
|
return uninterruptibleMask((restore) => withFiberRuntime((fiber) => {
|
|
const oldContext = fiber.getFiberRef(currentContext);
|
|
const oldRefs = fiber.getFiberRefs();
|
|
const newRefs = patch7(fiber.id(), oldRefs)(patchRefs);
|
|
const oldFlags = fiber.currentRuntimeFlags;
|
|
const newFlags = patch4(patchFlags)(oldFlags);
|
|
const rollbackRefs = diff6(newRefs, oldRefs);
|
|
const rollbackFlags = diff4(newFlags, oldFlags);
|
|
fiber.setFiberRefs(newRefs);
|
|
fiber.currentRuntimeFlags = newFlags;
|
|
return ensuring(provideSomeContext(restore(self2), merge3(oldContext, rt.context)), withFiberRuntime((fiber) => {
|
|
fiber.setFiberRefs(patch7(fiber.id(), fiber.getFiberRefs())(rollbackRefs));
|
|
fiber.currentRuntimeFlags = patch4(rollbackFlags)(fiber.currentRuntimeFlags);
|
|
return void_;
|
|
}));
|
|
}));
|
|
});
|
|
var effect_provide = /* @__PURE__ */ dual(2, (self2, source) => {
|
|
if (Array.isArray(source)) {
|
|
return provideSomeLayer(self2, mergeAll3(...source));
|
|
} else if (isLayer(source)) {
|
|
return provideSomeLayer(self2, source);
|
|
} else if (isContext2(source)) {
|
|
return provideSomeContext(self2, source);
|
|
} else if (TypeId12 in source) {
|
|
return flatMap7(source.runtimeEffect, (rt) => provideSomeRuntime(self2, rt));
|
|
} else {
|
|
return provideSomeRuntime(self2, source);
|
|
}
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/schedule.js
|
|
var ScheduleSymbolKey = "effect/Schedule";
|
|
var ScheduleTypeId = /* @__PURE__ */ Symbol.for(ScheduleSymbolKey);
|
|
var isSchedule = (u) => hasProperty(u, ScheduleTypeId);
|
|
var ScheduleDriverSymbolKey = "effect/ScheduleDriver";
|
|
var ScheduleDriverTypeId = /* @__PURE__ */ Symbol.for(ScheduleDriverSymbolKey);
|
|
var defaultIterationMetadata = {
|
|
start: 0,
|
|
now: 0,
|
|
input: undefined,
|
|
output: undefined,
|
|
elapsed: zero,
|
|
elapsedSincePrevious: zero,
|
|
recurrence: 0
|
|
};
|
|
var CurrentIterationMetadata = /* @__PURE__ */ Reference2()("effect/Schedule/CurrentIterationMetadata", {
|
|
defaultValue: () => defaultIterationMetadata
|
|
});
|
|
var scheduleVariance = {
|
|
_Out: (_) => _,
|
|
_In: (_) => _,
|
|
_R: (_) => _
|
|
};
|
|
var scheduleDriverVariance = {
|
|
_Out: (_) => _,
|
|
_In: (_) => _,
|
|
_R: (_) => _
|
|
};
|
|
|
|
class ScheduleImpl {
|
|
initial;
|
|
step;
|
|
[ScheduleTypeId] = scheduleVariance;
|
|
constructor(initial, step) {
|
|
this.initial = initial;
|
|
this.step = step;
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
}
|
|
var updateInfo = (iterationMetaRef, now, input, output) => update2(iterationMetaRef, (prev) => prev.recurrence === 0 ? {
|
|
now,
|
|
input,
|
|
output,
|
|
recurrence: prev.recurrence + 1,
|
|
elapsed: zero,
|
|
elapsedSincePrevious: zero,
|
|
start: now
|
|
} : {
|
|
now,
|
|
input,
|
|
output,
|
|
recurrence: prev.recurrence + 1,
|
|
elapsed: millis(now - prev.start),
|
|
elapsedSincePrevious: millis(now - prev.now),
|
|
start: prev.start
|
|
});
|
|
|
|
class ScheduleDriverImpl {
|
|
schedule;
|
|
ref;
|
|
[ScheduleDriverTypeId] = scheduleDriverVariance;
|
|
constructor(schedule, ref) {
|
|
this.schedule = schedule;
|
|
this.ref = ref;
|
|
}
|
|
get state() {
|
|
return map10(get9(this.ref), (tuple) => tuple[1]);
|
|
}
|
|
get last() {
|
|
return flatMap7(get9(this.ref), ([element, _]) => {
|
|
switch (element._tag) {
|
|
case "None": {
|
|
return failSync(() => new NoSuchElementException);
|
|
}
|
|
case "Some": {
|
|
return succeed(element.value);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
iterationMeta = /* @__PURE__ */ unsafeMake4(defaultIterationMetadata);
|
|
get reset() {
|
|
return set4(this.ref, [none2(), this.schedule.initial]).pipe(zipLeft(set4(this.iterationMeta, defaultIterationMetadata)));
|
|
}
|
|
next(input) {
|
|
return pipe(map10(get9(this.ref), (tuple) => tuple[1]), flatMap7((state) => pipe(currentTimeMillis2, flatMap7((now) => pipe(suspend(() => this.schedule.step(now, input, state)), flatMap7(([state, out, decision]) => {
|
|
const setState = set4(this.ref, [some2(out), state]);
|
|
if (isDone5(decision)) {
|
|
return setState.pipe(zipRight(fail2(none2())));
|
|
}
|
|
const millis2 = start2(decision.intervals) - now;
|
|
if (millis2 <= 0) {
|
|
return setState.pipe(zipRight(updateInfo(this.iterationMeta, now, input, out)), as(out));
|
|
}
|
|
const duration = millis(millis2);
|
|
return pipe(setState, zipRight(updateInfo(this.iterationMeta, now, input, out)), zipRight(sleep3(duration)), as(out));
|
|
}))))));
|
|
}
|
|
}
|
|
var makeWithState = (initial, step) => new ScheduleImpl(initial, step);
|
|
var check = /* @__PURE__ */ dual(2, (self2, test) => checkEffect(self2, (input, out) => sync(() => test(input, out))));
|
|
var checkEffect = /* @__PURE__ */ dual(2, (self2, test) => makeWithState(self2.initial, (now, input, state) => flatMap7(self2.step(now, input, state), ([state, out, decision]) => {
|
|
if (isDone5(decision)) {
|
|
return succeed([state, out, done5]);
|
|
}
|
|
return map10(test(input, out), (cont) => cont ? [state, out, decision] : [state, out, done5]);
|
|
})));
|
|
var driver = (self2) => pipe(make24([none2(), self2.initial]), map10((ref) => new ScheduleDriverImpl(self2, ref)));
|
|
var intersect6 = /* @__PURE__ */ dual(2, (self2, that) => intersectWith(self2, that, intersect5));
|
|
var intersectWith = /* @__PURE__ */ dual(3, (self2, that, f) => makeWithState([self2.initial, that.initial], (now, input, state) => pipe(zipWith2(self2.step(now, input, state[0]), that.step(now, input, state[1]), (a, b) => [a, b]), flatMap7(([[lState, out, lDecision], [rState, out2, rDecision]]) => {
|
|
if (isContinue2(lDecision) && isContinue2(rDecision)) {
|
|
return intersectWithLoop(self2, that, input, lState, out, lDecision.intervals, rState, out2, rDecision.intervals, f);
|
|
}
|
|
return succeed([[lState, rState], [out, out2], done5]);
|
|
}))));
|
|
var intersectWithLoop = (self2, that, input, lState, out, lInterval, rState, out2, rInterval, f) => {
|
|
const combined = f(lInterval, rInterval);
|
|
if (isNonEmpty4(combined)) {
|
|
return succeed([[lState, rState], [out, out2], _continue2(combined)]);
|
|
}
|
|
if (pipe(lInterval, lessThan5(rInterval))) {
|
|
return flatMap7(self2.step(end2(lInterval), input, lState), ([lState, out, decision]) => {
|
|
if (isDone5(decision)) {
|
|
return succeed([[lState, rState], [out, out2], done5]);
|
|
}
|
|
return intersectWithLoop(self2, that, input, lState, out, decision.intervals, rState, out2, rInterval, f);
|
|
});
|
|
}
|
|
return flatMap7(that.step(end2(rInterval), input, rState), ([rState, out2, decision]) => {
|
|
if (isDone5(decision)) {
|
|
return succeed([[lState, rState], [out, out2], done5]);
|
|
}
|
|
return intersectWithLoop(self2, that, input, lState, out, lInterval, rState, out2, decision.intervals, f);
|
|
});
|
|
};
|
|
var map14 = /* @__PURE__ */ dual(2, (self2, f) => mapEffect2(self2, (out) => sync(() => f(out))));
|
|
var mapEffect2 = /* @__PURE__ */ dual(2, (self2, f) => makeWithState(self2.initial, (now, input, state) => flatMap7(self2.step(now, input, state), ([state, out, decision]) => map10(f(out), (out2) => [state, out2, decision]))));
|
|
var passthrough = (self2) => makeWithState(self2.initial, (now, input, state) => pipe(self2.step(now, input, state), map10(([state, _, decision]) => [state, input, decision])));
|
|
var recurs = (n) => whileOutput(forever2, (out) => out < n);
|
|
var unfold2 = (initial, f) => makeWithState(initial, (now, _, state) => sync(() => [f(state), state, continueWith2(after2(now))]));
|
|
var untilInputEffect = /* @__PURE__ */ dual(2, (self2, f) => checkEffect(self2, (input, _) => negate(f(input))));
|
|
var whileInputEffect = /* @__PURE__ */ dual(2, (self2, f) => checkEffect(self2, (input, _) => f(input)));
|
|
var whileOutput = /* @__PURE__ */ dual(2, (self2, f) => check(self2, (_, out) => f(out)));
|
|
var ScheduleDefectTypeId = /* @__PURE__ */ Symbol.for("effect/Schedule/ScheduleDefect");
|
|
|
|
class ScheduleDefect {
|
|
error;
|
|
[ScheduleDefectTypeId];
|
|
constructor(error) {
|
|
this.error = error;
|
|
this[ScheduleDefectTypeId] = ScheduleDefectTypeId;
|
|
}
|
|
}
|
|
var isScheduleDefect = (u) => hasProperty(u, ScheduleDefectTypeId);
|
|
var scheduleDefectWrap = (self2) => catchAll(self2, (e) => die2(new ScheduleDefect(e)));
|
|
var scheduleDefectRefailCause = (cause) => match2(find(cause, (_) => isDieType(_) && isScheduleDefect(_.defect) ? some2(_.defect) : none2()), {
|
|
onNone: () => cause,
|
|
onSome: (error) => fail(error.error)
|
|
});
|
|
var scheduleDefectRefail = (effect) => catchAllCause(effect, (cause) => failCause(scheduleDefectRefailCause(cause)));
|
|
var repeat_Effect = /* @__PURE__ */ dual(2, (self2, schedule) => repeatOrElse_Effect(self2, schedule, (e, _) => fail2(e)));
|
|
var repeat_combined = /* @__PURE__ */ dual(2, (self2, options) => {
|
|
if (isSchedule(options)) {
|
|
return repeat_Effect(self2, options);
|
|
}
|
|
const base = options.schedule ?? passthrough(forever2);
|
|
const withWhile = options.while ? whileInputEffect(base, (a) => {
|
|
const applied = options.while(a);
|
|
if (typeof applied === "boolean") {
|
|
return succeed(applied);
|
|
}
|
|
return scheduleDefectWrap(applied);
|
|
}) : base;
|
|
const withUntil = options.until ? untilInputEffect(withWhile, (a) => {
|
|
const applied = options.until(a);
|
|
if (typeof applied === "boolean") {
|
|
return succeed(applied);
|
|
}
|
|
return scheduleDefectWrap(applied);
|
|
}) : withWhile;
|
|
const withTimes = options.times ? intersect6(withUntil, recurs(options.times)).pipe(map14((intersectionPair) => intersectionPair[0])) : withUntil;
|
|
return scheduleDefectRefail(repeat_Effect(self2, withTimes));
|
|
});
|
|
var repeatOrElse_Effect = /* @__PURE__ */ dual(3, (self2, schedule, orElse) => flatMap7(driver(schedule), (driver) => matchEffect(self2, {
|
|
onFailure: (error) => orElse(error, none2()),
|
|
onSuccess: (value) => repeatOrElseEffectLoop(provideServiceEffect(self2, CurrentIterationMetadata, get9(driver.iterationMeta)), driver, (error, option) => provideServiceEffect(orElse(error, option), CurrentIterationMetadata, get9(driver.iterationMeta)), value)
|
|
})));
|
|
var repeatOrElseEffectLoop = (self2, driver, orElse, value) => matchEffect(driver.next(value), {
|
|
onFailure: () => orDie(driver.last),
|
|
onSuccess: (b) => matchEffect(self2, {
|
|
onFailure: (error) => orElse(error, some2(b)),
|
|
onSuccess: (value) => repeatOrElseEffectLoop(self2, driver, orElse, value)
|
|
})
|
|
});
|
|
var forever2 = /* @__PURE__ */ unfold2(0, (n) => n + 1);
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/MutableList.js
|
|
var TypeId13 = /* @__PURE__ */ Symbol.for("effect/MutableList");
|
|
var MutableListProto = {
|
|
[TypeId13]: TypeId13,
|
|
[Symbol.iterator]() {
|
|
let done = false;
|
|
let head = this.head;
|
|
return {
|
|
next() {
|
|
if (done) {
|
|
return this.return();
|
|
}
|
|
if (head == null) {
|
|
done = true;
|
|
return this.return();
|
|
}
|
|
const value = head.value;
|
|
head = head.next;
|
|
return {
|
|
done,
|
|
value
|
|
};
|
|
},
|
|
return(value) {
|
|
if (!done) {
|
|
done = true;
|
|
}
|
|
return {
|
|
done: true,
|
|
value
|
|
};
|
|
}
|
|
};
|
|
},
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
},
|
|
toJSON() {
|
|
return {
|
|
_id: "MutableList",
|
|
values: Array.from(this).map(toJSON)
|
|
};
|
|
},
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
},
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var makeNode = (value) => ({
|
|
value,
|
|
removed: false,
|
|
prev: undefined,
|
|
next: undefined
|
|
});
|
|
var empty25 = () => {
|
|
const list = Object.create(MutableListProto);
|
|
list.head = undefined;
|
|
list.tail = undefined;
|
|
list._length = 0;
|
|
return list;
|
|
};
|
|
var isEmpty8 = (self2) => length(self2) === 0;
|
|
var length = (self2) => self2._length;
|
|
var append3 = /* @__PURE__ */ dual(2, (self2, value) => {
|
|
const node = makeNode(value);
|
|
if (self2.head === undefined) {
|
|
self2.head = node;
|
|
}
|
|
if (self2.tail === undefined) {
|
|
self2.tail = node;
|
|
} else {
|
|
self2.tail.next = node;
|
|
node.prev = self2.tail;
|
|
self2.tail = node;
|
|
}
|
|
self2._length += 1;
|
|
return self2;
|
|
});
|
|
var shift = (self2) => {
|
|
const head = self2.head;
|
|
if (head !== undefined) {
|
|
remove5(self2, head);
|
|
return head.value;
|
|
}
|
|
return;
|
|
};
|
|
var remove5 = (self2, node) => {
|
|
if (node.removed) {
|
|
return;
|
|
}
|
|
node.removed = true;
|
|
if (node.prev !== undefined && node.next !== undefined) {
|
|
node.prev.next = node.next;
|
|
node.next.prev = node.prev;
|
|
} else if (node.prev !== undefined) {
|
|
self2.tail = node.prev;
|
|
node.prev.next = undefined;
|
|
} else if (node.next !== undefined) {
|
|
self2.head = node.next;
|
|
node.next.prev = undefined;
|
|
} else {
|
|
self2.tail = undefined;
|
|
self2.head = undefined;
|
|
}
|
|
if (self2._length > 0) {
|
|
self2._length -= 1;
|
|
}
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/MutableQueue.js
|
|
var TypeId14 = /* @__PURE__ */ Symbol.for("effect/MutableQueue");
|
|
var EmptyMutableQueue = /* @__PURE__ */ Symbol.for("effect/mutable/MutableQueue/Empty");
|
|
var MutableQueueProto = {
|
|
[TypeId14]: TypeId14,
|
|
[Symbol.iterator]() {
|
|
return Array.from(this.queue)[Symbol.iterator]();
|
|
},
|
|
toString() {
|
|
return format2(this.toJSON());
|
|
},
|
|
toJSON() {
|
|
return {
|
|
_id: "MutableQueue",
|
|
values: Array.from(this).map(toJSON)
|
|
};
|
|
},
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
},
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var make37 = (capacity) => {
|
|
const queue = Object.create(MutableQueueProto);
|
|
queue.queue = empty25();
|
|
queue.capacity = capacity;
|
|
return queue;
|
|
};
|
|
var bounded = (capacity) => make37(capacity);
|
|
var unbounded = () => make37(undefined);
|
|
var length2 = (self2) => length(self2.queue);
|
|
var isEmpty9 = (self2) => isEmpty8(self2.queue);
|
|
var capacity = (self2) => self2.capacity === undefined ? Infinity : self2.capacity;
|
|
var offer = /* @__PURE__ */ dual(2, (self2, value) => {
|
|
const queueLength = length(self2.queue);
|
|
if (self2.capacity !== undefined && queueLength === self2.capacity) {
|
|
return false;
|
|
}
|
|
append3(value)(self2.queue);
|
|
return true;
|
|
});
|
|
var offerAll = /* @__PURE__ */ dual(2, (self2, values) => {
|
|
const iterator = values[Symbol.iterator]();
|
|
let next;
|
|
let remainder = empty4();
|
|
let offering = true;
|
|
while (offering && (next = iterator.next()) && !next.done) {
|
|
offering = offer(next.value)(self2);
|
|
}
|
|
while (next != null && !next.done) {
|
|
remainder = prepend2(next.value)(remainder);
|
|
next = iterator.next();
|
|
}
|
|
return reverse2(remainder);
|
|
});
|
|
var poll2 = /* @__PURE__ */ dual(2, (self2, def) => {
|
|
if (isEmpty8(self2.queue)) {
|
|
return def;
|
|
}
|
|
return shift(self2.queue);
|
|
});
|
|
var pollUpTo = /* @__PURE__ */ dual(2, (self2, n) => {
|
|
let result = empty4();
|
|
let count = 0;
|
|
while (count < n) {
|
|
const element = poll2(EmptyMutableQueue)(self2);
|
|
if (element === EmptyMutableQueue) {
|
|
break;
|
|
}
|
|
result = prepend2(element)(result);
|
|
count += 1;
|
|
}
|
|
return reverse2(result);
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Effect.js
|
|
var isEffect2 = isEffect;
|
|
var all4 = all3;
|
|
var forEach4 = forEach3;
|
|
var async = async_;
|
|
var withFiberRuntime2 = withFiberRuntime;
|
|
var fail6 = fail2;
|
|
var failCause6 = failCause;
|
|
var die5 = die2;
|
|
var dieMessage2 = dieMessage;
|
|
var gen2 = gen;
|
|
var promise2 = promise;
|
|
var succeed7 = succeed;
|
|
var suspend2 = suspend;
|
|
var sync3 = sync;
|
|
var _void = void_;
|
|
var catchAll2 = catchAll;
|
|
var catchAllCause2 = catchAllCause;
|
|
var catchTag2 = catchTag;
|
|
var ignore2 = ignore;
|
|
var try_3 = try_2;
|
|
var tryMap2 = tryMap;
|
|
var tryPromise2 = tryPromise;
|
|
var interrupt5 = interrupt2;
|
|
var interruptible4 = interruptible2;
|
|
var uninterruptible2 = uninterruptible;
|
|
var uninterruptibleMask3 = uninterruptibleMask;
|
|
var as3 = as;
|
|
var asVoid2 = asVoid;
|
|
var map15 = map10;
|
|
var mapBoth3 = mapBoth;
|
|
var mapError2 = mapError;
|
|
var acquireRelease2 = acquireRelease;
|
|
var acquireUseRelease2 = acquireUseRelease;
|
|
var ensuring2 = ensuring;
|
|
var onError2 = onError;
|
|
var scope2 = scope;
|
|
var scopeWith2 = scopeWith;
|
|
var scopedWith2 = scopedWith;
|
|
var scoped2 = scopedEffect;
|
|
var fiberIdWith2 = fiberIdWith;
|
|
var forkDaemon2 = forkDaemon;
|
|
var forkIn2 = forkIn;
|
|
var forkScoped2 = forkScoped;
|
|
var provide2 = effect_provide;
|
|
var serviceOption2 = serviceOption;
|
|
var either3 = either2;
|
|
var exit2 = exit;
|
|
var intoDeferred2 = intoDeferred;
|
|
var when2 = when;
|
|
var flatMap9 = flatMap7;
|
|
var flatten5 = flatten3;
|
|
var race2 = race;
|
|
var raceWith2 = raceWith;
|
|
var tap2 = tap;
|
|
var tapErrorCause2 = tapErrorCause;
|
|
var repeat = repeat_combined;
|
|
var match11 = match8;
|
|
var matchCause2 = matchCause;
|
|
var matchCauseEffect3 = matchCauseEffect;
|
|
var matchEffect2 = matchEffect;
|
|
var orDie2 = orDie;
|
|
var runtime3 = runtime2;
|
|
var unsafeMakeSemaphore2 = unsafeMakeSemaphore;
|
|
var makeSemaphore2 = makeSemaphore;
|
|
var runFork2 = unsafeForkEffect;
|
|
var runPromise = unsafeRunPromiseEffect;
|
|
var runSync = unsafeRunSyncEffect;
|
|
var zip5 = zipOptions;
|
|
var zipLeft2 = zipLeftOptions;
|
|
var zipRight3 = zipRightOptions;
|
|
var zipWith3 = zipWithOptions;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Layer.js
|
|
var effect = fromEffect3;
|
|
var succeed8 = succeed6;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/queue.js
|
|
var EnqueueSymbolKey = "effect/QueueEnqueue";
|
|
var EnqueueTypeId = /* @__PURE__ */ Symbol.for(EnqueueSymbolKey);
|
|
var DequeueSymbolKey = "effect/QueueDequeue";
|
|
var DequeueTypeId = /* @__PURE__ */ Symbol.for(DequeueSymbolKey);
|
|
var QueueStrategySymbolKey = "effect/QueueStrategy";
|
|
var QueueStrategyTypeId = /* @__PURE__ */ Symbol.for(QueueStrategySymbolKey);
|
|
var BackingQueueSymbolKey = "effect/BackingQueue";
|
|
var BackingQueueTypeId = /* @__PURE__ */ Symbol.for(BackingQueueSymbolKey);
|
|
var queueStrategyVariance = {
|
|
_A: (_) => _
|
|
};
|
|
var backingQueueVariance = {
|
|
_A: (_) => _
|
|
};
|
|
var enqueueVariance = {
|
|
_In: (_) => _
|
|
};
|
|
var dequeueVariance = {
|
|
_Out: (_) => _
|
|
};
|
|
|
|
class QueueImpl extends Class {
|
|
queue;
|
|
takers;
|
|
shutdownHook;
|
|
shutdownFlag;
|
|
strategy;
|
|
[EnqueueTypeId] = enqueueVariance;
|
|
[DequeueTypeId] = dequeueVariance;
|
|
constructor(queue, takers, shutdownHook, shutdownFlag, strategy) {
|
|
super();
|
|
this.queue = queue;
|
|
this.takers = takers;
|
|
this.shutdownHook = shutdownHook;
|
|
this.shutdownFlag = shutdownFlag;
|
|
this.strategy = strategy;
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
commit() {
|
|
return this.take;
|
|
}
|
|
capacity() {
|
|
return this.queue.capacity();
|
|
}
|
|
get size() {
|
|
return suspend(() => catchAll(this.unsafeSize(), () => interrupt2));
|
|
}
|
|
unsafeSize() {
|
|
if (get6(this.shutdownFlag)) {
|
|
return none2();
|
|
}
|
|
return some2(this.queue.length() - length2(this.takers) + this.strategy.surplusSize());
|
|
}
|
|
get isEmpty() {
|
|
return map10(this.size, (size) => size <= 0);
|
|
}
|
|
get isFull() {
|
|
return map10(this.size, (size) => size >= this.capacity());
|
|
}
|
|
get shutdown() {
|
|
return uninterruptible(withFiberRuntime((state) => {
|
|
pipe(this.shutdownFlag, set2(true));
|
|
return pipe(forEachConcurrentDiscard(unsafePollAll(this.takers), (d) => deferredInterruptWith(d, state.id()), false, false), zipRight(this.strategy.shutdown), whenEffect(deferredSucceed(this.shutdownHook, undefined)), asVoid);
|
|
}));
|
|
}
|
|
get isShutdown() {
|
|
return sync(() => get6(this.shutdownFlag));
|
|
}
|
|
get awaitShutdown() {
|
|
return deferredAwait(this.shutdownHook);
|
|
}
|
|
isActive() {
|
|
return !get6(this.shutdownFlag);
|
|
}
|
|
unsafeOffer(value) {
|
|
if (get6(this.shutdownFlag)) {
|
|
return false;
|
|
}
|
|
let noRemaining;
|
|
if (this.queue.length() === 0) {
|
|
const taker = pipe(this.takers, poll2(EmptyMutableQueue));
|
|
if (taker !== EmptyMutableQueue) {
|
|
unsafeCompleteDeferred(taker, value);
|
|
noRemaining = true;
|
|
} else {
|
|
noRemaining = false;
|
|
}
|
|
} else {
|
|
noRemaining = false;
|
|
}
|
|
if (noRemaining) {
|
|
return true;
|
|
}
|
|
const succeeded = this.queue.offer(value);
|
|
unsafeCompleteTakers(this.strategy, this.queue, this.takers);
|
|
return succeeded;
|
|
}
|
|
offer(value) {
|
|
return suspend(() => {
|
|
if (get6(this.shutdownFlag)) {
|
|
return interrupt2;
|
|
}
|
|
let noRemaining;
|
|
if (this.queue.length() === 0) {
|
|
const taker = pipe(this.takers, poll2(EmptyMutableQueue));
|
|
if (taker !== EmptyMutableQueue) {
|
|
unsafeCompleteDeferred(taker, value);
|
|
noRemaining = true;
|
|
} else {
|
|
noRemaining = false;
|
|
}
|
|
} else {
|
|
noRemaining = false;
|
|
}
|
|
if (noRemaining) {
|
|
return succeed(true);
|
|
}
|
|
const succeeded = this.queue.offer(value);
|
|
unsafeCompleteTakers(this.strategy, this.queue, this.takers);
|
|
return succeeded ? succeed(true) : this.strategy.handleSurplus([value], this.queue, this.takers, this.shutdownFlag);
|
|
});
|
|
}
|
|
offerAll(iterable) {
|
|
return suspend(() => {
|
|
if (get6(this.shutdownFlag)) {
|
|
return interrupt2;
|
|
}
|
|
const values = fromIterable(iterable);
|
|
const pTakers = this.queue.length() === 0 ? fromIterable(unsafePollN(this.takers, values.length)) : empty;
|
|
const [forTakers, remaining] = pipe(values, splitAt(pTakers.length));
|
|
for (let i = 0;i < pTakers.length; i++) {
|
|
const taker = pTakers[i];
|
|
const item = forTakers[i];
|
|
unsafeCompleteDeferred(taker, item);
|
|
}
|
|
if (remaining.length === 0) {
|
|
return succeed(true);
|
|
}
|
|
const surplus = this.queue.offerAll(remaining);
|
|
unsafeCompleteTakers(this.strategy, this.queue, this.takers);
|
|
return isEmpty(surplus) ? succeed(true) : this.strategy.handleSurplus(surplus, this.queue, this.takers, this.shutdownFlag);
|
|
});
|
|
}
|
|
get take() {
|
|
return withFiberRuntime((state) => {
|
|
if (get6(this.shutdownFlag)) {
|
|
return interrupt2;
|
|
}
|
|
const item = this.queue.poll(EmptyMutableQueue);
|
|
if (item !== EmptyMutableQueue) {
|
|
this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers);
|
|
return succeed(item);
|
|
} else {
|
|
const deferred = deferredUnsafeMake(state.id());
|
|
return pipe(suspend(() => {
|
|
pipe(this.takers, offer(deferred));
|
|
unsafeCompleteTakers(this.strategy, this.queue, this.takers);
|
|
return get6(this.shutdownFlag) ? interrupt2 : deferredAwait(deferred);
|
|
}), onInterrupt(() => {
|
|
return sync(() => unsafeRemove(this.takers, deferred));
|
|
}));
|
|
}
|
|
});
|
|
}
|
|
get takeAll() {
|
|
return suspend(() => {
|
|
return get6(this.shutdownFlag) ? interrupt2 : sync(() => {
|
|
const values = this.queue.pollUpTo(Number.POSITIVE_INFINITY);
|
|
this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers);
|
|
return fromIterable2(values);
|
|
});
|
|
});
|
|
}
|
|
takeUpTo(max) {
|
|
return suspend(() => get6(this.shutdownFlag) ? interrupt2 : sync(() => {
|
|
const values = this.queue.pollUpTo(max);
|
|
this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers);
|
|
return fromIterable2(values);
|
|
}));
|
|
}
|
|
takeBetween(min, max) {
|
|
return suspend(() => takeRemainderLoop(this, min, max, empty4()));
|
|
}
|
|
}
|
|
var takeRemainderLoop = (self2, min, max, acc) => {
|
|
if (max < min) {
|
|
return succeed(acc);
|
|
}
|
|
return pipe(takeUpTo(self2, max), flatMap7((bs) => {
|
|
const remaining = min - bs.length;
|
|
if (remaining === 1) {
|
|
return pipe(take(self2), map10((b) => pipe(acc, appendAll2(bs), append2(b))));
|
|
}
|
|
if (remaining > 1) {
|
|
return pipe(take(self2), flatMap7((b) => takeRemainderLoop(self2, remaining - 1, max - bs.length - 1, pipe(acc, appendAll2(bs), append2(b)))));
|
|
}
|
|
return succeed(pipe(acc, appendAll2(bs)));
|
|
}));
|
|
};
|
|
var bounded2 = (requestedCapacity) => pipe(sync(() => bounded(requestedCapacity)), flatMap7((queue) => make38(backingQueueFromMutableQueue(queue), backPressureStrategy())));
|
|
var dropping = (requestedCapacity) => pipe(sync(() => bounded(requestedCapacity)), flatMap7((queue) => make38(backingQueueFromMutableQueue(queue), droppingStrategy())));
|
|
var sliding = (requestedCapacity) => pipe(sync(() => bounded(requestedCapacity)), flatMap7((queue) => make38(backingQueueFromMutableQueue(queue), slidingStrategy())));
|
|
var unbounded2 = () => pipe(sync(() => unbounded()), flatMap7((queue) => make38(backingQueueFromMutableQueue(queue), droppingStrategy())));
|
|
var unsafeMake7 = (queue, takers, shutdownHook, shutdownFlag, strategy) => {
|
|
return new QueueImpl(queue, takers, shutdownHook, shutdownFlag, strategy);
|
|
};
|
|
var make38 = (queue, strategy) => pipe(deferredMake(), map10((deferred) => unsafeMake7(queue, unbounded(), deferred, make11(false), strategy)));
|
|
|
|
class BackingQueueFromMutableQueue {
|
|
mutable;
|
|
[BackingQueueTypeId] = backingQueueVariance;
|
|
constructor(mutable) {
|
|
this.mutable = mutable;
|
|
}
|
|
poll(def) {
|
|
return poll2(this.mutable, def);
|
|
}
|
|
pollUpTo(limit) {
|
|
return pollUpTo(this.mutable, limit);
|
|
}
|
|
offerAll(elements) {
|
|
return offerAll(this.mutable, elements);
|
|
}
|
|
offer(element) {
|
|
return offer(this.mutable, element);
|
|
}
|
|
capacity() {
|
|
return capacity(this.mutable);
|
|
}
|
|
length() {
|
|
return length2(this.mutable);
|
|
}
|
|
}
|
|
var backingQueueFromMutableQueue = (mutable) => new BackingQueueFromMutableQueue(mutable);
|
|
var size7 = (self2) => self2.size;
|
|
var shutdown = (self2) => self2.shutdown;
|
|
var offer2 = /* @__PURE__ */ dual(2, (self2, value) => self2.offer(value));
|
|
var take = (self2) => self2.take;
|
|
var takeUpTo = /* @__PURE__ */ dual(2, (self2, max) => self2.takeUpTo(max));
|
|
var backPressureStrategy = () => new BackPressureStrategy;
|
|
var droppingStrategy = () => new DroppingStrategy;
|
|
var slidingStrategy = () => new SlidingStrategy;
|
|
|
|
class BackPressureStrategy {
|
|
[QueueStrategyTypeId] = queueStrategyVariance;
|
|
putters = /* @__PURE__ */ unbounded();
|
|
surplusSize() {
|
|
return length2(this.putters);
|
|
}
|
|
onCompleteTakersWithEmptyQueue(takers) {
|
|
while (!isEmpty9(this.putters) && !isEmpty9(takers)) {
|
|
const taker = poll2(takers, undefined);
|
|
const putter = poll2(this.putters, undefined);
|
|
if (putter[2]) {
|
|
unsafeCompleteDeferred(putter[1], true);
|
|
}
|
|
unsafeCompleteDeferred(taker, putter[0]);
|
|
}
|
|
}
|
|
get shutdown() {
|
|
return pipe(fiberId, flatMap7((fiberId) => pipe(sync(() => unsafePollAll(this.putters)), flatMap7((putters) => forEachConcurrentDiscard(putters, ([_, deferred, isLastItem]) => isLastItem ? pipe(deferredInterruptWith(deferred, fiberId), asVoid) : void_, false, false)))));
|
|
}
|
|
handleSurplus(iterable, queue, takers, isShutdown) {
|
|
return withFiberRuntime((state) => {
|
|
const deferred = deferredUnsafeMake(state.id());
|
|
return pipe(suspend(() => {
|
|
this.unsafeOffer(iterable, deferred);
|
|
this.unsafeOnQueueEmptySpace(queue, takers);
|
|
unsafeCompleteTakers(this, queue, takers);
|
|
return get6(isShutdown) ? interrupt2 : deferredAwait(deferred);
|
|
}), onInterrupt(() => sync(() => this.unsafeRemove(deferred))));
|
|
});
|
|
}
|
|
unsafeOnQueueEmptySpace(queue, takers) {
|
|
let keepPolling = true;
|
|
while (keepPolling && (queue.capacity() === Number.POSITIVE_INFINITY || queue.length() < queue.capacity())) {
|
|
const putter = pipe(this.putters, poll2(EmptyMutableQueue));
|
|
if (putter === EmptyMutableQueue) {
|
|
keepPolling = false;
|
|
} else {
|
|
const offered = queue.offer(putter[0]);
|
|
if (offered && putter[2]) {
|
|
unsafeCompleteDeferred(putter[1], true);
|
|
} else if (!offered) {
|
|
unsafeOfferAll(this.putters, pipe(unsafePollAll(this.putters), prepend2(putter)));
|
|
}
|
|
unsafeCompleteTakers(this, queue, takers);
|
|
}
|
|
}
|
|
}
|
|
unsafeOffer(iterable, deferred) {
|
|
const stuff = fromIterable(iterable);
|
|
for (let i = 0;i < stuff.length; i++) {
|
|
const value = stuff[i];
|
|
if (i === stuff.length - 1) {
|
|
pipe(this.putters, offer([value, deferred, true]));
|
|
} else {
|
|
pipe(this.putters, offer([value, deferred, false]));
|
|
}
|
|
}
|
|
}
|
|
unsafeRemove(deferred) {
|
|
unsafeOfferAll(this.putters, pipe(unsafePollAll(this.putters), filter2(([, _]) => _ !== deferred)));
|
|
}
|
|
}
|
|
|
|
class DroppingStrategy {
|
|
[QueueStrategyTypeId] = queueStrategyVariance;
|
|
surplusSize() {
|
|
return 0;
|
|
}
|
|
get shutdown() {
|
|
return void_;
|
|
}
|
|
onCompleteTakersWithEmptyQueue() {}
|
|
handleSurplus(_iterable, _queue, _takers, _isShutdown) {
|
|
return succeed(false);
|
|
}
|
|
unsafeOnQueueEmptySpace(_queue, _takers) {}
|
|
}
|
|
|
|
class SlidingStrategy {
|
|
[QueueStrategyTypeId] = queueStrategyVariance;
|
|
surplusSize() {
|
|
return 0;
|
|
}
|
|
get shutdown() {
|
|
return void_;
|
|
}
|
|
onCompleteTakersWithEmptyQueue() {}
|
|
handleSurplus(iterable, queue, takers, _isShutdown) {
|
|
return sync(() => {
|
|
this.unsafeOffer(queue, iterable);
|
|
unsafeCompleteTakers(this, queue, takers);
|
|
return true;
|
|
});
|
|
}
|
|
unsafeOnQueueEmptySpace(_queue, _takers) {}
|
|
unsafeOffer(queue, iterable) {
|
|
const iterator = iterable[Symbol.iterator]();
|
|
let next;
|
|
let offering = true;
|
|
while (!(next = iterator.next()).done && offering) {
|
|
if (queue.capacity() === 0) {
|
|
return;
|
|
}
|
|
queue.poll(EmptyMutableQueue);
|
|
offering = queue.offer(next.value);
|
|
}
|
|
}
|
|
}
|
|
var unsafeCompleteDeferred = (deferred, a) => {
|
|
return deferredUnsafeDone(deferred, succeed(a));
|
|
};
|
|
var unsafeOfferAll = (queue, as) => {
|
|
return pipe(queue, offerAll(as));
|
|
};
|
|
var unsafePollAll = (queue) => {
|
|
return pipe(queue, pollUpTo(Number.POSITIVE_INFINITY));
|
|
};
|
|
var unsafePollN = (queue, max) => {
|
|
return pipe(queue, pollUpTo(max));
|
|
};
|
|
var unsafeRemove = (queue, a) => {
|
|
unsafeOfferAll(queue, pipe(unsafePollAll(queue), filter2((b) => a !== b)));
|
|
};
|
|
var unsafeCompleteTakers = (strategy, queue, takers) => {
|
|
let keepPolling = true;
|
|
while (keepPolling && queue.length() !== 0) {
|
|
const taker = pipe(takers, poll2(EmptyMutableQueue));
|
|
if (taker !== EmptyMutableQueue) {
|
|
const element = queue.poll(EmptyMutableQueue);
|
|
if (element !== EmptyMutableQueue) {
|
|
unsafeCompleteDeferred(taker, element);
|
|
strategy.unsafeOnQueueEmptySpace(queue, takers);
|
|
} else {
|
|
unsafeOfferAll(takers, pipe(unsafePollAll(takers), prepend2(taker)));
|
|
}
|
|
keepPolling = true;
|
|
} else {
|
|
keepPolling = false;
|
|
}
|
|
}
|
|
if (keepPolling && queue.length() === 0 && !isEmpty9(takers)) {
|
|
strategy.onCompleteTakersWithEmptyQueue(takers);
|
|
}
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Queue.js
|
|
var bounded3 = bounded2;
|
|
var dropping2 = dropping;
|
|
var sliding2 = sliding;
|
|
var unbounded3 = unbounded2;
|
|
var size8 = size7;
|
|
var shutdown2 = shutdown;
|
|
var offer3 = offer2;
|
|
var take2 = take;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/opCodes/channelChildExecutorDecision.js
|
|
var OP_CONTINUE2 = "Continue";
|
|
var OP_CLOSE = "Close";
|
|
var OP_YIELD2 = "Yield";
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/channel/childExecutorDecision.js
|
|
var ChildExecutorDecisionSymbolKey = "effect/ChannelChildExecutorDecision";
|
|
var ChildExecutorDecisionTypeId = /* @__PURE__ */ Symbol.for(ChildExecutorDecisionSymbolKey);
|
|
var proto4 = {
|
|
[ChildExecutorDecisionTypeId]: ChildExecutorDecisionTypeId
|
|
};
|
|
var Continue = (_) => {
|
|
const op = Object.create(proto4);
|
|
op._tag = OP_CONTINUE2;
|
|
return op;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/opCodes/continuation.js
|
|
var OP_CONTINUATION_K = "ContinuationK";
|
|
var OP_CONTINUATION_FINALIZER = "ContinuationFinalizer";
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/channel/continuation.js
|
|
var ContinuationTypeId = /* @__PURE__ */ Symbol.for("effect/ChannelContinuation");
|
|
var continuationVariance = {
|
|
_Env: (_) => _,
|
|
_InErr: (_) => _,
|
|
_InElem: (_) => _,
|
|
_InDone: (_) => _,
|
|
_OutErr: (_) => _,
|
|
_OutDone: (_) => _,
|
|
_OutErr2: (_) => _,
|
|
_OutElem: (_) => _,
|
|
_OutDone2: (_) => _
|
|
};
|
|
|
|
class ContinuationKImpl {
|
|
onSuccess;
|
|
onHalt;
|
|
_tag = OP_CONTINUATION_K;
|
|
[ContinuationTypeId] = continuationVariance;
|
|
constructor(onSuccess, onHalt) {
|
|
this.onSuccess = onSuccess;
|
|
this.onHalt = onHalt;
|
|
}
|
|
onExit(exit) {
|
|
return isFailure2(exit) ? this.onHalt(exit.cause) : this.onSuccess(exit.value);
|
|
}
|
|
}
|
|
|
|
class ContinuationFinalizerImpl {
|
|
finalizer;
|
|
_tag = OP_CONTINUATION_FINALIZER;
|
|
[ContinuationTypeId] = continuationVariance;
|
|
constructor(finalizer) {
|
|
this.finalizer = finalizer;
|
|
}
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/opCodes/channelUpstreamPullStrategy.js
|
|
var OP_PULL_AFTER_NEXT = "PullAfterNext";
|
|
var OP_PULL_AFTER_ALL_ENQUEUED = "PullAfterAllEnqueued";
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/channel/upstreamPullStrategy.js
|
|
var UpstreamPullStrategySymbolKey = "effect/ChannelUpstreamPullStrategy";
|
|
var UpstreamPullStrategyTypeId = /* @__PURE__ */ Symbol.for(UpstreamPullStrategySymbolKey);
|
|
var upstreamPullStrategyVariance = {
|
|
_A: (_) => _
|
|
};
|
|
var proto5 = {
|
|
[UpstreamPullStrategyTypeId]: upstreamPullStrategyVariance
|
|
};
|
|
var PullAfterNext = (emitSeparator) => {
|
|
const op = Object.create(proto5);
|
|
op._tag = OP_PULL_AFTER_NEXT;
|
|
op.emitSeparator = emitSeparator;
|
|
return op;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/opCodes/channel.js
|
|
var OP_BRACKET_OUT = "BracketOut";
|
|
var OP_BRIDGE = "Bridge";
|
|
var OP_CONCAT_ALL = "ConcatAll";
|
|
var OP_EMIT = "Emit";
|
|
var OP_ENSURING = "Ensuring";
|
|
var OP_FAIL3 = "Fail";
|
|
var OP_FOLD2 = "Fold";
|
|
var OP_FROM_EFFECT2 = "FromEffect";
|
|
var OP_PIPE_TO = "PipeTo";
|
|
var OP_PROVIDE2 = "Provide";
|
|
var OP_READ = "Read";
|
|
var OP_SUCCEED = "Succeed";
|
|
var OP_SUCCEED_NOW = "SucceedNow";
|
|
var OP_SUSPEND2 = "Suspend";
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/core-stream.js
|
|
var ChannelSymbolKey = "effect/Channel";
|
|
var ChannelTypeId2 = /* @__PURE__ */ Symbol.for(ChannelSymbolKey);
|
|
var channelVariance2 = {
|
|
_Env: (_) => _,
|
|
_InErr: (_) => _,
|
|
_InElem: (_) => _,
|
|
_InDone: (_) => _,
|
|
_OutErr: (_) => _,
|
|
_OutElem: (_) => _,
|
|
_OutDone: (_) => _
|
|
};
|
|
var proto6 = {
|
|
[ChannelTypeId2]: channelVariance2,
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
};
|
|
var isChannel = (u) => hasProperty(u, ChannelTypeId2) || isEffect2(u);
|
|
var acquireReleaseOut = /* @__PURE__ */ dual(2, (self2, release) => {
|
|
const op = Object.create(proto6);
|
|
op._tag = OP_BRACKET_OUT;
|
|
op.acquire = () => self2;
|
|
op.finalizer = release;
|
|
return op;
|
|
});
|
|
var concatAllWith = (channels, f, g) => {
|
|
const op = Object.create(proto6);
|
|
op._tag = OP_CONCAT_ALL;
|
|
op.combineInners = f;
|
|
op.combineAll = g;
|
|
op.onPull = () => PullAfterNext(none2());
|
|
op.onEmit = () => Continue;
|
|
op.value = () => channels;
|
|
op.k = identity;
|
|
return op;
|
|
};
|
|
var concatMapWith = /* @__PURE__ */ dual(4, (self2, f, g, h) => {
|
|
const op = Object.create(proto6);
|
|
op._tag = OP_CONCAT_ALL;
|
|
op.combineInners = g;
|
|
op.combineAll = h;
|
|
op.onPull = () => PullAfterNext(none2());
|
|
op.onEmit = () => Continue;
|
|
op.value = () => self2;
|
|
op.k = f;
|
|
return op;
|
|
});
|
|
var embedInput = /* @__PURE__ */ dual(2, (self2, input) => {
|
|
const op = Object.create(proto6);
|
|
op._tag = OP_BRIDGE;
|
|
op.input = input;
|
|
op.channel = self2;
|
|
return op;
|
|
});
|
|
var ensuringWith = /* @__PURE__ */ dual(2, (self2, finalizer) => {
|
|
const op = Object.create(proto6);
|
|
op._tag = OP_ENSURING;
|
|
op.channel = self2;
|
|
op.finalizer = finalizer;
|
|
return op;
|
|
});
|
|
var fail8 = (error) => failCause8(fail3(error));
|
|
var failCause8 = (cause) => failCauseSync3(() => cause);
|
|
var failCauseSync3 = (evaluate) => {
|
|
const op = Object.create(proto6);
|
|
op._tag = OP_FAIL3;
|
|
op.error = evaluate;
|
|
return op;
|
|
};
|
|
var flatMap11 = /* @__PURE__ */ dual(2, (self2, f) => {
|
|
const op = Object.create(proto6);
|
|
op._tag = OP_FOLD2;
|
|
op.channel = self2;
|
|
op.k = new ContinuationKImpl(f, failCause8);
|
|
return op;
|
|
});
|
|
var fromEffect4 = (effect) => {
|
|
const op = Object.create(proto6);
|
|
op._tag = OP_FROM_EFFECT2;
|
|
op.effect = () => effect;
|
|
return op;
|
|
};
|
|
var pipeTo = /* @__PURE__ */ dual(2, (self2, that) => {
|
|
const op = Object.create(proto6);
|
|
op._tag = OP_PIPE_TO;
|
|
op.left = () => self2;
|
|
op.right = () => that;
|
|
return op;
|
|
});
|
|
var readWith = (options) => readWithCause({
|
|
onInput: options.onInput,
|
|
onFailure: (cause) => match(failureOrCause2(cause), {
|
|
onLeft: options.onFailure,
|
|
onRight: failCause8
|
|
}),
|
|
onDone: options.onDone
|
|
});
|
|
var readWithCause = (options) => {
|
|
const op = Object.create(proto6);
|
|
op._tag = OP_READ;
|
|
op.more = options.onInput;
|
|
op.done = new ContinuationKImpl(options.onDone, options.onFailure);
|
|
return op;
|
|
};
|
|
var succeed9 = (value) => sync4(() => value);
|
|
var succeedNow = (result) => {
|
|
const op = Object.create(proto6);
|
|
op._tag = OP_SUCCEED_NOW;
|
|
op.terminal = result;
|
|
return op;
|
|
};
|
|
var suspend4 = (evaluate) => {
|
|
const op = Object.create(proto6);
|
|
op._tag = OP_SUSPEND2;
|
|
op.channel = evaluate;
|
|
return op;
|
|
};
|
|
var sync4 = (evaluate) => {
|
|
const op = Object.create(proto6);
|
|
op._tag = OP_SUCCEED;
|
|
op.evaluate = evaluate;
|
|
return op;
|
|
};
|
|
var void_5 = /* @__PURE__ */ succeedNow(undefined);
|
|
var write = (out) => {
|
|
const op = Object.create(proto6);
|
|
op._tag = OP_EMIT;
|
|
op.out = out;
|
|
return op;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/opCodes/channelState.js
|
|
var OP_DONE3 = "Done";
|
|
var OP_EMIT2 = "Emit";
|
|
var OP_FROM_EFFECT3 = "FromEffect";
|
|
var OP_READ2 = "Read";
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/channel/channelState.js
|
|
var ChannelStateTypeId = /* @__PURE__ */ Symbol.for("effect/ChannelState");
|
|
var channelStateVariance = {
|
|
_E: (_) => _,
|
|
_R: (_) => _
|
|
};
|
|
var proto7 = {
|
|
[ChannelStateTypeId]: channelStateVariance
|
|
};
|
|
var Done2 = () => {
|
|
const op = Object.create(proto7);
|
|
op._tag = OP_DONE3;
|
|
return op;
|
|
};
|
|
var Emit = () => {
|
|
const op = Object.create(proto7);
|
|
op._tag = OP_EMIT2;
|
|
return op;
|
|
};
|
|
var fromEffect5 = (effect) => {
|
|
const op = Object.create(proto7);
|
|
op._tag = OP_FROM_EFFECT3;
|
|
op.effect = effect;
|
|
return op;
|
|
};
|
|
var Read = (upstream, onEffect, onEmit, onDone) => {
|
|
const op = Object.create(proto7);
|
|
op._tag = OP_READ2;
|
|
op.upstream = upstream;
|
|
op.onEffect = onEffect;
|
|
op.onEmit = onEmit;
|
|
op.onDone = onDone;
|
|
return op;
|
|
};
|
|
var isFromEffect = (self2) => self2._tag === OP_FROM_EFFECT3;
|
|
var effect2 = (self2) => isFromEffect(self2) ? self2.effect : _void;
|
|
var effectOrUndefinedIgnored = (self2) => isFromEffect(self2) ? ignore2(self2.effect) : undefined;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/channel/subexecutor.js
|
|
var OP_PULL_FROM_CHILD = "PullFromChild";
|
|
var OP_PULL_FROM_UPSTREAM = "PullFromUpstream";
|
|
var OP_DRAIN_CHILD_EXECUTORS = "DrainChildExecutors";
|
|
var OP_EMIT3 = "Emit";
|
|
|
|
class PullFromChild {
|
|
childExecutor;
|
|
parentSubexecutor;
|
|
onEmit;
|
|
_tag = OP_PULL_FROM_CHILD;
|
|
constructor(childExecutor, parentSubexecutor, onEmit) {
|
|
this.childExecutor = childExecutor;
|
|
this.parentSubexecutor = parentSubexecutor;
|
|
this.onEmit = onEmit;
|
|
}
|
|
close(exit) {
|
|
const fin1 = this.childExecutor.close(exit);
|
|
const fin2 = this.parentSubexecutor.close(exit);
|
|
if (fin1 !== undefined && fin2 !== undefined) {
|
|
return zipWith3(exit2(fin1), exit2(fin2), (exit1, exit2) => pipe(exit1, zipRight2(exit2)));
|
|
} else if (fin1 !== undefined) {
|
|
return fin1;
|
|
} else if (fin2 !== undefined) {
|
|
return fin2;
|
|
} else {
|
|
return;
|
|
}
|
|
}
|
|
enqueuePullFromChild(_child) {
|
|
return this;
|
|
}
|
|
}
|
|
|
|
class PullFromUpstream {
|
|
upstreamExecutor;
|
|
createChild;
|
|
lastDone;
|
|
activeChildExecutors;
|
|
combineChildResults;
|
|
combineWithChildResult;
|
|
onPull;
|
|
onEmit;
|
|
_tag = OP_PULL_FROM_UPSTREAM;
|
|
constructor(upstreamExecutor, createChild, lastDone, activeChildExecutors, combineChildResults, combineWithChildResult, onPull, onEmit) {
|
|
this.upstreamExecutor = upstreamExecutor;
|
|
this.createChild = createChild;
|
|
this.lastDone = lastDone;
|
|
this.activeChildExecutors = activeChildExecutors;
|
|
this.combineChildResults = combineChildResults;
|
|
this.combineWithChildResult = combineWithChildResult;
|
|
this.onPull = onPull;
|
|
this.onEmit = onEmit;
|
|
}
|
|
close(exit) {
|
|
const fin1 = this.upstreamExecutor.close(exit);
|
|
const fins = [...this.activeChildExecutors.map((child) => child !== undefined ? child.childExecutor.close(exit) : undefined), fin1];
|
|
const result = fins.reduce((acc, next) => {
|
|
if (acc !== undefined && next !== undefined) {
|
|
return zipWith3(acc, exit2(next), (exit1, exit2) => zipRight2(exit1, exit2));
|
|
} else if (acc !== undefined) {
|
|
return acc;
|
|
} else if (next !== undefined) {
|
|
return exit2(next);
|
|
} else {
|
|
return;
|
|
}
|
|
}, undefined);
|
|
return result === undefined ? result : result;
|
|
}
|
|
enqueuePullFromChild(child) {
|
|
return new PullFromUpstream(this.upstreamExecutor, this.createChild, this.lastDone, [...this.activeChildExecutors, child], this.combineChildResults, this.combineWithChildResult, this.onPull, this.onEmit);
|
|
}
|
|
}
|
|
|
|
class DrainChildExecutors {
|
|
upstreamExecutor;
|
|
lastDone;
|
|
activeChildExecutors;
|
|
upstreamDone;
|
|
combineChildResults;
|
|
combineWithChildResult;
|
|
onPull;
|
|
_tag = OP_DRAIN_CHILD_EXECUTORS;
|
|
constructor(upstreamExecutor, lastDone, activeChildExecutors, upstreamDone, combineChildResults, combineWithChildResult, onPull) {
|
|
this.upstreamExecutor = upstreamExecutor;
|
|
this.lastDone = lastDone;
|
|
this.activeChildExecutors = activeChildExecutors;
|
|
this.upstreamDone = upstreamDone;
|
|
this.combineChildResults = combineChildResults;
|
|
this.combineWithChildResult = combineWithChildResult;
|
|
this.onPull = onPull;
|
|
}
|
|
close(exit) {
|
|
const fin1 = this.upstreamExecutor.close(exit);
|
|
const fins = [...this.activeChildExecutors.map((child) => child !== undefined ? child.childExecutor.close(exit) : undefined), fin1];
|
|
const result = fins.reduce((acc, next) => {
|
|
if (acc !== undefined && next !== undefined) {
|
|
return zipWith3(acc, exit2(next), (exit1, exit2) => zipRight2(exit1, exit2));
|
|
} else if (acc !== undefined) {
|
|
return acc;
|
|
} else if (next !== undefined) {
|
|
return exit2(next);
|
|
} else {
|
|
return;
|
|
}
|
|
}, undefined);
|
|
return result === undefined ? result : result;
|
|
}
|
|
enqueuePullFromChild(child) {
|
|
return new DrainChildExecutors(this.upstreamExecutor, this.lastDone, [...this.activeChildExecutors, child], this.upstreamDone, this.combineChildResults, this.combineWithChildResult, this.onPull);
|
|
}
|
|
}
|
|
|
|
class Emit2 {
|
|
value;
|
|
next;
|
|
_tag = OP_EMIT3;
|
|
constructor(value, next) {
|
|
this.value = value;
|
|
this.next = next;
|
|
}
|
|
close(exit) {
|
|
const result = this.next.close(exit);
|
|
return result === undefined ? result : result;
|
|
}
|
|
enqueuePullFromChild(_child) {
|
|
return this;
|
|
}
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/opCodes/channelUpstreamPullRequest.js
|
|
var OP_PULLED = "Pulled";
|
|
var OP_NO_UPSTREAM = "NoUpstream";
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/channel/upstreamPullRequest.js
|
|
var UpstreamPullRequestSymbolKey = "effect/ChannelUpstreamPullRequest";
|
|
var UpstreamPullRequestTypeId = /* @__PURE__ */ Symbol.for(UpstreamPullRequestSymbolKey);
|
|
var upstreamPullRequestVariance = {
|
|
_A: (_) => _
|
|
};
|
|
var proto8 = {
|
|
[UpstreamPullRequestTypeId]: upstreamPullRequestVariance
|
|
};
|
|
var Pulled = (value) => {
|
|
const op = Object.create(proto8);
|
|
op._tag = OP_PULLED;
|
|
op.value = value;
|
|
return op;
|
|
};
|
|
var NoUpstream = (activeDownstreamCount) => {
|
|
const op = Object.create(proto8);
|
|
op._tag = OP_NO_UPSTREAM;
|
|
op.activeDownstreamCount = activeDownstreamCount;
|
|
return op;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/channel/channelExecutor.js
|
|
class ChannelExecutor {
|
|
_activeSubexecutor = undefined;
|
|
_cancelled = undefined;
|
|
_closeLastSubstream = undefined;
|
|
_currentChannel;
|
|
_done = undefined;
|
|
_doneStack = [];
|
|
_emitted = undefined;
|
|
_executeCloseLastSubstream;
|
|
_input = undefined;
|
|
_inProgressFinalizer = undefined;
|
|
_providedEnv;
|
|
constructor(initialChannel, providedEnv, executeCloseLastSubstream) {
|
|
this._currentChannel = initialChannel;
|
|
this._executeCloseLastSubstream = executeCloseLastSubstream;
|
|
this._providedEnv = providedEnv;
|
|
}
|
|
run() {
|
|
let result = undefined;
|
|
while (result === undefined) {
|
|
if (this._cancelled !== undefined) {
|
|
result = this.processCancellation();
|
|
} else if (this._activeSubexecutor !== undefined) {
|
|
result = this.runSubexecutor();
|
|
} else {
|
|
try {
|
|
if (this._currentChannel === undefined) {
|
|
result = Done2();
|
|
} else {
|
|
if (isEffect2(this._currentChannel)) {
|
|
this._currentChannel = fromEffect4(this._currentChannel);
|
|
}
|
|
switch (this._currentChannel._tag) {
|
|
case OP_BRACKET_OUT: {
|
|
result = this.runBracketOut(this._currentChannel);
|
|
break;
|
|
}
|
|
case OP_BRIDGE: {
|
|
const bridgeInput = this._currentChannel.input;
|
|
this._currentChannel = this._currentChannel.channel;
|
|
if (this._input !== undefined) {
|
|
const inputExecutor = this._input;
|
|
this._input = undefined;
|
|
const drainer = () => flatMap9(bridgeInput.awaitRead(), () => suspend2(() => {
|
|
const state = inputExecutor.run();
|
|
switch (state._tag) {
|
|
case OP_DONE3: {
|
|
return match9(inputExecutor.getDone(), {
|
|
onFailure: (cause) => bridgeInput.error(cause),
|
|
onSuccess: (value) => bridgeInput.done(value)
|
|
});
|
|
}
|
|
case OP_EMIT2: {
|
|
return flatMap9(bridgeInput.emit(inputExecutor.getEmit()), () => drainer());
|
|
}
|
|
case OP_FROM_EFFECT3: {
|
|
return matchCauseEffect3(state.effect, {
|
|
onFailure: (cause) => bridgeInput.error(cause),
|
|
onSuccess: () => drainer()
|
|
});
|
|
}
|
|
case OP_READ2: {
|
|
return readUpstream(state, () => drainer(), (cause) => bridgeInput.error(cause));
|
|
}
|
|
}
|
|
}));
|
|
result = fromEffect5(flatMap9(forkDaemon2(interruptible4(drainer())), (fiber) => sync3(() => this.addFinalizer((exit) => flatMap9(interrupt4(fiber), () => suspend2(() => {
|
|
const effect = this.restorePipe(exit, inputExecutor);
|
|
return effect !== undefined ? effect : _void;
|
|
}))))));
|
|
}
|
|
break;
|
|
}
|
|
case OP_CONCAT_ALL: {
|
|
const executor = new ChannelExecutor(this._currentChannel.value(), this._providedEnv, (effect) => sync3(() => {
|
|
const prevLastClose = this._closeLastSubstream === undefined ? _void : this._closeLastSubstream;
|
|
this._closeLastSubstream = pipe(prevLastClose, zipRight3(effect));
|
|
}));
|
|
executor._input = this._input;
|
|
const channel = this._currentChannel;
|
|
this._activeSubexecutor = new PullFromUpstream(executor, (value) => channel.k(value), undefined, [], (x, y) => channel.combineInners(x, y), (x, y) => channel.combineAll(x, y), (request) => channel.onPull(request), (value) => channel.onEmit(value));
|
|
this._closeLastSubstream = undefined;
|
|
this._currentChannel = undefined;
|
|
break;
|
|
}
|
|
case OP_EMIT: {
|
|
this._emitted = this._currentChannel.out;
|
|
this._currentChannel = this._activeSubexecutor !== undefined ? undefined : void_5;
|
|
result = Emit();
|
|
break;
|
|
}
|
|
case OP_ENSURING: {
|
|
this.runEnsuring(this._currentChannel);
|
|
break;
|
|
}
|
|
case OP_FAIL3: {
|
|
result = this.doneHalt(this._currentChannel.error());
|
|
break;
|
|
}
|
|
case OP_FOLD2: {
|
|
this._doneStack.push(this._currentChannel.k);
|
|
this._currentChannel = this._currentChannel.channel;
|
|
break;
|
|
}
|
|
case OP_FROM_EFFECT2: {
|
|
const effect = this._providedEnv === undefined ? this._currentChannel.effect() : pipe(this._currentChannel.effect(), provide2(this._providedEnv));
|
|
result = fromEffect5(matchCauseEffect3(effect, {
|
|
onFailure: (cause) => {
|
|
const state = this.doneHalt(cause);
|
|
return state !== undefined && isFromEffect(state) ? state.effect : _void;
|
|
},
|
|
onSuccess: (value) => {
|
|
const state = this.doneSucceed(value);
|
|
return state !== undefined && isFromEffect(state) ? state.effect : _void;
|
|
}
|
|
}));
|
|
break;
|
|
}
|
|
case OP_PIPE_TO: {
|
|
const previousInput = this._input;
|
|
const leftExec = new ChannelExecutor(this._currentChannel.left(), this._providedEnv, (effect) => this._executeCloseLastSubstream(effect));
|
|
leftExec._input = previousInput;
|
|
this._input = leftExec;
|
|
this.addFinalizer((exit) => {
|
|
const effect = this.restorePipe(exit, previousInput);
|
|
return effect !== undefined ? effect : _void;
|
|
});
|
|
this._currentChannel = this._currentChannel.right();
|
|
break;
|
|
}
|
|
case OP_PROVIDE2: {
|
|
const previousEnv = this._providedEnv;
|
|
this._providedEnv = this._currentChannel.context();
|
|
this._currentChannel = this._currentChannel.inner;
|
|
this.addFinalizer(() => sync3(() => {
|
|
this._providedEnv = previousEnv;
|
|
}));
|
|
break;
|
|
}
|
|
case OP_READ: {
|
|
const read = this._currentChannel;
|
|
result = Read(this._input, identity, (emitted) => {
|
|
try {
|
|
this._currentChannel = read.more(emitted);
|
|
} catch (error) {
|
|
this._currentChannel = read.done.onExit(die4(error));
|
|
}
|
|
return;
|
|
}, (exit) => {
|
|
const onExit = (exit) => {
|
|
return read.done.onExit(exit);
|
|
};
|
|
this._currentChannel = onExit(exit);
|
|
return;
|
|
});
|
|
break;
|
|
}
|
|
case OP_SUCCEED: {
|
|
result = this.doneSucceed(this._currentChannel.evaluate());
|
|
break;
|
|
}
|
|
case OP_SUCCEED_NOW: {
|
|
result = this.doneSucceed(this._currentChannel.terminal);
|
|
break;
|
|
}
|
|
case OP_SUSPEND2: {
|
|
this._currentChannel = this._currentChannel.channel();
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
} catch (error) {
|
|
this._currentChannel = failCause8(die3(error));
|
|
}
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
getDone() {
|
|
return this._done;
|
|
}
|
|
getEmit() {
|
|
return this._emitted;
|
|
}
|
|
cancelWith(exit) {
|
|
this._cancelled = exit;
|
|
}
|
|
clearInProgressFinalizer() {
|
|
this._inProgressFinalizer = undefined;
|
|
}
|
|
storeInProgressFinalizer(finalizer) {
|
|
this._inProgressFinalizer = finalizer;
|
|
}
|
|
popAllFinalizers(exit) {
|
|
const finalizers = [];
|
|
let next = this._doneStack.pop();
|
|
while (next) {
|
|
if (next._tag === "ContinuationFinalizer") {
|
|
finalizers.push(next.finalizer);
|
|
}
|
|
next = this._doneStack.pop();
|
|
}
|
|
const effect = finalizers.length === 0 ? _void : runFinalizers(finalizers, exit);
|
|
this.storeInProgressFinalizer(effect);
|
|
return effect;
|
|
}
|
|
popNextFinalizers() {
|
|
const builder = [];
|
|
while (this._doneStack.length !== 0) {
|
|
const cont = this._doneStack[this._doneStack.length - 1];
|
|
if (cont._tag === OP_CONTINUATION_K) {
|
|
return builder;
|
|
}
|
|
builder.push(cont);
|
|
this._doneStack.pop();
|
|
}
|
|
return builder;
|
|
}
|
|
restorePipe(exit, prev) {
|
|
const currInput = this._input;
|
|
this._input = prev;
|
|
if (currInput !== undefined) {
|
|
const effect = currInput.close(exit);
|
|
return effect;
|
|
}
|
|
return _void;
|
|
}
|
|
close(exit) {
|
|
let runInProgressFinalizers = undefined;
|
|
const finalizer = this._inProgressFinalizer;
|
|
if (finalizer !== undefined) {
|
|
runInProgressFinalizers = pipe(finalizer, ensuring2(sync3(() => this.clearInProgressFinalizer())));
|
|
}
|
|
let closeSelf = undefined;
|
|
const selfFinalizers = this.popAllFinalizers(exit);
|
|
if (selfFinalizers !== undefined) {
|
|
closeSelf = pipe(selfFinalizers, ensuring2(sync3(() => this.clearInProgressFinalizer())));
|
|
}
|
|
const closeSubexecutors = this._activeSubexecutor === undefined ? undefined : this._activeSubexecutor.close(exit);
|
|
if (closeSubexecutors === undefined && runInProgressFinalizers === undefined && closeSelf === undefined) {
|
|
return;
|
|
}
|
|
return pipe(exit2(ifNotNull(closeSubexecutors)), zip5(exit2(ifNotNull(runInProgressFinalizers))), zip5(exit2(ifNotNull(closeSelf))), map15(([[exit1, exit2], exit3]) => pipe(exit1, zipRight2(exit2), zipRight2(exit3))), uninterruptible2, flatMap9((exit) => suspend2(() => exit)));
|
|
}
|
|
doneSucceed(value) {
|
|
if (this._doneStack.length === 0) {
|
|
this._done = succeed4(value);
|
|
this._currentChannel = undefined;
|
|
return Done2();
|
|
}
|
|
const head = this._doneStack[this._doneStack.length - 1];
|
|
if (head._tag === OP_CONTINUATION_K) {
|
|
this._doneStack.pop();
|
|
this._currentChannel = head.onSuccess(value);
|
|
return;
|
|
}
|
|
const finalizers = this.popNextFinalizers();
|
|
if (this._doneStack.length === 0) {
|
|
this._doneStack = finalizers.reverse();
|
|
this._done = succeed4(value);
|
|
this._currentChannel = undefined;
|
|
return Done2();
|
|
}
|
|
const finalizerEffect = runFinalizers(finalizers.map((f) => f.finalizer), succeed4(value));
|
|
this.storeInProgressFinalizer(finalizerEffect);
|
|
const effect = pipe(finalizerEffect, ensuring2(sync3(() => this.clearInProgressFinalizer())), uninterruptible2, flatMap9(() => sync3(() => this.doneSucceed(value))));
|
|
return fromEffect5(effect);
|
|
}
|
|
doneHalt(cause) {
|
|
if (this._doneStack.length === 0) {
|
|
this._done = failCause4(cause);
|
|
this._currentChannel = undefined;
|
|
return Done2();
|
|
}
|
|
const head = this._doneStack[this._doneStack.length - 1];
|
|
if (head._tag === OP_CONTINUATION_K) {
|
|
this._doneStack.pop();
|
|
try {
|
|
this._currentChannel = head.onHalt(cause);
|
|
} catch (error) {
|
|
this._currentChannel = failCause8(die3(error));
|
|
}
|
|
return;
|
|
}
|
|
const finalizers = this.popNextFinalizers();
|
|
if (this._doneStack.length === 0) {
|
|
this._doneStack = finalizers.reverse();
|
|
this._done = failCause4(cause);
|
|
this._currentChannel = undefined;
|
|
return Done2();
|
|
}
|
|
const finalizerEffect = runFinalizers(finalizers.map((f) => f.finalizer), failCause4(cause));
|
|
this.storeInProgressFinalizer(finalizerEffect);
|
|
const effect = pipe(finalizerEffect, ensuring2(sync3(() => this.clearInProgressFinalizer())), uninterruptible2, flatMap9(() => sync3(() => this.doneHalt(cause))));
|
|
return fromEffect5(effect);
|
|
}
|
|
processCancellation() {
|
|
this._currentChannel = undefined;
|
|
this._done = this._cancelled;
|
|
this._cancelled = undefined;
|
|
return Done2();
|
|
}
|
|
runBracketOut(bracketOut) {
|
|
const effect = uninterruptible2(matchCauseEffect3(this.provide(bracketOut.acquire()), {
|
|
onFailure: (cause) => sync3(() => {
|
|
this._currentChannel = failCause8(cause);
|
|
}),
|
|
onSuccess: (out) => sync3(() => {
|
|
this.addFinalizer((exit) => this.provide(bracketOut.finalizer(out, exit)));
|
|
this._currentChannel = write(out);
|
|
})
|
|
}));
|
|
return fromEffect5(effect);
|
|
}
|
|
provide(effect) {
|
|
if (this._providedEnv === undefined) {
|
|
return effect;
|
|
}
|
|
return pipe(effect, provide2(this._providedEnv));
|
|
}
|
|
runEnsuring(ensuring) {
|
|
this.addFinalizer(ensuring.finalizer);
|
|
this._currentChannel = ensuring.channel;
|
|
}
|
|
addFinalizer(f) {
|
|
this._doneStack.push(new ContinuationFinalizerImpl(f));
|
|
}
|
|
runSubexecutor() {
|
|
const subexecutor = this._activeSubexecutor;
|
|
switch (subexecutor._tag) {
|
|
case OP_PULL_FROM_CHILD: {
|
|
return this.pullFromChild(subexecutor.childExecutor, subexecutor.parentSubexecutor, subexecutor.onEmit, subexecutor);
|
|
}
|
|
case OP_PULL_FROM_UPSTREAM: {
|
|
return this.pullFromUpstream(subexecutor);
|
|
}
|
|
case OP_DRAIN_CHILD_EXECUTORS: {
|
|
return this.drainChildExecutors(subexecutor);
|
|
}
|
|
case OP_EMIT3: {
|
|
this._emitted = subexecutor.value;
|
|
this._activeSubexecutor = subexecutor.next;
|
|
return Emit();
|
|
}
|
|
}
|
|
}
|
|
replaceSubexecutor(nextSubExec) {
|
|
this._currentChannel = undefined;
|
|
this._activeSubexecutor = nextSubExec;
|
|
}
|
|
finishWithExit(exit) {
|
|
const state = match9(exit, {
|
|
onFailure: (cause) => this.doneHalt(cause),
|
|
onSuccess: (value) => this.doneSucceed(value)
|
|
});
|
|
this._activeSubexecutor = undefined;
|
|
return state === undefined ? _void : effect2(state);
|
|
}
|
|
finishSubexecutorWithCloseEffect(subexecutorDone, ...closeFuncs) {
|
|
this.addFinalizer(() => pipe(closeFuncs, forEach4((closeFunc) => pipe(sync3(() => closeFunc(subexecutorDone)), flatMap9((closeEffect) => closeEffect !== undefined ? closeEffect : _void)), {
|
|
discard: true
|
|
})));
|
|
const state = pipe(subexecutorDone, match9({
|
|
onFailure: (cause) => this.doneHalt(cause),
|
|
onSuccess: (value) => this.doneSucceed(value)
|
|
}));
|
|
this._activeSubexecutor = undefined;
|
|
return state;
|
|
}
|
|
applyUpstreamPullStrategy(upstreamFinished, queue, strategy) {
|
|
switch (strategy._tag) {
|
|
case OP_PULL_AFTER_NEXT: {
|
|
const shouldPrepend = !upstreamFinished || queue.some((subexecutor) => subexecutor !== undefined);
|
|
return [strategy.emitSeparator, shouldPrepend ? [undefined, ...queue] : queue];
|
|
}
|
|
case OP_PULL_AFTER_ALL_ENQUEUED: {
|
|
const shouldEnqueue = !upstreamFinished || queue.some((subexecutor) => subexecutor !== undefined);
|
|
return [strategy.emitSeparator, shouldEnqueue ? [...queue, undefined] : queue];
|
|
}
|
|
}
|
|
}
|
|
pullFromChild(childExecutor, parentSubexecutor, onEmitted, subexecutor) {
|
|
return Read(childExecutor, identity, (emitted) => {
|
|
const childExecutorDecision = onEmitted(emitted);
|
|
switch (childExecutorDecision._tag) {
|
|
case OP_CONTINUE2: {
|
|
break;
|
|
}
|
|
case OP_CLOSE: {
|
|
this.finishWithDoneValue(childExecutor, parentSubexecutor, childExecutorDecision.value);
|
|
break;
|
|
}
|
|
case OP_YIELD2: {
|
|
const modifiedParent = parentSubexecutor.enqueuePullFromChild(subexecutor);
|
|
this.replaceSubexecutor(modifiedParent);
|
|
break;
|
|
}
|
|
}
|
|
this._activeSubexecutor = new Emit2(emitted, this._activeSubexecutor);
|
|
return;
|
|
}, match9({
|
|
onFailure: (cause) => {
|
|
const state = this.handleSubexecutorFailure(childExecutor, parentSubexecutor, cause);
|
|
return state === undefined ? undefined : effectOrUndefinedIgnored(state);
|
|
},
|
|
onSuccess: (doneValue) => {
|
|
this.finishWithDoneValue(childExecutor, parentSubexecutor, doneValue);
|
|
return;
|
|
}
|
|
}));
|
|
}
|
|
finishWithDoneValue(childExecutor, parentSubexecutor, doneValue) {
|
|
const subexecutor = parentSubexecutor;
|
|
switch (subexecutor._tag) {
|
|
case OP_PULL_FROM_UPSTREAM: {
|
|
const modifiedParent = new PullFromUpstream(subexecutor.upstreamExecutor, subexecutor.createChild, subexecutor.lastDone !== undefined ? subexecutor.combineChildResults(subexecutor.lastDone, doneValue) : doneValue, subexecutor.activeChildExecutors, subexecutor.combineChildResults, subexecutor.combineWithChildResult, subexecutor.onPull, subexecutor.onEmit);
|
|
this._closeLastSubstream = childExecutor.close(succeed4(doneValue));
|
|
this.replaceSubexecutor(modifiedParent);
|
|
break;
|
|
}
|
|
case OP_DRAIN_CHILD_EXECUTORS: {
|
|
const modifiedParent = new DrainChildExecutors(subexecutor.upstreamExecutor, subexecutor.lastDone !== undefined ? subexecutor.combineChildResults(subexecutor.lastDone, doneValue) : doneValue, subexecutor.activeChildExecutors, subexecutor.upstreamDone, subexecutor.combineChildResults, subexecutor.combineWithChildResult, subexecutor.onPull);
|
|
this._closeLastSubstream = childExecutor.close(succeed4(doneValue));
|
|
this.replaceSubexecutor(modifiedParent);
|
|
break;
|
|
}
|
|
default: {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
handleSubexecutorFailure(childExecutor, parentSubexecutor, cause) {
|
|
return this.finishSubexecutorWithCloseEffect(failCause4(cause), (exit) => parentSubexecutor.close(exit), (exit) => childExecutor.close(exit));
|
|
}
|
|
pullFromUpstream(subexecutor) {
|
|
if (subexecutor.activeChildExecutors.length === 0) {
|
|
return this.performPullFromUpstream(subexecutor);
|
|
}
|
|
const activeChild = subexecutor.activeChildExecutors[0];
|
|
const parentSubexecutor = new PullFromUpstream(subexecutor.upstreamExecutor, subexecutor.createChild, subexecutor.lastDone, subexecutor.activeChildExecutors.slice(1), subexecutor.combineChildResults, subexecutor.combineWithChildResult, subexecutor.onPull, subexecutor.onEmit);
|
|
if (activeChild === undefined) {
|
|
return this.performPullFromUpstream(parentSubexecutor);
|
|
}
|
|
this.replaceSubexecutor(new PullFromChild(activeChild.childExecutor, parentSubexecutor, activeChild.onEmit));
|
|
return;
|
|
}
|
|
performPullFromUpstream(subexecutor) {
|
|
return Read(subexecutor.upstreamExecutor, (effect) => {
|
|
const closeLastSubstream = this._closeLastSubstream === undefined ? _void : this._closeLastSubstream;
|
|
this._closeLastSubstream = undefined;
|
|
return pipe(this._executeCloseLastSubstream(closeLastSubstream), zipRight3(effect));
|
|
}, (emitted) => {
|
|
if (this._closeLastSubstream !== undefined) {
|
|
const closeLastSubstream = this._closeLastSubstream;
|
|
this._closeLastSubstream = undefined;
|
|
return pipe(this._executeCloseLastSubstream(closeLastSubstream), map15(() => {
|
|
const childExecutor = new ChannelExecutor(subexecutor.createChild(emitted), this._providedEnv, this._executeCloseLastSubstream);
|
|
childExecutor._input = this._input;
|
|
const [emitSeparator, updatedChildExecutors] = this.applyUpstreamPullStrategy(false, subexecutor.activeChildExecutors, subexecutor.onPull(Pulled(emitted)));
|
|
this._activeSubexecutor = new PullFromChild(childExecutor, new PullFromUpstream(subexecutor.upstreamExecutor, subexecutor.createChild, subexecutor.lastDone, updatedChildExecutors, subexecutor.combineChildResults, subexecutor.combineWithChildResult, subexecutor.onPull, subexecutor.onEmit), subexecutor.onEmit);
|
|
if (isSome2(emitSeparator)) {
|
|
this._activeSubexecutor = new Emit2(emitSeparator.value, this._activeSubexecutor);
|
|
}
|
|
return;
|
|
}));
|
|
}
|
|
const childExecutor = new ChannelExecutor(subexecutor.createChild(emitted), this._providedEnv, this._executeCloseLastSubstream);
|
|
childExecutor._input = this._input;
|
|
const [emitSeparator, updatedChildExecutors] = this.applyUpstreamPullStrategy(false, subexecutor.activeChildExecutors, subexecutor.onPull(Pulled(emitted)));
|
|
this._activeSubexecutor = new PullFromChild(childExecutor, new PullFromUpstream(subexecutor.upstreamExecutor, subexecutor.createChild, subexecutor.lastDone, updatedChildExecutors, subexecutor.combineChildResults, subexecutor.combineWithChildResult, subexecutor.onPull, subexecutor.onEmit), subexecutor.onEmit);
|
|
if (isSome2(emitSeparator)) {
|
|
this._activeSubexecutor = new Emit2(emitSeparator.value, this._activeSubexecutor);
|
|
}
|
|
return;
|
|
}, (exit) => {
|
|
if (subexecutor.activeChildExecutors.some((subexecutor) => subexecutor !== undefined)) {
|
|
const drain = new DrainChildExecutors(subexecutor.upstreamExecutor, subexecutor.lastDone, [undefined, ...subexecutor.activeChildExecutors], subexecutor.upstreamExecutor.getDone(), subexecutor.combineChildResults, subexecutor.combineWithChildResult, subexecutor.onPull);
|
|
if (this._closeLastSubstream !== undefined) {
|
|
const closeLastSubstream = this._closeLastSubstream;
|
|
this._closeLastSubstream = undefined;
|
|
return pipe(this._executeCloseLastSubstream(closeLastSubstream), map15(() => this.replaceSubexecutor(drain)));
|
|
}
|
|
this.replaceSubexecutor(drain);
|
|
return;
|
|
}
|
|
const closeLastSubstream = this._closeLastSubstream;
|
|
const state = this.finishSubexecutorWithCloseEffect(pipe(exit, map12((a) => subexecutor.combineWithChildResult(subexecutor.lastDone, a))), () => closeLastSubstream, (exit) => subexecutor.upstreamExecutor.close(exit));
|
|
return state === undefined ? undefined : effectOrUndefinedIgnored(state);
|
|
});
|
|
}
|
|
drainChildExecutors(subexecutor) {
|
|
if (subexecutor.activeChildExecutors.length === 0) {
|
|
const lastClose = this._closeLastSubstream;
|
|
if (lastClose !== undefined) {
|
|
this.addFinalizer(() => succeed7(lastClose));
|
|
}
|
|
return this.finishSubexecutorWithCloseEffect(subexecutor.upstreamDone, () => lastClose, (exit) => subexecutor.upstreamExecutor.close(exit));
|
|
}
|
|
const activeChild = subexecutor.activeChildExecutors[0];
|
|
const rest = subexecutor.activeChildExecutors.slice(1);
|
|
if (activeChild === undefined) {
|
|
const [emitSeparator, remainingExecutors] = this.applyUpstreamPullStrategy(true, rest, subexecutor.onPull(NoUpstream(rest.reduce((n, curr) => curr !== undefined ? n + 1 : n, 0))));
|
|
this.replaceSubexecutor(new DrainChildExecutors(subexecutor.upstreamExecutor, subexecutor.lastDone, remainingExecutors, subexecutor.upstreamDone, subexecutor.combineChildResults, subexecutor.combineWithChildResult, subexecutor.onPull));
|
|
if (isSome2(emitSeparator)) {
|
|
this._emitted = emitSeparator.value;
|
|
return Emit();
|
|
}
|
|
return;
|
|
}
|
|
const parentSubexecutor = new DrainChildExecutors(subexecutor.upstreamExecutor, subexecutor.lastDone, rest, subexecutor.upstreamDone, subexecutor.combineChildResults, subexecutor.combineWithChildResult, subexecutor.onPull);
|
|
this.replaceSubexecutor(new PullFromChild(activeChild.childExecutor, parentSubexecutor, activeChild.onEmit));
|
|
return;
|
|
}
|
|
}
|
|
var ifNotNull = (effect) => effect !== undefined ? effect : _void;
|
|
var runFinalizers = (finalizers, exit) => {
|
|
return pipe(forEach4(finalizers, (fin) => exit2(fin(exit))), map15((exits) => pipe(all2(exits), getOrElse(() => void_3))), flatMap9((exit) => suspend2(() => exit)));
|
|
};
|
|
var readUpstream = (r, onSuccess, onFailure) => {
|
|
const readStack = [r];
|
|
const read = () => {
|
|
const current = readStack.pop();
|
|
if (current === undefined || current.upstream === undefined) {
|
|
return dieMessage2("Unexpected end of input for channel execution");
|
|
}
|
|
const state = current.upstream.run();
|
|
switch (state._tag) {
|
|
case OP_EMIT2: {
|
|
const emitEffect = current.onEmit(current.upstream.getEmit());
|
|
if (readStack.length === 0) {
|
|
if (emitEffect === undefined) {
|
|
return suspend2(onSuccess);
|
|
}
|
|
return pipe(emitEffect, matchCauseEffect3({
|
|
onFailure,
|
|
onSuccess
|
|
}));
|
|
}
|
|
if (emitEffect === undefined) {
|
|
return suspend2(() => read());
|
|
}
|
|
return pipe(emitEffect, matchCauseEffect3({
|
|
onFailure,
|
|
onSuccess: () => read()
|
|
}));
|
|
}
|
|
case OP_DONE3: {
|
|
const doneEffect = current.onDone(current.upstream.getDone());
|
|
if (readStack.length === 0) {
|
|
if (doneEffect === undefined) {
|
|
return suspend2(onSuccess);
|
|
}
|
|
return pipe(doneEffect, matchCauseEffect3({
|
|
onFailure,
|
|
onSuccess
|
|
}));
|
|
}
|
|
if (doneEffect === undefined) {
|
|
return suspend2(() => read());
|
|
}
|
|
return pipe(doneEffect, matchCauseEffect3({
|
|
onFailure,
|
|
onSuccess: () => read()
|
|
}));
|
|
}
|
|
case OP_FROM_EFFECT3: {
|
|
readStack.push(current);
|
|
return pipe(current.onEffect(state.effect), catchAllCause2((cause) => suspend2(() => {
|
|
const doneEffect = current.onDone(failCause4(cause));
|
|
return doneEffect === undefined ? _void : doneEffect;
|
|
})), matchCauseEffect3({
|
|
onFailure,
|
|
onSuccess: () => read()
|
|
}));
|
|
}
|
|
case OP_READ2: {
|
|
readStack.push(current);
|
|
readStack.push(state);
|
|
return suspend2(() => read());
|
|
}
|
|
}
|
|
};
|
|
return read();
|
|
};
|
|
var runIn = /* @__PURE__ */ dual(2, (self2, scope) => {
|
|
const run = (channelDeferred, scopeDeferred, scope) => acquireUseRelease2(sync3(() => new ChannelExecutor(self2, undefined, identity)), (exec) => suspend2(() => runScopedInterpret(exec.run(), exec).pipe(intoDeferred2(channelDeferred), zipRight3(_await(channelDeferred)), zipLeft2(_await(scopeDeferred)))), (exec, exit) => {
|
|
const finalize = exec.close(exit);
|
|
if (finalize === undefined) {
|
|
return _void;
|
|
}
|
|
return tapErrorCause2(finalize, (cause) => addFinalizer2(scope, failCause6(cause)));
|
|
});
|
|
return uninterruptibleMask3((restore) => all4([fork(scope, sequential3), make18(), make18()]).pipe(flatMap9(([child, channelDeferred, scopeDeferred]) => restore(run(channelDeferred, scopeDeferred, child)).pipe(forkIn2(scope), flatMap9((fiber) => scope.addFinalizer((exit) => {
|
|
const interruptors = isFailure2(exit) ? interruptors2(exit.cause) : undefined;
|
|
return isDone(channelDeferred).pipe(flatMap9((isDone) => isDone ? succeed2(scopeDeferred, undefined).pipe(zipRight3(_await3(fiber)), zipRight3(inheritAll2(fiber))) : succeed2(scopeDeferred, undefined).pipe(zipRight3(interruptors && size3(interruptors) > 0 ? interruptAs(fiber, combineAll2(interruptors)) : interrupt4(fiber)), zipRight3(inheritAll2(fiber)))));
|
|
}).pipe(zipRight3(restore(_await(channelDeferred)))))))));
|
|
});
|
|
var runScopedInterpret = (channelState, exec) => {
|
|
const op = channelState;
|
|
switch (op._tag) {
|
|
case OP_FROM_EFFECT3: {
|
|
return pipe(op.effect, flatMap9(() => runScopedInterpret(exec.run(), exec)));
|
|
}
|
|
case OP_EMIT2: {
|
|
return runScopedInterpret(exec.run(), exec);
|
|
}
|
|
case OP_DONE3: {
|
|
return suspend2(() => exec.getDone());
|
|
}
|
|
case OP_READ2: {
|
|
return readUpstream(op, () => runScopedInterpret(exec.run(), exec), failCause6);
|
|
}
|
|
}
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/opCodes/channelMergeDecision.js
|
|
var OP_DONE4 = "Done";
|
|
var OP_AWAIT = "Await";
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/channel/mergeDecision.js
|
|
var MergeDecisionSymbolKey = "effect/ChannelMergeDecision";
|
|
var MergeDecisionTypeId = /* @__PURE__ */ Symbol.for(MergeDecisionSymbolKey);
|
|
var proto9 = {
|
|
[MergeDecisionTypeId]: {
|
|
_R: (_) => _,
|
|
_E0: (_) => _,
|
|
_Z0: (_) => _,
|
|
_E: (_) => _,
|
|
_Z: (_) => _
|
|
}
|
|
};
|
|
var Await = (f) => {
|
|
const op = Object.create(proto9);
|
|
op._tag = OP_AWAIT;
|
|
op.f = f;
|
|
return op;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/opCodes/channelMergeState.js
|
|
var OP_BOTH_RUNNING = "BothRunning";
|
|
var OP_LEFT_DONE = "LeftDone";
|
|
var OP_RIGHT_DONE = "RightDone";
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/channel/mergeState.js
|
|
var MergeStateSymbolKey = "effect/ChannelMergeState";
|
|
var MergeStateTypeId = /* @__PURE__ */ Symbol.for(MergeStateSymbolKey);
|
|
var proto10 = {
|
|
[MergeStateTypeId]: MergeStateTypeId
|
|
};
|
|
var BothRunning = (left, right) => {
|
|
const op = Object.create(proto10);
|
|
op._tag = OP_BOTH_RUNNING;
|
|
op.left = left;
|
|
op.right = right;
|
|
return op;
|
|
};
|
|
var LeftDone = (f) => {
|
|
const op = Object.create(proto10);
|
|
op._tag = OP_LEFT_DONE;
|
|
op.f = f;
|
|
return op;
|
|
};
|
|
var RightDone = (f) => {
|
|
const op = Object.create(proto10);
|
|
op._tag = OP_RIGHT_DONE;
|
|
op.f = f;
|
|
return op;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/opCodes/channelMergeStrategy.js
|
|
var OP_BACK_PRESSURE = "BackPressure";
|
|
var OP_BUFFER_SLIDING = "BufferSliding";
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/channel/mergeStrategy.js
|
|
var MergeStrategySymbolKey = "effect/ChannelMergeStrategy";
|
|
var MergeStrategyTypeId = /* @__PURE__ */ Symbol.for(MergeStrategySymbolKey);
|
|
var proto11 = {
|
|
[MergeStrategyTypeId]: MergeStrategyTypeId
|
|
};
|
|
var BackPressure = (_) => {
|
|
const op = Object.create(proto11);
|
|
op._tag = OP_BACK_PRESSURE;
|
|
return op;
|
|
};
|
|
var BufferSliding = (_) => {
|
|
const op = Object.create(proto11);
|
|
op._tag = OP_BUFFER_SLIDING;
|
|
return op;
|
|
};
|
|
var match13 = /* @__PURE__ */ dual(2, (self2, {
|
|
onBackPressure,
|
|
onBufferSliding
|
|
}) => {
|
|
switch (self2._tag) {
|
|
case OP_BACK_PRESSURE: {
|
|
return onBackPressure();
|
|
}
|
|
case OP_BUFFER_SLIDING: {
|
|
return onBufferSliding();
|
|
}
|
|
}
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/channel/singleProducerAsyncInput.js
|
|
var OP_STATE_EMPTY = "Empty";
|
|
var OP_STATE_EMIT = "Emit";
|
|
var OP_STATE_ERROR = "Error";
|
|
var OP_STATE_DONE2 = "Done";
|
|
var stateEmpty = (notifyProducer) => ({
|
|
_tag: OP_STATE_EMPTY,
|
|
notifyProducer
|
|
});
|
|
var stateEmit = (notifyConsumers) => ({
|
|
_tag: OP_STATE_EMIT,
|
|
notifyConsumers
|
|
});
|
|
var stateError = (cause) => ({
|
|
_tag: OP_STATE_ERROR,
|
|
cause
|
|
});
|
|
var stateDone = (done) => ({
|
|
_tag: OP_STATE_DONE2,
|
|
done
|
|
});
|
|
|
|
class SingleProducerAsyncInputImpl {
|
|
ref;
|
|
constructor(ref) {
|
|
this.ref = ref;
|
|
}
|
|
awaitRead() {
|
|
return flatten5(modify4(this.ref, (state) => state._tag === OP_STATE_EMPTY ? [_await(state.notifyProducer), state] : [_void, state]));
|
|
}
|
|
get close() {
|
|
return fiberIdWith2((fiberId) => this.error(interrupt3(fiberId)));
|
|
}
|
|
done(value) {
|
|
return flatten5(modify4(this.ref, (state) => {
|
|
switch (state._tag) {
|
|
case OP_STATE_EMPTY: {
|
|
return [_await(state.notifyProducer), state];
|
|
}
|
|
case OP_STATE_EMIT: {
|
|
return [forEach4(state.notifyConsumers, (deferred) => succeed2(deferred, left2(value)), {
|
|
discard: true
|
|
}), stateDone(value)];
|
|
}
|
|
case OP_STATE_ERROR: {
|
|
return [interrupt5, state];
|
|
}
|
|
case OP_STATE_DONE2: {
|
|
return [interrupt5, state];
|
|
}
|
|
}
|
|
}));
|
|
}
|
|
emit(element) {
|
|
return flatMap9(make18(), (deferred) => flatten5(modify4(this.ref, (state) => {
|
|
switch (state._tag) {
|
|
case OP_STATE_EMPTY: {
|
|
return [_await(state.notifyProducer), state];
|
|
}
|
|
case OP_STATE_EMIT: {
|
|
const notifyConsumer = state.notifyConsumers[0];
|
|
const notifyConsumers = state.notifyConsumers.slice(1);
|
|
if (notifyConsumer !== undefined) {
|
|
return [succeed2(notifyConsumer, right2(element)), notifyConsumers.length === 0 ? stateEmpty(deferred) : stateEmit(notifyConsumers)];
|
|
}
|
|
throw new Error("Bug: Channel.SingleProducerAsyncInput.emit - Queue was empty! please report an issue at https://github.com/Effect-TS/effect/issues");
|
|
}
|
|
case OP_STATE_ERROR: {
|
|
return [interrupt5, state];
|
|
}
|
|
case OP_STATE_DONE2: {
|
|
return [interrupt5, state];
|
|
}
|
|
}
|
|
})));
|
|
}
|
|
error(cause) {
|
|
return flatten5(modify4(this.ref, (state) => {
|
|
switch (state._tag) {
|
|
case OP_STATE_EMPTY: {
|
|
return [_await(state.notifyProducer), state];
|
|
}
|
|
case OP_STATE_EMIT: {
|
|
return [forEach4(state.notifyConsumers, (deferred) => failCause2(deferred, cause), {
|
|
discard: true
|
|
}), stateError(cause)];
|
|
}
|
|
case OP_STATE_ERROR: {
|
|
return [interrupt5, state];
|
|
}
|
|
case OP_STATE_DONE2: {
|
|
return [interrupt5, state];
|
|
}
|
|
}
|
|
}));
|
|
}
|
|
get take() {
|
|
return this.takeWith((cause) => failCause4(map11(cause, left2)), (elem) => succeed4(elem), (done) => fail4(right2(done)));
|
|
}
|
|
takeWith(onError, onElement, onDone) {
|
|
return flatMap9(make18(), (deferred) => flatten5(modify4(this.ref, (state) => {
|
|
switch (state._tag) {
|
|
case OP_STATE_EMPTY: {
|
|
return [zipRight3(succeed2(state.notifyProducer, undefined), matchCause2(_await(deferred), {
|
|
onFailure: onError,
|
|
onSuccess: match({
|
|
onLeft: onDone,
|
|
onRight: onElement
|
|
})
|
|
})), stateEmit([deferred])];
|
|
}
|
|
case OP_STATE_EMIT: {
|
|
return [matchCause2(_await(deferred), {
|
|
onFailure: onError,
|
|
onSuccess: match({
|
|
onLeft: onDone,
|
|
onRight: onElement
|
|
})
|
|
}), stateEmit([...state.notifyConsumers, deferred])];
|
|
}
|
|
case OP_STATE_ERROR: {
|
|
return [succeed7(onError(state.cause)), state];
|
|
}
|
|
case OP_STATE_DONE2: {
|
|
return [succeed7(onDone(state.done)), state];
|
|
}
|
|
}
|
|
})));
|
|
}
|
|
}
|
|
var make39 = () => pipe(make18(), flatMap9((deferred) => make25(stateEmpty(deferred))), map15((ref) => new SingleProducerAsyncInputImpl(ref)));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/channel.js
|
|
var concatMap = /* @__PURE__ */ dual(2, (self2, f) => concatMapWith(self2, f, () => {
|
|
return;
|
|
}, () => {
|
|
return;
|
|
}));
|
|
var drain = (self2) => {
|
|
const drainer = readWithCause({
|
|
onInput: () => drainer,
|
|
onFailure: failCause8,
|
|
onDone: succeed9
|
|
});
|
|
return pipeTo(self2, drainer);
|
|
};
|
|
var ensuring3 = /* @__PURE__ */ dual(2, (self2, finalizer) => ensuringWith(self2, () => finalizer));
|
|
var flatten7 = (self2) => flatMap11(self2, identity);
|
|
var fromInput = (input) => unwrap(input.takeWith(failCause8, (elem) => flatMap11(write(elem), () => fromInput(input)), succeed9));
|
|
var map17 = /* @__PURE__ */ dual(2, (self2, f) => flatMap11(self2, (a) => sync4(() => f(a))));
|
|
var mapOut = /* @__PURE__ */ dual(2, (self2, f) => {
|
|
const reader = readWith({
|
|
onInput: (outElem) => flatMap11(write(f(outElem)), () => reader),
|
|
onFailure: fail8,
|
|
onDone: succeedNow
|
|
});
|
|
return pipeTo(self2, reader);
|
|
});
|
|
var mapOutEffect = /* @__PURE__ */ dual(2, (self2, f) => {
|
|
const reader = readWithCause({
|
|
onInput: (outElem) => pipe(fromEffect4(f(outElem)), flatMap11(write), flatMap11(() => reader)),
|
|
onFailure: failCause8,
|
|
onDone: succeedNow
|
|
});
|
|
return pipeTo(self2, reader);
|
|
});
|
|
var mergeAll5 = (options) => {
|
|
return (channels) => mergeAllWith(options)(channels, constVoid);
|
|
};
|
|
var mergeAllWith = ({
|
|
bufferSize = 16,
|
|
concurrency,
|
|
mergeStrategy = BackPressure()
|
|
}) => (channels, f) => unwrapScopedWith((scope) => gen2(function* () {
|
|
const concurrencyN = concurrency === "unbounded" ? Number.MAX_SAFE_INTEGER : concurrency;
|
|
const input = yield* make39();
|
|
const queueReader = fromInput(input);
|
|
const queue = yield* bounded3(bufferSize);
|
|
yield* addFinalizer2(scope, shutdown2(queue));
|
|
const cancelers = yield* unbounded3();
|
|
yield* addFinalizer2(scope, shutdown2(cancelers));
|
|
const lastDone = yield* make25(none2());
|
|
const errorSignal = yield* make18();
|
|
const withPermits = (yield* makeSemaphore2(concurrencyN)).withPermits;
|
|
const pull = yield* toPullIn(pipeTo(queueReader, channels), scope);
|
|
function evaluatePull(pull) {
|
|
return pull.pipe(flatMap9(match({
|
|
onLeft: (done) => succeed7(some2(done)),
|
|
onRight: (outElem) => as3(offer3(queue, succeed7(right2(outElem))), none2())
|
|
})), repeat({
|
|
until: (_) => isSome2(_)
|
|
}), flatMap9((outDone) => update3(lastDone, match2({
|
|
onNone: () => some2(outDone.value),
|
|
onSome: (lastDone) => some2(f(lastDone, outDone.value))
|
|
}))), catchAllCause2((cause) => isInterrupted2(cause) ? failCause6(cause) : offer3(queue, failCause6(cause)).pipe(zipRight3(succeed2(errorSignal, undefined)), asVoid2)));
|
|
}
|
|
yield* pull.pipe(matchCauseEffect3({
|
|
onFailure: (cause) => offer3(queue, failCause6(cause)).pipe(zipRight3(succeed7(false))),
|
|
onSuccess: match({
|
|
onLeft: (outDone) => raceWith2(interruptible4(_await(errorSignal)), interruptible4(withPermits(concurrencyN)(_void)), {
|
|
onSelfDone: (_, permitAcquisition) => as3(interrupt4(permitAcquisition), false),
|
|
onOtherDone: (_, failureAwait) => zipRight3(interrupt4(failureAwait), get10(lastDone).pipe(flatMap9(match2({
|
|
onNone: () => offer3(queue, succeed7(left2(outDone))),
|
|
onSome: (lastDone) => offer3(queue, succeed7(left2(f(lastDone, outDone))))
|
|
})), as3(false)))
|
|
}),
|
|
onRight: (channel) => match13(mergeStrategy, {
|
|
onBackPressure: () => gen2(function* () {
|
|
const latch = yield* make18();
|
|
const raceEffects = scopedWith2((scope) => toPullIn(pipeTo(queueReader, channel), scope).pipe(flatMap9((pull) => race2(exit2(evaluatePull(pull)), exit2(interruptible4(_await(errorSignal))))), flatMap9(identity)));
|
|
yield* succeed2(latch, undefined).pipe(zipRight3(raceEffects), withPermits(1), forkIn2(scope));
|
|
yield* _await(latch);
|
|
const errored = yield* isDone(errorSignal);
|
|
return !errored;
|
|
}),
|
|
onBufferSliding: () => gen2(function* () {
|
|
const canceler = yield* make18();
|
|
const latch = yield* make18();
|
|
const size = yield* size8(cancelers);
|
|
yield* take2(cancelers).pipe(flatMap9((canceler) => succeed2(canceler, undefined)), when2(() => size >= concurrencyN));
|
|
yield* offer3(cancelers, canceler);
|
|
const raceEffects = scopedWith2((scope) => toPullIn(pipeTo(queueReader, channel), scope).pipe(flatMap9((pull) => exit2(evaluatePull(pull)).pipe(race2(exit2(interruptible4(_await(errorSignal)))), race2(exit2(interruptible4(_await(canceler)))))), flatMap9(identity)));
|
|
yield* succeed2(latch, undefined).pipe(zipRight3(raceEffects), withPermits(1), forkIn2(scope));
|
|
yield* _await(latch);
|
|
const errored = yield* isDone(errorSignal);
|
|
return !errored;
|
|
})
|
|
})
|
|
})
|
|
}), repeat({
|
|
while: (_) => _
|
|
}), forkIn2(scope));
|
|
const consumer = pipe(take2(queue), flatten5, matchCause2({
|
|
onFailure: failCause8,
|
|
onSuccess: match({
|
|
onLeft: succeedNow,
|
|
onRight: (outElem) => flatMap11(write(outElem), () => consumer)
|
|
})
|
|
}), unwrap);
|
|
return embedInput(consumer, input);
|
|
}));
|
|
var mergeMap = /* @__PURE__ */ dual(3, (self2, f, options) => mergeAll5(options)(mapOut(self2, f)));
|
|
var mergeWith2 = /* @__PURE__ */ dual(2, (self2, options) => {
|
|
function merge(scope) {
|
|
return gen2(function* () {
|
|
const input = yield* make39();
|
|
const queueReader = fromInput(input);
|
|
const pullL = yield* toPullIn(pipeTo(queueReader, self2), scope);
|
|
const pullR = yield* toPullIn(pipeTo(queueReader, options.other), scope);
|
|
function handleSide(exit, fiber, pull) {
|
|
return (done, both, single) => {
|
|
function onDecision(decision) {
|
|
const op = decision;
|
|
if (op._tag === OP_DONE4) {
|
|
return succeed7(fromEffect4(zipRight3(interrupt4(fiber), op.effect)));
|
|
}
|
|
return map15(_await3(fiber), match9({
|
|
onFailure: (cause) => fromEffect4(op.f(failCause4(cause))),
|
|
onSuccess: match({
|
|
onLeft: (done) => fromEffect4(op.f(succeed4(done))),
|
|
onRight: (elem) => zipRight4(write(elem), go(single(op.f)))
|
|
})
|
|
}));
|
|
}
|
|
return match9(exit, {
|
|
onFailure: (cause) => onDecision(done(failCause4(cause))),
|
|
onSuccess: match({
|
|
onLeft: (z) => onDecision(done(succeed4(z))),
|
|
onRight: (elem) => succeed7(flatMap11(write(elem), () => flatMap11(fromEffect4(forkIn2(interruptible4(pull), scope)), (leftFiber) => go(both(leftFiber, fiber)))))
|
|
})
|
|
});
|
|
};
|
|
}
|
|
function go(state) {
|
|
switch (state._tag) {
|
|
case OP_BOTH_RUNNING: {
|
|
const leftJoin = interruptible4(join3(state.left));
|
|
const rightJoin = interruptible4(join3(state.right));
|
|
return unwrap(raceWith2(leftJoin, rightJoin, {
|
|
onSelfDone: (leftExit, rf) => zipRight3(interrupt4(rf), handleSide(leftExit, state.right, pullL)(options.onSelfDone, BothRunning, (f) => LeftDone(f))),
|
|
onOtherDone: (rightExit, lf) => zipRight3(interrupt4(lf), handleSide(rightExit, state.left, pullR)(options.onOtherDone, (left, right) => BothRunning(right, left), (f) => RightDone(f)))
|
|
}));
|
|
}
|
|
case OP_LEFT_DONE: {
|
|
return unwrap(map15(exit2(pullR), match9({
|
|
onFailure: (cause) => fromEffect4(state.f(failCause4(cause))),
|
|
onSuccess: match({
|
|
onLeft: (done) => fromEffect4(state.f(succeed4(done))),
|
|
onRight: (elem) => flatMap11(write(elem), () => go(LeftDone(state.f)))
|
|
})
|
|
})));
|
|
}
|
|
case OP_RIGHT_DONE: {
|
|
return unwrap(map15(exit2(pullL), match9({
|
|
onFailure: (cause) => fromEffect4(state.f(failCause4(cause))),
|
|
onSuccess: match({
|
|
onLeft: (done) => fromEffect4(state.f(succeed4(done))),
|
|
onRight: (elem) => flatMap11(write(elem), () => go(RightDone(state.f)))
|
|
})
|
|
})));
|
|
}
|
|
}
|
|
}
|
|
return fromEffect4(withFiberRuntime2((parent) => {
|
|
const inherit = withFiberRuntime2((state) => {
|
|
state.transferChildren(parent.scope());
|
|
return _void;
|
|
});
|
|
const leftFiber = interruptible4(pullL).pipe(ensuring2(inherit), forkIn2(scope));
|
|
const rightFiber = interruptible4(pullR).pipe(ensuring2(inherit), forkIn2(scope));
|
|
return zipWith3(leftFiber, rightFiber, (left, right) => BothRunning(left, right));
|
|
})).pipe(flatMap11(go), embedInput(input));
|
|
});
|
|
}
|
|
return unwrapScopedWith(merge);
|
|
});
|
|
var runScoped = (self2) => scopeWith2((scope) => runIn(self2, scope));
|
|
var scoped3 = (effect) => unwrap(uninterruptibleMask3((restore) => map15(make35(), (scope) => acquireReleaseOut(tapErrorCause2(restore(extend2(effect, scope)), (cause) => close(scope, failCause4(cause))), (_, exit) => close(scope, exit)))));
|
|
var scopedWith3 = (f) => unwrapScoped2(map15(scope2, (scope) => flatMap11(fromEffect4(f(scope)), write)));
|
|
var toPullIn = /* @__PURE__ */ dual(2, (self2, scope) => zip5(sync3(() => new ChannelExecutor(self2, undefined, identity)), runtime3()).pipe(tap2(([executor, runtime]) => addFinalizerExit(scope, (exit) => {
|
|
const finalizer = executor.close(exit);
|
|
return finalizer !== undefined ? provide2(finalizer, runtime) : _void;
|
|
})), uninterruptible2, map15(([executor]) => suspend2(() => interpretToPull(executor.run(), executor)))));
|
|
var interpretToPull = (channelState, exec) => {
|
|
const state = channelState;
|
|
switch (state._tag) {
|
|
case OP_DONE3: {
|
|
return match9(exec.getDone(), {
|
|
onFailure: failCause6,
|
|
onSuccess: (done) => succeed7(left2(done))
|
|
});
|
|
}
|
|
case OP_EMIT2: {
|
|
return succeed7(right2(exec.getEmit()));
|
|
}
|
|
case OP_FROM_EFFECT3: {
|
|
return pipe(state.effect, flatMap9(() => interpretToPull(exec.run(), exec)));
|
|
}
|
|
case OP_READ2: {
|
|
return readUpstream(state, () => interpretToPull(exec.run(), exec), (cause) => failCause6(cause));
|
|
}
|
|
}
|
|
};
|
|
var unwrap = (channel) => flatten7(fromEffect4(channel));
|
|
var unwrapScoped2 = (self2) => concatAllWith(scoped3(self2), (d, _) => d, (d, _) => d);
|
|
var unwrapScopedWith = (f) => concatAllWith(scopedWith3(f), (d, _) => d, (d, _) => d);
|
|
var writeChunk = (outs) => writeChunkWriter(0, outs.length, outs);
|
|
var writeChunkWriter = (idx, len, chunk) => {
|
|
return idx === len ? void_5 : pipe(write(pipe(chunk, unsafeGet4(idx))), flatMap11(() => writeChunkWriter(idx + 1, len, chunk)));
|
|
};
|
|
var zip6 = /* @__PURE__ */ dual((args) => isChannel(args[1]), (self2, that, options) => options?.concurrent ? mergeWith2(self2, {
|
|
other: that,
|
|
onSelfDone: (exit1) => Await((exit2) => suspend2(() => zip3(exit1, exit2))),
|
|
onOtherDone: (exit2) => Await((exit1) => suspend2(() => zip3(exit1, exit2)))
|
|
}) : flatMap11(self2, (a) => map17(that, (b) => [a, b])));
|
|
var zipRight4 = /* @__PURE__ */ dual((args) => isChannel(args[1]), (self2, that, options) => options?.concurrent ? map17(zip6(self2, that, {
|
|
concurrent: true
|
|
}), (tuple) => tuple[1]) : flatMap11(self2, () => that));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/sink.js
|
|
var SinkTypeId2 = /* @__PURE__ */ Symbol.for("effect/Sink");
|
|
var sinkVariance2 = {
|
|
_A: (_) => _,
|
|
_In: (_) => _,
|
|
_L: (_) => _,
|
|
_E: (_) => _,
|
|
_R: (_) => _
|
|
};
|
|
|
|
class SinkImpl {
|
|
channel;
|
|
[SinkTypeId2] = sinkVariance2;
|
|
constructor(channel) {
|
|
this.channel = channel;
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
}
|
|
var forEach5 = (f) => {
|
|
const process2 = readWithCause({
|
|
onInput: (input) => pipe(fromEffect4(forEach4(input, (v) => f(v), {
|
|
discard: true
|
|
})), flatMap11(() => process2)),
|
|
onFailure: failCause8,
|
|
onDone: () => void_5
|
|
});
|
|
return new SinkImpl(process2);
|
|
};
|
|
var fromEffect6 = (effect) => new SinkImpl(fromEffect4(effect));
|
|
var toChannel = (self2) => isEffect2(self2) ? toChannel(fromEffect6(self2)) : self2.channel;
|
|
var unwrapScoped3 = (effect) => new SinkImpl(unwrapScoped2(effect.pipe(map15((sink) => toChannel(sink)))));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Runtime.js
|
|
var runPromiseExit = unsafeRunPromiseExit;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/stream/emit.js
|
|
var make40 = (emit) => {
|
|
const ops = {
|
|
chunk(as) {
|
|
return this(succeed7(as));
|
|
},
|
|
die(defect) {
|
|
return this(die5(defect));
|
|
},
|
|
dieMessage(message) {
|
|
return this(dieMessage2(message));
|
|
},
|
|
done(exit) {
|
|
return this(suspend2(() => mapBoth2(exit, {
|
|
onFailure: some2,
|
|
onSuccess: of2
|
|
})));
|
|
},
|
|
end() {
|
|
return this(fail6(none2()));
|
|
},
|
|
fail(e) {
|
|
return this(fail6(some2(e)));
|
|
},
|
|
fromEffect(effect) {
|
|
return this(mapBoth3(effect, {
|
|
onFailure: some2,
|
|
onSuccess: of2
|
|
}));
|
|
},
|
|
fromEffectChunk(effect) {
|
|
return this(pipe(effect, mapError2(some2)));
|
|
},
|
|
halt(cause) {
|
|
return this(failCause6(pipe(cause, map11(some2))));
|
|
},
|
|
single(value) {
|
|
return this(succeed7(of2(value)));
|
|
}
|
|
};
|
|
return Object.assign(emit, ops);
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/take.js
|
|
var TakeSymbolKey = "effect/Take";
|
|
var TakeTypeId = /* @__PURE__ */ Symbol.for(TakeSymbolKey);
|
|
var takeVariance = {
|
|
_A: (_) => _,
|
|
_E: (_) => _
|
|
};
|
|
|
|
class TakeImpl {
|
|
exit;
|
|
[TakeTypeId] = takeVariance;
|
|
constructor(exit) {
|
|
this.exit = exit;
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
}
|
|
var chunk2 = (chunk) => new TakeImpl(succeed4(chunk));
|
|
var done7 = (self2) => suspend2(() => self2.exit);
|
|
var end3 = /* @__PURE__ */ new TakeImpl(/* @__PURE__ */ fail4(/* @__PURE__ */ none2()));
|
|
var failCause9 = (cause) => new TakeImpl(failCause4(pipe(cause, map11(some2))));
|
|
var fromPull = (pull) => matchCause2(pull, {
|
|
onFailure: (cause) => match2(flipCauseOption2(cause), {
|
|
onNone: () => end3,
|
|
onSome: failCause9
|
|
}),
|
|
onSuccess: chunk2
|
|
});
|
|
var match14 = /* @__PURE__ */ dual(2, (self2, {
|
|
onEnd,
|
|
onFailure,
|
|
onSuccess
|
|
}) => match9(self2.exit, {
|
|
onFailure: (cause) => match2(flipCauseOption2(cause), {
|
|
onNone: onEnd,
|
|
onSome: onFailure
|
|
}),
|
|
onSuccess
|
|
}));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/stream/pull.js
|
|
var end4 = () => fail6(none2());
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/stream.js
|
|
var StreamSymbolKey = "effect/Stream";
|
|
var StreamTypeId2 = /* @__PURE__ */ Symbol.for(StreamSymbolKey);
|
|
var streamVariance = {
|
|
_R: (_) => _,
|
|
_E: (_) => _,
|
|
_A: (_) => _
|
|
};
|
|
|
|
class StreamImpl {
|
|
channel;
|
|
[StreamTypeId2] = streamVariance;
|
|
constructor(channel) {
|
|
this.channel = channel;
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
}
|
|
var isStream = (u) => hasProperty(u, StreamTypeId2) || isEffect2(u);
|
|
var queueFromBufferOptions = (bufferSize) => {
|
|
if (bufferSize === "unbounded") {
|
|
return unbounded3();
|
|
} else if (typeof bufferSize === "number" || bufferSize === undefined) {
|
|
return bounded3(bufferSize ?? 16);
|
|
}
|
|
switch (bufferSize.strategy) {
|
|
case "dropping":
|
|
return dropping2(bufferSize.bufferSize ?? 16);
|
|
case "sliding":
|
|
return sliding2(bufferSize.bufferSize ?? 16);
|
|
default:
|
|
return bounded3(bufferSize.bufferSize ?? 16);
|
|
}
|
|
};
|
|
var asyncScoped = (register, bufferSize) => pipe(acquireRelease2(queueFromBufferOptions(bufferSize), (queue) => shutdown2(queue)), flatMap9((output) => pipe(runtime3(), flatMap9((runtime) => pipe(register(make40((k) => pipe(fromPull(k), flatMap9((take) => offer3(output, take)), asVoid2, runPromiseExit(runtime)).then((exit) => {
|
|
if (isFailure2(exit)) {
|
|
if (!isInterrupted2(exit.cause)) {
|
|
throw squash(exit.cause);
|
|
}
|
|
}
|
|
}))), zipRight3(make25(false)), flatMap9((ref) => pipe(get10(ref), map15((isDone) => isDone ? end4() : pipe(take2(output), flatMap9(done7), onError2(() => pipe(set5(ref, true), zipRight3(shutdown2(output)))))))))))), scoped4, flatMap13(repeatEffectChunkOption));
|
|
var bufferChunks = /* @__PURE__ */ dual(2, (self2, options) => {
|
|
if (options.strategy === "dropping") {
|
|
return bufferChunksDropping(self2, options.capacity);
|
|
} else if (options.strategy === "sliding") {
|
|
return bufferChunksSliding(self2, options.capacity);
|
|
}
|
|
const queue = toQueue(self2, options);
|
|
return new StreamImpl(unwrapScoped2(map15(queue, (queue) => {
|
|
const process2 = pipe(fromEffect4(take2(queue)), flatMap11(match14({
|
|
onEnd: () => void_5,
|
|
onFailure: failCause8,
|
|
onSuccess: (value) => pipe(write(value), flatMap11(() => process2))
|
|
})));
|
|
return process2;
|
|
})));
|
|
});
|
|
var bufferChunksDropping = /* @__PURE__ */ dual(2, (self2, capacity) => {
|
|
const queue = acquireRelease2(dropping2(capacity), (queue) => shutdown2(queue));
|
|
return new StreamImpl(bufferSignal(queue, toChannel2(self2)));
|
|
});
|
|
var bufferChunksSliding = /* @__PURE__ */ dual(2, (self2, capacity) => {
|
|
const queue = acquireRelease2(sliding2(capacity), (queue) => shutdown2(queue));
|
|
return new StreamImpl(bufferSignal(queue, toChannel2(self2)));
|
|
});
|
|
var bufferSignal = (scoped, bufferChannel) => {
|
|
const producer = (queue, ref) => {
|
|
const terminate = (take) => pipe(get10(ref), tap2(_await), zipRight3(make18()), flatMap9((deferred) => pipe(offer3(queue, [take, deferred]), zipRight3(set5(ref, deferred)), zipRight3(_await(deferred)))), asVoid2, fromEffect4);
|
|
return readWithCause({
|
|
onInput: (input) => pipe(make18(), flatMap9((deferred) => pipe(offer3(queue, [chunk2(input), deferred]), flatMap9((added) => pipe(set5(ref, deferred), when2(() => added))))), asVoid2, fromEffect4, flatMap11(() => producer(queue, ref))),
|
|
onFailure: (error) => terminate(failCause9(error)),
|
|
onDone: () => terminate(end3)
|
|
});
|
|
};
|
|
const consumer = (queue) => {
|
|
const process2 = pipe(fromEffect4(take2(queue)), flatMap11(([take, deferred]) => zipRight4(fromEffect4(succeed2(deferred, undefined)), match14(take, {
|
|
onEnd: () => void_5,
|
|
onFailure: failCause8,
|
|
onSuccess: (value) => pipe(write(value), flatMap11(() => process2))
|
|
}))));
|
|
return process2;
|
|
};
|
|
return unwrapScoped2(pipe(scoped, flatMap9((queue) => pipe(make18(), tap2((start) => succeed2(start, undefined)), flatMap9((start) => pipe(make25(start), flatMap9((ref) => pipe(bufferChannel, pipeTo(producer(queue, ref)), runScoped, forkScoped2)), as3(consumer(queue))))))));
|
|
};
|
|
var flatMap13 = /* @__PURE__ */ dual((args) => isStream(args[0]), (self2, f, options) => {
|
|
const bufferSize = options?.bufferSize ?? 16;
|
|
if (options?.switch) {
|
|
return matchConcurrency(options?.concurrency, () => flatMapParSwitchBuffer(self2, 1, bufferSize, f), (n) => flatMapParSwitchBuffer(self2, n, bufferSize, f));
|
|
}
|
|
return matchConcurrency(options?.concurrency, () => new StreamImpl(concatMap(toChannel2(self2), (as) => pipe(as, map4((a) => toChannel2(f(a))), reduce2(void_5, (left, right) => pipe(left, zipRight4(right)))))), (_) => new StreamImpl(pipe(toChannel2(self2), concatMap(writeChunk), mergeMap((out) => toChannel2(f(out)), options))));
|
|
});
|
|
var matchConcurrency = (concurrency, sequential, bounded) => {
|
|
switch (concurrency) {
|
|
case undefined:
|
|
return sequential();
|
|
case "unbounded":
|
|
return bounded(Number.MAX_SAFE_INTEGER);
|
|
default:
|
|
return concurrency > 1 ? bounded(concurrency) : sequential();
|
|
}
|
|
};
|
|
var flatMapParSwitchBuffer = /* @__PURE__ */ dual(4, (self2, n, bufferSize, f) => new StreamImpl(pipe(toChannel2(self2), concatMap(writeChunk), mergeMap((out) => toChannel2(f(out)), {
|
|
concurrency: n,
|
|
mergeStrategy: BufferSliding(),
|
|
bufferSize
|
|
}))));
|
|
var flatten9 = /* @__PURE__ */ dual((args) => isStream(args[0]), (self2, options) => flatMap13(self2, identity, options));
|
|
var fromChannel = (channel) => new StreamImpl(channel);
|
|
var toChannel2 = (stream) => {
|
|
if ("channel" in stream) {
|
|
return stream.channel;
|
|
} else if (isEffect2(stream)) {
|
|
return toChannel2(fromEffect7(stream));
|
|
} else {
|
|
throw new TypeError(`Expected a Stream.`);
|
|
}
|
|
};
|
|
var fromEffect7 = (effect) => pipe(effect, mapError2(some2), fromEffectOption);
|
|
var fromEffectOption = (effect) => new StreamImpl(unwrap(match11(effect, {
|
|
onFailure: match2({
|
|
onNone: () => void_5,
|
|
onSome: fail8
|
|
}),
|
|
onSuccess: (a) => write(of2(a))
|
|
})));
|
|
var repeatEffectChunkOption = (effect) => unfoldChunkEffect(effect, (effect) => pipe(map15(effect, (chunk) => some2([chunk, effect])), catchAll2(match2({
|
|
onNone: () => succeed7(none2()),
|
|
onSome: fail6
|
|
}))));
|
|
var runIntoQueueScoped = /* @__PURE__ */ dual(2, (self2, queue) => {
|
|
const writer = readWithCause({
|
|
onInput: (input) => flatMap11(write(chunk2(input)), () => writer),
|
|
onFailure: (cause) => write(failCause9(cause)),
|
|
onDone: () => write(end3)
|
|
});
|
|
return pipe(pipeTo(toChannel2(self2), writer), mapOutEffect((take) => offer3(queue, take)), drain, runScoped, asVoid2);
|
|
});
|
|
var scoped4 = (effect) => new StreamImpl(ensuring3(scoped3(pipe(effect, map15(of2))), _void));
|
|
var suspend5 = (stream) => new StreamImpl(suspend4(() => toChannel2(stream())));
|
|
var toQueue = /* @__PURE__ */ dual((args) => isStream(args[0]), (self2, options) => tap2(acquireRelease2(options?.strategy === "unbounded" ? unbounded3() : options?.strategy === "dropping" ? dropping2(options.capacity ?? 2) : options?.strategy === "sliding" ? sliding2(options.capacity ?? 2) : bounded3(options?.capacity ?? 2), (queue) => shutdown2(queue)), (queue) => forkScoped2(runIntoQueueScoped(self2, queue))));
|
|
var unfoldChunkEffect = (s, f) => suspend5(() => {
|
|
const loop = (s) => unwrap(map15(f(s), match2({
|
|
onNone: () => void_5,
|
|
onSome: ([chunk, s]) => flatMap11(write(chunk), () => loop(s))
|
|
})));
|
|
return new StreamImpl(loop(s));
|
|
});
|
|
var unwrap2 = (effect) => flatten9(fromEffect7(effect));
|
|
var unwrapScoped4 = (effect) => flatten9(scoped4(effect));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Channel.js
|
|
var flatMap14 = flatMap11;
|
|
var void_6 = void_5;
|
|
var write2 = write;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Sink.js
|
|
var forEach6 = forEach5;
|
|
var unwrapScoped5 = unwrapScoped3;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Stream.js
|
|
var asyncScoped2 = asyncScoped;
|
|
var bufferChunks2 = bufferChunks;
|
|
var fromChannel3 = fromChannel;
|
|
var unwrap4 = unwrap2;
|
|
var unwrapScoped6 = unwrapScoped4;
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/schema/util.js
|
|
var getKeysForIndexSignature = (input, parameter) => {
|
|
switch (parameter._tag) {
|
|
case "StringKeyword":
|
|
case "TemplateLiteral":
|
|
return Object.keys(input);
|
|
case "SymbolKeyword":
|
|
return Object.getOwnPropertySymbols(input);
|
|
case "Refinement":
|
|
return getKeysForIndexSignature(input, parameter.from);
|
|
}
|
|
};
|
|
var memoizeThunk = (f) => {
|
|
let done = false;
|
|
let a;
|
|
return () => {
|
|
if (done) {
|
|
return a;
|
|
}
|
|
a = f();
|
|
done = true;
|
|
return a;
|
|
};
|
|
};
|
|
var isNonEmpty5 = (x) => Array.isArray(x);
|
|
var isSingle = (x) => !Array.isArray(x);
|
|
var formatPathKey = (key) => `[${formatPropertyKey(key)}]`;
|
|
var formatPath = (path) => isNonEmpty5(path) ? path.map(formatPathKey).join("") : formatPathKey(path);
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/schema/errors.js
|
|
var getErrorMessage = (reason, details, path, ast) => {
|
|
let out = reason;
|
|
if (path && isNonEmptyReadonlyArray(path)) {
|
|
out += `
|
|
at path: ${formatPath(path)}`;
|
|
}
|
|
if (details !== undefined) {
|
|
out += `
|
|
details: ${details}`;
|
|
}
|
|
if (ast) {
|
|
out += `
|
|
schema (${ast._tag}): ${ast}`;
|
|
}
|
|
return out;
|
|
};
|
|
var getSchemaExtendErrorMessage = (x, y, path) => getErrorMessage("Unsupported schema or overlapping types", `cannot extend ${x} with ${y}`, path);
|
|
var getASTUnsupportedKeySchemaErrorMessage = (ast) => getErrorMessage("Unsupported key schema", undefined, undefined, ast);
|
|
var getASTUnsupportedLiteralErrorMessage = (literal) => getErrorMessage("Unsupported literal", `literal value: ${formatUnknown(literal)}`);
|
|
var getASTDuplicateIndexSignatureErrorMessage = (type) => getErrorMessage("Duplicate index signature", `${type} index signature`);
|
|
var getASTIndexSignatureParameterErrorMessage = /* @__PURE__ */ getErrorMessage("Unsupported index signature parameter", "An index signature parameter type must be `string`, `symbol`, a template literal type or a refinement of the previous types");
|
|
var getASTRequiredElementFollowinAnOptionalElementErrorMessage = /* @__PURE__ */ getErrorMessage("Invalid element", "A required element cannot follow an optional element. ts(1257)");
|
|
var getASTDuplicatePropertySignatureTransformationErrorMessage = (key) => getErrorMessage("Duplicate property signature transformation", `Duplicate key ${formatUnknown(key)}`);
|
|
var getASTDuplicatePropertySignatureErrorMessage = (key) => getErrorMessage("Duplicate property signature", `Duplicate key ${formatUnknown(key)}`);
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/internal/schema/schemaId.js
|
|
var DateFromSelfSchemaId = /* @__PURE__ */ Symbol.for("effect/SchemaId/DateFromSelf");
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/SchemaAST.js
|
|
var TypeConstructorAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/TypeConstructor");
|
|
var BrandAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/Brand");
|
|
var SchemaIdAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/SchemaId");
|
|
var MessageAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/Message");
|
|
var MissingMessageAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/MissingMessage");
|
|
var IdentifierAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/Identifier");
|
|
var TitleAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/Title");
|
|
var AutoTitleAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/AutoTitle");
|
|
var DescriptionAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/Description");
|
|
var ExamplesAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/Examples");
|
|
var DefaultAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/Default");
|
|
var JSONSchemaAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/JSONSchema");
|
|
var ArbitraryAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/Arbitrary");
|
|
var PrettyAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/Pretty");
|
|
var EquivalenceAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/Equivalence");
|
|
var DocumentationAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/Documentation");
|
|
var ConcurrencyAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/Concurrency");
|
|
var BatchingAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/Batching");
|
|
var ParseIssueTitleAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/ParseIssueTitle");
|
|
var ParseOptionsAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/ParseOptions");
|
|
var DecodingFallbackAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/DecodingFallback");
|
|
var SurrogateAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/Surrogate");
|
|
var StableFilterAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/StableFilter");
|
|
var getAnnotation = /* @__PURE__ */ dual(2, (annotated, key) => Object.prototype.hasOwnProperty.call(annotated.annotations, key) ? some2(annotated.annotations[key]) : none2());
|
|
var getBrandAnnotation = /* @__PURE__ */ getAnnotation(BrandAnnotationId);
|
|
var getMessageAnnotation = /* @__PURE__ */ getAnnotation(MessageAnnotationId);
|
|
var getMissingMessageAnnotation = /* @__PURE__ */ getAnnotation(MissingMessageAnnotationId);
|
|
var getTitleAnnotation = /* @__PURE__ */ getAnnotation(TitleAnnotationId);
|
|
var getAutoTitleAnnotation = /* @__PURE__ */ getAnnotation(AutoTitleAnnotationId);
|
|
var getIdentifierAnnotation = /* @__PURE__ */ getAnnotation(IdentifierAnnotationId);
|
|
var getDescriptionAnnotation = /* @__PURE__ */ getAnnotation(DescriptionAnnotationId);
|
|
var getConcurrencyAnnotation = /* @__PURE__ */ getAnnotation(ConcurrencyAnnotationId);
|
|
var getBatchingAnnotation = /* @__PURE__ */ getAnnotation(BatchingAnnotationId);
|
|
var getParseIssueTitleAnnotation = /* @__PURE__ */ getAnnotation(ParseIssueTitleAnnotationId);
|
|
var getParseOptionsAnnotation = /* @__PURE__ */ getAnnotation(ParseOptionsAnnotationId);
|
|
var getDecodingFallbackAnnotation = /* @__PURE__ */ getAnnotation(DecodingFallbackAnnotationId);
|
|
var getSurrogateAnnotation = /* @__PURE__ */ getAnnotation(SurrogateAnnotationId);
|
|
var getStableFilterAnnotation = /* @__PURE__ */ getAnnotation(StableFilterAnnotationId);
|
|
var hasStableFilter = (annotated) => exists(getStableFilterAnnotation(annotated), (b) => b === true);
|
|
var JSONIdentifierAnnotationId = /* @__PURE__ */ Symbol.for("effect/annotation/JSONIdentifier");
|
|
var getJSONIdentifierAnnotation = /* @__PURE__ */ getAnnotation(JSONIdentifierAnnotationId);
|
|
var getJSONIdentifier = (annotated) => orElse(getJSONIdentifierAnnotation(annotated), () => getIdentifierAnnotation(annotated));
|
|
var ParseJsonSchemaId = /* @__PURE__ */ Symbol.for("effect/schema/ParseJson");
|
|
|
|
class Declaration {
|
|
typeParameters;
|
|
decodeUnknown;
|
|
encodeUnknown;
|
|
annotations;
|
|
_tag = "Declaration";
|
|
constructor(typeParameters, decodeUnknown, encodeUnknown, annotations = {}) {
|
|
this.typeParameters = typeParameters;
|
|
this.decodeUnknown = decodeUnknown;
|
|
this.encodeUnknown = encodeUnknown;
|
|
this.annotations = annotations;
|
|
}
|
|
toString() {
|
|
return getOrElse(getExpected(this), () => "<declaration schema>");
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
typeParameters: this.typeParameters.map((ast) => ast.toJSON()),
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var createASTGuard = (tag) => (ast) => ast._tag === tag;
|
|
class Literal {
|
|
literal;
|
|
annotations;
|
|
_tag = "Literal";
|
|
constructor(literal, annotations = {}) {
|
|
this.literal = literal;
|
|
this.annotations = annotations;
|
|
}
|
|
toString() {
|
|
return getOrElse(getExpected(this), () => formatUnknown(this.literal));
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
literal: isBigInt(this.literal) ? String(this.literal) : this.literal,
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var isLiteral = /* @__PURE__ */ createASTGuard("Literal");
|
|
class UniqueSymbol {
|
|
symbol;
|
|
annotations;
|
|
_tag = "UniqueSymbol";
|
|
constructor(symbol, annotations = {}) {
|
|
this.symbol = symbol;
|
|
this.annotations = annotations;
|
|
}
|
|
toString() {
|
|
return getOrElse(getExpected(this), () => formatUnknown(this.symbol));
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
symbol: String(this.symbol),
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
class UndefinedKeyword {
|
|
annotations;
|
|
_tag = "UndefinedKeyword";
|
|
constructor(annotations = {}) {
|
|
this.annotations = annotations;
|
|
}
|
|
toString() {
|
|
return formatKeyword(this);
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var undefinedKeyword = /* @__PURE__ */ new UndefinedKeyword({
|
|
[TitleAnnotationId]: "undefined"
|
|
});
|
|
class VoidKeyword {
|
|
annotations;
|
|
_tag = "VoidKeyword";
|
|
constructor(annotations = {}) {
|
|
this.annotations = annotations;
|
|
}
|
|
toString() {
|
|
return formatKeyword(this);
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var voidKeyword = /* @__PURE__ */ new VoidKeyword({
|
|
[TitleAnnotationId]: "void"
|
|
});
|
|
class NeverKeyword {
|
|
annotations;
|
|
_tag = "NeverKeyword";
|
|
constructor(annotations = {}) {
|
|
this.annotations = annotations;
|
|
}
|
|
toString() {
|
|
return formatKeyword(this);
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var neverKeyword = /* @__PURE__ */ new NeverKeyword({
|
|
[TitleAnnotationId]: "never"
|
|
});
|
|
class UnknownKeyword {
|
|
annotations;
|
|
_tag = "UnknownKeyword";
|
|
constructor(annotations = {}) {
|
|
this.annotations = annotations;
|
|
}
|
|
toString() {
|
|
return formatKeyword(this);
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var unknownKeyword = /* @__PURE__ */ new UnknownKeyword({
|
|
[TitleAnnotationId]: "unknown"
|
|
});
|
|
class AnyKeyword {
|
|
annotations;
|
|
_tag = "AnyKeyword";
|
|
constructor(annotations = {}) {
|
|
this.annotations = annotations;
|
|
}
|
|
toString() {
|
|
return formatKeyword(this);
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var anyKeyword = /* @__PURE__ */ new AnyKeyword({
|
|
[TitleAnnotationId]: "any"
|
|
});
|
|
class StringKeyword {
|
|
annotations;
|
|
_tag = "StringKeyword";
|
|
constructor(annotations = {}) {
|
|
this.annotations = annotations;
|
|
}
|
|
toString() {
|
|
return formatKeyword(this);
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var stringKeyword = /* @__PURE__ */ new StringKeyword({
|
|
[TitleAnnotationId]: "string",
|
|
[DescriptionAnnotationId]: "a string"
|
|
});
|
|
var isStringKeyword = /* @__PURE__ */ createASTGuard("StringKeyword");
|
|
|
|
class NumberKeyword {
|
|
annotations;
|
|
_tag = "NumberKeyword";
|
|
constructor(annotations = {}) {
|
|
this.annotations = annotations;
|
|
}
|
|
toString() {
|
|
return formatKeyword(this);
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var numberKeyword = /* @__PURE__ */ new NumberKeyword({
|
|
[TitleAnnotationId]: "number",
|
|
[DescriptionAnnotationId]: "a number"
|
|
});
|
|
var isNumberKeyword = /* @__PURE__ */ createASTGuard("NumberKeyword");
|
|
|
|
class BooleanKeyword {
|
|
annotations;
|
|
_tag = "BooleanKeyword";
|
|
constructor(annotations = {}) {
|
|
this.annotations = annotations;
|
|
}
|
|
toString() {
|
|
return formatKeyword(this);
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var booleanKeyword = /* @__PURE__ */ new BooleanKeyword({
|
|
[TitleAnnotationId]: "boolean",
|
|
[DescriptionAnnotationId]: "a boolean"
|
|
});
|
|
var isBooleanKeyword = /* @__PURE__ */ createASTGuard("BooleanKeyword");
|
|
|
|
class BigIntKeyword {
|
|
annotations;
|
|
_tag = "BigIntKeyword";
|
|
constructor(annotations = {}) {
|
|
this.annotations = annotations;
|
|
}
|
|
toString() {
|
|
return formatKeyword(this);
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var bigIntKeyword = /* @__PURE__ */ new BigIntKeyword({
|
|
[TitleAnnotationId]: "bigint",
|
|
[DescriptionAnnotationId]: "a bigint"
|
|
});
|
|
class SymbolKeyword {
|
|
annotations;
|
|
_tag = "SymbolKeyword";
|
|
constructor(annotations = {}) {
|
|
this.annotations = annotations;
|
|
}
|
|
toString() {
|
|
return formatKeyword(this);
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var symbolKeyword = /* @__PURE__ */ new SymbolKeyword({
|
|
[TitleAnnotationId]: "symbol",
|
|
[DescriptionAnnotationId]: "a symbol"
|
|
});
|
|
var isSymbolKeyword = /* @__PURE__ */ createASTGuard("SymbolKeyword");
|
|
|
|
class ObjectKeyword {
|
|
annotations;
|
|
_tag = "ObjectKeyword";
|
|
constructor(annotations = {}) {
|
|
this.annotations = annotations;
|
|
}
|
|
toString() {
|
|
return formatKeyword(this);
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var objectKeyword = /* @__PURE__ */ new ObjectKeyword({
|
|
[TitleAnnotationId]: "object",
|
|
[DescriptionAnnotationId]: "an object in the TypeScript meaning, i.e. the `object` type"
|
|
});
|
|
class Type {
|
|
type;
|
|
annotations;
|
|
constructor(type, annotations = {}) {
|
|
this.type = type;
|
|
this.annotations = annotations;
|
|
}
|
|
toJSON() {
|
|
return {
|
|
type: this.type.toJSON(),
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
toString() {
|
|
return String(this.type);
|
|
}
|
|
}
|
|
|
|
class OptionalType extends Type {
|
|
isOptional;
|
|
constructor(type, isOptional, annotations = {}) {
|
|
super(type, annotations);
|
|
this.isOptional = isOptional;
|
|
}
|
|
toJSON() {
|
|
return {
|
|
type: this.type.toJSON(),
|
|
isOptional: this.isOptional,
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
toString() {
|
|
return String(this.type) + (this.isOptional ? "?" : "");
|
|
}
|
|
}
|
|
var getRestASTs = (rest) => rest.map((annotatedAST) => annotatedAST.type);
|
|
|
|
class TupleType {
|
|
elements;
|
|
rest;
|
|
isReadonly;
|
|
annotations;
|
|
_tag = "TupleType";
|
|
constructor(elements, rest, isReadonly, annotations = {}) {
|
|
this.elements = elements;
|
|
this.rest = rest;
|
|
this.isReadonly = isReadonly;
|
|
this.annotations = annotations;
|
|
let hasOptionalElement = false;
|
|
let hasIllegalRequiredElement = false;
|
|
for (const e of elements) {
|
|
if (e.isOptional) {
|
|
hasOptionalElement = true;
|
|
} else if (hasOptionalElement) {
|
|
hasIllegalRequiredElement = true;
|
|
break;
|
|
}
|
|
}
|
|
if (hasIllegalRequiredElement || hasOptionalElement && rest.length > 1) {
|
|
throw new Error(getASTRequiredElementFollowinAnOptionalElementErrorMessage);
|
|
}
|
|
}
|
|
toString() {
|
|
return getOrElse(getExpected(this), () => formatTuple(this));
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
elements: this.elements.map((e) => e.toJSON()),
|
|
rest: this.rest.map((ast) => ast.toJSON()),
|
|
isReadonly: this.isReadonly,
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var formatTuple = (ast) => {
|
|
const formattedElements = ast.elements.map(String).join(", ");
|
|
return matchLeft(ast.rest, {
|
|
onEmpty: () => `readonly [${formattedElements}]`,
|
|
onNonEmpty: (head, tail) => {
|
|
const formattedHead = String(head);
|
|
const wrappedHead = formattedHead.includes(" | ") ? `(${formattedHead})` : formattedHead;
|
|
if (tail.length > 0) {
|
|
const formattedTail = tail.map(String).join(", ");
|
|
if (ast.elements.length > 0) {
|
|
return `readonly [${formattedElements}, ...${wrappedHead}[], ${formattedTail}]`;
|
|
} else {
|
|
return `readonly [...${wrappedHead}[], ${formattedTail}]`;
|
|
}
|
|
} else {
|
|
if (ast.elements.length > 0) {
|
|
return `readonly [${formattedElements}, ...${wrappedHead}[]]`;
|
|
} else {
|
|
return `ReadonlyArray<${formattedHead}>`;
|
|
}
|
|
}
|
|
}
|
|
});
|
|
};
|
|
class PropertySignature extends OptionalType {
|
|
name;
|
|
isReadonly;
|
|
constructor(name, type, isOptional, isReadonly, annotations) {
|
|
super(type, isOptional, annotations);
|
|
this.name = name;
|
|
this.isReadonly = isReadonly;
|
|
}
|
|
toString() {
|
|
return (this.isReadonly ? "readonly " : "") + String(this.name) + (this.isOptional ? "?" : "") + ": " + this.type;
|
|
}
|
|
toJSON() {
|
|
return {
|
|
name: String(this.name),
|
|
type: this.type.toJSON(),
|
|
isOptional: this.isOptional,
|
|
isReadonly: this.isReadonly,
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var isParameter = (ast) => {
|
|
switch (ast._tag) {
|
|
case "StringKeyword":
|
|
case "SymbolKeyword":
|
|
case "TemplateLiteral":
|
|
return true;
|
|
case "Refinement":
|
|
return isParameter(ast.from);
|
|
}
|
|
return false;
|
|
};
|
|
|
|
class IndexSignature {
|
|
type;
|
|
isReadonly;
|
|
parameter;
|
|
constructor(parameter, type, isReadonly) {
|
|
this.type = type;
|
|
this.isReadonly = isReadonly;
|
|
if (isParameter(parameter)) {
|
|
this.parameter = parameter;
|
|
} else {
|
|
throw new Error(getASTIndexSignatureParameterErrorMessage);
|
|
}
|
|
}
|
|
toString() {
|
|
return (this.isReadonly ? "readonly " : "") + `[x: ${this.parameter}]: ${this.type}`;
|
|
}
|
|
toJSON() {
|
|
return {
|
|
parameter: this.parameter.toJSON(),
|
|
type: this.type.toJSON(),
|
|
isReadonly: this.isReadonly
|
|
};
|
|
}
|
|
}
|
|
|
|
class TypeLiteral {
|
|
annotations;
|
|
_tag = "TypeLiteral";
|
|
propertySignatures;
|
|
indexSignatures;
|
|
constructor(propertySignatures, indexSignatures, annotations = {}) {
|
|
this.annotations = annotations;
|
|
const keys = {};
|
|
for (let i = 0;i < propertySignatures.length; i++) {
|
|
const name = propertySignatures[i].name;
|
|
if (Object.prototype.hasOwnProperty.call(keys, name)) {
|
|
throw new Error(getASTDuplicatePropertySignatureErrorMessage(name));
|
|
}
|
|
keys[name] = null;
|
|
}
|
|
const parameters = {
|
|
string: false,
|
|
symbol: false
|
|
};
|
|
for (let i = 0;i < indexSignatures.length; i++) {
|
|
const encodedParameter = getEncodedParameter(indexSignatures[i].parameter);
|
|
if (isStringKeyword(encodedParameter)) {
|
|
if (parameters.string) {
|
|
throw new Error(getASTDuplicateIndexSignatureErrorMessage("string"));
|
|
}
|
|
parameters.string = true;
|
|
} else if (isSymbolKeyword(encodedParameter)) {
|
|
if (parameters.symbol) {
|
|
throw new Error(getASTDuplicateIndexSignatureErrorMessage("symbol"));
|
|
}
|
|
parameters.symbol = true;
|
|
}
|
|
}
|
|
this.propertySignatures = propertySignatures;
|
|
this.indexSignatures = indexSignatures;
|
|
}
|
|
toString() {
|
|
return getOrElse(getExpected(this), () => formatTypeLiteral(this));
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
propertySignatures: this.propertySignatures.map((ps) => ps.toJSON()),
|
|
indexSignatures: this.indexSignatures.map((ps) => ps.toJSON()),
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var formatIndexSignatures = (iss) => iss.map(String).join("; ");
|
|
var formatTypeLiteral = (ast) => {
|
|
if (ast.propertySignatures.length > 0) {
|
|
const pss = ast.propertySignatures.map(String).join("; ");
|
|
if (ast.indexSignatures.length > 0) {
|
|
return `{ ${pss}; ${formatIndexSignatures(ast.indexSignatures)} }`;
|
|
} else {
|
|
return `{ ${pss} }`;
|
|
}
|
|
} else {
|
|
if (ast.indexSignatures.length > 0) {
|
|
return `{ ${formatIndexSignatures(ast.indexSignatures)} }`;
|
|
} else {
|
|
return "{}";
|
|
}
|
|
}
|
|
};
|
|
var isTypeLiteral = /* @__PURE__ */ createASTGuard("TypeLiteral");
|
|
var sortCandidates = /* @__PURE__ */ sort(/* @__PURE__ */ mapInput2(Order, (ast) => {
|
|
switch (ast._tag) {
|
|
case "AnyKeyword":
|
|
return 0;
|
|
case "UnknownKeyword":
|
|
return 1;
|
|
case "ObjectKeyword":
|
|
return 2;
|
|
case "StringKeyword":
|
|
case "NumberKeyword":
|
|
case "BooleanKeyword":
|
|
case "BigIntKeyword":
|
|
case "SymbolKeyword":
|
|
return 3;
|
|
}
|
|
return 4;
|
|
}));
|
|
var literalMap = {
|
|
string: "StringKeyword",
|
|
number: "NumberKeyword",
|
|
boolean: "BooleanKeyword",
|
|
bigint: "BigIntKeyword"
|
|
};
|
|
var flatten10 = (candidates) => flatMap2(candidates, (ast) => isUnion(ast) ? flatten10(ast.types) : [ast]);
|
|
var unify = (candidates) => {
|
|
const cs = sortCandidates(candidates);
|
|
const out = [];
|
|
const uniques = {};
|
|
const literals = [];
|
|
for (const ast of cs) {
|
|
switch (ast._tag) {
|
|
case "NeverKeyword":
|
|
break;
|
|
case "AnyKeyword":
|
|
return [anyKeyword];
|
|
case "UnknownKeyword":
|
|
return [unknownKeyword];
|
|
case "ObjectKeyword":
|
|
case "UndefinedKeyword":
|
|
case "VoidKeyword":
|
|
case "StringKeyword":
|
|
case "NumberKeyword":
|
|
case "BooleanKeyword":
|
|
case "BigIntKeyword":
|
|
case "SymbolKeyword": {
|
|
if (!uniques[ast._tag]) {
|
|
uniques[ast._tag] = ast;
|
|
out.push(ast);
|
|
}
|
|
break;
|
|
}
|
|
case "Literal": {
|
|
const type = typeof ast.literal;
|
|
switch (type) {
|
|
case "string":
|
|
case "number":
|
|
case "bigint":
|
|
case "boolean": {
|
|
const _tag = literalMap[type];
|
|
if (!uniques[_tag] && !literals.includes(ast.literal)) {
|
|
literals.push(ast.literal);
|
|
out.push(ast);
|
|
}
|
|
break;
|
|
}
|
|
case "object": {
|
|
if (!literals.includes(ast.literal)) {
|
|
literals.push(ast.literal);
|
|
out.push(ast);
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case "UniqueSymbol": {
|
|
if (!uniques["SymbolKeyword"] && !literals.includes(ast.symbol)) {
|
|
literals.push(ast.symbol);
|
|
out.push(ast);
|
|
}
|
|
break;
|
|
}
|
|
case "TupleType": {
|
|
if (!uniques["ObjectKeyword"]) {
|
|
out.push(ast);
|
|
}
|
|
break;
|
|
}
|
|
case "TypeLiteral": {
|
|
if (ast.propertySignatures.length === 0 && ast.indexSignatures.length === 0) {
|
|
if (!uniques["{}"]) {
|
|
uniques["{}"] = ast;
|
|
out.push(ast);
|
|
}
|
|
} else if (!uniques["ObjectKeyword"]) {
|
|
out.push(ast);
|
|
}
|
|
break;
|
|
}
|
|
default:
|
|
out.push(ast);
|
|
}
|
|
}
|
|
return out;
|
|
};
|
|
|
|
class Union {
|
|
types;
|
|
annotations;
|
|
static make = (types, annotations) => {
|
|
return isMembers(types) ? new Union(types, annotations) : types.length === 1 ? types[0] : neverKeyword;
|
|
};
|
|
static unify = (candidates, annotations) => {
|
|
return Union.make(unify(flatten10(candidates)), annotations);
|
|
};
|
|
_tag = "Union";
|
|
constructor(types, annotations = {}) {
|
|
this.types = types;
|
|
this.annotations = annotations;
|
|
}
|
|
toString() {
|
|
return getOrElse(getExpected(this), () => this.types.map(String).join(" | "));
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
types: this.types.map((ast) => ast.toJSON()),
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var mapMembers = (members, f) => members.map(f);
|
|
var isMembers = (as) => as.length > 1;
|
|
var isUnion = /* @__PURE__ */ createASTGuard("Union");
|
|
var toJSONMemoMap = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/Schema/AST/toJSONMemoMap"), () => new WeakMap);
|
|
|
|
class Suspend {
|
|
f;
|
|
annotations;
|
|
_tag = "Suspend";
|
|
constructor(f, annotations = {}) {
|
|
this.f = f;
|
|
this.annotations = annotations;
|
|
this.f = memoizeThunk(f);
|
|
}
|
|
toString() {
|
|
return getExpected(this).pipe(orElse(() => flatMap(liftThrowable(this.f)(), (ast) => getExpected(ast))), getOrElse(() => "<suspended schema>"));
|
|
}
|
|
toJSON() {
|
|
const ast = this.f();
|
|
let out = toJSONMemoMap.get(ast);
|
|
if (out) {
|
|
return out;
|
|
}
|
|
toJSONMemoMap.set(ast, {
|
|
_tag: this._tag
|
|
});
|
|
out = {
|
|
_tag: this._tag,
|
|
ast: ast.toJSON(),
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
toJSONMemoMap.set(ast, out);
|
|
return out;
|
|
}
|
|
}
|
|
class Refinement {
|
|
from;
|
|
filter;
|
|
annotations;
|
|
_tag = "Refinement";
|
|
constructor(from, filter, annotations = {}) {
|
|
this.from = from;
|
|
this.filter = filter;
|
|
this.annotations = annotations;
|
|
}
|
|
toString() {
|
|
return getIdentifierAnnotation(this).pipe(getOrElse(() => match2(getOrElseExpected(this), {
|
|
onNone: () => `{ ${this.from} | filter }`,
|
|
onSome: (expected) => isRefinement(this.from) ? String(this.from) + " & " + expected : expected
|
|
})));
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
from: this.from.toJSON(),
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var isRefinement = /* @__PURE__ */ createASTGuard("Refinement");
|
|
var defaultParseOption = {};
|
|
|
|
class Transformation {
|
|
from;
|
|
to;
|
|
transformation;
|
|
annotations;
|
|
_tag = "Transformation";
|
|
constructor(from, to, transformation, annotations = {}) {
|
|
this.from = from;
|
|
this.to = to;
|
|
this.transformation = transformation;
|
|
this.annotations = annotations;
|
|
}
|
|
toString() {
|
|
return getOrElse(getExpected(this), () => `(${String(this.from)} <-> ${String(this.to)})`);
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_tag: this._tag,
|
|
from: this.from.toJSON(),
|
|
to: this.to.toJSON(),
|
|
annotations: toJSONAnnotations(this.annotations)
|
|
};
|
|
}
|
|
}
|
|
var isTransformation = /* @__PURE__ */ createASTGuard("Transformation");
|
|
|
|
class FinalTransformation {
|
|
decode;
|
|
encode;
|
|
_tag = "FinalTransformation";
|
|
constructor(decode, encode) {
|
|
this.decode = decode;
|
|
this.encode = encode;
|
|
}
|
|
}
|
|
var createTransformationGuard = (tag) => (ast) => ast._tag === tag;
|
|
class ComposeTransformation {
|
|
_tag = "ComposeTransformation";
|
|
}
|
|
var composeTransformation = /* @__PURE__ */ new ComposeTransformation;
|
|
class PropertySignatureTransformation {
|
|
from;
|
|
to;
|
|
decode;
|
|
encode;
|
|
constructor(from, to, decode, encode) {
|
|
this.from = from;
|
|
this.to = to;
|
|
this.decode = decode;
|
|
this.encode = encode;
|
|
}
|
|
}
|
|
class TypeLiteralTransformation {
|
|
propertySignatureTransformations;
|
|
_tag = "TypeLiteralTransformation";
|
|
constructor(propertySignatureTransformations) {
|
|
this.propertySignatureTransformations = propertySignatureTransformations;
|
|
const fromKeys = {};
|
|
const toKeys = {};
|
|
for (const pst of propertySignatureTransformations) {
|
|
const from = pst.from;
|
|
if (fromKeys[from]) {
|
|
throw new Error(getASTDuplicatePropertySignatureTransformationErrorMessage(from));
|
|
}
|
|
fromKeys[from] = true;
|
|
const to = pst.to;
|
|
if (toKeys[to]) {
|
|
throw new Error(getASTDuplicatePropertySignatureTransformationErrorMessage(to));
|
|
}
|
|
toKeys[to] = true;
|
|
}
|
|
}
|
|
}
|
|
var isTypeLiteralTransformation = /* @__PURE__ */ createTransformationGuard("TypeLiteralTransformation");
|
|
var annotations = (ast, overrides) => {
|
|
const d = Object.getOwnPropertyDescriptors(ast);
|
|
const base = {
|
|
...ast.annotations
|
|
};
|
|
delete base[IdentifierAnnotationId];
|
|
const value = {
|
|
...base,
|
|
...overrides
|
|
};
|
|
const surrogate = getSurrogateAnnotation(ast);
|
|
if (isSome2(surrogate)) {
|
|
value[SurrogateAnnotationId] = annotations(surrogate.value, overrides);
|
|
}
|
|
d.annotations.value = value;
|
|
return Object.create(Object.getPrototypeOf(ast), d);
|
|
};
|
|
var STRING_KEYWORD_PATTERN = "[\\s\\S]*?";
|
|
var NUMBER_KEYWORD_PATTERN = "[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?";
|
|
var getTemplateLiteralSpanTypePattern = (type, capture) => {
|
|
switch (type._tag) {
|
|
case "Literal":
|
|
return escape2(String(type.literal));
|
|
case "StringKeyword":
|
|
return STRING_KEYWORD_PATTERN;
|
|
case "NumberKeyword":
|
|
return NUMBER_KEYWORD_PATTERN;
|
|
case "TemplateLiteral":
|
|
return getTemplateLiteralPattern(type, capture, false);
|
|
case "Union":
|
|
return type.types.map((type) => getTemplateLiteralSpanTypePattern(type, capture)).join("|");
|
|
}
|
|
};
|
|
var handleTemplateLiteralSpanTypeParens = (type, s, capture, top) => {
|
|
if (isUnion(type)) {
|
|
if (capture && !top) {
|
|
return `(?:${s})`;
|
|
}
|
|
} else if (!capture || !top) {
|
|
return s;
|
|
}
|
|
return `(${s})`;
|
|
};
|
|
var getTemplateLiteralPattern = (ast, capture, top) => {
|
|
let pattern = ``;
|
|
if (ast.head !== "") {
|
|
const head = escape2(ast.head);
|
|
pattern += capture && top ? `(${head})` : head;
|
|
}
|
|
for (const span of ast.spans) {
|
|
const spanPattern = getTemplateLiteralSpanTypePattern(span.type, capture);
|
|
pattern += handleTemplateLiteralSpanTypeParens(span.type, spanPattern, capture, top);
|
|
if (span.literal !== "") {
|
|
const literal = escape2(span.literal);
|
|
pattern += capture && top ? `(${literal})` : literal;
|
|
}
|
|
}
|
|
return pattern;
|
|
};
|
|
var getTemplateLiteralRegExp = (ast) => new RegExp(`^${getTemplateLiteralPattern(ast, false, true)}$`);
|
|
var record = (key, value) => {
|
|
const propertySignatures = [];
|
|
const indexSignatures = [];
|
|
const go = (key) => {
|
|
switch (key._tag) {
|
|
case "NeverKeyword":
|
|
break;
|
|
case "StringKeyword":
|
|
case "SymbolKeyword":
|
|
case "TemplateLiteral":
|
|
case "Refinement":
|
|
indexSignatures.push(new IndexSignature(key, value, true));
|
|
break;
|
|
case "Literal":
|
|
if (isString(key.literal) || isNumber(key.literal)) {
|
|
propertySignatures.push(new PropertySignature(key.literal, value, false, true));
|
|
} else {
|
|
throw new Error(getASTUnsupportedLiteralErrorMessage(key.literal));
|
|
}
|
|
break;
|
|
case "Enums": {
|
|
for (const [_, name] of key.enums) {
|
|
propertySignatures.push(new PropertySignature(name, value, false, true));
|
|
}
|
|
break;
|
|
}
|
|
case "UniqueSymbol":
|
|
propertySignatures.push(new PropertySignature(key.symbol, value, false, true));
|
|
break;
|
|
case "Union":
|
|
key.types.forEach(go);
|
|
break;
|
|
default:
|
|
throw new Error(getASTUnsupportedKeySchemaErrorMessage(key));
|
|
}
|
|
};
|
|
go(key);
|
|
return {
|
|
propertySignatures,
|
|
indexSignatures
|
|
};
|
|
};
|
|
var pickAnnotations = (annotationIds) => (annotated) => {
|
|
let out = undefined;
|
|
for (const id of annotationIds) {
|
|
if (Object.prototype.hasOwnProperty.call(annotated.annotations, id)) {
|
|
if (out === undefined) {
|
|
out = {};
|
|
}
|
|
out[id] = annotated.annotations[id];
|
|
}
|
|
}
|
|
return out;
|
|
};
|
|
var omitAnnotations = (annotationIds) => (annotated) => {
|
|
const out = {
|
|
...annotated.annotations
|
|
};
|
|
for (const id of annotationIds) {
|
|
delete out[id];
|
|
}
|
|
return out;
|
|
};
|
|
var preserveTransformationAnnotations = /* @__PURE__ */ pickAnnotations([ExamplesAnnotationId, DefaultAnnotationId, JSONSchemaAnnotationId, ArbitraryAnnotationId, PrettyAnnotationId, EquivalenceAnnotationId]);
|
|
var typeAST = (ast) => {
|
|
switch (ast._tag) {
|
|
case "Declaration": {
|
|
const typeParameters = changeMap(ast.typeParameters, typeAST);
|
|
return typeParameters === ast.typeParameters ? ast : new Declaration(typeParameters, ast.decodeUnknown, ast.encodeUnknown, ast.annotations);
|
|
}
|
|
case "TupleType": {
|
|
const elements = changeMap(ast.elements, (e) => {
|
|
const type = typeAST(e.type);
|
|
return type === e.type ? e : new OptionalType(type, e.isOptional);
|
|
});
|
|
const restASTs = getRestASTs(ast.rest);
|
|
const rest = changeMap(restASTs, typeAST);
|
|
return elements === ast.elements && rest === restASTs ? ast : new TupleType(elements, rest.map((type) => new Type(type)), ast.isReadonly, ast.annotations);
|
|
}
|
|
case "TypeLiteral": {
|
|
const propertySignatures = changeMap(ast.propertySignatures, (p) => {
|
|
const type = typeAST(p.type);
|
|
return type === p.type ? p : new PropertySignature(p.name, type, p.isOptional, p.isReadonly);
|
|
});
|
|
const indexSignatures = changeMap(ast.indexSignatures, (is) => {
|
|
const type = typeAST(is.type);
|
|
return type === is.type ? is : new IndexSignature(is.parameter, type, is.isReadonly);
|
|
});
|
|
return propertySignatures === ast.propertySignatures && indexSignatures === ast.indexSignatures ? ast : new TypeLiteral(propertySignatures, indexSignatures, ast.annotations);
|
|
}
|
|
case "Union": {
|
|
const types = changeMap(ast.types, typeAST);
|
|
return types === ast.types ? ast : Union.make(types, ast.annotations);
|
|
}
|
|
case "Suspend":
|
|
return new Suspend(() => typeAST(ast.f()), ast.annotations);
|
|
case "Refinement": {
|
|
const from = typeAST(ast.from);
|
|
return from === ast.from ? ast : new Refinement(from, ast.filter, ast.annotations);
|
|
}
|
|
case "Transformation": {
|
|
const preserve = preserveTransformationAnnotations(ast);
|
|
return typeAST(preserve !== undefined ? annotations(ast.to, preserve) : ast.to);
|
|
}
|
|
}
|
|
return ast;
|
|
};
|
|
function changeMap(as, f) {
|
|
let changed = false;
|
|
const out = allocate(as.length);
|
|
for (let i = 0;i < as.length; i++) {
|
|
const a = as[i];
|
|
const fa = f(a);
|
|
if (fa !== a) {
|
|
changed = true;
|
|
}
|
|
out[i] = fa;
|
|
}
|
|
return changed ? out : as;
|
|
}
|
|
var getTransformationFrom = (ast) => {
|
|
switch (ast._tag) {
|
|
case "Transformation":
|
|
return ast.from;
|
|
case "Refinement":
|
|
return getTransformationFrom(ast.from);
|
|
case "Suspend":
|
|
return getTransformationFrom(ast.f());
|
|
}
|
|
};
|
|
var encodedAST_ = (ast, isBound) => {
|
|
switch (ast._tag) {
|
|
case "Declaration": {
|
|
const typeParameters = changeMap(ast.typeParameters, (ast) => encodedAST_(ast, isBound));
|
|
return typeParameters === ast.typeParameters ? ast : new Declaration(typeParameters, ast.decodeUnknown, ast.encodeUnknown);
|
|
}
|
|
case "TupleType": {
|
|
const elements = changeMap(ast.elements, (e) => {
|
|
const type = encodedAST_(e.type, isBound);
|
|
return type === e.type ? e : new OptionalType(type, e.isOptional);
|
|
});
|
|
const restASTs = getRestASTs(ast.rest);
|
|
const rest = changeMap(restASTs, (ast) => encodedAST_(ast, isBound));
|
|
return elements === ast.elements && rest === restASTs ? ast : new TupleType(elements, rest.map((ast) => new Type(ast)), ast.isReadonly);
|
|
}
|
|
case "TypeLiteral": {
|
|
const propertySignatures = changeMap(ast.propertySignatures, (ps) => {
|
|
const type = encodedAST_(ps.type, isBound);
|
|
return type === ps.type ? ps : new PropertySignature(ps.name, type, ps.isOptional, ps.isReadonly);
|
|
});
|
|
const indexSignatures = changeMap(ast.indexSignatures, (is) => {
|
|
const type = encodedAST_(is.type, isBound);
|
|
return type === is.type ? is : new IndexSignature(is.parameter, type, is.isReadonly);
|
|
});
|
|
return propertySignatures === ast.propertySignatures && indexSignatures === ast.indexSignatures ? ast : new TypeLiteral(propertySignatures, indexSignatures);
|
|
}
|
|
case "Union": {
|
|
const types = changeMap(ast.types, (ast) => encodedAST_(ast, isBound));
|
|
return types === ast.types ? ast : Union.make(types);
|
|
}
|
|
case "Suspend": {
|
|
let borrowedAnnotations = undefined;
|
|
const identifier = getJSONIdentifier(ast);
|
|
if (isSome2(identifier)) {
|
|
const suffix = isBound ? "Bound" : "";
|
|
borrowedAnnotations = {
|
|
[JSONIdentifierAnnotationId]: `${identifier.value}Encoded${suffix}`
|
|
};
|
|
}
|
|
return new Suspend(() => encodedAST_(ast.f(), isBound), borrowedAnnotations);
|
|
}
|
|
case "Refinement": {
|
|
const from = encodedAST_(ast.from, isBound);
|
|
if (isBound) {
|
|
if (from === ast.from)
|
|
return ast;
|
|
if (getTransformationFrom(ast.from) === undefined && hasStableFilter(ast)) {
|
|
return new Refinement(from, ast.filter, ast.annotations);
|
|
}
|
|
return from;
|
|
} else {
|
|
return from;
|
|
}
|
|
}
|
|
case "Transformation":
|
|
return encodedAST_(ast.from, isBound);
|
|
}
|
|
return ast;
|
|
};
|
|
var encodedAST = (ast) => encodedAST_(ast, false);
|
|
var toJSONAnnotations = (annotations) => {
|
|
const out = {};
|
|
for (const k of Object.getOwnPropertySymbols(annotations)) {
|
|
out[String(k)] = annotations[k];
|
|
}
|
|
return out;
|
|
};
|
|
var getEncodedParameter = (ast) => {
|
|
switch (ast._tag) {
|
|
case "StringKeyword":
|
|
case "SymbolKeyword":
|
|
case "TemplateLiteral":
|
|
return ast;
|
|
case "Refinement":
|
|
return getEncodedParameter(ast.from);
|
|
}
|
|
};
|
|
var compose = (ab, cd) => new Transformation(ab, cd, composeTransformation);
|
|
var formatKeyword = (ast) => getOrElse(getExpected(ast), () => ast._tag);
|
|
function getBrands(ast) {
|
|
return match2(getBrandAnnotation(ast), {
|
|
onNone: () => "",
|
|
onSome: (brands) => brands.map((brand) => ` & Brand<${formatUnknown(brand)}>`).join("")
|
|
});
|
|
}
|
|
var getOrElseExpected = (ast) => getTitleAnnotation(ast).pipe(orElse(() => getDescriptionAnnotation(ast)), orElse(() => getAutoTitleAnnotation(ast)), map2((s) => s + getBrands(ast)));
|
|
var getExpected = (ast) => orElse(getIdentifierAnnotation(ast), () => getOrElseExpected(ast));
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/ParseResult.js
|
|
class Pointer {
|
|
path;
|
|
actual;
|
|
issue;
|
|
_tag = "Pointer";
|
|
constructor(path, actual, issue) {
|
|
this.path = path;
|
|
this.actual = actual;
|
|
this.issue = issue;
|
|
}
|
|
}
|
|
|
|
class Unexpected {
|
|
actual;
|
|
message;
|
|
_tag = "Unexpected";
|
|
constructor(actual, message) {
|
|
this.actual = actual;
|
|
this.message = message;
|
|
}
|
|
}
|
|
|
|
class Missing {
|
|
ast;
|
|
message;
|
|
_tag = "Missing";
|
|
actual = undefined;
|
|
constructor(ast, message) {
|
|
this.ast = ast;
|
|
this.message = message;
|
|
}
|
|
}
|
|
|
|
class Composite2 {
|
|
ast;
|
|
actual;
|
|
issues;
|
|
output;
|
|
_tag = "Composite";
|
|
constructor(ast, actual, issues, output) {
|
|
this.ast = ast;
|
|
this.actual = actual;
|
|
this.issues = issues;
|
|
this.output = output;
|
|
}
|
|
}
|
|
|
|
class Refinement2 {
|
|
ast;
|
|
actual;
|
|
kind;
|
|
issue;
|
|
_tag = "Refinement";
|
|
constructor(ast, actual, kind, issue) {
|
|
this.ast = ast;
|
|
this.actual = actual;
|
|
this.kind = kind;
|
|
this.issue = issue;
|
|
}
|
|
}
|
|
|
|
class Transformation2 {
|
|
ast;
|
|
actual;
|
|
kind;
|
|
issue;
|
|
_tag = "Transformation";
|
|
constructor(ast, actual, kind, issue) {
|
|
this.ast = ast;
|
|
this.actual = actual;
|
|
this.kind = kind;
|
|
this.issue = issue;
|
|
}
|
|
}
|
|
|
|
class Type2 {
|
|
ast;
|
|
actual;
|
|
message;
|
|
_tag = "Type";
|
|
constructor(ast, actual, message) {
|
|
this.ast = ast;
|
|
this.actual = actual;
|
|
this.message = message;
|
|
}
|
|
}
|
|
|
|
class Forbidden {
|
|
ast;
|
|
actual;
|
|
message;
|
|
_tag = "Forbidden";
|
|
constructor(ast, actual, message) {
|
|
this.ast = ast;
|
|
this.actual = actual;
|
|
this.message = message;
|
|
}
|
|
}
|
|
var ParseErrorTypeId = /* @__PURE__ */ Symbol.for("effect/Schema/ParseErrorTypeId");
|
|
class ParseError extends (/* @__PURE__ */ TaggedError("ParseError")) {
|
|
[ParseErrorTypeId] = ParseErrorTypeId;
|
|
get message() {
|
|
return this.toString();
|
|
}
|
|
toString() {
|
|
return TreeFormatter.formatIssueSync(this.issue);
|
|
}
|
|
toJSON() {
|
|
return {
|
|
_id: "ParseError",
|
|
message: this.toString()
|
|
};
|
|
}
|
|
[NodeInspectSymbol]() {
|
|
return this.toJSON();
|
|
}
|
|
}
|
|
var parseError = (issue) => new ParseError({
|
|
issue
|
|
});
|
|
var succeed12 = right2;
|
|
var fail12 = left2;
|
|
var _try = try_;
|
|
var isEither3 = isEither2;
|
|
var flatMap16 = /* @__PURE__ */ dual(2, (self2, f) => {
|
|
return isEither3(self2) ? match(self2, {
|
|
onLeft: left2,
|
|
onRight: f
|
|
}) : flatMap9(self2, f);
|
|
});
|
|
var map20 = /* @__PURE__ */ dual(2, (self2, f) => {
|
|
return isEither3(self2) ? map(self2, f) : map15(self2, f);
|
|
});
|
|
var mapError7 = /* @__PURE__ */ dual(2, (self2, f) => {
|
|
return isEither3(self2) ? mapLeft(self2, f) : mapError2(self2, f);
|
|
});
|
|
var orElse9 = /* @__PURE__ */ dual(2, (self2, f) => {
|
|
return isEither3(self2) ? match(self2, {
|
|
onLeft: f,
|
|
onRight: right2
|
|
}) : catchAll2(self2, f);
|
|
});
|
|
var mergeInternalOptions = (options, overrideOptions) => {
|
|
if (overrideOptions === undefined || isNumber(overrideOptions)) {
|
|
return options;
|
|
}
|
|
if (options === undefined) {
|
|
return overrideOptions;
|
|
}
|
|
return {
|
|
...options,
|
|
...overrideOptions
|
|
};
|
|
};
|
|
var getEither = (ast, isDecoding, options) => {
|
|
const parser = goMemo(ast, isDecoding);
|
|
return (u, overrideOptions) => parser(u, mergeInternalOptions(options, overrideOptions));
|
|
};
|
|
var getSync = (ast, isDecoding, options) => {
|
|
const parser = getEither(ast, isDecoding, options);
|
|
return (input, overrideOptions) => getOrThrowWith(parser(input, overrideOptions), parseError);
|
|
};
|
|
var getEffect = (ast, isDecoding, options) => {
|
|
const parser = goMemo(ast, isDecoding);
|
|
return (input, overrideOptions) => parser(input, {
|
|
...mergeInternalOptions(options, overrideOptions),
|
|
isEffectAllowed: true
|
|
});
|
|
};
|
|
var decodeUnknownSync = (schema, options) => getSync(schema.ast, true, options);
|
|
var encodeUnknown = (schema, options) => getEffect(schema.ast, false, options);
|
|
var validateSync = (schema, options) => getSync(typeAST(schema.ast), true, options);
|
|
var is = (schema, options) => {
|
|
const parser = goMemo(typeAST(schema.ast), true);
|
|
return (u, overrideOptions) => isRight2(parser(u, {
|
|
exact: true,
|
|
...mergeInternalOptions(options, overrideOptions)
|
|
}));
|
|
};
|
|
var decodeMemoMap = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/ParseResult/decodeMemoMap"), () => new WeakMap);
|
|
var encodeMemoMap = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/ParseResult/encodeMemoMap"), () => new WeakMap);
|
|
var goMemo = (ast, isDecoding) => {
|
|
const memoMap = isDecoding ? decodeMemoMap : encodeMemoMap;
|
|
const memo = memoMap.get(ast);
|
|
if (memo) {
|
|
return memo;
|
|
}
|
|
const raw = go(ast, isDecoding);
|
|
const parseOptionsAnnotation = getParseOptionsAnnotation(ast);
|
|
const parserWithOptions = isSome2(parseOptionsAnnotation) ? (i, options) => raw(i, mergeInternalOptions(options, parseOptionsAnnotation.value)) : raw;
|
|
const decodingFallbackAnnotation = getDecodingFallbackAnnotation(ast);
|
|
const parser = isDecoding && isSome2(decodingFallbackAnnotation) ? (i, options) => handleForbidden(orElse9(parserWithOptions(i, options), decodingFallbackAnnotation.value), ast, i, options) : parserWithOptions;
|
|
memoMap.set(ast, parser);
|
|
return parser;
|
|
};
|
|
var getConcurrency = (ast) => getOrUndefined(getConcurrencyAnnotation(ast));
|
|
var getBatching = (ast) => getOrUndefined(getBatchingAnnotation(ast));
|
|
var go = (ast, isDecoding) => {
|
|
switch (ast._tag) {
|
|
case "Refinement": {
|
|
if (isDecoding) {
|
|
const from = goMemo(ast.from, true);
|
|
return (i, options) => {
|
|
options = options ?? defaultParseOption;
|
|
const allErrors = options?.errors === "all";
|
|
const result = flatMap16(orElse9(from(i, options), (ef) => {
|
|
const issue = new Refinement2(ast, i, "From", ef);
|
|
if (allErrors && hasStableFilter(ast) && isComposite2(ef)) {
|
|
return match2(ast.filter(i, options, ast), {
|
|
onNone: () => left2(issue),
|
|
onSome: (ep) => left2(new Composite2(ast, i, [issue, new Refinement2(ast, i, "Predicate", ep)]))
|
|
});
|
|
}
|
|
return left2(issue);
|
|
}), (a) => match2(ast.filter(a, options, ast), {
|
|
onNone: () => right2(a),
|
|
onSome: (ep) => left2(new Refinement2(ast, i, "Predicate", ep))
|
|
}));
|
|
return handleForbidden(result, ast, i, options);
|
|
};
|
|
} else {
|
|
const from = goMemo(typeAST(ast), true);
|
|
const to = goMemo(dropRightRefinement(ast.from), false);
|
|
return (i, options) => handleForbidden(flatMap16(from(i, options), (a) => to(a, options)), ast, i, options);
|
|
}
|
|
}
|
|
case "Transformation": {
|
|
const transform = getFinalTransformation(ast.transformation, isDecoding);
|
|
const from = isDecoding ? goMemo(ast.from, true) : goMemo(ast.to, false);
|
|
const to = isDecoding ? goMemo(ast.to, true) : goMemo(ast.from, false);
|
|
return (i, options) => handleForbidden(flatMap16(mapError7(from(i, options), (e) => new Transformation2(ast, i, isDecoding ? "Encoded" : "Type", e)), (a) => flatMap16(mapError7(transform(a, options ?? defaultParseOption, ast, i), (e) => new Transformation2(ast, i, "Transformation", e)), (i2) => mapError7(to(i2, options), (e) => new Transformation2(ast, i, isDecoding ? "Type" : "Encoded", e)))), ast, i, options);
|
|
}
|
|
case "Declaration": {
|
|
const parse = isDecoding ? ast.decodeUnknown(...ast.typeParameters) : ast.encodeUnknown(...ast.typeParameters);
|
|
return (i, options) => handleForbidden(parse(i, options ?? defaultParseOption, ast), ast, i, options);
|
|
}
|
|
case "Literal":
|
|
return fromRefinement(ast, (u) => u === ast.literal);
|
|
case "UniqueSymbol":
|
|
return fromRefinement(ast, (u) => u === ast.symbol);
|
|
case "UndefinedKeyword":
|
|
return fromRefinement(ast, isUndefined);
|
|
case "NeverKeyword":
|
|
return fromRefinement(ast, isNever);
|
|
case "UnknownKeyword":
|
|
case "AnyKeyword":
|
|
case "VoidKeyword":
|
|
return right2;
|
|
case "StringKeyword":
|
|
return fromRefinement(ast, isString);
|
|
case "NumberKeyword":
|
|
return fromRefinement(ast, isNumber);
|
|
case "BooleanKeyword":
|
|
return fromRefinement(ast, isBoolean);
|
|
case "BigIntKeyword":
|
|
return fromRefinement(ast, isBigInt);
|
|
case "SymbolKeyword":
|
|
return fromRefinement(ast, isSymbol);
|
|
case "ObjectKeyword":
|
|
return fromRefinement(ast, isObject2);
|
|
case "Enums":
|
|
return fromRefinement(ast, (u) => ast.enums.some(([_, value]) => value === u));
|
|
case "TemplateLiteral": {
|
|
if (ast.spans.every((span) => isStringKeyword(span.type))) {
|
|
return fromRefinement(ast, (u) => {
|
|
if (!isString(u) || !u.startsWith(ast.head)) {
|
|
return false;
|
|
}
|
|
let position = ast.head.length;
|
|
for (let i = 0;i < ast.spans.length - 1; i++) {
|
|
const literal = ast.spans[i].literal;
|
|
const index = u.indexOf(literal, position);
|
|
if (index === -1) {
|
|
return false;
|
|
}
|
|
position = index + literal.length;
|
|
}
|
|
const literal = ast.spans[ast.spans.length - 1].literal;
|
|
return u.endsWith(literal) && u.length - literal.length >= position;
|
|
});
|
|
}
|
|
const regex = getTemplateLiteralRegExp(ast);
|
|
return fromRefinement(ast, (u) => isString(u) && regex.test(u));
|
|
}
|
|
case "TupleType": {
|
|
const elements = ast.elements.map((e) => goMemo(e.type, isDecoding));
|
|
const rest = ast.rest.map((annotatedAST) => goMemo(annotatedAST.type, isDecoding));
|
|
let requiredTypes = ast.elements.filter((e) => !e.isOptional);
|
|
if (ast.rest.length > 0) {
|
|
requiredTypes = requiredTypes.concat(ast.rest.slice(1));
|
|
}
|
|
const requiredLen = requiredTypes.length;
|
|
const expectedIndexes = ast.elements.length > 0 ? ast.elements.map((_, i) => i).join(" | ") : "never";
|
|
const concurrency = getConcurrency(ast);
|
|
const batching = getBatching(ast);
|
|
return (input, options) => {
|
|
if (!isArray(input)) {
|
|
return left2(new Type2(ast, input));
|
|
}
|
|
const allErrors = options?.errors === "all";
|
|
const es = [];
|
|
let stepKey = 0;
|
|
const output = [];
|
|
const len = input.length;
|
|
for (let i = len;i <= requiredLen - 1; i++) {
|
|
const e = new Pointer(i, input, new Missing(requiredTypes[i - len]));
|
|
if (allErrors) {
|
|
es.push([stepKey++, e]);
|
|
continue;
|
|
} else {
|
|
return left2(new Composite2(ast, input, e, output));
|
|
}
|
|
}
|
|
if (ast.rest.length === 0) {
|
|
for (let i = ast.elements.length;i <= len - 1; i++) {
|
|
const e = new Pointer(i, input, new Unexpected(input[i], `is unexpected, expected: ${expectedIndexes}`));
|
|
if (allErrors) {
|
|
es.push([stepKey++, e]);
|
|
continue;
|
|
} else {
|
|
return left2(new Composite2(ast, input, e, output));
|
|
}
|
|
}
|
|
}
|
|
let i = 0;
|
|
let queue = undefined;
|
|
for (;i < elements.length; i++) {
|
|
if (len < i + 1) {
|
|
if (ast.elements[i].isOptional) {
|
|
continue;
|
|
}
|
|
} else {
|
|
const parser = elements[i];
|
|
const te = parser(input[i], options);
|
|
if (isEither3(te)) {
|
|
if (isLeft2(te)) {
|
|
const e = new Pointer(i, input, te.left);
|
|
if (allErrors) {
|
|
es.push([stepKey++, e]);
|
|
continue;
|
|
} else {
|
|
return left2(new Composite2(ast, input, e, sortByIndex(output)));
|
|
}
|
|
}
|
|
output.push([stepKey++, te.right]);
|
|
} else {
|
|
const nk = stepKey++;
|
|
const index = i;
|
|
if (!queue) {
|
|
queue = [];
|
|
}
|
|
queue.push(({
|
|
es,
|
|
output
|
|
}) => flatMap9(either3(te), (t) => {
|
|
if (isLeft2(t)) {
|
|
const e = new Pointer(index, input, t.left);
|
|
if (allErrors) {
|
|
es.push([nk, e]);
|
|
return _void;
|
|
} else {
|
|
return left2(new Composite2(ast, input, e, sortByIndex(output)));
|
|
}
|
|
}
|
|
output.push([nk, t.right]);
|
|
return _void;
|
|
}));
|
|
}
|
|
}
|
|
}
|
|
if (isNonEmptyReadonlyArray(rest)) {
|
|
const [head, ...tail] = rest;
|
|
for (;i < len - tail.length; i++) {
|
|
const te = head(input[i], options);
|
|
if (isEither3(te)) {
|
|
if (isLeft2(te)) {
|
|
const e = new Pointer(i, input, te.left);
|
|
if (allErrors) {
|
|
es.push([stepKey++, e]);
|
|
continue;
|
|
} else {
|
|
return left2(new Composite2(ast, input, e, sortByIndex(output)));
|
|
}
|
|
} else {
|
|
output.push([stepKey++, te.right]);
|
|
}
|
|
} else {
|
|
const nk = stepKey++;
|
|
const index = i;
|
|
if (!queue) {
|
|
queue = [];
|
|
}
|
|
queue.push(({
|
|
es,
|
|
output
|
|
}) => flatMap9(either3(te), (t) => {
|
|
if (isLeft2(t)) {
|
|
const e = new Pointer(index, input, t.left);
|
|
if (allErrors) {
|
|
es.push([nk, e]);
|
|
return _void;
|
|
} else {
|
|
return left2(new Composite2(ast, input, e, sortByIndex(output)));
|
|
}
|
|
} else {
|
|
output.push([nk, t.right]);
|
|
return _void;
|
|
}
|
|
}));
|
|
}
|
|
}
|
|
for (let j = 0;j < tail.length; j++) {
|
|
const index = i + j;
|
|
if (len < index + 1) {
|
|
continue;
|
|
} else {
|
|
const te = tail[j](input[index], options);
|
|
if (isEither3(te)) {
|
|
if (isLeft2(te)) {
|
|
const e = new Pointer(index, input, te.left);
|
|
if (allErrors) {
|
|
es.push([stepKey++, e]);
|
|
continue;
|
|
} else {
|
|
return left2(new Composite2(ast, input, e, sortByIndex(output)));
|
|
}
|
|
}
|
|
output.push([stepKey++, te.right]);
|
|
} else {
|
|
const nk = stepKey++;
|
|
if (!queue) {
|
|
queue = [];
|
|
}
|
|
queue.push(({
|
|
es,
|
|
output
|
|
}) => flatMap9(either3(te), (t) => {
|
|
if (isLeft2(t)) {
|
|
const e = new Pointer(index, input, t.left);
|
|
if (allErrors) {
|
|
es.push([nk, e]);
|
|
return _void;
|
|
} else {
|
|
return left2(new Composite2(ast, input, e, sortByIndex(output)));
|
|
}
|
|
}
|
|
output.push([nk, t.right]);
|
|
return _void;
|
|
}));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
const computeResult = ({
|
|
es,
|
|
output
|
|
}) => isNonEmptyArray2(es) ? left2(new Composite2(ast, input, sortByIndex(es), sortByIndex(output))) : right2(sortByIndex(output));
|
|
if (queue && queue.length > 0) {
|
|
const cqueue = queue;
|
|
return suspend2(() => {
|
|
const state = {
|
|
es: copy(es),
|
|
output: copy(output)
|
|
};
|
|
return flatMap9(forEach4(cqueue, (f) => f(state), {
|
|
concurrency,
|
|
batching,
|
|
discard: true
|
|
}), () => computeResult(state));
|
|
});
|
|
}
|
|
return computeResult({
|
|
output,
|
|
es
|
|
});
|
|
};
|
|
}
|
|
case "TypeLiteral": {
|
|
if (ast.propertySignatures.length === 0 && ast.indexSignatures.length === 0) {
|
|
return fromRefinement(ast, isNotNullable);
|
|
}
|
|
const propertySignatures = [];
|
|
const expectedKeysMap = {};
|
|
const expectedKeys = [];
|
|
for (const ps of ast.propertySignatures) {
|
|
propertySignatures.push([goMemo(ps.type, isDecoding), ps]);
|
|
expectedKeysMap[ps.name] = null;
|
|
expectedKeys.push(ps.name);
|
|
}
|
|
const indexSignatures = ast.indexSignatures.map((is) => [goMemo(is.parameter, isDecoding), goMemo(is.type, isDecoding), is.parameter]);
|
|
const expectedAST = Union.make(ast.indexSignatures.map((is) => is.parameter).concat(expectedKeys.map((key) => isSymbol(key) ? new UniqueSymbol(key) : new Literal(key))));
|
|
const expected = goMemo(expectedAST, isDecoding);
|
|
const concurrency = getConcurrency(ast);
|
|
const batching = getBatching(ast);
|
|
return (input, options) => {
|
|
if (!isRecord(input)) {
|
|
return left2(new Type2(ast, input));
|
|
}
|
|
const allErrors = options?.errors === "all";
|
|
const es = [];
|
|
let stepKey = 0;
|
|
const onExcessPropertyError = options?.onExcessProperty === "error";
|
|
const onExcessPropertyPreserve = options?.onExcessProperty === "preserve";
|
|
const output = {};
|
|
let inputKeys;
|
|
if (onExcessPropertyError || onExcessPropertyPreserve) {
|
|
inputKeys = Reflect.ownKeys(input);
|
|
for (const key of inputKeys) {
|
|
const te = expected(key, options);
|
|
if (isEither3(te) && isLeft2(te)) {
|
|
if (onExcessPropertyError) {
|
|
const e = new Pointer(key, input, new Unexpected(input[key], `is unexpected, expected: ${String(expectedAST)}`));
|
|
if (allErrors) {
|
|
es.push([stepKey++, e]);
|
|
continue;
|
|
} else {
|
|
return left2(new Composite2(ast, input, e, output));
|
|
}
|
|
} else {
|
|
output[key] = input[key];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
let queue = undefined;
|
|
const isExact = options?.exact === true;
|
|
for (let i = 0;i < propertySignatures.length; i++) {
|
|
const ps = propertySignatures[i][1];
|
|
const name = ps.name;
|
|
const hasKey = Object.prototype.hasOwnProperty.call(input, name);
|
|
if (!hasKey) {
|
|
if (ps.isOptional) {
|
|
continue;
|
|
} else if (isExact) {
|
|
const e = new Pointer(name, input, new Missing(ps));
|
|
if (allErrors) {
|
|
es.push([stepKey++, e]);
|
|
continue;
|
|
} else {
|
|
return left2(new Composite2(ast, input, e, output));
|
|
}
|
|
}
|
|
}
|
|
const parser = propertySignatures[i][0];
|
|
const te = parser(input[name], options);
|
|
if (isEither3(te)) {
|
|
if (isLeft2(te)) {
|
|
const e = new Pointer(name, input, hasKey ? te.left : new Missing(ps));
|
|
if (allErrors) {
|
|
es.push([stepKey++, e]);
|
|
continue;
|
|
} else {
|
|
return left2(new Composite2(ast, input, e, output));
|
|
}
|
|
}
|
|
output[name] = te.right;
|
|
} else {
|
|
const nk = stepKey++;
|
|
const index = name;
|
|
if (!queue) {
|
|
queue = [];
|
|
}
|
|
queue.push(({
|
|
es,
|
|
output
|
|
}) => flatMap9(either3(te), (t) => {
|
|
if (isLeft2(t)) {
|
|
const e = new Pointer(index, input, hasKey ? t.left : new Missing(ps));
|
|
if (allErrors) {
|
|
es.push([nk, e]);
|
|
return _void;
|
|
} else {
|
|
return left2(new Composite2(ast, input, e, output));
|
|
}
|
|
}
|
|
output[index] = t.right;
|
|
return _void;
|
|
}));
|
|
}
|
|
}
|
|
for (let i = 0;i < indexSignatures.length; i++) {
|
|
const indexSignature = indexSignatures[i];
|
|
const parameter = indexSignature[0];
|
|
const type = indexSignature[1];
|
|
const keys = getKeysForIndexSignature(input, indexSignature[2]);
|
|
for (const key of keys) {
|
|
const keu = parameter(key, options);
|
|
if (isEither3(keu) && isRight2(keu)) {
|
|
const vpr = type(input[key], options);
|
|
if (isEither3(vpr)) {
|
|
if (isLeft2(vpr)) {
|
|
const e = new Pointer(key, input, vpr.left);
|
|
if (allErrors) {
|
|
es.push([stepKey++, e]);
|
|
continue;
|
|
} else {
|
|
return left2(new Composite2(ast, input, e, output));
|
|
}
|
|
} else {
|
|
if (!Object.prototype.hasOwnProperty.call(expectedKeysMap, key)) {
|
|
output[key] = vpr.right;
|
|
}
|
|
}
|
|
} else {
|
|
const nk = stepKey++;
|
|
const index = key;
|
|
if (!queue) {
|
|
queue = [];
|
|
}
|
|
queue.push(({
|
|
es,
|
|
output
|
|
}) => flatMap9(either3(vpr), (tv) => {
|
|
if (isLeft2(tv)) {
|
|
const e = new Pointer(index, input, tv.left);
|
|
if (allErrors) {
|
|
es.push([nk, e]);
|
|
return _void;
|
|
} else {
|
|
return left2(new Composite2(ast, input, e, output));
|
|
}
|
|
} else {
|
|
if (!Object.prototype.hasOwnProperty.call(expectedKeysMap, key)) {
|
|
output[key] = tv.right;
|
|
}
|
|
return _void;
|
|
}
|
|
}));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
const computeResult = ({
|
|
es,
|
|
output
|
|
}) => {
|
|
if (isNonEmptyArray2(es)) {
|
|
return left2(new Composite2(ast, input, sortByIndex(es), output));
|
|
}
|
|
if (options?.propertyOrder === "original") {
|
|
const keys = inputKeys || Reflect.ownKeys(input);
|
|
for (const name of expectedKeys) {
|
|
if (keys.indexOf(name) === -1) {
|
|
keys.push(name);
|
|
}
|
|
}
|
|
const out = {};
|
|
for (const key of keys) {
|
|
if (Object.prototype.hasOwnProperty.call(output, key)) {
|
|
out[key] = output[key];
|
|
}
|
|
}
|
|
return right2(out);
|
|
}
|
|
return right2(output);
|
|
};
|
|
if (queue && queue.length > 0) {
|
|
const cqueue = queue;
|
|
return suspend2(() => {
|
|
const state = {
|
|
es: copy(es),
|
|
output: Object.assign({}, output)
|
|
};
|
|
return flatMap9(forEach4(cqueue, (f) => f(state), {
|
|
concurrency,
|
|
batching,
|
|
discard: true
|
|
}), () => computeResult(state));
|
|
});
|
|
}
|
|
return computeResult({
|
|
es,
|
|
output
|
|
});
|
|
};
|
|
}
|
|
case "Union": {
|
|
const searchTree = getSearchTree(ast.types, isDecoding);
|
|
const ownKeys = Reflect.ownKeys(searchTree.keys);
|
|
const ownKeysLen = ownKeys.length;
|
|
const astTypesLen = ast.types.length;
|
|
const map = new Map;
|
|
for (let i = 0;i < astTypesLen; i++) {
|
|
map.set(ast.types[i], goMemo(ast.types[i], isDecoding));
|
|
}
|
|
const concurrency = getConcurrency(ast) ?? 1;
|
|
const batching = getBatching(ast);
|
|
return (input, options) => {
|
|
const es = [];
|
|
let stepKey = 0;
|
|
let candidates = [];
|
|
if (ownKeysLen > 0) {
|
|
if (isRecordOrArray(input)) {
|
|
for (let i = 0;i < ownKeysLen; i++) {
|
|
const name = ownKeys[i];
|
|
const buckets = searchTree.keys[name].buckets;
|
|
if (Object.prototype.hasOwnProperty.call(input, name)) {
|
|
const literal = String(input[name]);
|
|
if (Object.prototype.hasOwnProperty.call(buckets, literal)) {
|
|
candidates = candidates.concat(buckets[literal]);
|
|
} else {
|
|
const {
|
|
candidates,
|
|
literals
|
|
} = searchTree.keys[name];
|
|
const literalsUnion = Union.make(literals);
|
|
const errorAst = candidates.length === astTypesLen ? new TypeLiteral([new PropertySignature(name, literalsUnion, false, true)], []) : Union.make(candidates);
|
|
es.push([stepKey++, new Composite2(errorAst, input, new Pointer(name, input, new Type2(literalsUnion, input[name])))]);
|
|
}
|
|
} else {
|
|
const {
|
|
candidates,
|
|
literals
|
|
} = searchTree.keys[name];
|
|
const fakePropertySignature = new PropertySignature(name, Union.make(literals), false, true);
|
|
const errorAst = candidates.length === astTypesLen ? new TypeLiteral([fakePropertySignature], []) : Union.make(candidates);
|
|
es.push([stepKey++, new Composite2(errorAst, input, new Pointer(name, input, new Missing(fakePropertySignature)))]);
|
|
}
|
|
}
|
|
} else {
|
|
const errorAst = searchTree.candidates.length === astTypesLen ? ast : Union.make(searchTree.candidates);
|
|
es.push([stepKey++, new Type2(errorAst, input)]);
|
|
}
|
|
}
|
|
if (searchTree.otherwise.length > 0) {
|
|
candidates = candidates.concat(searchTree.otherwise);
|
|
}
|
|
let queue = undefined;
|
|
for (let i = 0;i < candidates.length; i++) {
|
|
const candidate = candidates[i];
|
|
const pr = map.get(candidate)(input, options);
|
|
if (isEither3(pr) && (!queue || queue.length === 0)) {
|
|
if (isRight2(pr)) {
|
|
return pr;
|
|
} else {
|
|
es.push([stepKey++, pr.left]);
|
|
}
|
|
} else {
|
|
const nk = stepKey++;
|
|
if (!queue) {
|
|
queue = [];
|
|
}
|
|
queue.push((state) => suspend2(() => {
|
|
if ("finalResult" in state) {
|
|
return _void;
|
|
} else {
|
|
return flatMap9(either3(pr), (t) => {
|
|
if (isRight2(t)) {
|
|
state.finalResult = t;
|
|
} else {
|
|
state.es.push([nk, t.left]);
|
|
}
|
|
return _void;
|
|
});
|
|
}
|
|
}));
|
|
}
|
|
}
|
|
const computeResult = (es) => isNonEmptyArray2(es) ? es.length === 1 && es[0][1]._tag === "Type" ? left2(es[0][1]) : left2(new Composite2(ast, input, sortByIndex(es))) : left2(new Type2(ast, input));
|
|
if (queue && queue.length > 0) {
|
|
const cqueue = queue;
|
|
return suspend2(() => {
|
|
const state = {
|
|
es: copy(es)
|
|
};
|
|
return flatMap9(forEach4(cqueue, (f) => f(state), {
|
|
concurrency,
|
|
batching,
|
|
discard: true
|
|
}), () => {
|
|
if ("finalResult" in state) {
|
|
return state.finalResult;
|
|
}
|
|
return computeResult(state.es);
|
|
});
|
|
});
|
|
}
|
|
return computeResult(es);
|
|
};
|
|
}
|
|
case "Suspend": {
|
|
const get = memoizeThunk(() => goMemo(ast.f(), isDecoding));
|
|
return (a, options) => get()(a, options);
|
|
}
|
|
}
|
|
};
|
|
var fromRefinement = (ast, refinement) => (u) => refinement(u) ? right2(u) : left2(new Type2(ast, u));
|
|
var getLiterals = (ast, isDecoding) => {
|
|
switch (ast._tag) {
|
|
case "Declaration": {
|
|
const annotation = getSurrogateAnnotation(ast);
|
|
if (isSome2(annotation)) {
|
|
return getLiterals(annotation.value, isDecoding);
|
|
}
|
|
break;
|
|
}
|
|
case "TypeLiteral": {
|
|
const out = [];
|
|
for (let i = 0;i < ast.propertySignatures.length; i++) {
|
|
const propertySignature = ast.propertySignatures[i];
|
|
const type = isDecoding ? encodedAST(propertySignature.type) : typeAST(propertySignature.type);
|
|
if (isLiteral(type) && !propertySignature.isOptional) {
|
|
out.push([propertySignature.name, type]);
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
case "TupleType": {
|
|
const out = [];
|
|
for (let i = 0;i < ast.elements.length; i++) {
|
|
const element = ast.elements[i];
|
|
const type = isDecoding ? encodedAST(element.type) : typeAST(element.type);
|
|
if (isLiteral(type) && !element.isOptional) {
|
|
out.push([i, type]);
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
case "Refinement":
|
|
return getLiterals(ast.from, isDecoding);
|
|
case "Suspend":
|
|
return getLiterals(ast.f(), isDecoding);
|
|
case "Transformation":
|
|
return getLiterals(isDecoding ? ast.from : ast.to, isDecoding);
|
|
}
|
|
return [];
|
|
};
|
|
var getSearchTree = (members, isDecoding) => {
|
|
const keys = {};
|
|
const otherwise = [];
|
|
const candidates = [];
|
|
for (let i = 0;i < members.length; i++) {
|
|
const member = members[i];
|
|
const tags = getLiterals(member, isDecoding);
|
|
if (tags.length > 0) {
|
|
candidates.push(member);
|
|
for (let j = 0;j < tags.length; j++) {
|
|
const [key, literal] = tags[j];
|
|
const hash = String(literal.literal);
|
|
keys[key] = keys[key] || {
|
|
buckets: {},
|
|
literals: [],
|
|
candidates: []
|
|
};
|
|
const buckets = keys[key].buckets;
|
|
if (Object.prototype.hasOwnProperty.call(buckets, hash)) {
|
|
if (j < tags.length - 1) {
|
|
continue;
|
|
}
|
|
buckets[hash].push(member);
|
|
keys[key].literals.push(literal);
|
|
keys[key].candidates.push(member);
|
|
} else {
|
|
buckets[hash] = [member];
|
|
keys[key].literals.push(literal);
|
|
keys[key].candidates.push(member);
|
|
break;
|
|
}
|
|
}
|
|
} else {
|
|
otherwise.push(member);
|
|
}
|
|
}
|
|
return {
|
|
keys,
|
|
otherwise,
|
|
candidates
|
|
};
|
|
};
|
|
var dropRightRefinement = (ast) => isRefinement(ast) ? dropRightRefinement(ast.from) : ast;
|
|
var handleForbidden = (effect, ast, actual, options) => {
|
|
if (options?.isEffectAllowed === true) {
|
|
return effect;
|
|
}
|
|
if (isEither3(effect)) {
|
|
return effect;
|
|
}
|
|
const scheduler = new SyncScheduler;
|
|
const fiber = runFork2(effect, {
|
|
scheduler
|
|
});
|
|
scheduler.flush();
|
|
const exit = fiber.unsafePoll();
|
|
if (exit) {
|
|
if (isSuccess(exit)) {
|
|
return right2(exit.value);
|
|
}
|
|
const cause = exit.cause;
|
|
if (isFailType2(cause)) {
|
|
return left2(cause.error);
|
|
}
|
|
return left2(new Forbidden(ast, actual, pretty2(cause)));
|
|
}
|
|
return left2(new Forbidden(ast, actual, "cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work"));
|
|
};
|
|
var compare = ([a], [b]) => a > b ? 1 : a < b ? -1 : 0;
|
|
function sortByIndex(es) {
|
|
return es.sort(compare).map((t) => t[1]);
|
|
}
|
|
var getFinalTransformation = (transformation, isDecoding) => {
|
|
switch (transformation._tag) {
|
|
case "FinalTransformation":
|
|
return isDecoding ? transformation.decode : transformation.encode;
|
|
case "ComposeTransformation":
|
|
return right2;
|
|
case "TypeLiteralTransformation":
|
|
return (input) => {
|
|
let out = right2(input);
|
|
for (const pst of transformation.propertySignatureTransformations) {
|
|
const [from, to] = isDecoding ? [pst.from, pst.to] : [pst.to, pst.from];
|
|
const transformation = isDecoding ? pst.decode : pst.encode;
|
|
const f = (input) => {
|
|
const o = transformation(Object.prototype.hasOwnProperty.call(input, from) ? some2(input[from]) : none2());
|
|
delete input[from];
|
|
if (isSome2(o)) {
|
|
input[to] = o.value;
|
|
}
|
|
return input;
|
|
};
|
|
out = map20(out, f);
|
|
}
|
|
return out;
|
|
};
|
|
}
|
|
};
|
|
var makeTree = (value, forest = []) => ({
|
|
value,
|
|
forest
|
|
});
|
|
var TreeFormatter = {
|
|
formatIssue: (issue) => map20(formatTree(issue), drawTree),
|
|
formatIssueSync: (issue) => {
|
|
const e = TreeFormatter.formatIssue(issue);
|
|
return isEither3(e) ? getOrThrow(e) : runSync(e);
|
|
},
|
|
formatError: (error) => TreeFormatter.formatIssue(error.issue),
|
|
formatErrorSync: (error) => TreeFormatter.formatIssueSync(error.issue)
|
|
};
|
|
var drawTree = (tree) => tree.value + draw(`
|
|
`, tree.forest);
|
|
var draw = (indentation, forest) => {
|
|
let r = "";
|
|
const len = forest.length;
|
|
let tree;
|
|
for (let i = 0;i < len; i++) {
|
|
tree = forest[i];
|
|
const isLast = i === len - 1;
|
|
r += indentation + (isLast ? "\u2514" : "\u251C") + "\u2500 " + tree.value;
|
|
r += draw(indentation + (len > 1 && !isLast ? "\u2502 " : " "), tree.forest);
|
|
}
|
|
return r;
|
|
};
|
|
var formatTransformationKind = (kind) => {
|
|
switch (kind) {
|
|
case "Encoded":
|
|
return "Encoded side transformation failure";
|
|
case "Transformation":
|
|
return "Transformation process failure";
|
|
case "Type":
|
|
return "Type side transformation failure";
|
|
}
|
|
};
|
|
var formatRefinementKind = (kind) => {
|
|
switch (kind) {
|
|
case "From":
|
|
return "From side refinement failure";
|
|
case "Predicate":
|
|
return "Predicate refinement failure";
|
|
}
|
|
};
|
|
var getAnnotated = (issue) => ("ast" in issue) ? some2(issue.ast) : none2();
|
|
var Either_void = /* @__PURE__ */ right2(undefined);
|
|
var getCurrentMessage = (issue) => getAnnotated(issue).pipe(flatMap(getMessageAnnotation), match2({
|
|
onNone: () => Either_void,
|
|
onSome: (messageAnnotation) => {
|
|
const union = messageAnnotation(issue);
|
|
if (isString(union)) {
|
|
return right2({
|
|
message: union,
|
|
override: false
|
|
});
|
|
}
|
|
if (isEffect2(union)) {
|
|
return map15(union, (message) => ({
|
|
message,
|
|
override: false
|
|
}));
|
|
}
|
|
if (isString(union.message)) {
|
|
return right2({
|
|
message: union.message,
|
|
override: union.override
|
|
});
|
|
}
|
|
return map15(union.message, (message) => ({
|
|
message,
|
|
override: union.override
|
|
}));
|
|
}
|
|
}));
|
|
var createParseIssueGuard = (tag) => (issue) => issue._tag === tag;
|
|
var isComposite2 = /* @__PURE__ */ createParseIssueGuard("Composite");
|
|
var isRefinement2 = /* @__PURE__ */ createParseIssueGuard("Refinement");
|
|
var isTransformation2 = /* @__PURE__ */ createParseIssueGuard("Transformation");
|
|
var getMessage = (issue) => flatMap16(getCurrentMessage(issue), (currentMessage) => {
|
|
if (currentMessage !== undefined) {
|
|
const useInnerMessage = !currentMessage.override && (isComposite2(issue) || isRefinement2(issue) && issue.kind === "From" || isTransformation2(issue) && issue.kind !== "Transformation");
|
|
return useInnerMessage ? isTransformation2(issue) || isRefinement2(issue) ? getMessage(issue.issue) : Either_void : right2(currentMessage.message);
|
|
}
|
|
return Either_void;
|
|
});
|
|
var getParseIssueTitleAnnotation2 = (issue) => getAnnotated(issue).pipe(flatMap(getParseIssueTitleAnnotation), flatMapNullable((annotation) => annotation(issue)), getOrUndefined);
|
|
function getRefinementExpected(ast) {
|
|
return getDescriptionAnnotation(ast).pipe(orElse(() => getTitleAnnotation(ast)), orElse(() => getAutoTitleAnnotation(ast)), orElse(() => getIdentifierAnnotation(ast)), getOrElse(() => `{ ${ast.from} | filter }`));
|
|
}
|
|
function getDefaultTypeMessage(issue) {
|
|
if (issue.message !== undefined) {
|
|
return issue.message;
|
|
}
|
|
const expected = isRefinement(issue.ast) ? getRefinementExpected(issue.ast) : String(issue.ast);
|
|
return `Expected ${expected}, actual ${formatUnknown(issue.actual)}`;
|
|
}
|
|
var formatTypeMessage = (issue) => map20(getMessage(issue), (message) => message ?? getParseIssueTitleAnnotation2(issue) ?? getDefaultTypeMessage(issue));
|
|
var getParseIssueTitle = (issue) => getParseIssueTitleAnnotation2(issue) ?? String(issue.ast);
|
|
var formatForbiddenMessage = (issue) => issue.message ?? "is forbidden";
|
|
var formatUnexpectedMessage = (issue) => issue.message ?? "is unexpected";
|
|
var formatMissingMessage = (issue) => {
|
|
const missingMessageAnnotation = getMissingMessageAnnotation(issue.ast);
|
|
if (isSome2(missingMessageAnnotation)) {
|
|
const annotation = missingMessageAnnotation.value();
|
|
return isString(annotation) ? right2(annotation) : annotation;
|
|
}
|
|
return right2(issue.message ?? "is missing");
|
|
};
|
|
var formatTree = (issue) => {
|
|
switch (issue._tag) {
|
|
case "Type":
|
|
return map20(formatTypeMessage(issue), makeTree);
|
|
case "Forbidden":
|
|
return right2(makeTree(getParseIssueTitle(issue), [makeTree(formatForbiddenMessage(issue))]));
|
|
case "Unexpected":
|
|
return right2(makeTree(formatUnexpectedMessage(issue)));
|
|
case "Missing":
|
|
return map20(formatMissingMessage(issue), makeTree);
|
|
case "Transformation":
|
|
return flatMap16(getMessage(issue), (message) => {
|
|
if (message !== undefined) {
|
|
return right2(makeTree(message));
|
|
}
|
|
return map20(formatTree(issue.issue), (tree) => makeTree(getParseIssueTitle(issue), [makeTree(formatTransformationKind(issue.kind), [tree])]));
|
|
});
|
|
case "Refinement":
|
|
return flatMap16(getMessage(issue), (message) => {
|
|
if (message !== undefined) {
|
|
return right2(makeTree(message));
|
|
}
|
|
return map20(formatTree(issue.issue), (tree) => makeTree(getParseIssueTitle(issue), [makeTree(formatRefinementKind(issue.kind), [tree])]));
|
|
});
|
|
case "Pointer":
|
|
return map20(formatTree(issue.issue), (tree) => makeTree(formatPath(issue.path), [tree]));
|
|
case "Composite":
|
|
return flatMap16(getMessage(issue), (message) => {
|
|
if (message !== undefined) {
|
|
return right2(makeTree(message));
|
|
}
|
|
const parseIssueTitle = getParseIssueTitle(issue);
|
|
return isNonEmpty5(issue.issues) ? map20(forEach4(issue.issues, formatTree), (forest) => makeTree(parseIssueTitle, forest)) : map20(formatTree(issue.issues), (tree) => makeTree(parseIssueTitle, [tree]));
|
|
});
|
|
}
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Struct.js
|
|
var pick2 = /* @__PURE__ */ dual((args) => isObject2(args[0]), (s, ...keys) => {
|
|
const out = {};
|
|
for (const k of keys) {
|
|
if (k in s) {
|
|
out[k] = s[k];
|
|
}
|
|
}
|
|
return out;
|
|
});
|
|
var omit3 = /* @__PURE__ */ dual((args) => isObject2(args[0]), (s, ...keys) => {
|
|
const out = {
|
|
...s
|
|
};
|
|
for (const k of keys) {
|
|
delete out[k];
|
|
}
|
|
return out;
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/effect@3.22.1/node_modules/effect/dist/esm/Schema.js
|
|
var TypeId15 = /* @__PURE__ */ Symbol.for("effect/Schema");
|
|
function make42(ast) {
|
|
return class SchemaClass {
|
|
[TypeId15] = variance5;
|
|
static ast = ast;
|
|
static annotations(annotations) {
|
|
return make42(mergeSchemaAnnotations(this.ast, annotations));
|
|
}
|
|
static pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
static toString() {
|
|
return String(ast);
|
|
}
|
|
static Type;
|
|
static Encoded;
|
|
static Context;
|
|
static [TypeId15] = variance5;
|
|
};
|
|
}
|
|
var variance5 = {
|
|
_A: (_) => _,
|
|
_I: (_) => _,
|
|
_R: (_) => _
|
|
};
|
|
var builtInAnnotations = {
|
|
typeConstructor: TypeConstructorAnnotationId,
|
|
schemaId: SchemaIdAnnotationId,
|
|
message: MessageAnnotationId,
|
|
missingMessage: MissingMessageAnnotationId,
|
|
identifier: IdentifierAnnotationId,
|
|
title: TitleAnnotationId,
|
|
description: DescriptionAnnotationId,
|
|
examples: ExamplesAnnotationId,
|
|
default: DefaultAnnotationId,
|
|
documentation: DocumentationAnnotationId,
|
|
jsonSchema: JSONSchemaAnnotationId,
|
|
arbitrary: ArbitraryAnnotationId,
|
|
pretty: PrettyAnnotationId,
|
|
equivalence: EquivalenceAnnotationId,
|
|
concurrency: ConcurrencyAnnotationId,
|
|
batching: BatchingAnnotationId,
|
|
parseIssueTitle: ParseIssueTitleAnnotationId,
|
|
parseOptions: ParseOptionsAnnotationId,
|
|
decodingFallback: DecodingFallbackAnnotationId
|
|
};
|
|
var toASTAnnotations = (annotations) => {
|
|
if (!annotations) {
|
|
return {};
|
|
}
|
|
const out = {
|
|
...annotations
|
|
};
|
|
for (const key in builtInAnnotations) {
|
|
if (key in annotations) {
|
|
const id = builtInAnnotations[key];
|
|
out[id] = annotations[key];
|
|
delete out[key];
|
|
}
|
|
}
|
|
return out;
|
|
};
|
|
var mergeSchemaAnnotations = (ast, annotations2) => annotations(ast, toASTAnnotations(annotations2));
|
|
var encodedSchema = (schema) => make42(encodedAST(schema.ast));
|
|
var typeSchema = (schema) => make42(typeAST(schema.ast));
|
|
var isSchema = (u) => hasProperty(u, TypeId15) && isObject2(u[TypeId15]);
|
|
function getDefaultLiteralAST(literals) {
|
|
return isMembers(literals) ? Union.make(mapMembers(literals, (literal) => new Literal(literal))) : new Literal(literals[0]);
|
|
}
|
|
function makeLiteralClass(literals, ast = getDefaultLiteralAST(literals)) {
|
|
return class LiteralClass extends make42(ast) {
|
|
static annotations(annotations) {
|
|
return makeLiteralClass(this.literals, mergeSchemaAnnotations(this.ast, annotations));
|
|
}
|
|
static literals = [...literals];
|
|
};
|
|
}
|
|
function Literal2(...literals) {
|
|
return isNonEmptyReadonlyArray(literals) ? makeLiteralClass(literals) : Never;
|
|
}
|
|
var declareConstructor = (typeParameters, options, annotations) => makeDeclareClass(typeParameters, new Declaration(typeParameters.map((tp) => tp.ast), (...typeParameters) => options.decode(...typeParameters.map(make42)), (...typeParameters) => options.encode(...typeParameters.map(make42)), toASTAnnotations(annotations)));
|
|
var declarePrimitive = (is, annotations) => {
|
|
const decodeUnknown = () => (input, _, ast) => is(input) ? succeed12(input) : fail12(new Type2(ast, input));
|
|
const encodeUnknown = decodeUnknown;
|
|
return makeDeclareClass([], new Declaration([], decodeUnknown, encodeUnknown, toASTAnnotations(annotations)));
|
|
};
|
|
function makeDeclareClass(typeParameters, ast) {
|
|
return class DeclareClass extends make42(ast) {
|
|
static annotations(annotations) {
|
|
return makeDeclareClass(this.typeParameters, mergeSchemaAnnotations(this.ast, annotations));
|
|
}
|
|
static typeParameters = [...typeParameters];
|
|
};
|
|
}
|
|
var declare = function() {
|
|
if (Array.isArray(arguments[0])) {
|
|
const typeParameters = arguments[0];
|
|
const options = arguments[1];
|
|
const annotations = arguments[2];
|
|
return declareConstructor(typeParameters, options, annotations);
|
|
}
|
|
const is = arguments[0];
|
|
const annotations = arguments[1];
|
|
return declarePrimitive(is, annotations);
|
|
};
|
|
class Undefined extends (/* @__PURE__ */ make42(undefinedKeyword)) {
|
|
}
|
|
class Never extends (/* @__PURE__ */ make42(neverKeyword)) {
|
|
}
|
|
|
|
class Unknown extends (/* @__PURE__ */ make42(unknownKeyword)) {
|
|
}
|
|
class String$ extends (/* @__PURE__ */ make42(stringKeyword)) {
|
|
}
|
|
|
|
class Number$ extends (/* @__PURE__ */ make42(numberKeyword)) {
|
|
}
|
|
var getDefaultUnionAST = (members) => Union.make(members.map((m) => m.ast));
|
|
function makeUnionClass(members, ast = getDefaultUnionAST(members)) {
|
|
return class UnionClass extends make42(ast) {
|
|
static annotations(annotations) {
|
|
return makeUnionClass(this.members, mergeSchemaAnnotations(this.ast, annotations));
|
|
}
|
|
static members = [...members];
|
|
};
|
|
}
|
|
function Union2(...members) {
|
|
return isMembers(members) ? makeUnionClass(members) : isNonEmptyReadonlyArray(members) ? members[0] : Never;
|
|
}
|
|
var UndefinedOr = (self2) => Union2(self2, Undefined);
|
|
var formatPropertySignatureToken = (isOptional) => isOptional ? '"?:"' : '":"';
|
|
|
|
class PropertySignatureDeclaration extends OptionalType {
|
|
isReadonly;
|
|
defaultValue;
|
|
_tag = "PropertySignatureDeclaration";
|
|
constructor(type, isOptional, isReadonly, annotations, defaultValue) {
|
|
super(type, isOptional, annotations);
|
|
this.isReadonly = isReadonly;
|
|
this.defaultValue = defaultValue;
|
|
}
|
|
toString() {
|
|
const token = formatPropertySignatureToken(this.isOptional);
|
|
const type = String(this.type);
|
|
return `PropertySignature<${token}, ${type}, never, ${token}, ${type}>`;
|
|
}
|
|
}
|
|
class ToPropertySignature extends OptionalType {
|
|
isReadonly;
|
|
defaultValue;
|
|
constructor(type, isOptional, isReadonly, annotations, defaultValue) {
|
|
super(type, isOptional, annotations);
|
|
this.isReadonly = isReadonly;
|
|
this.defaultValue = defaultValue;
|
|
}
|
|
}
|
|
var formatPropertyKey2 = (p) => {
|
|
if (p === undefined) {
|
|
return "never";
|
|
}
|
|
if (isString(p)) {
|
|
return JSON.stringify(p);
|
|
}
|
|
return String(p);
|
|
};
|
|
|
|
class PropertySignatureTransformation2 {
|
|
from;
|
|
to;
|
|
decode;
|
|
encode;
|
|
_tag = "PropertySignatureTransformation";
|
|
constructor(from, to, decode, encode) {
|
|
this.from = from;
|
|
this.to = to;
|
|
this.decode = decode;
|
|
this.encode = encode;
|
|
}
|
|
toString() {
|
|
return `PropertySignature<${formatPropertySignatureToken(this.to.isOptional)}, ${this.to.type}, ${formatPropertyKey2(this.from.fromKey)}, ${formatPropertySignatureToken(this.from.isOptional)}, ${this.from.type}>`;
|
|
}
|
|
}
|
|
var mergeSignatureAnnotations = (ast, annotations) => {
|
|
switch (ast._tag) {
|
|
case "PropertySignatureDeclaration": {
|
|
return new PropertySignatureDeclaration(ast.type, ast.isOptional, ast.isReadonly, {
|
|
...ast.annotations,
|
|
...annotations
|
|
}, ast.defaultValue);
|
|
}
|
|
case "PropertySignatureTransformation": {
|
|
return new PropertySignatureTransformation2(ast.from, new ToPropertySignature(ast.to.type, ast.to.isOptional, ast.to.isReadonly, {
|
|
...ast.to.annotations,
|
|
...annotations
|
|
}, ast.to.defaultValue), ast.decode, ast.encode);
|
|
}
|
|
}
|
|
};
|
|
var PropertySignatureTypeId = /* @__PURE__ */ Symbol.for("effect/PropertySignature");
|
|
var isPropertySignature = (u) => hasProperty(u, PropertySignatureTypeId);
|
|
|
|
class PropertySignatureImpl {
|
|
ast;
|
|
[TypeId15];
|
|
[PropertySignatureTypeId] = null;
|
|
_TypeToken;
|
|
_Key;
|
|
_EncodedToken;
|
|
_HasDefault;
|
|
constructor(ast) {
|
|
this.ast = ast;
|
|
}
|
|
pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
annotations(annotations) {
|
|
return new PropertySignatureImpl(mergeSignatureAnnotations(this.ast, toASTAnnotations(annotations)));
|
|
}
|
|
toString() {
|
|
return String(this.ast);
|
|
}
|
|
}
|
|
var makePropertySignature = (ast) => new PropertySignatureImpl(ast);
|
|
|
|
class PropertySignatureWithFromImpl extends PropertySignatureImpl {
|
|
from;
|
|
constructor(ast, from) {
|
|
super(ast);
|
|
this.from = from;
|
|
}
|
|
annotations(annotations) {
|
|
return new PropertySignatureWithFromImpl(mergeSignatureAnnotations(this.ast, toASTAnnotations(annotations)), this.from);
|
|
}
|
|
}
|
|
var propertySignature = (self2) => new PropertySignatureWithFromImpl(new PropertySignatureDeclaration(self2.ast, false, true, {}, undefined), self2);
|
|
var withConstructorDefault = /* @__PURE__ */ dual(2, (self2, defaultValue) => {
|
|
const ast = self2.ast;
|
|
switch (ast._tag) {
|
|
case "PropertySignatureDeclaration":
|
|
return makePropertySignature(new PropertySignatureDeclaration(ast.type, ast.isOptional, ast.isReadonly, ast.annotations, defaultValue));
|
|
case "PropertySignatureTransformation":
|
|
return makePropertySignature(new PropertySignatureTransformation2(ast.from, new ToPropertySignature(ast.to.type, ast.to.isOptional, ast.to.isReadonly, ast.to.annotations, defaultValue), ast.decode, ast.encode));
|
|
}
|
|
});
|
|
var optional = (self2) => {
|
|
const ast = self2.ast === undefinedKeyword || self2.ast === neverKeyword ? undefinedKeyword : UndefinedOr(self2).ast;
|
|
return new PropertySignatureWithFromImpl(new PropertySignatureDeclaration(ast, true, true, {}, undefined), self2);
|
|
};
|
|
var preserveMissingMessageAnnotation = /* @__PURE__ */ pickAnnotations([MissingMessageAnnotationId]);
|
|
var getDefaultTypeLiteralAST = (fields, records) => {
|
|
const ownKeys = Reflect.ownKeys(fields);
|
|
const pss = [];
|
|
if (ownKeys.length > 0) {
|
|
const from = [];
|
|
const to = [];
|
|
const transformations = [];
|
|
for (let i = 0;i < ownKeys.length; i++) {
|
|
const key = ownKeys[i];
|
|
const field = fields[key];
|
|
if (isPropertySignature(field)) {
|
|
const ast = field.ast;
|
|
switch (ast._tag) {
|
|
case "PropertySignatureDeclaration": {
|
|
const type = ast.type;
|
|
const isOptional = ast.isOptional;
|
|
const toAnnotations = ast.annotations;
|
|
from.push(new PropertySignature(key, type, isOptional, true, preserveMissingMessageAnnotation(ast)));
|
|
to.push(new PropertySignature(key, typeAST(type), isOptional, true, toAnnotations));
|
|
pss.push(new PropertySignature(key, type, isOptional, true, toAnnotations));
|
|
break;
|
|
}
|
|
case "PropertySignatureTransformation": {
|
|
const fromKey = ast.from.fromKey ?? key;
|
|
from.push(new PropertySignature(fromKey, ast.from.type, ast.from.isOptional, true, ast.from.annotations));
|
|
to.push(new PropertySignature(key, ast.to.type, ast.to.isOptional, true, ast.to.annotations));
|
|
transformations.push(new PropertySignatureTransformation(fromKey, key, ast.decode, ast.encode));
|
|
break;
|
|
}
|
|
}
|
|
} else {
|
|
from.push(new PropertySignature(key, field.ast, false, true));
|
|
to.push(new PropertySignature(key, typeAST(field.ast), false, true));
|
|
pss.push(new PropertySignature(key, field.ast, false, true));
|
|
}
|
|
}
|
|
if (isNonEmptyReadonlyArray(transformations)) {
|
|
const issFrom = [];
|
|
const issTo = [];
|
|
for (const r of records) {
|
|
const {
|
|
indexSignatures,
|
|
propertySignatures
|
|
} = record(r.key.ast, r.value.ast);
|
|
propertySignatures.forEach((ps) => {
|
|
from.push(ps);
|
|
to.push(new PropertySignature(ps.name, typeAST(ps.type), ps.isOptional, ps.isReadonly, ps.annotations));
|
|
});
|
|
indexSignatures.forEach((is) => {
|
|
issFrom.push(is);
|
|
issTo.push(new IndexSignature(is.parameter, typeAST(is.type), is.isReadonly));
|
|
});
|
|
}
|
|
return new Transformation(new TypeLiteral(from, issFrom, {
|
|
[AutoTitleAnnotationId]: "Struct (Encoded side)"
|
|
}), new TypeLiteral(to, issTo, {
|
|
[AutoTitleAnnotationId]: "Struct (Type side)"
|
|
}), new TypeLiteralTransformation(transformations));
|
|
}
|
|
}
|
|
const iss = [];
|
|
for (const r of records) {
|
|
const {
|
|
indexSignatures,
|
|
propertySignatures
|
|
} = record(r.key.ast, r.value.ast);
|
|
propertySignatures.forEach((ps) => pss.push(ps));
|
|
indexSignatures.forEach((is) => iss.push(is));
|
|
}
|
|
return new TypeLiteral(pss, iss);
|
|
};
|
|
var lazilyMergeDefaults = (fields, out) => {
|
|
const ownKeys = Reflect.ownKeys(fields);
|
|
for (const key of ownKeys) {
|
|
const field = fields[key];
|
|
if (out[key] === undefined && isPropertySignature(field)) {
|
|
const ast = field.ast;
|
|
const defaultValue = ast._tag === "PropertySignatureDeclaration" ? ast.defaultValue : ast.to.defaultValue;
|
|
if (defaultValue !== undefined) {
|
|
out[key] = defaultValue();
|
|
}
|
|
}
|
|
}
|
|
return out;
|
|
};
|
|
function makeTypeLiteralClass(fields, records, ast = getDefaultTypeLiteralAST(fields, records)) {
|
|
return class TypeLiteralClass extends make42(ast) {
|
|
static annotations(annotations) {
|
|
return makeTypeLiteralClass(this.fields, this.records, mergeSchemaAnnotations(this.ast, annotations));
|
|
}
|
|
static fields = {
|
|
...fields
|
|
};
|
|
static records = [...records];
|
|
static make = (props, options) => {
|
|
const propsWithDefaults = lazilyMergeDefaults(fields, {
|
|
...props
|
|
});
|
|
return getDisableValidationMakeOption(options) ? propsWithDefaults : validateSync(this)(propsWithDefaults);
|
|
};
|
|
static pick(...keys) {
|
|
return Struct(pick2(fields, ...keys));
|
|
}
|
|
static omit(...keys) {
|
|
return Struct(omit3(fields, ...keys));
|
|
}
|
|
};
|
|
}
|
|
function Struct(fields, ...records) {
|
|
return makeTypeLiteralClass(fields, records);
|
|
}
|
|
function makeRecordClass(key, value, ast) {
|
|
return class RecordClass extends makeTypeLiteralClass({}, [{
|
|
key,
|
|
value
|
|
}], ast) {
|
|
static annotations(annotations) {
|
|
return makeRecordClass(key, value, mergeSchemaAnnotations(this.ast, annotations));
|
|
}
|
|
static key = key;
|
|
static value = value;
|
|
};
|
|
}
|
|
var Record = (options) => makeRecordClass(options.key, options.value);
|
|
var intersectTypeLiterals = (x, y, path) => {
|
|
if (isTypeLiteral(x) && isTypeLiteral(y)) {
|
|
const propertySignatures = [...x.propertySignatures];
|
|
for (const ps of y.propertySignatures) {
|
|
const name = ps.name;
|
|
const i = propertySignatures.findIndex((ps) => ps.name === name);
|
|
if (i === -1) {
|
|
propertySignatures.push(ps);
|
|
} else {
|
|
const {
|
|
isOptional,
|
|
type
|
|
} = propertySignatures[i];
|
|
propertySignatures[i] = new PropertySignature(name, extendAST(type, ps.type, path.concat(name)), isOptional, true);
|
|
}
|
|
}
|
|
return new TypeLiteral(propertySignatures, x.indexSignatures.concat(y.indexSignatures));
|
|
}
|
|
throw new Error(getSchemaExtendErrorMessage(x, y, path));
|
|
};
|
|
var preserveRefinementAnnotations = /* @__PURE__ */ omitAnnotations([IdentifierAnnotationId]);
|
|
var addRefinementToMembers = (refinement, asts) => asts.map((ast) => new Refinement(ast, refinement.filter, preserveRefinementAnnotations(refinement)));
|
|
var extendAST = (x, y, path) => Union.make(intersectUnionMembers([x], [y], path));
|
|
var getTypes = (ast) => isUnion(ast) ? ast.types : [ast];
|
|
var intersectUnionMembers = (xs, ys, path) => flatMap2(xs, (x) => flatMap2(ys, (y) => {
|
|
switch (y._tag) {
|
|
case "Literal": {
|
|
if (isString(y.literal) && isStringKeyword(x) || isNumber(y.literal) && isNumberKeyword(x) || isBoolean(y.literal) && isBooleanKeyword(x)) {
|
|
return [y];
|
|
}
|
|
break;
|
|
}
|
|
case "StringKeyword": {
|
|
if (y === stringKeyword) {
|
|
if (isStringKeyword(x) || isLiteral(x) && isString(x.literal)) {
|
|
return [x];
|
|
} else if (isRefinement(x)) {
|
|
return addRefinementToMembers(x, intersectUnionMembers(getTypes(x.from), [y], path));
|
|
}
|
|
} else if (x === stringKeyword) {
|
|
return [y];
|
|
}
|
|
break;
|
|
}
|
|
case "NumberKeyword": {
|
|
if (y === numberKeyword) {
|
|
if (isNumberKeyword(x) || isLiteral(x) && isNumber(x.literal)) {
|
|
return [x];
|
|
} else if (isRefinement(x)) {
|
|
return addRefinementToMembers(x, intersectUnionMembers(getTypes(x.from), [y], path));
|
|
}
|
|
} else if (x === numberKeyword) {
|
|
return [y];
|
|
}
|
|
break;
|
|
}
|
|
case "BooleanKeyword": {
|
|
if (y === booleanKeyword) {
|
|
if (isBooleanKeyword(x) || isLiteral(x) && isBoolean(x.literal)) {
|
|
return [x];
|
|
} else if (isRefinement(x)) {
|
|
return addRefinementToMembers(x, intersectUnionMembers(getTypes(x.from), [y], path));
|
|
}
|
|
} else if (x === booleanKeyword) {
|
|
return [y];
|
|
}
|
|
break;
|
|
}
|
|
case "Union":
|
|
return intersectUnionMembers(getTypes(x), y.types, path);
|
|
case "Suspend":
|
|
return [new Suspend(() => extendAST(x, y.f(), path))];
|
|
case "Refinement":
|
|
return addRefinementToMembers(y, intersectUnionMembers(getTypes(x), getTypes(y.from), path));
|
|
case "TypeLiteral": {
|
|
switch (x._tag) {
|
|
case "Union":
|
|
return intersectUnionMembers(x.types, [y], path);
|
|
case "Suspend":
|
|
return [new Suspend(() => extendAST(x.f(), y, path))];
|
|
case "Refinement":
|
|
return addRefinementToMembers(x, intersectUnionMembers(getTypes(x.from), [y], path));
|
|
case "TypeLiteral":
|
|
return [intersectTypeLiterals(x, y, path)];
|
|
case "Transformation": {
|
|
const transformation = x.transformation;
|
|
const from = intersectTypeLiterals(x.from, y, path);
|
|
const to = intersectTypeLiterals(x.to, typeAST(y), path);
|
|
switch (transformation._tag) {
|
|
case "TypeLiteralTransformation":
|
|
return [new Transformation(from, to, new TypeLiteralTransformation(transformation.propertySignatureTransformations))];
|
|
case "ComposeTransformation":
|
|
return [new Transformation(from, to, composeTransformation)];
|
|
case "FinalTransformation":
|
|
return [new Transformation(from, to, new FinalTransformation((fromA, options, ast, fromI) => map20(transformation.decode(fromA, options, ast, fromI), (partial) => ({
|
|
...fromA,
|
|
...partial
|
|
})), (toI, options, ast, toA) => map20(transformation.encode(toI, options, ast, toA), (partial) => ({
|
|
...toI,
|
|
...partial
|
|
}))))];
|
|
}
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case "Transformation": {
|
|
if (isTransformation(x)) {
|
|
if (isTypeLiteralTransformation(y.transformation) && isTypeLiteralTransformation(x.transformation)) {
|
|
return [new Transformation(intersectTypeLiterals(x.from, y.from, path), intersectTypeLiterals(x.to, y.to, path), new TypeLiteralTransformation(y.transformation.propertySignatureTransformations.concat(x.transformation.propertySignatureTransformations)))];
|
|
}
|
|
} else {
|
|
return intersectUnionMembers([y], [x], path);
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
throw new Error(getSchemaExtendErrorMessage(x, y, path));
|
|
}));
|
|
var extend3 = /* @__PURE__ */ dual(2, (self2, that) => make42(extendAST(self2.ast, that.ast, [])));
|
|
var compose2 = /* @__PURE__ */ dual((args) => isSchema(args[1]), (from, to) => makeTransformationClass(from, to, compose(from.ast, to.ast)));
|
|
var RefineSchemaId = /* @__PURE__ */ Symbol.for("effect/SchemaId/Refine");
|
|
function makeRefineClass(from, filter, ast) {
|
|
return class RefineClass extends make42(ast) {
|
|
static annotations(annotations) {
|
|
return makeRefineClass(this.from, this.filter, mergeSchemaAnnotations(this.ast, annotations));
|
|
}
|
|
static [RefineSchemaId] = from;
|
|
static from = from;
|
|
static filter = filter;
|
|
static make = (a, options) => {
|
|
return getDisableValidationMakeOption(options) ? a : validateSync(this)(a);
|
|
};
|
|
};
|
|
}
|
|
var fromFilterPredicateReturnTypeItem = (item, ast, input) => {
|
|
if (isBoolean(item)) {
|
|
return item ? none2() : some2(new Type2(ast, input));
|
|
}
|
|
if (isString(item)) {
|
|
return some2(new Type2(ast, input, item));
|
|
}
|
|
if (item !== undefined) {
|
|
if ("_tag" in item) {
|
|
return some2(item);
|
|
}
|
|
const issue = new Type2(ast, input, item.message);
|
|
return some2(isNonEmptyReadonlyArray(item.path) ? new Pointer(item.path, input, issue) : issue);
|
|
}
|
|
return none2();
|
|
};
|
|
var toFilterParseIssue = (out, ast, input) => {
|
|
if (isSingle(out)) {
|
|
return fromFilterPredicateReturnTypeItem(out, ast, input);
|
|
}
|
|
if (isNonEmptyReadonlyArray(out)) {
|
|
const issues = filterMap(out, (issue) => fromFilterPredicateReturnTypeItem(issue, ast, input));
|
|
if (isNonEmptyReadonlyArray(issues)) {
|
|
return some2(issues.length === 1 ? issues[0] : new Composite2(ast, input, issues));
|
|
}
|
|
}
|
|
return none2();
|
|
};
|
|
function filter10(predicate, annotations) {
|
|
return (self2) => {
|
|
function filter(input, options, ast) {
|
|
return toFilterParseIssue(predicate(input, options, ast), ast, input);
|
|
}
|
|
const ast = new Refinement(self2.ast, filter, toASTAnnotations(annotations));
|
|
return makeRefineClass(self2, filter, ast);
|
|
};
|
|
}
|
|
function makeTransformationClass(from, to, ast) {
|
|
return class TransformationClass extends make42(ast) {
|
|
static annotations(annotations) {
|
|
return makeTransformationClass(this.from, this.to, mergeSchemaAnnotations(this.ast, annotations));
|
|
}
|
|
static from = from;
|
|
static to = to;
|
|
};
|
|
}
|
|
var transformOrFail = /* @__PURE__ */ dual((args) => isSchema(args[0]) && isSchema(args[1]), (from, to, options) => makeTransformationClass(from, to, new Transformation(from.ast, to.ast, new FinalTransformation(options.decode, options.encode))));
|
|
var transform2 = /* @__PURE__ */ dual((args) => isSchema(args[0]) && isSchema(args[1]), (from, to, options) => transformOrFail(from, to, {
|
|
strict: true,
|
|
decode: (fromA, _options, _ast, toA) => succeed12(options.decode(fromA, toA)),
|
|
encode: (toI, _options, _ast, toA) => succeed12(options.encode(toI, toA))
|
|
}));
|
|
var PatternSchemaId = /* @__PURE__ */ Symbol.for("effect/SchemaId/Pattern");
|
|
var pattern = (regex, annotations) => (self2) => {
|
|
const source = regex.source;
|
|
return self2.pipe(filter10((a) => {
|
|
regex.lastIndex = 0;
|
|
return regex.test(a);
|
|
}, {
|
|
schemaId: PatternSchemaId,
|
|
[PatternSchemaId]: {
|
|
regex
|
|
},
|
|
description: `a string matching the pattern ${source}`,
|
|
jsonSchema: {
|
|
pattern: source
|
|
},
|
|
...annotations
|
|
}));
|
|
};
|
|
var getErrorMessage2 = (e) => e instanceof Error ? e.message : String(e);
|
|
var getParseJsonTransformation = (options) => transformOrFail(String$.annotations({
|
|
description: "a string to be decoded into JSON"
|
|
}), Unknown, {
|
|
strict: true,
|
|
decode: (i, _, ast) => _try({
|
|
try: () => JSON.parse(i, options?.reviver),
|
|
catch: (e) => new Type2(ast, i, getErrorMessage2(e))
|
|
}),
|
|
encode: (a, _, ast) => _try({
|
|
try: () => JSON.stringify(a, options?.replacer, options?.space),
|
|
catch: (e) => new Type2(ast, a, getErrorMessage2(e))
|
|
})
|
|
}).annotations({
|
|
title: "parseJson",
|
|
schemaId: ParseJsonSchemaId
|
|
});
|
|
var parseJson = (schemaOrOptions, o) => isSchema(schemaOrOptions) ? compose2(parseJson(o), schemaOrOptions) : getParseJsonTransformation(schemaOrOptions);
|
|
var UUIDSchemaId = /* @__PURE__ */ Symbol.for("effect/SchemaId/UUID");
|
|
var uuidRegexp = /^[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}$/i;
|
|
|
|
class UUID2 extends (/* @__PURE__ */ String$.pipe(/* @__PURE__ */ pattern(uuidRegexp, {
|
|
schemaId: UUIDSchemaId,
|
|
identifier: "UUID",
|
|
jsonSchema: {
|
|
format: "uuid",
|
|
pattern: uuidRegexp.source
|
|
},
|
|
description: "a Universally Unique Identifier",
|
|
arbitrary: () => (fc) => fc.uuid()
|
|
}))) {
|
|
}
|
|
var DateFromSelfSchemaId2 = DateFromSelfSchemaId;
|
|
|
|
class DateFromSelf extends (/* @__PURE__ */ declare(isDate, {
|
|
typeConstructor: {
|
|
_tag: "Date"
|
|
},
|
|
identifier: "DateFromSelf",
|
|
schemaId: DateFromSelfSchemaId2,
|
|
[DateFromSelfSchemaId2]: {
|
|
noInvalidDate: false
|
|
},
|
|
description: "a potentially invalid Date instance",
|
|
pretty: () => (date) => `new Date(${JSON.stringify(date)})`,
|
|
arbitrary: () => (fc) => fc.date({
|
|
noInvalidDate: false
|
|
}),
|
|
equivalence: () => Date2
|
|
})) {
|
|
}
|
|
var isField = (u) => isSchema(u) || isPropertySignature(u);
|
|
var isFields = (fields) => Reflect.ownKeys(fields).every((key) => isField(fields[key]));
|
|
var getFields = (hasFields) => ("fields" in hasFields) ? hasFields.fields : getFields(hasFields[RefineSchemaId]);
|
|
var getSchemaFromFieldsOr = (fieldsOr) => isFields(fieldsOr) ? Struct(fieldsOr) : isSchema(fieldsOr) ? fieldsOr : Struct(getFields(fieldsOr));
|
|
var getFieldsFromFieldsOr = (fieldsOr) => isFields(fieldsOr) ? fieldsOr : getFields(fieldsOr);
|
|
var getClassTag = (tag) => withConstructorDefault(propertySignature(Literal2(tag)), () => tag);
|
|
var TaggedError2 = (identifier) => (tag, fieldsOr, annotations) => {
|
|
class Base extends Error2 {
|
|
}
|
|
Base.prototype.name = tag;
|
|
const fields = getFieldsFromFieldsOr(fieldsOr);
|
|
const schema = getSchemaFromFieldsOr(fieldsOr);
|
|
const newFields = {
|
|
_tag: getClassTag(tag)
|
|
};
|
|
const taggedFields = extendFields(newFields, fields);
|
|
const hasMessageField = "message" in taggedFields;
|
|
|
|
class TaggedErrorClass extends makeClass({
|
|
kind: "TaggedError",
|
|
identifier: identifier ?? tag,
|
|
schema: extend3(schema, Struct(newFields)),
|
|
fields: taggedFields,
|
|
Base,
|
|
annotations,
|
|
disableToString: true
|
|
}) {
|
|
static _tag = tag;
|
|
}
|
|
if (!hasMessageField) {
|
|
Object.defineProperty(TaggedErrorClass.prototype, "message", {
|
|
get() {
|
|
return `{ ${Reflect.ownKeys(fields).map((p) => `${formatPropertyKey(p)}: ${formatUnknown(this[p])}`).join(", ")} }`;
|
|
},
|
|
enumerable: false,
|
|
configurable: true
|
|
});
|
|
}
|
|
return TaggedErrorClass;
|
|
};
|
|
var extendFields = (a, b) => {
|
|
const out = {
|
|
...a
|
|
};
|
|
for (const key of Reflect.ownKeys(b)) {
|
|
if (key in a) {
|
|
throw new Error(getASTDuplicatePropertySignatureErrorMessage(key));
|
|
}
|
|
out[key] = b[key];
|
|
}
|
|
return out;
|
|
};
|
|
function getDisableValidationMakeOption(options) {
|
|
return isBoolean(options) ? options : options?.disableValidation ?? false;
|
|
}
|
|
var astCache = /* @__PURE__ */ globalValue("effect/Schema/astCache", () => new WeakMap);
|
|
var getClassAnnotations = (annotations) => {
|
|
if (annotations === undefined) {
|
|
return [];
|
|
} else if (Array.isArray(annotations)) {
|
|
return annotations;
|
|
} else {
|
|
return [annotations];
|
|
}
|
|
};
|
|
var makeClass = ({
|
|
Base,
|
|
annotations,
|
|
disableToString,
|
|
fields,
|
|
identifier,
|
|
kind,
|
|
schema
|
|
}) => {
|
|
const classSymbol = Symbol.for(`effect/Schema/${kind}/${identifier}`);
|
|
const [typeAnnotations, transformationAnnotations, encodedAnnotations] = getClassAnnotations(annotations);
|
|
const typeSchema_ = typeSchema(schema);
|
|
const declarationSurrogate = typeSchema_.annotations({
|
|
identifier,
|
|
...typeAnnotations
|
|
});
|
|
const typeSide = typeSchema_.annotations({
|
|
[AutoTitleAnnotationId]: `${identifier} (Type side)`,
|
|
...typeAnnotations
|
|
});
|
|
const constructorSchema = schema.annotations({
|
|
[AutoTitleAnnotationId]: `${identifier} (Constructor)`,
|
|
...typeAnnotations
|
|
});
|
|
const encodedSide = schema.annotations({
|
|
[AutoTitleAnnotationId]: `${identifier} (Encoded side)`,
|
|
...encodedAnnotations
|
|
});
|
|
const transformationSurrogate = schema.annotations({
|
|
...encodedAnnotations,
|
|
...typeAnnotations,
|
|
...transformationAnnotations
|
|
});
|
|
const fallbackInstanceOf = (u) => hasProperty(u, classSymbol) && is(typeSide)(u);
|
|
const klass = class extends Base {
|
|
constructor(props = {}, options = false) {
|
|
props = {
|
|
...props
|
|
};
|
|
if (kind !== "Class") {
|
|
delete props["_tag"];
|
|
}
|
|
props = lazilyMergeDefaults(fields, props);
|
|
if (!getDisableValidationMakeOption(options)) {
|
|
props = validateSync(constructorSchema)(props);
|
|
}
|
|
super(props, true);
|
|
}
|
|
static [TypeId15] = variance5;
|
|
static get ast() {
|
|
let out = astCache.get(this);
|
|
if (out) {
|
|
return out;
|
|
}
|
|
const declaration = declare([schema], {
|
|
decode: () => (input, _, ast) => input instanceof this || fallbackInstanceOf(input) ? succeed12(input) : fail12(new Type2(ast, input)),
|
|
encode: () => (input, options) => input instanceof this ? succeed12(input) : map20(encodeUnknown(typeSide)(input, options), (props) => new this(props, true))
|
|
}, {
|
|
identifier,
|
|
pretty: (pretty) => (self2) => `${identifier}(${pretty(self2)})`,
|
|
arbitrary: (arb) => (fc) => arb(fc).map((props) => new this(props)),
|
|
equivalence: identity,
|
|
[SurrogateAnnotationId]: declarationSurrogate.ast,
|
|
...typeAnnotations
|
|
});
|
|
out = transform2(encodedSide, declaration, {
|
|
strict: true,
|
|
decode: (i) => new this(i, true),
|
|
encode: identity
|
|
}).annotations({
|
|
[SurrogateAnnotationId]: transformationSurrogate.ast,
|
|
...transformationAnnotations
|
|
}).ast;
|
|
astCache.set(this, out);
|
|
return out;
|
|
}
|
|
static pipe() {
|
|
return pipeArguments(this, arguments);
|
|
}
|
|
static annotations(annotations) {
|
|
return make42(this.ast).annotations(annotations);
|
|
}
|
|
static toString() {
|
|
return `(${String(encodedSide)} <-> ${identifier})`;
|
|
}
|
|
static make(...args) {
|
|
return new this(...args);
|
|
}
|
|
static fields = {
|
|
...fields
|
|
};
|
|
static identifier = identifier;
|
|
static extend(identifier2) {
|
|
return (newFieldsOr, annotations) => {
|
|
const newFields = getFieldsFromFieldsOr(newFieldsOr);
|
|
const newSchema = getSchemaFromFieldsOr(newFieldsOr);
|
|
const extendedFields = extendFields(fields, newFields);
|
|
return makeClass({
|
|
kind,
|
|
identifier: identifier2,
|
|
schema: extend3(schema, newSchema),
|
|
fields: extendedFields,
|
|
Base: this,
|
|
annotations
|
|
});
|
|
};
|
|
}
|
|
static transformOrFail(identifier2) {
|
|
return (newFieldsOr, options, annotations) => {
|
|
const transformedFields = extendFields(fields, newFieldsOr);
|
|
return makeClass({
|
|
kind,
|
|
identifier: identifier2,
|
|
schema: transformOrFail(schema, typeSchema(Struct(transformedFields)), options),
|
|
fields: transformedFields,
|
|
Base: this,
|
|
annotations
|
|
});
|
|
};
|
|
}
|
|
static transformOrFailFrom(identifier2) {
|
|
return (newFields, options, annotations) => {
|
|
const transformedFields = extendFields(fields, newFields);
|
|
return makeClass({
|
|
kind,
|
|
identifier: identifier2,
|
|
schema: transformOrFail(encodedSchema(schema), Struct(transformedFields), options),
|
|
fields: transformedFields,
|
|
Base: this,
|
|
annotations
|
|
});
|
|
};
|
|
}
|
|
get [classSymbol]() {
|
|
return classSymbol;
|
|
}
|
|
};
|
|
if (disableToString !== true) {
|
|
Object.defineProperty(klass.prototype, "toString", {
|
|
value() {
|
|
return `${identifier}({ ${Reflect.ownKeys(fields).map((p) => `${formatPropertyKey(p)}: ${formatUnknown(this[p])}`).join(", ")} })`;
|
|
},
|
|
configurable: true,
|
|
writable: true
|
|
});
|
|
}
|
|
return klass;
|
|
};
|
|
class Defect extends (/* @__PURE__ */ transform2(Unknown, Unknown, {
|
|
strict: true,
|
|
decode: (i) => {
|
|
if (isObject2(i) && "message" in i && typeof i.message === "string") {
|
|
const err = new Error(i.message, {
|
|
cause: i
|
|
});
|
|
if ("name" in i && typeof i.name === "string") {
|
|
err.name = i.name;
|
|
}
|
|
err.stack = "stack" in i && typeof i.stack === "string" ? i.stack : "";
|
|
return err;
|
|
}
|
|
return prettyErrorMessage(i);
|
|
},
|
|
encode: (a) => {
|
|
if (a instanceof Error) {
|
|
return {
|
|
name: a.name,
|
|
message: a.message
|
|
};
|
|
}
|
|
return prettyErrorMessage(a);
|
|
}
|
|
}).annotations({
|
|
identifier: "Defect"
|
|
})) {
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/@effect+platform@0.97.1_effect@3.22.1/node_modules/@effect/platform/dist/esm/Error.js
|
|
var TypeId16 = /* @__PURE__ */ Symbol.for("@effect/platform/Error");
|
|
var Module = /* @__PURE__ */ Literal2("Clipboard", "Command", "FileSystem", "KeyValueStore", "Path", "Stream", "Terminal");
|
|
|
|
class BadArgument extends (/* @__PURE__ */ TaggedError2("@effect/platform/Error/BadArgument")("BadArgument", {
|
|
module: Module,
|
|
method: String$,
|
|
description: /* @__PURE__ */ optional(String$),
|
|
cause: /* @__PURE__ */ optional(Defect)
|
|
})) {
|
|
[TypeId16] = TypeId16;
|
|
get message() {
|
|
return `${this.module}.${this.method}${this.description ? `: ${this.description}` : ""}`;
|
|
}
|
|
}
|
|
var SystemErrorReason = /* @__PURE__ */ Literal2("AlreadyExists", "BadResource", "Busy", "InvalidData", "NotFound", "PermissionDenied", "TimedOut", "UnexpectedEof", "Unknown", "WouldBlock", "WriteZero");
|
|
|
|
class SystemError extends (/* @__PURE__ */ TaggedError2("@effect/platform/Error/SystemError")("SystemError", {
|
|
reason: SystemErrorReason,
|
|
module: Module,
|
|
method: String$,
|
|
description: /* @__PURE__ */ optional(String$),
|
|
syscall: /* @__PURE__ */ optional(String$),
|
|
pathOrDescriptor: /* @__PURE__ */ optional(/* @__PURE__ */ Union2(String$, Number$)),
|
|
cause: /* @__PURE__ */ optional(Defect)
|
|
})) {
|
|
[TypeId16] = TypeId16;
|
|
get message() {
|
|
return `${this.reason}: ${this.module}.${this.method}${this.pathOrDescriptor !== undefined ? ` (${this.pathOrDescriptor})` : ""}${this.description ? `: ${this.description}` : ""}`;
|
|
}
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/@effect+platform@0.97.1_effect@3.22.1/node_modules/@effect/platform/dist/esm/internal/fileSystem.js
|
|
var tag = /* @__PURE__ */ GenericTag("@effect/platform/FileSystem");
|
|
var Size = (bytes) => typeof bytes === "bigint" ? bytes : BigInt(bytes);
|
|
var bigint1024 = /* @__PURE__ */ BigInt(1024);
|
|
var bigintPiB = bigint1024 * bigint1024 * bigint1024 * bigint1024 * bigint1024;
|
|
var make43 = (impl) => {
|
|
return tag.of({
|
|
...impl,
|
|
exists: (path) => pipe(impl.access(path), as3(true), catchTag2("SystemError", (e) => e.reason === "NotFound" ? succeed7(false) : fail6(e))),
|
|
readFileString: (path, encoding) => tryMap2(impl.readFile(path), {
|
|
try: (_) => new TextDecoder(encoding).decode(_),
|
|
catch: (cause) => new BadArgument({
|
|
module: "FileSystem",
|
|
method: "readFileString",
|
|
description: "invalid encoding",
|
|
cause
|
|
})
|
|
}),
|
|
stream: (path, options) => pipe(impl.open(path, {
|
|
flag: "r"
|
|
}), options?.offset ? tap2((file) => file.seek(options.offset, "start")) : identity, map15((file) => stream(file, options)), unwrapScoped6),
|
|
sink: (path, options) => pipe(impl.open(path, {
|
|
flag: "w",
|
|
...options
|
|
}), map15((file) => forEach6((_) => file.writeAll(_))), unwrapScoped5),
|
|
writeFileString: (path, data, options) => flatMap9(try_3({
|
|
try: () => new TextEncoder().encode(data),
|
|
catch: (cause) => new BadArgument({
|
|
module: "FileSystem",
|
|
method: "writeFileString",
|
|
description: "could not encode string",
|
|
cause
|
|
})
|
|
}), (_) => impl.writeFile(path, _, options))
|
|
});
|
|
};
|
|
var stream = (file, {
|
|
bufferSize = 16,
|
|
bytesToRead: bytesToRead_,
|
|
chunkSize: chunkSize_ = Size(64 * 1024)
|
|
} = {}) => {
|
|
const bytesToRead = bytesToRead_ !== undefined ? Size(bytesToRead_) : undefined;
|
|
const chunkSize = Size(chunkSize_);
|
|
function loop(totalBytesRead) {
|
|
if (bytesToRead !== undefined && bytesToRead <= totalBytesRead) {
|
|
return void_6;
|
|
}
|
|
const toRead = bytesToRead !== undefined && bytesToRead - totalBytesRead < chunkSize ? bytesToRead - totalBytesRead : chunkSize;
|
|
return flatMap14(file.readAlloc(toRead), match2({
|
|
onNone: () => void_6,
|
|
onSome: (buf) => flatMap14(write2(of2(buf)), (_) => loop(totalBytesRead + BigInt(buf.length)))
|
|
}));
|
|
}
|
|
return bufferChunks2(fromChannel3(loop(BigInt(0))), {
|
|
capacity: bufferSize
|
|
});
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/@effect+platform@0.97.1_effect@3.22.1/node_modules/@effect/platform/dist/esm/FileSystem.js
|
|
var Size2 = Size;
|
|
var FileSystem = tag;
|
|
var make44 = make43;
|
|
var FileTypeId = /* @__PURE__ */ Symbol.for("@effect/platform/FileSystem/File");
|
|
var FileDescriptor = /* @__PURE__ */ nominal();
|
|
var WatchEventCreate = /* @__PURE__ */ tagged("Create");
|
|
var WatchEventUpdate = /* @__PURE__ */ tagged("Update");
|
|
var WatchEventRemove = /* @__PURE__ */ tagged("Remove");
|
|
|
|
class WatchBackend extends (/* @__PURE__ */ Tag2("@effect/platform/FileSystem/WatchBackend")()) {
|
|
}
|
|
// ../../../node_modules/.pnpm/@effect+platform@0.97.1_effect@3.22.1/node_modules/@effect/platform/dist/esm/internal/effectify.js
|
|
var effectify = (fn, onError, onSyncError) => (...args) => async((resume) => {
|
|
try {
|
|
fn(...args, (err, result) => {
|
|
if (err) {
|
|
resume(fail6(onError ? onError(err, args) : err));
|
|
} else {
|
|
resume(succeed7(result));
|
|
}
|
|
});
|
|
} catch (err) {
|
|
resume(onSyncError ? fail6(onSyncError(err, args)) : die5(err));
|
|
}
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/@effect+platform@0.97.1_effect@3.22.1/node_modules/@effect/platform/dist/esm/Effectify.js
|
|
var effectify2 = effectify;
|
|
|
|
// ../../../node_modules/.pnpm/@effect+platform-node-shared@0.61.1_@effect+cluster@0.60.2_@effect+platform@0.97.1_effe_d4ef128a009d382f95e6e1a2e11e2a47/node_modules/@effect/platform-node-shared/dist/esm/internal/fileSystem.js
|
|
import * as Crypto from "crypto";
|
|
import * as NFS from "fs";
|
|
import * as OS from "os";
|
|
import * as Path2 from "path";
|
|
|
|
// ../../../node_modules/.pnpm/@effect+platform-node-shared@0.61.1_@effect+cluster@0.60.2_@effect+platform@0.97.1_effe_d4ef128a009d382f95e6e1a2e11e2a47/node_modules/@effect/platform-node-shared/dist/esm/internal/error.js
|
|
var handleErrnoException = (module, method) => (err, [path]) => {
|
|
let reason = "Unknown";
|
|
switch (err.code) {
|
|
case "ENOENT":
|
|
reason = "NotFound";
|
|
break;
|
|
case "EACCES":
|
|
reason = "PermissionDenied";
|
|
break;
|
|
case "EEXIST":
|
|
reason = "AlreadyExists";
|
|
break;
|
|
case "EISDIR":
|
|
reason = "BadResource";
|
|
break;
|
|
case "ENOTDIR":
|
|
reason = "BadResource";
|
|
break;
|
|
case "EBUSY":
|
|
reason = "Busy";
|
|
break;
|
|
case "ELOOP":
|
|
reason = "BadResource";
|
|
break;
|
|
}
|
|
return new SystemError({
|
|
reason,
|
|
module,
|
|
method,
|
|
pathOrDescriptor: path,
|
|
syscall: err.syscall,
|
|
description: err.message,
|
|
cause: err
|
|
});
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/@effect+platform-node-shared@0.61.1_@effect+cluster@0.60.2_@effect+platform@0.97.1_effe_d4ef128a009d382f95e6e1a2e11e2a47/node_modules/@effect/platform-node-shared/dist/esm/internal/fileSystem.js
|
|
var handleBadArgument = (method) => (cause) => new BadArgument({
|
|
module: "FileSystem",
|
|
method,
|
|
cause
|
|
});
|
|
var access2 = /* @__PURE__ */ (() => {
|
|
const nodeAccess = /* @__PURE__ */ effectify2(NFS.access, /* @__PURE__ */ handleErrnoException("FileSystem", "access"), /* @__PURE__ */ handleBadArgument("access"));
|
|
return (path, options) => {
|
|
let mode = NFS.constants.F_OK;
|
|
if (options?.readable) {
|
|
mode |= NFS.constants.R_OK;
|
|
}
|
|
if (options?.writable) {
|
|
mode |= NFS.constants.W_OK;
|
|
}
|
|
return nodeAccess(path, mode);
|
|
};
|
|
})();
|
|
var copy3 = /* @__PURE__ */ (() => {
|
|
const nodeCp = /* @__PURE__ */ effectify2(NFS.cp, /* @__PURE__ */ handleErrnoException("FileSystem", "copy"), /* @__PURE__ */ handleBadArgument("copy"));
|
|
return (fromPath, toPath, options) => nodeCp(fromPath, toPath, {
|
|
force: options?.overwrite ?? false,
|
|
preserveTimestamps: options?.preserveTimestamps ?? false,
|
|
recursive: true
|
|
});
|
|
})();
|
|
var copyFile2 = /* @__PURE__ */ (() => {
|
|
const nodeCopyFile = /* @__PURE__ */ effectify2(NFS.copyFile, /* @__PURE__ */ handleErrnoException("FileSystem", "copyFile"), /* @__PURE__ */ handleBadArgument("copyFile"));
|
|
return (fromPath, toPath) => nodeCopyFile(fromPath, toPath);
|
|
})();
|
|
var chmod2 = /* @__PURE__ */ (() => {
|
|
const nodeChmod = /* @__PURE__ */ effectify2(NFS.chmod, /* @__PURE__ */ handleErrnoException("FileSystem", "chmod"), /* @__PURE__ */ handleBadArgument("chmod"));
|
|
return (path, mode) => nodeChmod(path, mode);
|
|
})();
|
|
var chown2 = /* @__PURE__ */ (() => {
|
|
const nodeChown = /* @__PURE__ */ effectify2(NFS.chown, /* @__PURE__ */ handleErrnoException("FileSystem", "chown"), /* @__PURE__ */ handleBadArgument("chown"));
|
|
return (path, uid, gid) => nodeChown(path, uid, gid);
|
|
})();
|
|
var link2 = /* @__PURE__ */ (() => {
|
|
const nodeLink = /* @__PURE__ */ effectify2(NFS.link, /* @__PURE__ */ handleErrnoException("FileSystem", "link"), /* @__PURE__ */ handleBadArgument("link"));
|
|
return (existingPath, newPath) => nodeLink(existingPath, newPath);
|
|
})();
|
|
var makeDirectory = /* @__PURE__ */ (() => {
|
|
const nodeMkdir = /* @__PURE__ */ effectify2(NFS.mkdir, /* @__PURE__ */ handleErrnoException("FileSystem", "makeDirectory"), /* @__PURE__ */ handleBadArgument("makeDirectory"));
|
|
return (path, options) => nodeMkdir(path, {
|
|
recursive: options?.recursive ?? false,
|
|
mode: options?.mode
|
|
});
|
|
})();
|
|
var makeTempDirectoryFactory = (method) => {
|
|
const nodeMkdtemp = effectify2(NFS.mkdtemp, handleErrnoException("FileSystem", method), handleBadArgument(method));
|
|
return (options) => suspend2(() => {
|
|
const prefix = options?.prefix ?? "";
|
|
const directory = typeof options?.directory === "string" ? Path2.join(options.directory, ".") : OS.tmpdir();
|
|
return nodeMkdtemp(prefix ? Path2.join(directory, prefix) : directory + "/");
|
|
});
|
|
};
|
|
var makeTempDirectory = /* @__PURE__ */ makeTempDirectoryFactory("makeTempDirectory");
|
|
var removeFactory = (method) => {
|
|
const nodeRm = effectify2(NFS.rm, handleErrnoException("FileSystem", method), handleBadArgument(method));
|
|
return (path, options) => nodeRm(path, {
|
|
recursive: options?.recursive ?? false,
|
|
force: options?.force ?? false
|
|
});
|
|
};
|
|
var remove6 = /* @__PURE__ */ removeFactory("remove");
|
|
var makeTempDirectoryScoped = /* @__PURE__ */ (() => {
|
|
const makeDirectory = /* @__PURE__ */ makeTempDirectoryFactory("makeTempDirectoryScoped");
|
|
const removeDirectory = /* @__PURE__ */ removeFactory("makeTempDirectoryScoped");
|
|
return (options) => acquireRelease2(makeDirectory(options), (directory) => orDie2(removeDirectory(directory, {
|
|
recursive: true
|
|
})));
|
|
})();
|
|
var openFactory = (method) => {
|
|
const nodeOpen = effectify2(NFS.open, handleErrnoException("FileSystem", method), handleBadArgument(method));
|
|
const nodeClose = effectify2(NFS.close, handleErrnoException("FileSystem", method), handleBadArgument(method));
|
|
return (path, options) => pipe(acquireRelease2(nodeOpen(path, options?.flag ?? "r", options?.mode), (fd) => orDie2(nodeClose(fd))), map15((fd) => makeFile(FileDescriptor(fd), options?.flag?.startsWith("a") ?? false)));
|
|
};
|
|
var open2 = /* @__PURE__ */ openFactory("open");
|
|
var makeFile = /* @__PURE__ */ (() => {
|
|
const nodeReadFactory = (method) => effectify2(NFS.read, handleErrnoException("FileSystem", method), handleBadArgument(method));
|
|
const nodeRead = /* @__PURE__ */ nodeReadFactory("read");
|
|
const nodeReadAlloc = /* @__PURE__ */ nodeReadFactory("readAlloc");
|
|
const nodeStat = /* @__PURE__ */ effectify2(NFS.fstat, /* @__PURE__ */ handleErrnoException("FileSystem", "stat"), /* @__PURE__ */ handleBadArgument("stat"));
|
|
const nodeTruncate = /* @__PURE__ */ effectify2(NFS.ftruncate, /* @__PURE__ */ handleErrnoException("FileSystem", "truncate"), /* @__PURE__ */ handleBadArgument("truncate"));
|
|
const nodeSync = /* @__PURE__ */ effectify2(NFS.fsync, /* @__PURE__ */ handleErrnoException("FileSystem", "sync"), /* @__PURE__ */ handleBadArgument("sync"));
|
|
const nodeWriteFactory = (method) => effectify2(NFS.write, handleErrnoException("FileSystem", method), handleBadArgument(method));
|
|
const nodeWrite = /* @__PURE__ */ nodeWriteFactory("write");
|
|
const nodeWriteAll = /* @__PURE__ */ nodeWriteFactory("writeAll");
|
|
|
|
class FileImpl {
|
|
fd;
|
|
append;
|
|
[FileTypeId];
|
|
semaphore = /* @__PURE__ */ unsafeMakeSemaphore2(1);
|
|
position = 0n;
|
|
constructor(fd, append) {
|
|
this.fd = fd;
|
|
this.append = append;
|
|
this[FileTypeId] = FileTypeId;
|
|
}
|
|
get stat() {
|
|
return map15(nodeStat(this.fd), makeFileInfo);
|
|
}
|
|
get sync() {
|
|
return nodeSync(this.fd);
|
|
}
|
|
seek(offset, from) {
|
|
const offsetSize = Size2(offset);
|
|
return this.semaphore.withPermits(1)(sync3(() => {
|
|
if (from === "start") {
|
|
this.position = offsetSize;
|
|
} else if (from === "current") {
|
|
this.position = this.position + offsetSize;
|
|
}
|
|
return this.position;
|
|
}));
|
|
}
|
|
read(buffer) {
|
|
return this.semaphore.withPermits(1)(map15(suspend2(() => nodeRead(this.fd, {
|
|
buffer,
|
|
position: this.position
|
|
})), (bytesRead) => {
|
|
const sizeRead = Size2(bytesRead);
|
|
this.position = this.position + sizeRead;
|
|
return sizeRead;
|
|
}));
|
|
}
|
|
readAlloc(size) {
|
|
const sizeNumber = Number(size);
|
|
return this.semaphore.withPermits(1)(flatMap9(sync3(() => Buffer.allocUnsafeSlow(sizeNumber)), (buffer) => map15(nodeReadAlloc(this.fd, {
|
|
buffer,
|
|
position: this.position
|
|
}), (bytesRead) => {
|
|
if (bytesRead === 0) {
|
|
return none2();
|
|
}
|
|
this.position = this.position + BigInt(bytesRead);
|
|
if (bytesRead === sizeNumber) {
|
|
return some2(buffer);
|
|
}
|
|
const dst = Buffer.allocUnsafeSlow(bytesRead);
|
|
buffer.copy(dst, 0, 0, bytesRead);
|
|
return some2(dst);
|
|
})));
|
|
}
|
|
truncate(length) {
|
|
return this.semaphore.withPermits(1)(map15(nodeTruncate(this.fd, length ? Number(length) : undefined), () => {
|
|
if (!this.append) {
|
|
const len = BigInt(length ?? 0);
|
|
if (this.position > len) {
|
|
this.position = len;
|
|
}
|
|
}
|
|
}));
|
|
}
|
|
write(buffer) {
|
|
return this.semaphore.withPermits(1)(map15(suspend2(() => nodeWrite(this.fd, buffer, undefined, undefined, this.append ? undefined : Number(this.position))), (bytesWritten) => {
|
|
const sizeWritten = Size2(bytesWritten);
|
|
if (!this.append) {
|
|
this.position = this.position + sizeWritten;
|
|
}
|
|
return sizeWritten;
|
|
}));
|
|
}
|
|
writeAllChunk(buffer) {
|
|
return flatMap9(suspend2(() => nodeWriteAll(this.fd, buffer, undefined, undefined, this.append ? undefined : Number(this.position))), (bytesWritten) => {
|
|
if (bytesWritten === 0) {
|
|
return fail6(new SystemError({
|
|
module: "FileSystem",
|
|
method: "writeAll",
|
|
reason: "WriteZero",
|
|
pathOrDescriptor: this.fd,
|
|
description: "write returned 0 bytes written"
|
|
}));
|
|
}
|
|
if (!this.append) {
|
|
this.position = this.position + BigInt(bytesWritten);
|
|
}
|
|
return bytesWritten < buffer.length ? this.writeAllChunk(buffer.subarray(bytesWritten)) : _void;
|
|
});
|
|
}
|
|
writeAll(buffer) {
|
|
return this.semaphore.withPermits(1)(this.writeAllChunk(buffer));
|
|
}
|
|
}
|
|
return (fd, append) => new FileImpl(fd, append);
|
|
})();
|
|
var makeTempFileFactory = (method) => {
|
|
const makeDirectory = makeTempDirectoryFactory(method);
|
|
const open = openFactory(method);
|
|
const randomHexString = (bytes) => sync3(() => Crypto.randomBytes(bytes).toString("hex"));
|
|
return (options) => pipe(zip5(makeDirectory(options), randomHexString(6)), map15(([directory, random]) => Path2.join(directory, random + (options?.suffix ?? ""))), tap2((path) => scoped2(open(path, {
|
|
flag: "w+"
|
|
}))));
|
|
};
|
|
var makeTempFile = /* @__PURE__ */ makeTempFileFactory("makeTempFile");
|
|
var makeTempFileScoped = /* @__PURE__ */ (() => {
|
|
const makeFile = /* @__PURE__ */ makeTempFileFactory("makeTempFileScoped");
|
|
const removeDirectory = /* @__PURE__ */ removeFactory("makeTempFileScoped");
|
|
return (options) => acquireRelease2(makeFile(options), (file) => orDie2(removeDirectory(Path2.dirname(file), {
|
|
recursive: true
|
|
})));
|
|
})();
|
|
var readDirectory = (path, options) => tryPromise2({
|
|
try: () => NFS.promises.readdir(path, options),
|
|
catch: (err) => handleErrnoException("FileSystem", "readDirectory")(err, [path])
|
|
});
|
|
var readFile2 = (path) => async((resume, signal) => {
|
|
try {
|
|
NFS.readFile(path, {
|
|
signal
|
|
}, (err, data) => {
|
|
if (err) {
|
|
resume(fail6(handleErrnoException("FileSystem", "readFile")(err, [path])));
|
|
} else {
|
|
resume(succeed7(data));
|
|
}
|
|
});
|
|
} catch (err) {
|
|
resume(fail6(handleBadArgument("readFile")(err)));
|
|
}
|
|
});
|
|
var readLink = /* @__PURE__ */ (() => {
|
|
const nodeReadLink = /* @__PURE__ */ effectify2(NFS.readlink, /* @__PURE__ */ handleErrnoException("FileSystem", "readLink"), /* @__PURE__ */ handleBadArgument("readLink"));
|
|
return (path) => nodeReadLink(path);
|
|
})();
|
|
var realPath = /* @__PURE__ */ (() => {
|
|
const nodeRealPath = /* @__PURE__ */ effectify2(NFS.realpath, /* @__PURE__ */ handleErrnoException("FileSystem", "realPath"), /* @__PURE__ */ handleBadArgument("realPath"));
|
|
return (path) => nodeRealPath(path);
|
|
})();
|
|
var rename3 = /* @__PURE__ */ (() => {
|
|
const nodeRename = /* @__PURE__ */ effectify2(NFS.rename, /* @__PURE__ */ handleErrnoException("FileSystem", "rename"), /* @__PURE__ */ handleBadArgument("rename"));
|
|
return (oldPath, newPath) => nodeRename(oldPath, newPath);
|
|
})();
|
|
var makeFileInfo = (stat) => ({
|
|
type: stat.isFile() ? "File" : stat.isDirectory() ? "Directory" : stat.isSymbolicLink() ? "SymbolicLink" : stat.isBlockDevice() ? "BlockDevice" : stat.isCharacterDevice() ? "CharacterDevice" : stat.isFIFO() ? "FIFO" : stat.isSocket() ? "Socket" : "Unknown",
|
|
mtime: fromNullable(stat.mtime),
|
|
atime: fromNullable(stat.atime),
|
|
birthtime: fromNullable(stat.birthtime),
|
|
dev: stat.dev,
|
|
rdev: fromNullable(stat.rdev),
|
|
ino: fromNullable(stat.ino),
|
|
mode: stat.mode,
|
|
nlink: fromNullable(stat.nlink),
|
|
uid: fromNullable(stat.uid),
|
|
gid: fromNullable(stat.gid),
|
|
size: Size2(stat.size),
|
|
blksize: map2(fromNullable(stat.blksize), Size2),
|
|
blocks: fromNullable(stat.blocks)
|
|
});
|
|
var stat2 = /* @__PURE__ */ (() => {
|
|
const nodeStat = /* @__PURE__ */ effectify2(NFS.stat, /* @__PURE__ */ handleErrnoException("FileSystem", "stat"), /* @__PURE__ */ handleBadArgument("stat"));
|
|
return (path) => map15(nodeStat(path), makeFileInfo);
|
|
})();
|
|
var symlink2 = /* @__PURE__ */ (() => {
|
|
const nodeSymlink = /* @__PURE__ */ effectify2(NFS.symlink, /* @__PURE__ */ handleErrnoException("FileSystem", "symlink"), /* @__PURE__ */ handleBadArgument("symlink"));
|
|
return (target, path) => nodeSymlink(target, path);
|
|
})();
|
|
var truncate2 = /* @__PURE__ */ (() => {
|
|
const nodeTruncate = /* @__PURE__ */ effectify2(NFS.truncate, /* @__PURE__ */ handleErrnoException("FileSystem", "truncate"), /* @__PURE__ */ handleBadArgument("truncate"));
|
|
return (path, length) => nodeTruncate(path, length !== undefined ? Number(length) : undefined);
|
|
})();
|
|
var utimes2 = /* @__PURE__ */ (() => {
|
|
const nodeUtimes = /* @__PURE__ */ effectify2(NFS.utimes, /* @__PURE__ */ handleErrnoException("FileSystem", "utime"), /* @__PURE__ */ handleBadArgument("utime"));
|
|
return (path, atime, mtime) => nodeUtimes(path, atime, mtime);
|
|
})();
|
|
var watchNode = (path, options) => asyncScoped2((emit) => acquireRelease2(sync3(() => {
|
|
const watcher = NFS.watch(path, {
|
|
recursive: options?.recursive
|
|
}, (event, path) => {
|
|
if (!path)
|
|
return;
|
|
switch (event) {
|
|
case "rename": {
|
|
emit.fromEffect(matchEffect2(stat2(path), {
|
|
onSuccess: (_) => succeed7(WatchEventCreate({
|
|
path
|
|
})),
|
|
onFailure: (err) => err._tag === "SystemError" && err.reason === "NotFound" ? succeed7(WatchEventRemove({
|
|
path
|
|
})) : fail6(err)
|
|
}));
|
|
return;
|
|
}
|
|
case "change": {
|
|
emit.single(WatchEventUpdate({
|
|
path
|
|
}));
|
|
return;
|
|
}
|
|
}
|
|
});
|
|
watcher.on("error", (error) => {
|
|
emit.fail(new SystemError({
|
|
module: "FileSystem",
|
|
reason: "Unknown",
|
|
method: "watch",
|
|
pathOrDescriptor: path,
|
|
cause: error
|
|
}));
|
|
});
|
|
watcher.on("close", () => {
|
|
emit.end();
|
|
});
|
|
return watcher;
|
|
}), (watcher) => sync3(() => watcher.close())));
|
|
var watch2 = (backend, path, options) => stat2(path).pipe(map15((stat) => backend.pipe(flatMap((_) => _.register(path, stat, options)), getOrElse(() => watchNode(path, options)))), unwrap4);
|
|
var writeFile2 = (path, data, options) => async((resume, signal) => {
|
|
try {
|
|
NFS.writeFile(path, data, {
|
|
signal,
|
|
flag: options?.flag,
|
|
mode: options?.mode
|
|
}, (err) => {
|
|
if (err) {
|
|
resume(fail6(handleErrnoException("FileSystem", "writeFile")(err, [path])));
|
|
} else {
|
|
resume(_void);
|
|
}
|
|
});
|
|
} catch (err) {
|
|
resume(fail6(handleBadArgument("writeFile")(err)));
|
|
}
|
|
});
|
|
var makeFileSystem = /* @__PURE__ */ map15(/* @__PURE__ */ serviceOption2(WatchBackend), (backend) => make44({
|
|
access: access2,
|
|
chmod: chmod2,
|
|
chown: chown2,
|
|
copy: copy3,
|
|
copyFile: copyFile2,
|
|
link: link2,
|
|
makeDirectory,
|
|
makeTempDirectory,
|
|
makeTempDirectoryScoped,
|
|
makeTempFile,
|
|
makeTempFileScoped,
|
|
open: open2,
|
|
readDirectory,
|
|
readFile: readFile2,
|
|
readLink,
|
|
realPath,
|
|
remove: remove6,
|
|
rename: rename3,
|
|
stat: stat2,
|
|
symlink: symlink2,
|
|
truncate: truncate2,
|
|
utimes: utimes2,
|
|
watch(path, options) {
|
|
return watch2(backend, path, options);
|
|
},
|
|
writeFile: writeFile2
|
|
}));
|
|
var layer = /* @__PURE__ */ effect(FileSystem, makeFileSystem);
|
|
|
|
// ../../../node_modules/.pnpm/@effect+platform-node-shared@0.61.1_@effect+cluster@0.60.2_@effect+platform@0.97.1_effe_d4ef128a009d382f95e6e1a2e11e2a47/node_modules/@effect/platform-node-shared/dist/esm/NodeFileSystem.js
|
|
var layer2 = layer;
|
|
|
|
// ../../../node_modules/.pnpm/@effect+platform-bun@0.91.2_@effect+cluster@0.60.2_@effect+platform@0.97.1_effect@3.22._b18ffd96f84aa74287d9f7a4f42aa04c/node_modules/@effect/platform-bun/dist/esm/BunFileSystem.js
|
|
var layer3 = layer2;
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js
|
|
var _a;
|
|
function $constructor(name, initializer, params) {
|
|
function init(inst, def) {
|
|
if (!inst._zod) {
|
|
Object.defineProperty(inst, "_zod", {
|
|
value: {
|
|
def,
|
|
constr: _,
|
|
traits: new Set
|
|
},
|
|
enumerable: false
|
|
});
|
|
}
|
|
if (inst._zod.traits.has(name)) {
|
|
return;
|
|
}
|
|
inst._zod.traits.add(name);
|
|
initializer(inst, def);
|
|
const proto = _.prototype;
|
|
const keys = Object.keys(proto);
|
|
for (let i = 0;i < keys.length; i++) {
|
|
const k = keys[i];
|
|
if (!(k in inst)) {
|
|
inst[k] = proto[k].bind(inst);
|
|
}
|
|
}
|
|
}
|
|
const Parent = params?.Parent ?? Object;
|
|
|
|
class Definition extends Parent {
|
|
}
|
|
Object.defineProperty(Definition, "name", { value: name });
|
|
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(name);
|
|
}
|
|
});
|
|
Object.defineProperty(_, "name", { value: name });
|
|
return _;
|
|
}
|
|
var $brand = Symbol("zod_brand");
|
|
|
|
class $ZodAsyncError extends Error {
|
|
constructor() {
|
|
super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
|
|
}
|
|
}
|
|
|
|
class $ZodEncodeError extends Error {
|
|
constructor(name) {
|
|
super(`Encountered unidirectional transform during encode: ${name}`);
|
|
this.name = "ZodEncodeError";
|
|
}
|
|
}
|
|
(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});
|
|
var globalConfig = globalThis.__zod_globalConfig;
|
|
function config(newConfig) {
|
|
if (newConfig)
|
|
Object.assign(globalConfig, newConfig);
|
|
return globalConfig;
|
|
}
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js
|
|
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(array, separator = "|") {
|
|
return array.map((val) => stringifyPrimitive(val)).join(separator);
|
|
}
|
|
function jsonStringifyReplacer(_, value) {
|
|
if (typeof value === "bigint")
|
|
return value.toString();
|
|
return value;
|
|
}
|
|
function cached3(getter) {
|
|
const set = false;
|
|
return {
|
|
get value() {
|
|
if (!set) {
|
|
const value = getter();
|
|
Object.defineProperty(this, "value", { value });
|
|
return value;
|
|
}
|
|
throw new Error("cached value already set");
|
|
}
|
|
};
|
|
}
|
|
function nullish(input) {
|
|
return input === null || input === undefined;
|
|
}
|
|
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, step) {
|
|
const ratio = val / step;
|
|
const roundedRatio = Math.round(ratio);
|
|
const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);
|
|
if (Math.abs(ratio - roundedRatio) < tolerance)
|
|
return 0;
|
|
return ratio - roundedRatio;
|
|
}
|
|
var EVALUATING = /* @__PURE__ */ Symbol("evaluating");
|
|
function defineLazy(object, key, getter) {
|
|
let value = undefined;
|
|
Object.defineProperty(object, key, {
|
|
get() {
|
|
if (value === EVALUATING) {
|
|
return;
|
|
}
|
|
if (value === undefined) {
|
|
value = EVALUATING;
|
|
value = getter();
|
|
}
|
|
return value;
|
|
},
|
|
set(v) {
|
|
Object.defineProperty(object, key, {
|
|
value: v
|
|
});
|
|
},
|
|
configurable: true
|
|
});
|
|
}
|
|
function assignProp(target, prop, value) {
|
|
Object.defineProperty(target, prop, {
|
|
value,
|
|
writable: true,
|
|
enumerable: true,
|
|
configurable: true
|
|
});
|
|
}
|
|
function mergeDefs(...defs) {
|
|
const mergedDescriptors = {};
|
|
for (const def of defs) {
|
|
const descriptors = Object.getOwnPropertyDescriptors(def);
|
|
Object.assign(mergedDescriptors, descriptors);
|
|
}
|
|
return Object.defineProperties({}, mergedDescriptors);
|
|
}
|
|
function esc(str) {
|
|
return JSON.stringify(str);
|
|
}
|
|
function slugify(input) {
|
|
return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
}
|
|
var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
|
|
function isObject3(data) {
|
|
return typeof data === "object" && data !== null && !Array.isArray(data);
|
|
}
|
|
var allowsEval = /* @__PURE__ */ cached3(() => {
|
|
if (globalConfig.jitless) {
|
|
return false;
|
|
}
|
|
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 (isObject3(o) === false)
|
|
return false;
|
|
const ctor = o.constructor;
|
|
if (ctor === undefined)
|
|
return true;
|
|
if (typeof ctor !== "function")
|
|
return true;
|
|
const prot = ctor.prototype;
|
|
if (isObject3(prot) === false)
|
|
return false;
|
|
if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
function shallowClone(o) {
|
|
if (isPlainObject(o))
|
|
return { ...o };
|
|
if (Array.isArray(o))
|
|
return [...o];
|
|
if (o instanceof Map)
|
|
return new Map(o);
|
|
if (o instanceof Set)
|
|
return new Set(o);
|
|
return o;
|
|
}
|
|
var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
|
|
function escapeRegex(str) {
|
|
return str.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 !== undefined) {
|
|
if (params?.error !== undefined)
|
|
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 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: [-340282346638528860000000000000000000000, 340282346638528860000000000000000000000],
|
|
float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
|
|
};
|
|
function pick4(schema, mask) {
|
|
const currDef = schema._zod.def;
|
|
const checks = currDef.checks;
|
|
const hasChecks = checks && checks.length > 0;
|
|
if (hasChecks) {
|
|
throw new Error(".pick() cannot be used on object schemas containing refinements");
|
|
}
|
|
const def = mergeDefs(schema._zod.def, {
|
|
get shape() {
|
|
const newShape = {};
|
|
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];
|
|
}
|
|
assignProp(this, "shape", newShape);
|
|
return newShape;
|
|
},
|
|
checks: []
|
|
});
|
|
return clone(schema, def);
|
|
}
|
|
function omit5(schema, mask) {
|
|
const currDef = schema._zod.def;
|
|
const checks = currDef.checks;
|
|
const hasChecks = checks && checks.length > 0;
|
|
if (hasChecks) {
|
|
throw new Error(".omit() cannot be used on object schemas containing refinements");
|
|
}
|
|
const def = mergeDefs(schema._zod.def, {
|
|
get shape() {
|
|
const newShape = { ...schema._zod.def.shape };
|
|
for (const key in mask) {
|
|
if (!(key in currDef.shape)) {
|
|
throw new Error(`Unrecognized key: "${key}"`);
|
|
}
|
|
if (!mask[key])
|
|
continue;
|
|
delete newShape[key];
|
|
}
|
|
assignProp(this, "shape", newShape);
|
|
return newShape;
|
|
},
|
|
checks: []
|
|
});
|
|
return clone(schema, def);
|
|
}
|
|
function extend4(schema, shape) {
|
|
if (!isPlainObject(shape)) {
|
|
throw new Error("Invalid input to extend: expected a plain object");
|
|
}
|
|
const checks = schema._zod.def.checks;
|
|
const hasChecks = checks && checks.length > 0;
|
|
if (hasChecks) {
|
|
const existingShape = schema._zod.def.shape;
|
|
for (const key in shape) {
|
|
if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {
|
|
throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
|
|
}
|
|
}
|
|
}
|
|
const def = mergeDefs(schema._zod.def, {
|
|
get shape() {
|
|
const _shape = { ...schema._zod.def.shape, ...shape };
|
|
assignProp(this, "shape", _shape);
|
|
return _shape;
|
|
}
|
|
});
|
|
return clone(schema, def);
|
|
}
|
|
function safeExtend(schema, shape) {
|
|
if (!isPlainObject(shape)) {
|
|
throw new Error("Invalid input to safeExtend: expected a plain object");
|
|
}
|
|
const def = mergeDefs(schema._zod.def, {
|
|
get shape() {
|
|
const _shape = { ...schema._zod.def.shape, ...shape };
|
|
assignProp(this, "shape", _shape);
|
|
return _shape;
|
|
}
|
|
});
|
|
return clone(schema, def);
|
|
}
|
|
function merge8(a, b) {
|
|
if (a._zod.def.checks?.length) {
|
|
throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
|
|
}
|
|
const def = mergeDefs(a._zod.def, {
|
|
get shape() {
|
|
const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
|
|
assignProp(this, "shape", _shape);
|
|
return _shape;
|
|
},
|
|
get catchall() {
|
|
return b._zod.def.catchall;
|
|
},
|
|
checks: b._zod.def.checks ?? []
|
|
});
|
|
return clone(a, def);
|
|
}
|
|
function partial2(Class, schema, mask) {
|
|
const currDef = schema._zod.def;
|
|
const checks = currDef.checks;
|
|
const hasChecks = checks && checks.length > 0;
|
|
if (hasChecks) {
|
|
throw new Error(".partial() cannot be used on object schemas containing refinements");
|
|
}
|
|
const def = mergeDefs(schema._zod.def, {
|
|
get shape() {
|
|
const oldShape = schema._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] = Class ? new Class({
|
|
type: "optional",
|
|
innerType: oldShape[key]
|
|
}) : oldShape[key];
|
|
}
|
|
} else {
|
|
for (const key in oldShape) {
|
|
shape[key] = Class ? new Class({
|
|
type: "optional",
|
|
innerType: oldShape[key]
|
|
}) : oldShape[key];
|
|
}
|
|
}
|
|
assignProp(this, "shape", shape);
|
|
return shape;
|
|
},
|
|
checks: []
|
|
});
|
|
return clone(schema, def);
|
|
}
|
|
function required2(Class, schema, mask) {
|
|
const def = mergeDefs(schema._zod.def, {
|
|
get shape() {
|
|
const oldShape = schema._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 Class({
|
|
type: "nonoptional",
|
|
innerType: oldShape[key]
|
|
});
|
|
}
|
|
} else {
|
|
for (const key in oldShape) {
|
|
shape[key] = new Class({
|
|
type: "nonoptional",
|
|
innerType: oldShape[key]
|
|
});
|
|
}
|
|
}
|
|
assignProp(this, "shape", shape);
|
|
return shape;
|
|
}
|
|
});
|
|
return clone(schema, def);
|
|
}
|
|
function aborted(x, startIndex = 0) {
|
|
if (x.aborted === true)
|
|
return true;
|
|
for (let i = startIndex;i < x.issues.length; i++) {
|
|
if (x.issues[i]?.continue !== true) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
function explicitlyAborted(x, startIndex = 0) {
|
|
if (x.aborted === true)
|
|
return true;
|
|
for (let i = startIndex;i < x.issues.length; i++) {
|
|
if (x.issues[i]?.continue === false) {
|
|
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, config) {
|
|
const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
|
|
const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;
|
|
rest.path ?? (rest.path = []);
|
|
rest.message = message;
|
|
if (ctx?.reportInput) {
|
|
rest.input = _input;
|
|
}
|
|
return rest;
|
|
}
|
|
function getLengthableOrigin(input) {
|
|
if (Array.isArray(input))
|
|
return "array";
|
|
if (typeof input === "string")
|
|
return "string";
|
|
return "unknown";
|
|
}
|
|
function parsedType(data) {
|
|
const t = typeof data;
|
|
switch (t) {
|
|
case "number": {
|
|
return Number.isNaN(data) ? "nan" : "number";
|
|
}
|
|
case "object": {
|
|
if (data === null) {
|
|
return "null";
|
|
}
|
|
if (Array.isArray(data)) {
|
|
return "array";
|
|
}
|
|
const obj = data;
|
|
if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) {
|
|
return obj.constructor.name;
|
|
}
|
|
}
|
|
}
|
|
return t;
|
|
}
|
|
function issue(...args) {
|
|
const [iss, input, inst] = args;
|
|
if (typeof iss === "string") {
|
|
return {
|
|
message: iss,
|
|
code: "custom",
|
|
input,
|
|
inst
|
|
};
|
|
}
|
|
return { ...iss };
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/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
|
|
});
|
|
inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
|
|
Object.defineProperty(inst, "toString", {
|
|
value: () => inst.message,
|
|
enumerable: false
|
|
});
|
|
};
|
|
var $ZodError = $constructor("$ZodError", initializer);
|
|
var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
|
|
function flattenError(error, mapper = (issue) => issue.message) {
|
|
const fieldErrors = {};
|
|
const formErrors = [];
|
|
for (const sub of error.issues) {
|
|
if (sub.path.length > 0) {
|
|
fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
|
|
fieldErrors[sub.path[0]].push(mapper(sub));
|
|
} else {
|
|
formErrors.push(mapper(sub));
|
|
}
|
|
}
|
|
return { formErrors, fieldErrors };
|
|
}
|
|
function formatError(error, mapper = (issue) => issue.message) {
|
|
const fieldErrors = { _errors: [] };
|
|
const processError = (error, path = []) => {
|
|
for (const issue of error.issues) {
|
|
if (issue.code === "invalid_union" && issue.errors.length) {
|
|
issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));
|
|
} else if (issue.code === "invalid_key") {
|
|
processError({ issues: issue.issues }, [...path, ...issue.path]);
|
|
} else if (issue.code === "invalid_element") {
|
|
processError({ issues: issue.issues }, [...path, ...issue.path]);
|
|
} else {
|
|
const fullpath = [...path, ...issue.path];
|
|
if (fullpath.length === 0) {
|
|
fieldErrors._errors.push(mapper(issue));
|
|
} else {
|
|
let curr = fieldErrors;
|
|
let i = 0;
|
|
while (i < fullpath.length) {
|
|
const el = fullpath[i];
|
|
const terminal = i === fullpath.length - 1;
|
|
if (!terminal) {
|
|
curr[el] = curr[el] || { _errors: [] };
|
|
} else {
|
|
curr[el] = curr[el] || { _errors: [] };
|
|
curr[el]._errors.push(mapper(issue));
|
|
}
|
|
curr = curr[el];
|
|
i++;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
};
|
|
processError(error);
|
|
return fieldErrors;
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js
|
|
var _parse = (_Err) => (schema, value, _ctx, _params) => {
|
|
const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
|
|
const result = schema._zod.run({ value, issues: [] }, ctx);
|
|
if (result instanceof Promise) {
|
|
throw new $ZodAsyncError;
|
|
}
|
|
if (result.issues.length) {
|
|
const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
|
|
captureStackTrace(e, _params?.callee);
|
|
throw e;
|
|
}
|
|
return result.value;
|
|
};
|
|
var parse = /* @__PURE__ */ _parse($ZodRealError);
|
|
var _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
|
|
const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
|
|
let result = schema._zod.run({ value, issues: [] }, ctx);
|
|
if (result instanceof Promise)
|
|
result = await result;
|
|
if (result.issues.length) {
|
|
const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
|
|
captureStackTrace(e, params?.callee);
|
|
throw e;
|
|
}
|
|
return result.value;
|
|
};
|
|
var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError);
|
|
var _safeParse = (_Err) => (schema, value, _ctx) => {
|
|
const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
|
|
const result = schema._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 (schema, value, _ctx) => {
|
|
const ctx = _ctx ? { ..._ctx, async: true } : { async: true };
|
|
let result = schema._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);
|
|
var _encode = (_Err) => (schema, value, _ctx) => {
|
|
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
|
|
return _parse(_Err)(schema, value, ctx);
|
|
};
|
|
var _decode = (_Err) => (schema, value, _ctx) => {
|
|
return _parse(_Err)(schema, value, _ctx);
|
|
};
|
|
var _encodeAsync = (_Err) => async (schema, value, _ctx) => {
|
|
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
|
|
return _parseAsync(_Err)(schema, value, ctx);
|
|
};
|
|
var _decodeAsync = (_Err) => async (schema, value, _ctx) => {
|
|
return _parseAsync(_Err)(schema, value, _ctx);
|
|
};
|
|
var _safeEncode = (_Err) => (schema, value, _ctx) => {
|
|
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
|
|
return _safeParse(_Err)(schema, value, ctx);
|
|
};
|
|
var _safeDecode = (_Err) => (schema, value, _ctx) => {
|
|
return _safeParse(_Err)(schema, value, _ctx);
|
|
};
|
|
var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
|
|
const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
|
|
return _safeParseAsync(_Err)(schema, value, ctx);
|
|
};
|
|
var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
|
|
return _safeParseAsync(_Err)(schema, value, _ctx);
|
|
};
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js
|
|
var cuid = /^[cC][0-9a-z]{6,}$/;
|
|
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 = (version) => {
|
|
if (!version)
|
|
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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
|
|
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
|
|
};
|
|
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}:){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}|:))$/;
|
|
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 httpProtocol = /^https?$/;
|
|
var e164 = /^\+[1-9]\d{6,14}$/;
|
|
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 date2 = /* @__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 time2(args) {
|
|
return new RegExp(`^${timeSource(args)}$`);
|
|
}
|
|
function datetime(args) {
|
|
const time = timeSource({ precision: args.precision });
|
|
const opts = ["Z"];
|
|
if (args.local)
|
|
opts.push("");
|
|
if (args.offset)
|
|
opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
|
|
const timeRegex = `${time}(?:${opts.join("|")})`;
|
|
return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
|
|
}
|
|
var string2 = (params) => {
|
|
const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
|
|
return new RegExp(`^${regex}$`);
|
|
};
|
|
var integer = /^-?\d+$/;
|
|
var number4 = /^-?\d+(?:\.\d+)?$/;
|
|
var boolean = /^(?:true|false)$/i;
|
|
var _null = /^null$/i;
|
|
var lowercase = /^[^A-Z]*$/;
|
|
var uppercase = /^[^a-z]*$/;
|
|
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/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((inst) => {
|
|
const bag = inst._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: typeof def.value === "object" ? def.value.getTime() : 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((inst) => {
|
|
const bag = inst._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: typeof def.value === "object" ? def.value.getTime() : 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((inst) => {
|
|
var _a;
|
|
(_a = inst._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((inst) => {
|
|
const bag = inst._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",
|
|
continue: false,
|
|
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,
|
|
inclusive: true,
|
|
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,
|
|
inclusive: true,
|
|
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,
|
|
inclusive: true,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
}
|
|
};
|
|
});
|
|
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 !== undefined;
|
|
});
|
|
inst._zod.onattach.push((inst) => {
|
|
const curr = inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY;
|
|
if (def.maximum < curr)
|
|
inst._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 !== undefined;
|
|
});
|
|
inst._zod.onattach.push((inst) => {
|
|
const curr = inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY;
|
|
if (def.minimum > curr)
|
|
inst._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 !== undefined;
|
|
});
|
|
inst._zod.onattach.push((inst) => {
|
|
const bag = inst._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((inst) => {
|
|
const bag = inst._zod.bag;
|
|
bag.format = def.format;
|
|
if (def.pattern) {
|
|
bag.patterns ?? (bag.patterns = 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((inst) => {
|
|
const bag = inst._zod.bag;
|
|
bag.patterns ?? (bag.patterns = 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((inst) => {
|
|
const bag = inst._zod.bag;
|
|
bag.patterns ?? (bag.patterns = 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((inst) => {
|
|
const bag = inst._zod.bag;
|
|
bag.patterns ?? (bag.patterns = 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@4.4.3/node_modules/zod/v4/core/doc.js
|
|
class Doc {
|
|
constructor(args = []) {
|
|
this.content = [];
|
|
this.indent = 0;
|
|
if (this)
|
|
this.args = args;
|
|
}
|
|
indented(fn) {
|
|
this.indent += 1;
|
|
fn(this);
|
|
this.indent -= 1;
|
|
}
|
|
write(arg) {
|
|
if (typeof arg === "function") {
|
|
arg(this, { execution: "sync" });
|
|
arg(this, { execution: "async" });
|
|
return;
|
|
}
|
|
const content = arg;
|
|
const lines = content.split(`
|
|
`).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(`
|
|
`));
|
|
}
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js
|
|
var version = {
|
|
major: 4,
|
|
minor: 4,
|
|
patch: 3
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/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, checks, ctx) => {
|
|
let isAborted = aborted(payload);
|
|
let asyncResult;
|
|
for (const ch of checks) {
|
|
if (ch._zod.def.when) {
|
|
if (explicitlyAborted(payload))
|
|
continue;
|
|
const shouldRun = ch._zod.def.when(payload);
|
|
if (!shouldRun)
|
|
continue;
|
|
} else if (isAborted) {
|
|
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 (!isAborted)
|
|
isAborted = aborted(payload, currLen);
|
|
});
|
|
} else {
|
|
const nextLen = payload.issues.length;
|
|
if (nextLen === currLen)
|
|
continue;
|
|
if (!isAborted)
|
|
isAborted = aborted(payload, currLen);
|
|
}
|
|
}
|
|
if (asyncResult) {
|
|
return asyncResult.then(() => {
|
|
return payload;
|
|
});
|
|
}
|
|
return payload;
|
|
};
|
|
const handleCanaryResult = (canary, payload, ctx) => {
|
|
if (aborted(canary)) {
|
|
canary.aborted = true;
|
|
return canary;
|
|
}
|
|
const checkResult = runChecks(payload, checks, ctx);
|
|
if (checkResult instanceof Promise) {
|
|
if (ctx.async === false)
|
|
throw new $ZodAsyncError;
|
|
return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));
|
|
}
|
|
return inst._zod.parse(checkResult, ctx);
|
|
};
|
|
inst._zod.run = (payload, ctx) => {
|
|
if (ctx.skipChecks) {
|
|
return inst._zod.parse(payload, ctx);
|
|
}
|
|
if (ctx.direction === "backward") {
|
|
const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });
|
|
if (canary instanceof Promise) {
|
|
return canary.then((canary) => {
|
|
return handleCanaryResult(canary, payload, ctx);
|
|
});
|
|
}
|
|
return handleCanaryResult(canary, payload, ctx);
|
|
}
|
|
const result = inst._zod.parse(payload, ctx);
|
|
if (result instanceof Promise) {
|
|
if (ctx.async === false)
|
|
throw new $ZodAsyncError;
|
|
return result.then((result) => runChecks(result, checks, ctx));
|
|
}
|
|
return runChecks(result, checks, ctx);
|
|
};
|
|
}
|
|
defineLazy(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() ?? string2(inst._zod.bag);
|
|
inst._zod.parse = (payload, _) => {
|
|
if (def.coerce)
|
|
try {
|
|
payload.value = String(payload.value);
|
|
} catch (_) {}
|
|
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 === undefined)
|
|
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 trimmed = payload.value.trim();
|
|
if (!def.normalize && def.protocol?.source === httpProtocol.source) {
|
|
if (!/^https?:\/\//i.test(trimmed)) {
|
|
payload.issues.push({
|
|
code: "invalid_format",
|
|
format: "url",
|
|
note: "Invalid URL format",
|
|
input: payload.value,
|
|
inst,
|
|
continue: !def.abort
|
|
});
|
|
return;
|
|
}
|
|
}
|
|
const url = new URL(trimmed);
|
|
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: def.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 (def.normalize) {
|
|
payload.value = url.href;
|
|
} else {
|
|
payload.value = trimmed;
|
|
}
|
|
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 = date2);
|
|
$ZodStringFormat.init(inst, def);
|
|
});
|
|
var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
|
|
def.pattern ?? (def.pattern = time2(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.bag.format = `ipv4`;
|
|
});
|
|
var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
|
|
def.pattern ?? (def.pattern = ipv6);
|
|
$ZodStringFormat.init(inst, def);
|
|
inst._zod.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 parts = payload.value.split("/");
|
|
try {
|
|
if (parts.length !== 2)
|
|
throw new Error;
|
|
const [address, prefix] = parts;
|
|
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 (/\s/.test(data))
|
|
return false;
|
|
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.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 base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
|
|
const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
|
|
return isValidBase64(padded);
|
|
}
|
|
var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
|
|
def.pattern ?? (def.pattern = base64url);
|
|
$ZodStringFormat.init(inst, def);
|
|
inst._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 ?? number4;
|
|
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" : undefined : undefined;
|
|
payload.issues.push({
|
|
expected: "number",
|
|
code: "invalid_type",
|
|
input,
|
|
inst,
|
|
...received ? { received } : {}
|
|
});
|
|
return payload;
|
|
};
|
|
});
|
|
var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (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 = 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, index) {
|
|
if (result.issues.length) {
|
|
final.issues.push(...prefixIssues(index, result.issues));
|
|
}
|
|
final.value[index] = 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 i = 0;i < input.length; i++) {
|
|
const item = input[i];
|
|
const result = def.element._zod.run({
|
|
value: item,
|
|
issues: []
|
|
}, ctx);
|
|
if (result instanceof Promise) {
|
|
proms.push(result.then((result) => handleArrayResult(result, payload, i)));
|
|
} else {
|
|
handleArrayResult(result, payload, i);
|
|
}
|
|
}
|
|
if (proms.length) {
|
|
return Promise.all(proms).then(() => payload);
|
|
}
|
|
return payload;
|
|
};
|
|
});
|
|
function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {
|
|
const isPresent = key in input;
|
|
if (result.issues.length) {
|
|
if (isOptionalIn && isOptionalOut && !isPresent) {
|
|
return;
|
|
}
|
|
final.issues.push(...prefixIssues(key, result.issues));
|
|
}
|
|
if (!isPresent && !isOptionalIn) {
|
|
if (!result.issues.length) {
|
|
final.issues.push({
|
|
code: "invalid_type",
|
|
expected: "nonoptional",
|
|
input: undefined,
|
|
path: [key]
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
if (result.value === undefined) {
|
|
if (isPresent) {
|
|
final.value[key] = undefined;
|
|
}
|
|
} else {
|
|
final.value[key] = result.value;
|
|
}
|
|
}
|
|
function normalizeDef(def) {
|
|
const keys = Object.keys(def.shape);
|
|
for (const k of keys) {
|
|
if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) {
|
|
throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
|
|
}
|
|
}
|
|
const okeys = optionalKeys(def.shape);
|
|
return {
|
|
...def,
|
|
keys,
|
|
keySet: new Set(keys),
|
|
numKeys: keys.length,
|
|
optionalKeys: new Set(okeys)
|
|
};
|
|
}
|
|
function handleCatchall(proms, input, payload, ctx, def, inst) {
|
|
const unrecognized = [];
|
|
const keySet = def.keySet;
|
|
const _catchall = def.catchall._zod;
|
|
const t = _catchall.def.type;
|
|
const isOptionalIn = _catchall.optin === "optional";
|
|
const isOptionalOut = _catchall.optout === "optional";
|
|
for (const key in input) {
|
|
if (key === "__proto__")
|
|
continue;
|
|
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((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));
|
|
} else {
|
|
handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
|
|
}
|
|
}
|
|
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;
|
|
});
|
|
}
|
|
var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
const desc = Object.getOwnPropertyDescriptor(def, "shape");
|
|
if (!desc?.get) {
|
|
const sh = def.shape;
|
|
Object.defineProperty(def, "shape", {
|
|
get: () => {
|
|
const newSh = { ...sh };
|
|
Object.defineProperty(def, "shape", {
|
|
value: newSh
|
|
});
|
|
return newSh;
|
|
}
|
|
});
|
|
}
|
|
const _normalized = cached3(() => normalizeDef(def));
|
|
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] = new Set);
|
|
for (const v of field.values)
|
|
propValues[key].add(v);
|
|
}
|
|
}
|
|
return propValues;
|
|
});
|
|
const isObject = isObject3;
|
|
const catchall = def.catchall;
|
|
let value;
|
|
inst._zod.parse = (payload, ctx) => {
|
|
value ?? (value = _normalized.value);
|
|
const input = payload.value;
|
|
if (!isObject(input)) {
|
|
payload.issues.push({
|
|
expected: "object",
|
|
code: "invalid_type",
|
|
input,
|
|
inst
|
|
});
|
|
return payload;
|
|
}
|
|
payload.value = {};
|
|
const proms = [];
|
|
const shape = value.shape;
|
|
for (const key of value.keys) {
|
|
const el = shape[key];
|
|
const isOptionalIn = el._zod.optin === "optional";
|
|
const isOptionalOut = el._zod.optout === "optional";
|
|
const r = el._zod.run({ value: input[key], issues: [] }, ctx);
|
|
if (r instanceof Promise) {
|
|
proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));
|
|
} else {
|
|
handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);
|
|
}
|
|
}
|
|
if (!catchall) {
|
|
return proms.length ? Promise.all(proms).then(() => payload) : payload;
|
|
}
|
|
return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
|
|
};
|
|
});
|
|
var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
|
|
$ZodObject.init(inst, def);
|
|
const superParse = inst._zod.parse;
|
|
const _normalized = cached3(() => normalizeDef(def));
|
|
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 = 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) {
|
|
const id = ids[key];
|
|
const k = esc(key);
|
|
const schema = shape[key];
|
|
const isOptionalIn = schema?._zod?.optin === "optional";
|
|
const isOptionalOut = schema?._zod?.optout === "optional";
|
|
doc.write(`const ${id} = ${parseStr(key)};`);
|
|
if (isOptionalIn && isOptionalOut) {
|
|
doc.write(`
|
|
if (${id}.issues.length) {
|
|
if (${k} in input) {
|
|
payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
|
|
...iss,
|
|
path: iss.path ? [${k}, ...iss.path] : [${k}]
|
|
})));
|
|
}
|
|
}
|
|
|
|
if (${id}.value === undefined) {
|
|
if (${k} in input) {
|
|
newResult[${k}] = undefined;
|
|
}
|
|
} else {
|
|
newResult[${k}] = ${id}.value;
|
|
}
|
|
|
|
`);
|
|
} else if (!isOptionalIn) {
|
|
doc.write(`
|
|
const ${id}_present = ${k} in input;
|
|
if (${id}.issues.length) {
|
|
payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
|
|
...iss,
|
|
path: iss.path ? [${k}, ...iss.path] : [${k}]
|
|
})));
|
|
}
|
|
if (!${id}_present && !${id}.issues.length) {
|
|
payload.issues.push({
|
|
code: "invalid_type",
|
|
expected: "nonoptional",
|
|
input: undefined,
|
|
path: [${k}]
|
|
});
|
|
}
|
|
|
|
if (${id}_present) {
|
|
if (${id}.value === undefined) {
|
|
newResult[${k}] = undefined;
|
|
} else {
|
|
newResult[${k}] = ${id}.value;
|
|
}
|
|
}
|
|
|
|
`);
|
|
} else {
|
|
doc.write(`
|
|
if (${id}.issues.length) {
|
|
payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
|
|
...iss,
|
|
path: iss.path ? [${k}, ...iss.path] : [${k}]
|
|
})));
|
|
}
|
|
|
|
if (${id}.value === undefined) {
|
|
if (${k} in input) {
|
|
newResult[${k}] = undefined;
|
|
}
|
|
} else {
|
|
newResult[${k}] = ${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 isObject = isObject3;
|
|
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 (!isObject(input)) {
|
|
payload.issues.push({
|
|
expected: "object",
|
|
code: "invalid_type",
|
|
input,
|
|
inst
|
|
});
|
|
return payload;
|
|
}
|
|
if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
|
|
if (!fastpass)
|
|
fastpass = generateFastpass(def.shape);
|
|
payload = fastpass(payload, ctx);
|
|
if (!catchall)
|
|
return payload;
|
|
return handleCatchall([], input, payload, ctx, value, inst);
|
|
}
|
|
return superParse(payload, ctx);
|
|
};
|
|
});
|
|
function handleUnionResults(results, final, inst, ctx) {
|
|
for (const result of results) {
|
|
if (result.issues.length === 0) {
|
|
final.value = result.value;
|
|
return final;
|
|
}
|
|
}
|
|
const nonaborted = results.filter((r) => !aborted(r));
|
|
if (nonaborted.length === 1) {
|
|
final.value = nonaborted[0].value;
|
|
return nonaborted[0];
|
|
}
|
|
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" : undefined);
|
|
defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined);
|
|
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;
|
|
});
|
|
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;
|
|
});
|
|
const first = def.options.length === 1 ? def.options[0]._zod.run : null;
|
|
inst._zod.parse = (payload, ctx) => {
|
|
if (first) {
|
|
return first(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((results) => {
|
|
return handleUnionResults(results, payload, inst, ctx);
|
|
});
|
|
};
|
|
});
|
|
var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
|
|
def.inclusive = false;
|
|
$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] = new Set;
|
|
for (const val of v) {
|
|
propValues[k].add(val);
|
|
}
|
|
}
|
|
}
|
|
return propValues;
|
|
});
|
|
const disc = cached3(() => {
|
|
const opts = def.options;
|
|
const map = 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 (map.has(v)) {
|
|
throw new Error(`Duplicate discriminator value "${String(v)}"`);
|
|
}
|
|
map.set(v, o);
|
|
}
|
|
}
|
|
return map;
|
|
});
|
|
inst._zod.parse = (payload, ctx) => {
|
|
const input = payload.value;
|
|
if (!isObject3(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 || ctx.direction === "backward") {
|
|
return _super(payload, ctx);
|
|
}
|
|
payload.issues.push({
|
|
code: "invalid_union",
|
|
errors: [],
|
|
note: "No matching discriminator",
|
|
discriminator: def.discriminator,
|
|
options: Array.from(disc.value.keys()),
|
|
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(([left, right]) => {
|
|
return handleIntersectionResults(payload, left, right);
|
|
});
|
|
}
|
|
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 index = 0;index < a.length; index++) {
|
|
const itemA = a[index];
|
|
const itemB = b[index];
|
|
const sharedValue = mergeValues2(itemA, itemB);
|
|
if (!sharedValue.valid) {
|
|
return {
|
|
valid: false,
|
|
mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
|
|
};
|
|
}
|
|
newArray.push(sharedValue.data);
|
|
}
|
|
return { valid: true, data: newArray };
|
|
}
|
|
return { valid: false, mergeErrorPath: [] };
|
|
}
|
|
function handleIntersectionResults(result, left, right) {
|
|
const unrecKeys = new Map;
|
|
let unrecIssue;
|
|
for (const iss of left.issues) {
|
|
if (iss.code === "unrecognized_keys") {
|
|
unrecIssue ?? (unrecIssue = iss);
|
|
for (const k of iss.keys) {
|
|
if (!unrecKeys.has(k))
|
|
unrecKeys.set(k, {});
|
|
unrecKeys.get(k).l = true;
|
|
}
|
|
} else {
|
|
result.issues.push(iss);
|
|
}
|
|
}
|
|
for (const iss of right.issues) {
|
|
if (iss.code === "unrecognized_keys") {
|
|
for (const k of iss.keys) {
|
|
if (!unrecKeys.has(k))
|
|
unrecKeys.set(k, {});
|
|
unrecKeys.get(k).r = true;
|
|
}
|
|
} else {
|
|
result.issues.push(iss);
|
|
}
|
|
}
|
|
const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
|
|
if (bothKeys.length && unrecIssue) {
|
|
result.issues.push({ ...unrecIssue, keys: bothKeys });
|
|
}
|
|
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 = [];
|
|
const values = def.keyType._zod.values;
|
|
if (values) {
|
|
payload.value = {};
|
|
const recordKeys = new Set;
|
|
for (const key of values) {
|
|
if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
|
|
recordKeys.add(typeof key === "number" ? key.toString() : key);
|
|
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({
|
|
code: "invalid_key",
|
|
origin: "record",
|
|
issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
|
|
input: key,
|
|
path: [key],
|
|
inst
|
|
});
|
|
continue;
|
|
}
|
|
const outKey = keyResult.value;
|
|
const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
|
|
if (result instanceof Promise) {
|
|
proms.push(result.then((result) => {
|
|
if (result.issues.length) {
|
|
payload.issues.push(...prefixIssues(key, result.issues));
|
|
}
|
|
payload.value[outKey] = result.value;
|
|
}));
|
|
} else {
|
|
if (result.issues.length) {
|
|
payload.issues.push(...prefixIssues(key, result.issues));
|
|
}
|
|
payload.value[outKey] = result.value;
|
|
}
|
|
}
|
|
}
|
|
let unrecognized;
|
|
for (const key in input) {
|
|
if (!recordKeys.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;
|
|
if (!Object.prototype.propertyIsEnumerable.call(input, key))
|
|
continue;
|
|
let 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 checkNumericKey = typeof key === "string" && number4.test(key) && keyResult.issues.length;
|
|
if (checkNumericKey) {
|
|
const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);
|
|
if (retryResult instanceof Promise) {
|
|
throw new Error("Async schemas not supported in object keys currently");
|
|
}
|
|
if (retryResult.issues.length === 0) {
|
|
keyResult = retryResult;
|
|
}
|
|
}
|
|
if (keyResult.issues.length) {
|
|
if (def.mode === "loose") {
|
|
payload.value[key] = input[key];
|
|
} else {
|
|
payload.issues.push({
|
|
code: "invalid_key",
|
|
origin: "record",
|
|
issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
|
|
input: key,
|
|
path: [key],
|
|
inst
|
|
});
|
|
}
|
|
continue;
|
|
}
|
|
const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
|
|
if (result instanceof Promise) {
|
|
proms.push(result.then((result) => {
|
|
if (result.issues.length) {
|
|
payload.issues.push(...prefixIssues(key, result.issues));
|
|
}
|
|
payload.value[keyResult.value] = result.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);
|
|
const valuesSet = new Set(values);
|
|
inst._zod.values = valuesSet;
|
|
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 (valuesSet.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);
|
|
if (def.values.length === 0) {
|
|
throw new Error("Cannot create literal schema with no valid values");
|
|
}
|
|
const values = new Set(def.values);
|
|
inst._zod.values = values;
|
|
inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
|
|
inst._zod.parse = (payload, _ctx) => {
|
|
const input = payload.value;
|
|
if (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.optin = "optional";
|
|
inst._zod.parse = (payload, ctx) => {
|
|
if (ctx.direction === "backward") {
|
|
throw new $ZodEncodeError(inst.constructor.name);
|
|
}
|
|
const _out = def.transform(payload.value, payload);
|
|
if (ctx.async) {
|
|
const output = _out instanceof Promise ? _out : Promise.resolve(_out);
|
|
return output.then((output) => {
|
|
payload.value = output;
|
|
payload.fallback = true;
|
|
return payload;
|
|
});
|
|
}
|
|
if (_out instanceof Promise) {
|
|
throw new $ZodAsyncError;
|
|
}
|
|
payload.value = _out;
|
|
payload.fallback = true;
|
|
return payload;
|
|
};
|
|
});
|
|
function handleOptionalResult(result, input) {
|
|
if (input === undefined && (result.issues.length || result.fallback)) {
|
|
return { issues: [], value: undefined };
|
|
}
|
|
return result;
|
|
}
|
|
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 ? new Set([...def.innerType._zod.values, undefined]) : undefined;
|
|
});
|
|
defineLazy(inst._zod, "pattern", () => {
|
|
const pattern = def.innerType._zod.pattern;
|
|
return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined;
|
|
});
|
|
inst._zod.parse = (payload, ctx) => {
|
|
if (def.innerType._zod.optin === "optional") {
|
|
const input = payload.value;
|
|
const result = def.innerType._zod.run(payload, ctx);
|
|
if (result instanceof Promise)
|
|
return result.then((r) => handleOptionalResult(r, input));
|
|
return handleOptionalResult(result, input);
|
|
}
|
|
if (payload.value === undefined) {
|
|
return payload;
|
|
}
|
|
return def.innerType._zod.run(payload, ctx);
|
|
};
|
|
});
|
|
var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => {
|
|
$ZodOptional.init(inst, def);
|
|
defineLazy(inst._zod, "values", () => def.innerType._zod.values);
|
|
defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern);
|
|
inst._zod.parse = (payload, ctx) => {
|
|
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)$`) : undefined;
|
|
});
|
|
defineLazy(inst._zod, "values", () => {
|
|
return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;
|
|
});
|
|
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 (ctx.direction === "backward") {
|
|
return def.innerType._zod.run(payload, ctx);
|
|
}
|
|
if (payload.value === undefined) {
|
|
payload.value = def.defaultValue;
|
|
return payload;
|
|
}
|
|
const result = def.innerType._zod.run(payload, ctx);
|
|
if (result instanceof Promise) {
|
|
return result.then((result) => handleDefaultResult(result, def));
|
|
}
|
|
return handleDefaultResult(result, def);
|
|
};
|
|
});
|
|
function handleDefaultResult(payload, def) {
|
|
if (payload.value === undefined) {
|
|
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 (ctx.direction === "backward") {
|
|
return def.innerType._zod.run(payload, ctx);
|
|
}
|
|
if (payload.value === undefined) {
|
|
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 !== undefined)) : undefined;
|
|
});
|
|
inst._zod.parse = (payload, ctx) => {
|
|
const result = def.innerType._zod.run(payload, ctx);
|
|
if (result instanceof Promise) {
|
|
return result.then((result) => handleNonOptionalResult(result, inst));
|
|
}
|
|
return handleNonOptionalResult(result, inst);
|
|
};
|
|
});
|
|
function handleNonOptionalResult(payload, inst) {
|
|
if (!payload.issues.length && payload.value === undefined) {
|
|
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) => {
|
|
if (ctx.direction === "backward") {
|
|
return def.innerType._zod.run(payload, ctx);
|
|
}
|
|
const result = def.innerType._zod.run(payload, ctx);
|
|
if (result instanceof Promise) {
|
|
return result.then((result) => {
|
|
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 = [];
|
|
payload.fallback = true;
|
|
}
|
|
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 = [];
|
|
payload.fallback = true;
|
|
}
|
|
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);
|
|
defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
|
|
inst._zod.parse = (payload, ctx) => {
|
|
if (ctx.direction === "backward") {
|
|
const right = def.out._zod.run(payload, ctx);
|
|
if (right instanceof Promise) {
|
|
return right.then((right) => handlePipeResult(right, def.in, ctx));
|
|
}
|
|
return handlePipeResult(right, def.in, ctx);
|
|
}
|
|
const left = def.in._zod.run(payload, ctx);
|
|
if (left instanceof Promise) {
|
|
return left.then((left) => handlePipeResult(left, def.out, ctx));
|
|
}
|
|
return handlePipeResult(left, def.out, ctx);
|
|
};
|
|
});
|
|
function handlePipeResult(left, next, ctx) {
|
|
if (left.issues.length) {
|
|
left.aborted = true;
|
|
return left;
|
|
}
|
|
return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);
|
|
}
|
|
var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) => {
|
|
$ZodPipe.init(inst, def);
|
|
});
|
|
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) => {
|
|
if (ctx.direction === "backward") {
|
|
return def.innerType._zod.run(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((r) => handleRefineResult(r, payload, input, inst));
|
|
}
|
|
handleRefineResult(r, payload, input, inst);
|
|
return;
|
|
};
|
|
});
|
|
function handleRefineResult(result, payload, input, inst) {
|
|
if (!result) {
|
|
const _iss = {
|
|
code: "custom",
|
|
input,
|
|
inst,
|
|
path: [...inst._zod.def.path ?? []],
|
|
continue: !inst._zod.def.abort
|
|
};
|
|
if (inst._zod.def.params)
|
|
_iss.params = inst._zod.def.params;
|
|
payload.issues.push(issue(_iss));
|
|
}
|
|
}
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/locales/en.js
|
|
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" },
|
|
map: { unit: "entries", verb: "to have" }
|
|
};
|
|
function getSizing(origin) {
|
|
return Sizable[origin] ?? null;
|
|
}
|
|
const FormatDictionary = {
|
|
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",
|
|
mac: "MAC 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"
|
|
};
|
|
const TypeDictionary = {
|
|
nan: "NaN"
|
|
};
|
|
return (issue) => {
|
|
switch (issue.code) {
|
|
case "invalid_type": {
|
|
const expected = TypeDictionary[issue.expected] ?? issue.expected;
|
|
const receivedType = parsedType(issue.input);
|
|
const received = TypeDictionary[receivedType] ?? receivedType;
|
|
return `Invalid input: expected ${expected}, received ${received}`;
|
|
}
|
|
case "invalid_value":
|
|
if (issue.values.length === 1)
|
|
return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`;
|
|
return `Invalid option: expected one of ${joinValues(issue.values, "|")}`;
|
|
case "too_big": {
|
|
const adj = issue.inclusive ? "<=" : "<";
|
|
const sizing = getSizing(issue.origin);
|
|
if (sizing)
|
|
return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`;
|
|
return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`;
|
|
}
|
|
case "too_small": {
|
|
const adj = issue.inclusive ? ">=" : ">";
|
|
const sizing = getSizing(issue.origin);
|
|
if (sizing) {
|
|
return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;
|
|
}
|
|
return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;
|
|
}
|
|
case "invalid_format": {
|
|
const _issue = issue;
|
|
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 ${FormatDictionary[_issue.format] ?? issue.format}`;
|
|
}
|
|
case "not_multiple_of":
|
|
return `Invalid number: must be a multiple of ${issue.divisor}`;
|
|
case "unrecognized_keys":
|
|
return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`;
|
|
case "invalid_key":
|
|
return `Invalid key in ${issue.origin}`;
|
|
case "invalid_union":
|
|
if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {
|
|
const opts = issue.options.map((o) => `'${o}'`).join(" | ");
|
|
return `Invalid discriminator value. Expected ${opts}`;
|
|
}
|
|
return "Invalid input";
|
|
case "invalid_element":
|
|
return `Invalid value in ${issue.origin}`;
|
|
default:
|
|
return `Invalid input`;
|
|
}
|
|
};
|
|
};
|
|
function en_default2() {
|
|
return {
|
|
localeError: error()
|
|
};
|
|
}
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js
|
|
var _a2;
|
|
var $output = Symbol("ZodOutput");
|
|
var $input = Symbol("ZodInput");
|
|
|
|
class $ZodRegistry {
|
|
constructor() {
|
|
this._map = new WeakMap;
|
|
this._idmap = new Map;
|
|
}
|
|
add(schema, ..._meta) {
|
|
const meta = _meta[0];
|
|
this._map.set(schema, meta);
|
|
if (meta && typeof meta === "object" && "id" in meta) {
|
|
this._idmap.set(meta.id, schema);
|
|
}
|
|
return this;
|
|
}
|
|
clear() {
|
|
this._map = new WeakMap;
|
|
this._idmap = new Map;
|
|
return this;
|
|
}
|
|
remove(schema) {
|
|
const meta = this._map.get(schema);
|
|
if (meta && typeof meta === "object" && "id" in meta) {
|
|
this._idmap.delete(meta.id);
|
|
}
|
|
this._map.delete(schema);
|
|
return this;
|
|
}
|
|
get(schema) {
|
|
const p = schema._zod.parent;
|
|
if (p) {
|
|
const pm = { ...this.get(p) ?? {} };
|
|
delete pm.id;
|
|
const f = { ...pm, ...this._map.get(schema) };
|
|
return Object.keys(f).length ? f : undefined;
|
|
}
|
|
return this._map.get(schema);
|
|
}
|
|
has(schema) {
|
|
return this._map.has(schema);
|
|
}
|
|
}
|
|
function registry() {
|
|
return new $ZodRegistry;
|
|
}
|
|
(_a2 = globalThis).__zod_globalRegistry ?? (_a2.__zod_globalRegistry = registry());
|
|
var globalRegistry = globalThis.__zod_globalRegistry;
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js
|
|
function _string(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _email(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "email",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _guid(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "guid",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _uuid(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "uuid",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _uuidv4(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "uuid",
|
|
check: "string_format",
|
|
abort: false,
|
|
version: "v4",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _uuidv6(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "uuid",
|
|
check: "string_format",
|
|
abort: false,
|
|
version: "v6",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _uuidv7(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "uuid",
|
|
check: "string_format",
|
|
abort: false,
|
|
version: "v7",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _url(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "url",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _emoji2(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "emoji",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _nanoid(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "nanoid",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _cuid(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "cuid",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _cuid2(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "cuid2",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _ulid(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "ulid",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _xid(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "xid",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _ksuid(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "ksuid",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _ipv4(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "ipv4",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _ipv6(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "ipv6",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _cidrv4(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "cidrv4",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _cidrv6(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "cidrv6",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _base64(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "base64",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _base64url(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "base64url",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _e164(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "e164",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _jwt(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "jwt",
|
|
check: "string_format",
|
|
abort: false,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _isoDateTime(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "datetime",
|
|
check: "string_format",
|
|
offset: false,
|
|
local: false,
|
|
precision: null,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _isoDate(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "date",
|
|
check: "string_format",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _isoTime(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "time",
|
|
check: "string_format",
|
|
precision: null,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _isoDuration(Class, params) {
|
|
return new Class({
|
|
type: "string",
|
|
format: "duration",
|
|
check: "string_format",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _number(Class, params) {
|
|
return new Class({
|
|
type: "number",
|
|
checks: [],
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _int(Class, params) {
|
|
return new Class({
|
|
type: "number",
|
|
check: "number_format",
|
|
abort: false,
|
|
format: "safeint",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _boolean(Class, params) {
|
|
return new Class({
|
|
type: "boolean",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _null2(Class, params) {
|
|
return new Class({
|
|
type: "null",
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _unknown(Class) {
|
|
return new Class({
|
|
type: "unknown"
|
|
});
|
|
}
|
|
function _never2(Class, params) {
|
|
return new Class({
|
|
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
|
|
});
|
|
}
|
|
function _normalize(form) {
|
|
return _overwrite((input) => input.normalize(form));
|
|
}
|
|
function _trim() {
|
|
return _overwrite((input) => input.trim());
|
|
}
|
|
function _toLowerCase() {
|
|
return _overwrite((input) => input.toLowerCase());
|
|
}
|
|
function _toUpperCase() {
|
|
return _overwrite((input) => input.toUpperCase());
|
|
}
|
|
function _slugify() {
|
|
return _overwrite((input) => slugify(input));
|
|
}
|
|
function _array(Class, element, params) {
|
|
return new Class({
|
|
type: "array",
|
|
element,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
function _custom(Class, fn, _params) {
|
|
const norm = normalizeParams(_params);
|
|
norm.abort ?? (norm.abort = true);
|
|
const schema = new Class({
|
|
type: "custom",
|
|
check: "custom",
|
|
fn,
|
|
...norm
|
|
});
|
|
return schema;
|
|
}
|
|
function _refine(Class, fn, _params) {
|
|
const schema = new Class({
|
|
type: "custom",
|
|
check: "custom",
|
|
fn,
|
|
...normalizeParams(_params)
|
|
});
|
|
return schema;
|
|
}
|
|
function _superRefine(fn, params) {
|
|
const ch = _check((payload) => {
|
|
payload.addIssue = (issue2) => {
|
|
if (typeof issue2 === "string") {
|
|
payload.issues.push(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(issue(_issue));
|
|
}
|
|
};
|
|
return fn(payload.value, payload);
|
|
}, params);
|
|
return ch;
|
|
}
|
|
function _check(fn, params) {
|
|
const ch = new $ZodCheck({
|
|
check: "custom",
|
|
...normalizeParams(params)
|
|
});
|
|
ch._zod.check = fn;
|
|
return ch;
|
|
}
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js
|
|
function initializeContext(params) {
|
|
let target = params?.target ?? "draft-2020-12";
|
|
if (target === "draft-4")
|
|
target = "draft-04";
|
|
if (target === "draft-7")
|
|
target = "draft-07";
|
|
return {
|
|
processors: params.processors ?? {},
|
|
metadataRegistry: params?.metadata ?? globalRegistry,
|
|
target,
|
|
unrepresentable: params?.unrepresentable ?? "throw",
|
|
override: params?.override ?? (() => {}),
|
|
io: params?.io ?? "output",
|
|
counter: 0,
|
|
seen: new Map,
|
|
cycles: params?.cycles ?? "ref",
|
|
reused: params?.reused ?? "inline",
|
|
external: params?.external ?? undefined
|
|
};
|
|
}
|
|
function process2(schema, ctx, _params = { path: [], schemaPath: [] }) {
|
|
var _a;
|
|
const def = schema._zod.def;
|
|
const seen = ctx.seen.get(schema);
|
|
if (seen) {
|
|
seen.count++;
|
|
const isCycle = _params.schemaPath.includes(schema);
|
|
if (isCycle) {
|
|
seen.cycle = _params.path;
|
|
}
|
|
return seen.schema;
|
|
}
|
|
const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };
|
|
ctx.seen.set(schema, result);
|
|
const overrideSchema = schema._zod.toJSONSchema?.();
|
|
if (overrideSchema) {
|
|
result.schema = overrideSchema;
|
|
} else {
|
|
const params = {
|
|
..._params,
|
|
schemaPath: [..._params.schemaPath, schema],
|
|
path: _params.path
|
|
};
|
|
if (schema._zod.processJSONSchema) {
|
|
schema._zod.processJSONSchema(ctx, result.schema, params);
|
|
} else {
|
|
const _json = result.schema;
|
|
const processor = ctx.processors[def.type];
|
|
if (!processor) {
|
|
throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
|
|
}
|
|
processor(schema, ctx, _json, params);
|
|
}
|
|
const parent = schema._zod.parent;
|
|
if (parent) {
|
|
if (!result.ref)
|
|
result.ref = parent;
|
|
process2(parent, ctx, params);
|
|
ctx.seen.get(parent).isParent = true;
|
|
}
|
|
}
|
|
const meta = ctx.metadataRegistry.get(schema);
|
|
if (meta)
|
|
Object.assign(result.schema, meta);
|
|
if (ctx.io === "input" && isTransforming(schema)) {
|
|
delete result.schema.examples;
|
|
delete result.schema.default;
|
|
}
|
|
if (ctx.io === "input" && "_prefault" in result.schema)
|
|
(_a = result.schema).default ?? (_a.default = result.schema._prefault);
|
|
delete result.schema._prefault;
|
|
const _result = ctx.seen.get(schema);
|
|
return _result.schema;
|
|
}
|
|
function extractDefs(ctx, schema) {
|
|
const root = ctx.seen.get(schema);
|
|
if (!root)
|
|
throw new Error("Unprocessed schema. This is a bug in Zod.");
|
|
const idToSchema = new Map;
|
|
for (const entry of ctx.seen.entries()) {
|
|
const id = ctx.metadataRegistry.get(entry[0])?.id;
|
|
if (id) {
|
|
const existing = idToSchema.get(id);
|
|
if (existing && existing !== entry[0]) {
|
|
throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
|
|
}
|
|
idToSchema.set(id, entry[0]);
|
|
}
|
|
}
|
|
const makeURI = (entry) => {
|
|
const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
|
|
if (ctx.external) {
|
|
const externalId = ctx.external.registry.get(entry[0])?.id;
|
|
const uriGenerator = ctx.external.uri ?? ((id) => id);
|
|
if (externalId) {
|
|
return { ref: uriGenerator(externalId) };
|
|
}
|
|
const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.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${ctx.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 schema = seen.schema;
|
|
for (const key in schema) {
|
|
delete schema[key];
|
|
}
|
|
schema.$ref = ref;
|
|
};
|
|
if (ctx.cycles === "throw") {
|
|
for (const entry of ctx.seen.entries()) {
|
|
const seen = entry[1];
|
|
if (seen.cycle) {
|
|
throw new Error("Cycle detected: " + `#/${seen.cycle?.join("/")}/<root>` + '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.');
|
|
}
|
|
}
|
|
}
|
|
for (const entry of ctx.seen.entries()) {
|
|
const seen = entry[1];
|
|
if (schema === entry[0]) {
|
|
extractToDef(entry);
|
|
continue;
|
|
}
|
|
if (ctx.external) {
|
|
const ext = ctx.external.registry.get(entry[0])?.id;
|
|
if (schema !== entry[0] && ext) {
|
|
extractToDef(entry);
|
|
continue;
|
|
}
|
|
}
|
|
const id = ctx.metadataRegistry.get(entry[0])?.id;
|
|
if (id) {
|
|
extractToDef(entry);
|
|
continue;
|
|
}
|
|
if (seen.cycle) {
|
|
extractToDef(entry);
|
|
continue;
|
|
}
|
|
if (seen.count > 1) {
|
|
if (ctx.reused === "ref") {
|
|
extractToDef(entry);
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
function finalize(ctx, schema) {
|
|
const root = ctx.seen.get(schema);
|
|
if (!root)
|
|
throw new Error("Unprocessed schema. This is a bug in Zod.");
|
|
const flattenRef = (zodSchema) => {
|
|
const seen = ctx.seen.get(zodSchema);
|
|
if (seen.ref === null)
|
|
return;
|
|
const schema = seen.def ?? seen.schema;
|
|
const _cached = { ...schema };
|
|
const ref = seen.ref;
|
|
seen.ref = null;
|
|
if (ref) {
|
|
flattenRef(ref);
|
|
const refSeen = ctx.seen.get(ref);
|
|
const refSchema = refSeen.schema;
|
|
if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
|
|
schema.allOf = schema.allOf ?? [];
|
|
schema.allOf.push(refSchema);
|
|
} else {
|
|
Object.assign(schema, refSchema);
|
|
}
|
|
Object.assign(schema, _cached);
|
|
const isParentRef = zodSchema._zod.parent === ref;
|
|
if (isParentRef) {
|
|
for (const key in schema) {
|
|
if (key === "$ref" || key === "allOf")
|
|
continue;
|
|
if (!(key in _cached)) {
|
|
delete schema[key];
|
|
}
|
|
}
|
|
}
|
|
if (refSchema.$ref && refSeen.def) {
|
|
for (const key in schema) {
|
|
if (key === "$ref" || key === "allOf")
|
|
continue;
|
|
if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {
|
|
delete schema[key];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
const parent = zodSchema._zod.parent;
|
|
if (parent && parent !== ref) {
|
|
flattenRef(parent);
|
|
const parentSeen = ctx.seen.get(parent);
|
|
if (parentSeen?.schema.$ref) {
|
|
schema.$ref = parentSeen.schema.$ref;
|
|
if (parentSeen.def) {
|
|
for (const key in schema) {
|
|
if (key === "$ref" || key === "allOf")
|
|
continue;
|
|
if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {
|
|
delete schema[key];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
ctx.override({
|
|
zodSchema,
|
|
jsonSchema: schema,
|
|
path: seen.path ?? []
|
|
});
|
|
};
|
|
for (const entry of [...ctx.seen.entries()].reverse()) {
|
|
flattenRef(entry[0]);
|
|
}
|
|
const result = {};
|
|
if (ctx.target === "draft-2020-12") {
|
|
result.$schema = "https://json-schema.org/draft/2020-12/schema";
|
|
} else if (ctx.target === "draft-07") {
|
|
result.$schema = "http://json-schema.org/draft-07/schema#";
|
|
} else if (ctx.target === "draft-04") {
|
|
result.$schema = "http://json-schema.org/draft-04/schema#";
|
|
} else if (ctx.target === "openapi-3.0") {}
|
|
if (ctx.external?.uri) {
|
|
const id = ctx.external.registry.get(schema)?.id;
|
|
if (!id)
|
|
throw new Error("Schema is missing an `id` property");
|
|
result.$id = ctx.external.uri(id);
|
|
}
|
|
Object.assign(result, root.def ?? root.schema);
|
|
const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
|
|
if (rootMetaId !== undefined && result.id === rootMetaId)
|
|
delete result.id;
|
|
const defs = ctx.external?.defs ?? {};
|
|
for (const entry of ctx.seen.entries()) {
|
|
const seen = entry[1];
|
|
if (seen.def && seen.defId) {
|
|
if (seen.def.id === seen.defId)
|
|
delete seen.def.id;
|
|
defs[seen.defId] = seen.def;
|
|
}
|
|
}
|
|
if (ctx.external) {} else {
|
|
if (Object.keys(defs).length > 0) {
|
|
if (ctx.target === "draft-2020-12") {
|
|
result.$defs = defs;
|
|
} else {
|
|
result.definitions = defs;
|
|
}
|
|
}
|
|
}
|
|
try {
|
|
const finalized = JSON.parse(JSON.stringify(result));
|
|
Object.defineProperty(finalized, "~standard", {
|
|
value: {
|
|
...schema["~standard"],
|
|
jsonSchema: {
|
|
input: createStandardJSONSchemaMethod(schema, "input", ctx.processors),
|
|
output: createStandardJSONSchemaMethod(schema, "output", ctx.processors)
|
|
}
|
|
},
|
|
enumerable: false,
|
|
writable: false
|
|
});
|
|
return finalized;
|
|
} catch (_err) {
|
|
throw new Error("Error converting schema to JSON.");
|
|
}
|
|
}
|
|
function isTransforming(_schema, _ctx) {
|
|
const ctx = _ctx ?? { seen: new Set };
|
|
if (ctx.seen.has(_schema))
|
|
return false;
|
|
ctx.seen.add(_schema);
|
|
const def = _schema._zod.def;
|
|
if (def.type === "transform")
|
|
return true;
|
|
if (def.type === "array")
|
|
return isTransforming(def.element, ctx);
|
|
if (def.type === "set")
|
|
return isTransforming(def.valueType, ctx);
|
|
if (def.type === "lazy")
|
|
return isTransforming(def.getter(), ctx);
|
|
if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") {
|
|
return isTransforming(def.innerType, ctx);
|
|
}
|
|
if (def.type === "intersection") {
|
|
return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
|
|
}
|
|
if (def.type === "record" || def.type === "map") {
|
|
return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
|
|
}
|
|
if (def.type === "pipe") {
|
|
if (_schema._zod.traits.has("$ZodCodec"))
|
|
return true;
|
|
return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
|
|
}
|
|
if (def.type === "object") {
|
|
for (const key in def.shape) {
|
|
if (isTransforming(def.shape[key], ctx))
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
if (def.type === "union") {
|
|
for (const option of def.options) {
|
|
if (isTransforming(option, ctx))
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
if (def.type === "tuple") {
|
|
for (const item of def.items) {
|
|
if (isTransforming(item, ctx))
|
|
return true;
|
|
}
|
|
if (def.rest && isTransforming(def.rest, ctx))
|
|
return true;
|
|
return false;
|
|
}
|
|
return false;
|
|
}
|
|
var createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
|
|
const ctx = initializeContext({ ...params, processors });
|
|
process2(schema, ctx);
|
|
extractDefs(ctx, schema);
|
|
return finalize(ctx, schema);
|
|
};
|
|
var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
|
|
const { libraryOptions, target } = params ?? {};
|
|
const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors });
|
|
process2(schema, ctx);
|
|
extractDefs(ctx, schema);
|
|
return finalize(ctx, schema);
|
|
};
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js
|
|
var formatMap = {
|
|
guid: "uuid",
|
|
url: "uri",
|
|
datetime: "date-time",
|
|
json_string: "json-string",
|
|
regex: ""
|
|
};
|
|
var stringProcessor = (schema, ctx, _json, _params) => {
|
|
const json = _json;
|
|
json.type = "string";
|
|
const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag;
|
|
if (typeof minimum === "number")
|
|
json.minLength = minimum;
|
|
if (typeof maximum === "number")
|
|
json.maxLength = maximum;
|
|
if (format) {
|
|
json.format = formatMap[format] ?? format;
|
|
if (json.format === "")
|
|
delete json.format;
|
|
if (format === "time") {
|
|
delete json.format;
|
|
}
|
|
}
|
|
if (contentEncoding)
|
|
json.contentEncoding = contentEncoding;
|
|
if (patterns && patterns.size > 0) {
|
|
const regexes = [...patterns];
|
|
if (regexes.length === 1)
|
|
json.pattern = regexes[0].source;
|
|
else if (regexes.length > 1) {
|
|
json.allOf = [
|
|
...regexes.map((regex) => ({
|
|
...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
|
|
pattern: regex.source
|
|
}))
|
|
];
|
|
}
|
|
}
|
|
};
|
|
var numberProcessor = (schema, ctx, _json, _params) => {
|
|
const json = _json;
|
|
const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
|
|
if (typeof format === "string" && format.includes("int"))
|
|
json.type = "integer";
|
|
else
|
|
json.type = "number";
|
|
const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
|
|
const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
|
|
const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
|
|
if (exMin) {
|
|
if (legacy) {
|
|
json.minimum = exclusiveMinimum;
|
|
json.exclusiveMinimum = true;
|
|
} else {
|
|
json.exclusiveMinimum = exclusiveMinimum;
|
|
}
|
|
} else if (typeof minimum === "number") {
|
|
json.minimum = minimum;
|
|
}
|
|
if (exMax) {
|
|
if (legacy) {
|
|
json.maximum = exclusiveMaximum;
|
|
json.exclusiveMaximum = true;
|
|
} else {
|
|
json.exclusiveMaximum = exclusiveMaximum;
|
|
}
|
|
} else if (typeof maximum === "number") {
|
|
json.maximum = maximum;
|
|
}
|
|
if (typeof multipleOf === "number")
|
|
json.multipleOf = multipleOf;
|
|
};
|
|
var booleanProcessor = (_schema, _ctx, json, _params) => {
|
|
json.type = "boolean";
|
|
};
|
|
var bigintProcessor = (_schema, ctx, _json, _params) => {
|
|
if (ctx.unrepresentable === "throw") {
|
|
throw new Error("BigInt cannot be represented in JSON Schema");
|
|
}
|
|
};
|
|
var symbolProcessor = (_schema, ctx, _json, _params) => {
|
|
if (ctx.unrepresentable === "throw") {
|
|
throw new Error("Symbols cannot be represented in JSON Schema");
|
|
}
|
|
};
|
|
var nullProcessor = (_schema, ctx, json, _params) => {
|
|
if (ctx.target === "openapi-3.0") {
|
|
json.type = "string";
|
|
json.nullable = true;
|
|
json.enum = [null];
|
|
} else {
|
|
json.type = "null";
|
|
}
|
|
};
|
|
var undefinedProcessor = (_schema, ctx, _json, _params) => {
|
|
if (ctx.unrepresentable === "throw") {
|
|
throw new Error("Undefined cannot be represented in JSON Schema");
|
|
}
|
|
};
|
|
var voidProcessor = (_schema, ctx, _json, _params) => {
|
|
if (ctx.unrepresentable === "throw") {
|
|
throw new Error("Void cannot be represented in JSON Schema");
|
|
}
|
|
};
|
|
var neverProcessor = (_schema, _ctx, json, _params) => {
|
|
json.not = {};
|
|
};
|
|
var anyProcessor = (_schema, _ctx, _json, _params) => {};
|
|
var unknownProcessor = (_schema, _ctx, _json, _params) => {};
|
|
var dateProcessor = (_schema, ctx, _json, _params) => {
|
|
if (ctx.unrepresentable === "throw") {
|
|
throw new Error("Date cannot be represented in JSON Schema");
|
|
}
|
|
};
|
|
var enumProcessor = (schema, _ctx, json, _params) => {
|
|
const def = schema._zod.def;
|
|
const values = getEnumValues(def.entries);
|
|
if (values.every((v) => typeof v === "number"))
|
|
json.type = "number";
|
|
if (values.every((v) => typeof v === "string"))
|
|
json.type = "string";
|
|
json.enum = values;
|
|
};
|
|
var literalProcessor = (schema, ctx, json, _params) => {
|
|
const def = schema._zod.def;
|
|
const vals = [];
|
|
for (const val of def.values) {
|
|
if (val === undefined) {
|
|
if (ctx.unrepresentable === "throw") {
|
|
throw new Error("Literal `undefined` cannot be represented in JSON Schema");
|
|
}
|
|
} else if (typeof val === "bigint") {
|
|
if (ctx.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];
|
|
json.type = val === null ? "null" : typeof val;
|
|
if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
|
|
json.enum = [val];
|
|
} else {
|
|
json.const = val;
|
|
}
|
|
} else {
|
|
if (vals.every((v) => typeof v === "number"))
|
|
json.type = "number";
|
|
if (vals.every((v) => typeof v === "string"))
|
|
json.type = "string";
|
|
if (vals.every((v) => typeof v === "boolean"))
|
|
json.type = "boolean";
|
|
if (vals.every((v) => v === null))
|
|
json.type = "null";
|
|
json.enum = vals;
|
|
}
|
|
};
|
|
var nanProcessor = (_schema, ctx, _json, _params) => {
|
|
if (ctx.unrepresentable === "throw") {
|
|
throw new Error("NaN cannot be represented in JSON Schema");
|
|
}
|
|
};
|
|
var templateLiteralProcessor = (schema, _ctx, json, _params) => {
|
|
const _json = json;
|
|
const pattern = schema._zod.pattern;
|
|
if (!pattern)
|
|
throw new Error("Pattern not found in template literal");
|
|
_json.type = "string";
|
|
_json.pattern = pattern.source;
|
|
};
|
|
var fileProcessor = (schema, _ctx, json, _params) => {
|
|
const _json = json;
|
|
const file = {
|
|
type: "string",
|
|
format: "binary",
|
|
contentEncoding: "binary"
|
|
};
|
|
const { minimum, maximum, mime } = schema._zod.bag;
|
|
if (minimum !== undefined)
|
|
file.minLength = minimum;
|
|
if (maximum !== undefined)
|
|
file.maxLength = maximum;
|
|
if (mime) {
|
|
if (mime.length === 1) {
|
|
file.contentMediaType = mime[0];
|
|
Object.assign(_json, file);
|
|
} else {
|
|
Object.assign(_json, file);
|
|
_json.anyOf = mime.map((m) => ({ contentMediaType: m }));
|
|
}
|
|
} else {
|
|
Object.assign(_json, file);
|
|
}
|
|
};
|
|
var successProcessor = (_schema, _ctx, json, _params) => {
|
|
json.type = "boolean";
|
|
};
|
|
var customProcessor = (_schema, ctx, _json, _params) => {
|
|
if (ctx.unrepresentable === "throw") {
|
|
throw new Error("Custom types cannot be represented in JSON Schema");
|
|
}
|
|
};
|
|
var functionProcessor = (_schema, ctx, _json, _params) => {
|
|
if (ctx.unrepresentable === "throw") {
|
|
throw new Error("Function types cannot be represented in JSON Schema");
|
|
}
|
|
};
|
|
var transformProcessor = (_schema, ctx, _json, _params) => {
|
|
if (ctx.unrepresentable === "throw") {
|
|
throw new Error("Transforms cannot be represented in JSON Schema");
|
|
}
|
|
};
|
|
var mapProcessor = (_schema, ctx, _json, _params) => {
|
|
if (ctx.unrepresentable === "throw") {
|
|
throw new Error("Map cannot be represented in JSON Schema");
|
|
}
|
|
};
|
|
var setProcessor = (_schema, ctx, _json, _params) => {
|
|
if (ctx.unrepresentable === "throw") {
|
|
throw new Error("Set cannot be represented in JSON Schema");
|
|
}
|
|
};
|
|
var arrayProcessor = (schema, ctx, _json, params) => {
|
|
const json = _json;
|
|
const def = schema._zod.def;
|
|
const { minimum, maximum } = schema._zod.bag;
|
|
if (typeof minimum === "number")
|
|
json.minItems = minimum;
|
|
if (typeof maximum === "number")
|
|
json.maxItems = maximum;
|
|
json.type = "array";
|
|
json.items = process2(def.element, ctx, {
|
|
...params,
|
|
path: [...params.path, "items"]
|
|
});
|
|
};
|
|
var objectProcessor = (schema, ctx, _json, params) => {
|
|
const json = _json;
|
|
const def = schema._zod.def;
|
|
json.type = "object";
|
|
json.properties = {};
|
|
const shape = def.shape;
|
|
for (const key in shape) {
|
|
json.properties[key] = process2(shape[key], ctx, {
|
|
...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 (ctx.io === "input") {
|
|
return v.optin === undefined;
|
|
} else {
|
|
return v.optout === undefined;
|
|
}
|
|
}));
|
|
if (requiredKeys.size > 0) {
|
|
json.required = Array.from(requiredKeys);
|
|
}
|
|
if (def.catchall?._zod.def.type === "never") {
|
|
json.additionalProperties = false;
|
|
} else if (!def.catchall) {
|
|
if (ctx.io === "output")
|
|
json.additionalProperties = false;
|
|
} else if (def.catchall) {
|
|
json.additionalProperties = process2(def.catchall, ctx, {
|
|
...params,
|
|
path: [...params.path, "additionalProperties"]
|
|
});
|
|
}
|
|
};
|
|
var unionProcessor = (schema, ctx, json, params) => {
|
|
const def = schema._zod.def;
|
|
const isExclusive = def.inclusive === false;
|
|
const options = def.options.map((x, i) => process2(x, ctx, {
|
|
...params,
|
|
path: [...params.path, isExclusive ? "oneOf" : "anyOf", i]
|
|
}));
|
|
if (isExclusive) {
|
|
json.oneOf = options;
|
|
} else {
|
|
json.anyOf = options;
|
|
}
|
|
};
|
|
var intersectionProcessor = (schema, ctx, json, params) => {
|
|
const def = schema._zod.def;
|
|
const a = process2(def.left, ctx, {
|
|
...params,
|
|
path: [...params.path, "allOf", 0]
|
|
});
|
|
const b = process2(def.right, ctx, {
|
|
...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]
|
|
];
|
|
json.allOf = allOf;
|
|
};
|
|
var tupleProcessor = (schema, ctx, _json, params) => {
|
|
const json = _json;
|
|
const def = schema._zod.def;
|
|
json.type = "array";
|
|
const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items";
|
|
const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems";
|
|
const prefixItems = def.items.map((x, i) => process2(x, ctx, {
|
|
...params,
|
|
path: [...params.path, prefixPath, i]
|
|
}));
|
|
const rest = def.rest ? process2(def.rest, ctx, {
|
|
...params,
|
|
path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []]
|
|
}) : null;
|
|
if (ctx.target === "draft-2020-12") {
|
|
json.prefixItems = prefixItems;
|
|
if (rest) {
|
|
json.items = rest;
|
|
}
|
|
} else if (ctx.target === "openapi-3.0") {
|
|
json.items = {
|
|
anyOf: prefixItems
|
|
};
|
|
if (rest) {
|
|
json.items.anyOf.push(rest);
|
|
}
|
|
json.minItems = prefixItems.length;
|
|
if (!rest) {
|
|
json.maxItems = prefixItems.length;
|
|
}
|
|
} else {
|
|
json.items = prefixItems;
|
|
if (rest) {
|
|
json.additionalItems = rest;
|
|
}
|
|
}
|
|
const { minimum, maximum } = schema._zod.bag;
|
|
if (typeof minimum === "number")
|
|
json.minItems = minimum;
|
|
if (typeof maximum === "number")
|
|
json.maxItems = maximum;
|
|
};
|
|
var recordProcessor = (schema, ctx, _json, params) => {
|
|
const json = _json;
|
|
const def = schema._zod.def;
|
|
json.type = "object";
|
|
const keyType = def.keyType;
|
|
const keyBag = keyType._zod.bag;
|
|
const patterns = keyBag?.patterns;
|
|
if (def.mode === "loose" && patterns && patterns.size > 0) {
|
|
const valueSchema = process2(def.valueType, ctx, {
|
|
...params,
|
|
path: [...params.path, "patternProperties", "*"]
|
|
});
|
|
json.patternProperties = {};
|
|
for (const pattern of patterns) {
|
|
json.patternProperties[pattern.source] = valueSchema;
|
|
}
|
|
} else {
|
|
if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
|
|
json.propertyNames = process2(def.keyType, ctx, {
|
|
...params,
|
|
path: [...params.path, "propertyNames"]
|
|
});
|
|
}
|
|
json.additionalProperties = process2(def.valueType, ctx, {
|
|
...params,
|
|
path: [...params.path, "additionalProperties"]
|
|
});
|
|
}
|
|
const keyValues = keyType._zod.values;
|
|
if (keyValues) {
|
|
const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
|
|
if (validKeyValues.length > 0) {
|
|
json.required = validKeyValues;
|
|
}
|
|
}
|
|
};
|
|
var nullableProcessor = (schema, ctx, json, params) => {
|
|
const def = schema._zod.def;
|
|
const inner = process2(def.innerType, ctx, params);
|
|
const seen = ctx.seen.get(schema);
|
|
if (ctx.target === "openapi-3.0") {
|
|
seen.ref = def.innerType;
|
|
json.nullable = true;
|
|
} else {
|
|
json.anyOf = [inner, { type: "null" }];
|
|
}
|
|
};
|
|
var nonoptionalProcessor = (schema, ctx, _json, params) => {
|
|
const def = schema._zod.def;
|
|
process2(def.innerType, ctx, params);
|
|
const seen = ctx.seen.get(schema);
|
|
seen.ref = def.innerType;
|
|
};
|
|
var defaultProcessor = (schema, ctx, json, params) => {
|
|
const def = schema._zod.def;
|
|
process2(def.innerType, ctx, params);
|
|
const seen = ctx.seen.get(schema);
|
|
seen.ref = def.innerType;
|
|
json.default = JSON.parse(JSON.stringify(def.defaultValue));
|
|
};
|
|
var prefaultProcessor = (schema, ctx, json, params) => {
|
|
const def = schema._zod.def;
|
|
process2(def.innerType, ctx, params);
|
|
const seen = ctx.seen.get(schema);
|
|
seen.ref = def.innerType;
|
|
if (ctx.io === "input")
|
|
json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
|
|
};
|
|
var catchProcessor = (schema, ctx, json, params) => {
|
|
const def = schema._zod.def;
|
|
process2(def.innerType, ctx, params);
|
|
const seen = ctx.seen.get(schema);
|
|
seen.ref = def.innerType;
|
|
let catchValue;
|
|
try {
|
|
catchValue = def.catchValue(undefined);
|
|
} catch {
|
|
throw new Error("Dynamic catch values are not supported in JSON Schema");
|
|
}
|
|
json.default = catchValue;
|
|
};
|
|
var pipeProcessor = (schema, ctx, _json, params) => {
|
|
const def = schema._zod.def;
|
|
const inIsTransform = def.in._zod.traits.has("$ZodTransform");
|
|
const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out;
|
|
process2(innerType, ctx, params);
|
|
const seen = ctx.seen.get(schema);
|
|
seen.ref = innerType;
|
|
};
|
|
var readonlyProcessor = (schema, ctx, json, params) => {
|
|
const def = schema._zod.def;
|
|
process2(def.innerType, ctx, params);
|
|
const seen = ctx.seen.get(schema);
|
|
seen.ref = def.innerType;
|
|
json.readOnly = true;
|
|
};
|
|
var promiseProcessor = (schema, ctx, _json, params) => {
|
|
const def = schema._zod.def;
|
|
process2(def.innerType, ctx, params);
|
|
const seen = ctx.seen.get(schema);
|
|
seen.ref = def.innerType;
|
|
};
|
|
var optionalProcessor = (schema, ctx, _json, params) => {
|
|
const def = schema._zod.def;
|
|
process2(def.innerType, ctx, params);
|
|
const seen = ctx.seen.get(schema);
|
|
seen.ref = def.innerType;
|
|
};
|
|
var lazyProcessor = (schema, ctx, _json, params) => {
|
|
const innerType = schema._zod.innerType;
|
|
process2(innerType, ctx, params);
|
|
const seen = ctx.seen.get(schema);
|
|
seen.ref = innerType;
|
|
};
|
|
var allProcessors = {
|
|
string: stringProcessor,
|
|
number: numberProcessor,
|
|
boolean: booleanProcessor,
|
|
bigint: bigintProcessor,
|
|
symbol: symbolProcessor,
|
|
null: nullProcessor,
|
|
undefined: undefinedProcessor,
|
|
void: voidProcessor,
|
|
never: neverProcessor,
|
|
any: anyProcessor,
|
|
unknown: unknownProcessor,
|
|
date: dateProcessor,
|
|
enum: enumProcessor,
|
|
literal: literalProcessor,
|
|
nan: nanProcessor,
|
|
template_literal: templateLiteralProcessor,
|
|
file: fileProcessor,
|
|
success: successProcessor,
|
|
custom: customProcessor,
|
|
function: functionProcessor,
|
|
transform: transformProcessor,
|
|
map: mapProcessor,
|
|
set: setProcessor,
|
|
array: arrayProcessor,
|
|
object: objectProcessor,
|
|
union: unionProcessor,
|
|
intersection: intersectionProcessor,
|
|
tuple: tupleProcessor,
|
|
record: recordProcessor,
|
|
nullable: nullableProcessor,
|
|
nonoptional: nonoptionalProcessor,
|
|
default: defaultProcessor,
|
|
prefault: prefaultProcessor,
|
|
catch: catchProcessor,
|
|
pipe: pipeProcessor,
|
|
readonly: readonlyProcessor,
|
|
promise: promiseProcessor,
|
|
optional: optionalProcessor,
|
|
lazy: lazyProcessor
|
|
};
|
|
function toJSONSchema(input, params) {
|
|
if ("_idmap" in input) {
|
|
const registry = input;
|
|
const ctx = initializeContext({ ...params, processors: allProcessors });
|
|
const defs = {};
|
|
for (const entry of registry._idmap.entries()) {
|
|
const [_, schema] = entry;
|
|
process2(schema, ctx);
|
|
}
|
|
const schemas = {};
|
|
const external = {
|
|
registry,
|
|
uri: params?.uri,
|
|
defs
|
|
};
|
|
ctx.external = external;
|
|
for (const entry of registry._idmap.entries()) {
|
|
const [key, schema] = entry;
|
|
extractDefs(ctx, schema);
|
|
schemas[key] = finalize(ctx, schema);
|
|
}
|
|
if (Object.keys(defs).length > 0) {
|
|
const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
|
|
schemas.__shared = {
|
|
[defsSegment]: defs
|
|
};
|
|
}
|
|
return { schemas };
|
|
}
|
|
const ctx = initializeContext({ ...params, processors: allProcessors });
|
|
process2(input, ctx);
|
|
extractDefs(ctx, input);
|
|
return finalize(ctx, input);
|
|
}
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/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.type = def.type;
|
|
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 });
|
|
};
|
|
inst.with = inst.check;
|
|
inst.clone = (_def, params) => clone(inst, _def, params);
|
|
inst.brand = () => inst;
|
|
inst.register = (reg, meta) => {
|
|
reg.add(inst, meta);
|
|
return inst;
|
|
};
|
|
inst.apply = (fn) => fn(inst);
|
|
});
|
|
var ZodMiniObject = /* @__PURE__ */ $constructor("ZodMiniObject", (inst, def) => {
|
|
$ZodObject.init(inst, def);
|
|
ZodMiniType.init(inst, def);
|
|
defineLazy(inst, "shape", () => def.shape);
|
|
});
|
|
function object(shape, params) {
|
|
const def = {
|
|
type: "object",
|
|
shape: shape ?? {},
|
|
...normalizeParams(params)
|
|
};
|
|
return new ZodMiniObject(def);
|
|
}
|
|
// ../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_@cfworker+json-schema@4.1.1_supports-color@10.2.2_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
|
|
function isZ4Schema(s) {
|
|
const schema = s;
|
|
return !!schema._zod;
|
|
}
|
|
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 safeParse2(schema, data) {
|
|
if (isZ4Schema(schema)) {
|
|
const result = safeParse(schema, data);
|
|
return result;
|
|
}
|
|
const v3Schema = schema;
|
|
const result = v3Schema.safeParse(data);
|
|
return result;
|
|
}
|
|
async function safeParseAsync2(schema, data) {
|
|
if (isZ4Schema(schema)) {
|
|
const result = await safeParseAsync(schema, data);
|
|
return result;
|
|
}
|
|
const v3Schema = schema;
|
|
const result = await v3Schema.safeParseAsync(data);
|
|
return result;
|
|
}
|
|
function getObjectShape(schema) {
|
|
if (!schema)
|
|
return;
|
|
let rawShape;
|
|
if (isZ4Schema(schema)) {
|
|
const v4Schema = schema;
|
|
rawShape = v4Schema._zod?.def?.shape;
|
|
} else {
|
|
const v3Schema = schema;
|
|
rawShape = v3Schema.shape;
|
|
}
|
|
if (!rawShape)
|
|
return;
|
|
if (typeof rawShape === "function") {
|
|
try {
|
|
return rawShape();
|
|
} catch {
|
|
return;
|
|
}
|
|
}
|
|
return rawShape;
|
|
}
|
|
function normalizeObjectSchema(schema) {
|
|
if (!schema)
|
|
return;
|
|
if (typeof schema === "object") {
|
|
const asV3 = schema;
|
|
const asV4 = schema;
|
|
if (!asV3._def && !asV4._zod) {
|
|
const values = Object.values(schema);
|
|
if (values.length > 0 && values.every((v) => typeof v === "object" && v !== null && (v._def !== undefined || v._zod !== undefined || typeof v.parse === "function"))) {
|
|
return objectFromShape(schema);
|
|
}
|
|
}
|
|
}
|
|
if (isZ4Schema(schema)) {
|
|
const v4Schema = schema;
|
|
const def = v4Schema._zod?.def;
|
|
if (def && (def.type === "object" || def.shape !== undefined)) {
|
|
return schema;
|
|
}
|
|
} else {
|
|
const v3Schema = schema;
|
|
if (v3Schema.shape !== undefined) {
|
|
return schema;
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
function getDotPath(path) {
|
|
if (path.length === 0) {
|
|
return "object root";
|
|
}
|
|
return path.reduce((acc, seg, index) => {
|
|
if (index === 0) {
|
|
return String(seg);
|
|
}
|
|
if (typeof seg === "number") {
|
|
return `${acc}[${seg}]`;
|
|
}
|
|
return `${acc}.${seg}`;
|
|
}, "");
|
|
}
|
|
function getParseErrorMessage(error) {
|
|
if (error && typeof error === "object") {
|
|
if ("issues" in error && Array.isArray(error.issues) && error.issues.length > 0) {
|
|
return error.issues.map((i) => {
|
|
if (!i.path?.length) {
|
|
return i.message;
|
|
}
|
|
return `${i.message} at ${getDotPath(i.path)}`;
|
|
}).join(`
|
|
`);
|
|
}
|
|
if ("message" in error && typeof error.message === "string") {
|
|
return error.message;
|
|
}
|
|
try {
|
|
return JSON.stringify(error);
|
|
} catch {
|
|
return String(error);
|
|
}
|
|
}
|
|
return String(error);
|
|
}
|
|
function getSchemaDescription(schema) {
|
|
return schema.description;
|
|
}
|
|
function isSchemaOptional(schema) {
|
|
if (isZ4Schema(schema)) {
|
|
const v4Schema = schema;
|
|
return v4Schema._zod?.def?.type === "optional";
|
|
}
|
|
const v3Schema = schema;
|
|
if (typeof schema.isOptional === "function") {
|
|
return schema.isOptional();
|
|
}
|
|
return v3Schema._def?.typeName === "ZodOptional";
|
|
}
|
|
function getLiteralValue(schema) {
|
|
if (isZ4Schema(schema)) {
|
|
const v4Schema = schema;
|
|
const def = v4Schema._zod?.def;
|
|
if (def) {
|
|
if (def.value !== undefined)
|
|
return def.value;
|
|
if (Array.isArray(def.values) && def.values.length > 0) {
|
|
return def.values[0];
|
|
}
|
|
}
|
|
}
|
|
const v3Schema = schema;
|
|
const def = v3Schema._def;
|
|
if (def) {
|
|
if (def.value !== undefined)
|
|
return def.value;
|
|
if (Array.isArray(def.values) && def.values.length > 0) {
|
|
return def.values[0];
|
|
}
|
|
}
|
|
const directValue = schema.value;
|
|
if (directValue !== undefined)
|
|
return directValue;
|
|
return;
|
|
}
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js
|
|
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 date3(params) {
|
|
return _isoDate(ZodISODate, params);
|
|
}
|
|
var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
|
|
$ZodISOTime.init(inst, def);
|
|
ZodStringFormat.init(inst, def);
|
|
});
|
|
function time3(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@4.4.3/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)
|
|
},
|
|
flatten: {
|
|
value: (mapper) => flattenError(inst, mapper)
|
|
},
|
|
addIssue: {
|
|
value: (issue) => {
|
|
inst.issues.push(issue);
|
|
inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
|
|
}
|
|
},
|
|
addIssues: {
|
|
value: (issues) => {
|
|
inst.issues.push(...issues);
|
|
inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
|
|
}
|
|
},
|
|
isEmpty: {
|
|
get() {
|
|
return inst.issues.length === 0;
|
|
}
|
|
}
|
|
});
|
|
};
|
|
var ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, {
|
|
Parent: Error
|
|
});
|
|
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js
|
|
var parse4 = /* @__PURE__ */ _parse(ZodRealError);
|
|
var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
|
|
var safeParse3 = /* @__PURE__ */ _safeParse(ZodRealError);
|
|
var safeParseAsync3 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
|
|
var encode2 = /* @__PURE__ */ _encode(ZodRealError);
|
|
var decode3 = /* @__PURE__ */ _decode(ZodRealError);
|
|
var encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError);
|
|
var decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError);
|
|
var safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError);
|
|
var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError);
|
|
var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
|
|
var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
|
|
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js
|
|
var _installedGroups = /* @__PURE__ */ new WeakMap;
|
|
function _installLazyMethods(inst, group, methods) {
|
|
const proto = Object.getPrototypeOf(inst);
|
|
let installed = _installedGroups.get(proto);
|
|
if (!installed) {
|
|
installed = new Set;
|
|
_installedGroups.set(proto, installed);
|
|
}
|
|
if (installed.has(group))
|
|
return;
|
|
installed.add(group);
|
|
for (const key in methods) {
|
|
const fn = methods[key];
|
|
Object.defineProperty(proto, key, {
|
|
configurable: true,
|
|
enumerable: false,
|
|
get() {
|
|
const bound = fn.bind(this);
|
|
Object.defineProperty(this, key, {
|
|
configurable: true,
|
|
writable: true,
|
|
enumerable: true,
|
|
value: bound
|
|
});
|
|
return bound;
|
|
},
|
|
set(v) {
|
|
Object.defineProperty(this, key, {
|
|
configurable: true,
|
|
writable: true,
|
|
enumerable: true,
|
|
value: v
|
|
});
|
|
}
|
|
});
|
|
}
|
|
}
|
|
var ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
|
|
$ZodType.init(inst, def);
|
|
Object.assign(inst["~standard"], {
|
|
jsonSchema: {
|
|
input: createStandardJSONSchemaMethod(inst, "input"),
|
|
output: createStandardJSONSchemaMethod(inst, "output")
|
|
}
|
|
});
|
|
inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
|
|
inst.def = def;
|
|
inst.type = def.type;
|
|
Object.defineProperty(inst, "_def", { value: def });
|
|
inst.parse = (data, params) => parse4(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.encode = (data, params) => encode2(inst, data, params);
|
|
inst.decode = (data, params) => decode3(inst, data, params);
|
|
inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params);
|
|
inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params);
|
|
inst.safeEncode = (data, params) => safeEncode2(inst, data, params);
|
|
inst.safeDecode = (data, params) => safeDecode2(inst, data, params);
|
|
inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params);
|
|
inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params);
|
|
_installLazyMethods(inst, "ZodType", {
|
|
check(...chks) {
|
|
const def = this.def;
|
|
return this.clone(mergeDefs(def, {
|
|
checks: [
|
|
...def.checks ?? [],
|
|
...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
|
|
]
|
|
}), { parent: true });
|
|
},
|
|
with(...chks) {
|
|
return this.check(...chks);
|
|
},
|
|
clone(def, params) {
|
|
return clone(this, def, params);
|
|
},
|
|
brand() {
|
|
return this;
|
|
},
|
|
register(reg, meta) {
|
|
reg.add(this, meta);
|
|
return this;
|
|
},
|
|
refine(check, params) {
|
|
return this.check(refine(check, params));
|
|
},
|
|
superRefine(refinement, params) {
|
|
return this.check(superRefine(refinement, params));
|
|
},
|
|
overwrite(fn) {
|
|
return this.check(_overwrite(fn));
|
|
},
|
|
optional() {
|
|
return optional2(this);
|
|
},
|
|
exactOptional() {
|
|
return exactOptional(this);
|
|
},
|
|
nullable() {
|
|
return nullable(this);
|
|
},
|
|
nullish() {
|
|
return optional2(nullable(this));
|
|
},
|
|
nonoptional(params) {
|
|
return nonoptional(this, params);
|
|
},
|
|
array() {
|
|
return array4(this);
|
|
},
|
|
or(arg) {
|
|
return union8([this, arg]);
|
|
},
|
|
and(arg) {
|
|
return intersection3(this, arg);
|
|
},
|
|
transform(tx) {
|
|
return pipe2(this, transform3(tx));
|
|
},
|
|
default(d) {
|
|
return _default(this, d);
|
|
},
|
|
prefault(d) {
|
|
return prefault(this, d);
|
|
},
|
|
catch(params) {
|
|
return _catch2(this, params);
|
|
},
|
|
pipe(target) {
|
|
return pipe2(this, target);
|
|
},
|
|
readonly() {
|
|
return readonly(this);
|
|
},
|
|
describe(description) {
|
|
const cl = this.clone();
|
|
globalRegistry.add(cl, { description });
|
|
return cl;
|
|
},
|
|
meta(...args) {
|
|
if (args.length === 0)
|
|
return globalRegistry.get(this);
|
|
const cl = this.clone();
|
|
globalRegistry.add(cl, args[0]);
|
|
return cl;
|
|
},
|
|
isOptional() {
|
|
return this.safeParse(undefined).success;
|
|
},
|
|
isNullable() {
|
|
return this.safeParse(null).success;
|
|
},
|
|
apply(fn) {
|
|
return fn(this);
|
|
}
|
|
});
|
|
Object.defineProperty(inst, "description", {
|
|
get() {
|
|
return globalRegistry.get(inst)?.description;
|
|
},
|
|
configurable: true
|
|
});
|
|
return inst;
|
|
});
|
|
var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
|
|
$ZodString.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params);
|
|
const bag = inst._zod.bag;
|
|
inst.format = bag.format ?? null;
|
|
inst.minLength = bag.minimum ?? null;
|
|
inst.maxLength = bag.maximum ?? null;
|
|
_installLazyMethods(inst, "_ZodString", {
|
|
regex(...args) {
|
|
return this.check(_regex(...args));
|
|
},
|
|
includes(...args) {
|
|
return this.check(_includes(...args));
|
|
},
|
|
startsWith(...args) {
|
|
return this.check(_startsWith(...args));
|
|
},
|
|
endsWith(...args) {
|
|
return this.check(_endsWith(...args));
|
|
},
|
|
min(...args) {
|
|
return this.check(_minLength(...args));
|
|
},
|
|
max(...args) {
|
|
return this.check(_maxLength(...args));
|
|
},
|
|
length(...args) {
|
|
return this.check(_length(...args));
|
|
},
|
|
nonempty(...args) {
|
|
return this.check(_minLength(1, ...args));
|
|
},
|
|
lowercase(params) {
|
|
return this.check(_lowercase(params));
|
|
},
|
|
uppercase(params) {
|
|
return this.check(_uppercase(params));
|
|
},
|
|
trim() {
|
|
return this.check(_trim());
|
|
},
|
|
normalize(...args) {
|
|
return this.check(_normalize(...args));
|
|
},
|
|
toLowerCase() {
|
|
return this.check(_toLowerCase());
|
|
},
|
|
toUpperCase() {
|
|
return this.check(_toUpperCase());
|
|
},
|
|
slugify() {
|
|
return this.check(_slugify());
|
|
}
|
|
});
|
|
});
|
|
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(date3(params));
|
|
inst.time = (params) => inst.check(time3(params));
|
|
inst.duration = (params) => inst.check(duration2(params));
|
|
});
|
|
function string3(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._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params);
|
|
_installLazyMethods(inst, "ZodNumber", {
|
|
gt(value, params) {
|
|
return this.check(_gt(value, params));
|
|
},
|
|
gte(value, params) {
|
|
return this.check(_gte(value, params));
|
|
},
|
|
min(value, params) {
|
|
return this.check(_gte(value, params));
|
|
},
|
|
lt(value, params) {
|
|
return this.check(_lt(value, params));
|
|
},
|
|
lte(value, params) {
|
|
return this.check(_lte(value, params));
|
|
},
|
|
max(value, params) {
|
|
return this.check(_lte(value, params));
|
|
},
|
|
int(params) {
|
|
return this.check(int(params));
|
|
},
|
|
safe(params) {
|
|
return this.check(int(params));
|
|
},
|
|
positive(params) {
|
|
return this.check(_gt(0, params));
|
|
},
|
|
nonnegative(params) {
|
|
return this.check(_gte(0, params));
|
|
},
|
|
negative(params) {
|
|
return this.check(_lt(0, params));
|
|
},
|
|
nonpositive(params) {
|
|
return this.check(_lte(0, params));
|
|
},
|
|
multipleOf(value, params) {
|
|
return this.check(_multipleOf(value, params));
|
|
},
|
|
step(value, params) {
|
|
return this.check(_multipleOf(value, params));
|
|
},
|
|
finite() {
|
|
return this;
|
|
}
|
|
});
|
|
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 number5(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);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params);
|
|
});
|
|
function boolean2(params) {
|
|
return _boolean(ZodBoolean2, params);
|
|
}
|
|
var ZodNull2 = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => {
|
|
$ZodNull.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params);
|
|
});
|
|
function _null3(params) {
|
|
return _null2(ZodNull2, params);
|
|
}
|
|
var ZodUnknown2 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
|
|
$ZodUnknown.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params);
|
|
});
|
|
function unknown() {
|
|
return _unknown(ZodUnknown2);
|
|
}
|
|
var ZodNever2 = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
|
|
$ZodNever.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params);
|
|
});
|
|
function never6(params) {
|
|
return _never2(ZodNever2, params);
|
|
}
|
|
var ZodArray2 = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
|
|
$ZodArray.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params);
|
|
inst.element = def.element;
|
|
_installLazyMethods(inst, "ZodArray", {
|
|
min(n, params) {
|
|
return this.check(_minLength(n, params));
|
|
},
|
|
nonempty(params) {
|
|
return this.check(_minLength(1, params));
|
|
},
|
|
max(n, params) {
|
|
return this.check(_maxLength(n, params));
|
|
},
|
|
length(n, params) {
|
|
return this.check(_length(n, params));
|
|
},
|
|
unwrap() {
|
|
return this.element;
|
|
}
|
|
});
|
|
});
|
|
function array4(element, params) {
|
|
return _array(ZodArray2, element, params);
|
|
}
|
|
var ZodObject2 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
|
|
$ZodObjectJIT.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params);
|
|
defineLazy(inst, "shape", () => {
|
|
return def.shape;
|
|
});
|
|
_installLazyMethods(inst, "ZodObject", {
|
|
keyof() {
|
|
return _enum(Object.keys(this._zod.def.shape));
|
|
},
|
|
catchall(catchall) {
|
|
return this.clone({ ...this._zod.def, catchall });
|
|
},
|
|
passthrough() {
|
|
return this.clone({ ...this._zod.def, catchall: unknown() });
|
|
},
|
|
loose() {
|
|
return this.clone({ ...this._zod.def, catchall: unknown() });
|
|
},
|
|
strict() {
|
|
return this.clone({ ...this._zod.def, catchall: never6() });
|
|
},
|
|
strip() {
|
|
return this.clone({ ...this._zod.def, catchall: undefined });
|
|
},
|
|
extend(incoming) {
|
|
return extend4(this, incoming);
|
|
},
|
|
safeExtend(incoming) {
|
|
return safeExtend(this, incoming);
|
|
},
|
|
merge(other) {
|
|
return merge8(this, other);
|
|
},
|
|
pick(mask) {
|
|
return pick4(this, mask);
|
|
},
|
|
omit(mask) {
|
|
return omit5(this, mask);
|
|
},
|
|
partial(...args) {
|
|
return partial2(ZodOptional2, this, args[0]);
|
|
},
|
|
required(...args) {
|
|
return required2(ZodNonOptional, this, args[0]);
|
|
}
|
|
});
|
|
});
|
|
function object2(shape, params) {
|
|
const def = {
|
|
type: "object",
|
|
shape: shape ?? {},
|
|
...normalizeParams(params)
|
|
};
|
|
return new ZodObject2(def);
|
|
}
|
|
function looseObject(shape, params) {
|
|
return new ZodObject2({
|
|
type: "object",
|
|
shape,
|
|
catchall: unknown(),
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
var ZodUnion2 = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
|
|
$ZodUnion.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params);
|
|
inst.options = def.options;
|
|
});
|
|
function union8(options, params) {
|
|
return new ZodUnion2({
|
|
type: "union",
|
|
options,
|
|
...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,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
var ZodIntersection2 = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
|
|
$ZodIntersection.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params);
|
|
});
|
|
function intersection3(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._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params);
|
|
inst.keyType = def.keyType;
|
|
inst.valueType = def.valueType;
|
|
});
|
|
function record2(keyType, valueType, params) {
|
|
if (!valueType || !valueType._zod) {
|
|
return new ZodRecord2({
|
|
type: "record",
|
|
keyType: string3(),
|
|
valueType: keyType,
|
|
...normalizeParams(valueType)
|
|
});
|
|
}
|
|
return new ZodRecord2({
|
|
type: "record",
|
|
keyType,
|
|
valueType,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
var ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
|
|
$ZodEnum.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params);
|
|
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`);
|
|
}
|
|
return new ZodEnum2({
|
|
...def,
|
|
checks: [],
|
|
...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`);
|
|
}
|
|
return new ZodEnum2({
|
|
...def,
|
|
checks: [],
|
|
...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,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
var ZodLiteral2 = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
|
|
$ZodLiteral.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params);
|
|
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];
|
|
}
|
|
});
|
|
});
|
|
function literal(value, params) {
|
|
return new ZodLiteral2({
|
|
type: "literal",
|
|
values: Array.isArray(value) ? value : [value],
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
|
|
$ZodTransform.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params);
|
|
inst._zod.parse = (payload, _ctx) => {
|
|
if (_ctx.direction === "backward") {
|
|
throw new $ZodEncodeError(inst.constructor.name);
|
|
}
|
|
payload.addIssue = (issue2) => {
|
|
if (typeof issue2 === "string") {
|
|
payload.issues.push(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);
|
|
payload.issues.push(issue(_issue));
|
|
}
|
|
};
|
|
const output = def.transform(payload.value, payload);
|
|
if (output instanceof Promise) {
|
|
return output.then((output) => {
|
|
payload.value = output;
|
|
payload.fallback = true;
|
|
return payload;
|
|
});
|
|
}
|
|
payload.value = output;
|
|
payload.fallback = true;
|
|
return payload;
|
|
};
|
|
});
|
|
function transform3(fn) {
|
|
return new ZodTransform({
|
|
type: "transform",
|
|
transform: fn
|
|
});
|
|
}
|
|
var ZodOptional2 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
|
|
$ZodOptional.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
|
|
inst.unwrap = () => inst._zod.def.innerType;
|
|
});
|
|
function optional2(innerType) {
|
|
return new ZodOptional2({
|
|
type: "optional",
|
|
innerType
|
|
});
|
|
}
|
|
var ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => {
|
|
$ZodExactOptional.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
|
|
inst.unwrap = () => inst._zod.def.innerType;
|
|
});
|
|
function exactOptional(innerType) {
|
|
return new ZodExactOptional({
|
|
type: "optional",
|
|
innerType
|
|
});
|
|
}
|
|
var ZodNullable2 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
|
|
$ZodNullable.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params);
|
|
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._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params);
|
|
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() : shallowClone(defaultValue);
|
|
}
|
|
});
|
|
}
|
|
var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
|
|
$ZodPrefault.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params);
|
|
inst.unwrap = () => inst._zod.def.innerType;
|
|
});
|
|
function prefault(innerType, defaultValue) {
|
|
return new ZodPrefault({
|
|
type: "prefault",
|
|
innerType,
|
|
get defaultValue() {
|
|
return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
|
|
}
|
|
});
|
|
}
|
|
var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
|
|
$ZodNonOptional.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params);
|
|
inst.unwrap = () => inst._zod.def.innerType;
|
|
});
|
|
function nonoptional(innerType, params) {
|
|
return new ZodNonOptional({
|
|
type: "nonoptional",
|
|
innerType,
|
|
...normalizeParams(params)
|
|
});
|
|
}
|
|
var ZodCatch2 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
|
|
$ZodCatch.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params);
|
|
inst.unwrap = () => inst._zod.def.innerType;
|
|
inst.removeCatch = inst.unwrap;
|
|
});
|
|
function _catch2(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._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params);
|
|
inst.in = def.in;
|
|
inst.out = def.out;
|
|
});
|
|
function pipe2(in_, out) {
|
|
return new ZodPipe({
|
|
type: "pipe",
|
|
in: in_,
|
|
out
|
|
});
|
|
}
|
|
var ZodPreprocess = /* @__PURE__ */ $constructor("ZodPreprocess", (inst, def) => {
|
|
ZodPipe.init(inst, def);
|
|
$ZodPreprocess.init(inst, def);
|
|
});
|
|
var ZodReadonly2 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
|
|
$ZodReadonly.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params);
|
|
inst.unwrap = () => inst._zod.def.innerType;
|
|
});
|
|
function readonly(innerType) {
|
|
return new ZodReadonly2({
|
|
type: "readonly",
|
|
innerType
|
|
});
|
|
}
|
|
var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
|
|
$ZodCustom.init(inst, def);
|
|
ZodType2.init(inst, def);
|
|
inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params);
|
|
});
|
|
function custom3(fn, _params) {
|
|
return _custom(ZodCustom, fn ?? (() => true), _params);
|
|
}
|
|
function refine(fn, _params = {}) {
|
|
return _refine(ZodCustom, fn, _params);
|
|
}
|
|
function superRefine(fn, params) {
|
|
return _superRefine(fn, params);
|
|
}
|
|
function preprocess(fn, schema) {
|
|
return new ZodPreprocess({
|
|
type: "pipe",
|
|
in: transform3(fn),
|
|
out: schema
|
|
});
|
|
}
|
|
// ../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js
|
|
config(en_default2());
|
|
|
|
// ../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_@cfworker+json-schema@4.1.1_supports-color@10.2.2_zod@4.4.3/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 = custom3((v) => v !== null && (typeof v === "object" || typeof v === "function"));
|
|
var ProgressTokenSchema = union8([string3(), number5().int()]);
|
|
var CursorSchema = string3();
|
|
var TaskCreationParamsSchema = looseObject({
|
|
ttl: number5().optional(),
|
|
pollInterval: number5().optional()
|
|
});
|
|
var TaskMetadataSchema = object2({
|
|
ttl: number5().optional()
|
|
});
|
|
var RelatedTaskMetadataSchema = object2({
|
|
taskId: string3()
|
|
});
|
|
var RequestMetaSchema = looseObject({
|
|
progressToken: ProgressTokenSchema.optional(),
|
|
[RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
|
|
});
|
|
var BaseRequestParamsSchema = object2({
|
|
_meta: RequestMetaSchema.optional()
|
|
});
|
|
var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
task: TaskMetadataSchema.optional()
|
|
});
|
|
var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;
|
|
var RequestSchema = object2({
|
|
method: string3(),
|
|
params: BaseRequestParamsSchema.loose().optional()
|
|
});
|
|
var NotificationsParamsSchema = object2({
|
|
_meta: RequestMetaSchema.optional()
|
|
});
|
|
var NotificationSchema = object2({
|
|
method: string3(),
|
|
params: NotificationsParamsSchema.loose().optional()
|
|
});
|
|
var ResultSchema = looseObject({
|
|
_meta: RequestMetaSchema.optional()
|
|
});
|
|
var RequestIdSchema = union8([string3(), number5().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(ErrorCode) {
|
|
ErrorCode[ErrorCode["ConnectionClosed"] = -32000] = "ConnectionClosed";
|
|
ErrorCode[ErrorCode["RequestTimeout"] = -32001] = "RequestTimeout";
|
|
ErrorCode[ErrorCode["ParseError"] = -32700] = "ParseError";
|
|
ErrorCode[ErrorCode["InvalidRequest"] = -32600] = "InvalidRequest";
|
|
ErrorCode[ErrorCode["MethodNotFound"] = -32601] = "MethodNotFound";
|
|
ErrorCode[ErrorCode["InvalidParams"] = -32602] = "InvalidParams";
|
|
ErrorCode[ErrorCode["InternalError"] = -32603] = "InternalError";
|
|
ErrorCode[ErrorCode["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
|
|
})(ErrorCode || (ErrorCode = {}));
|
|
var JSONRPCErrorResponseSchema = object2({
|
|
jsonrpc: literal(JSONRPC_VERSION),
|
|
id: RequestIdSchema.optional(),
|
|
error: object2({
|
|
code: number5().int(),
|
|
message: string3(),
|
|
data: unknown().optional()
|
|
})
|
|
}).strict();
|
|
var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;
|
|
var JSONRPCMessageSchema = union8([
|
|
JSONRPCRequestSchema,
|
|
JSONRPCNotificationSchema,
|
|
JSONRPCResultResponseSchema,
|
|
JSONRPCErrorResponseSchema
|
|
]);
|
|
var JSONRPCResponseSchema = union8([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
|
|
var EmptyResultSchema = ResultSchema.strict();
|
|
var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
|
|
requestId: RequestIdSchema.optional(),
|
|
reason: string3().optional()
|
|
});
|
|
var CancelledNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/cancelled"),
|
|
params: CancelledNotificationParamsSchema
|
|
});
|
|
var IconSchema = object2({
|
|
src: string3(),
|
|
mimeType: string3().optional(),
|
|
sizes: array4(string3()).optional(),
|
|
theme: _enum(["light", "dark"]).optional()
|
|
});
|
|
var IconsSchema = object2({
|
|
icons: array4(IconSchema).optional()
|
|
});
|
|
var BaseMetadataSchema = object2({
|
|
name: string3(),
|
|
title: string3().optional()
|
|
});
|
|
var ImplementationSchema = BaseMetadataSchema.extend({
|
|
...BaseMetadataSchema.shape,
|
|
...IconsSchema.shape,
|
|
version: string3(),
|
|
websiteUrl: string3().optional(),
|
|
description: string3().optional()
|
|
});
|
|
var FormElicitationCapabilitySchema = intersection3(object2({
|
|
applyDefaults: boolean2().optional()
|
|
}), record2(string3(), unknown()));
|
|
var ElicitationCapabilitySchema = preprocess((value) => {
|
|
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
if (Object.keys(value).length === 0) {
|
|
return { form: {} };
|
|
}
|
|
}
|
|
return value;
|
|
}, intersection3(object2({
|
|
form: FormElicitationCapabilitySchema.optional(),
|
|
url: AssertObjectSchema.optional()
|
|
}), record2(string3(), unknown()).optional()));
|
|
var ClientTasksCapabilitySchema = looseObject({
|
|
list: AssertObjectSchema.optional(),
|
|
cancel: AssertObjectSchema.optional(),
|
|
requests: looseObject({
|
|
sampling: looseObject({
|
|
createMessage: AssertObjectSchema.optional()
|
|
}).optional(),
|
|
elicitation: looseObject({
|
|
create: AssertObjectSchema.optional()
|
|
}).optional()
|
|
}).optional()
|
|
});
|
|
var ServerTasksCapabilitySchema = looseObject({
|
|
list: AssertObjectSchema.optional(),
|
|
cancel: AssertObjectSchema.optional(),
|
|
requests: looseObject({
|
|
tools: looseObject({
|
|
call: AssertObjectSchema.optional()
|
|
}).optional()
|
|
}).optional()
|
|
});
|
|
var ClientCapabilitiesSchema = object2({
|
|
experimental: record2(string3(), AssertObjectSchema).optional(),
|
|
sampling: object2({
|
|
context: AssertObjectSchema.optional(),
|
|
tools: AssertObjectSchema.optional()
|
|
}).optional(),
|
|
elicitation: ElicitationCapabilitySchema.optional(),
|
|
roots: object2({
|
|
listChanged: boolean2().optional()
|
|
}).optional(),
|
|
tasks: ClientTasksCapabilitySchema.optional(),
|
|
extensions: record2(string3(), AssertObjectSchema).optional()
|
|
});
|
|
var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
protocolVersion: string3(),
|
|
capabilities: ClientCapabilitiesSchema,
|
|
clientInfo: ImplementationSchema
|
|
});
|
|
var InitializeRequestSchema = RequestSchema.extend({
|
|
method: literal("initialize"),
|
|
params: InitializeRequestParamsSchema
|
|
});
|
|
var ServerCapabilitiesSchema = object2({
|
|
experimental: record2(string3(), AssertObjectSchema).optional(),
|
|
logging: AssertObjectSchema.optional(),
|
|
completions: AssertObjectSchema.optional(),
|
|
prompts: object2({
|
|
listChanged: boolean2().optional()
|
|
}).optional(),
|
|
resources: object2({
|
|
subscribe: boolean2().optional(),
|
|
listChanged: boolean2().optional()
|
|
}).optional(),
|
|
tools: object2({
|
|
listChanged: boolean2().optional()
|
|
}).optional(),
|
|
tasks: ServerTasksCapabilitySchema.optional(),
|
|
extensions: record2(string3(), AssertObjectSchema).optional()
|
|
});
|
|
var InitializeResultSchema = ResultSchema.extend({
|
|
protocolVersion: string3(),
|
|
capabilities: ServerCapabilitiesSchema,
|
|
serverInfo: ImplementationSchema,
|
|
instructions: string3().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({
|
|
progress: number5(),
|
|
total: optional2(number5()),
|
|
message: optional2(string3())
|
|
});
|
|
var ProgressNotificationParamsSchema = object2({
|
|
...NotificationsParamsSchema.shape,
|
|
...ProgressSchema.shape,
|
|
progressToken: ProgressTokenSchema
|
|
});
|
|
var ProgressNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/progress"),
|
|
params: ProgressNotificationParamsSchema
|
|
});
|
|
var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
cursor: CursorSchema.optional()
|
|
});
|
|
var PaginatedRequestSchema = RequestSchema.extend({
|
|
params: PaginatedRequestParamsSchema.optional()
|
|
});
|
|
var PaginatedResultSchema = ResultSchema.extend({
|
|
nextCursor: CursorSchema.optional()
|
|
});
|
|
var TaskStatusSchema = _enum(["working", "input_required", "completed", "failed", "cancelled"]);
|
|
var TaskSchema = object2({
|
|
taskId: string3(),
|
|
status: TaskStatusSchema,
|
|
ttl: union8([number5(), _null3()]),
|
|
createdAt: string3(),
|
|
lastUpdatedAt: string3(),
|
|
pollInterval: optional2(number5()),
|
|
statusMessage: optional2(string3())
|
|
});
|
|
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: string3()
|
|
})
|
|
});
|
|
var GetTaskResultSchema = ResultSchema.merge(TaskSchema);
|
|
var GetTaskPayloadRequestSchema = RequestSchema.extend({
|
|
method: literal("tasks/result"),
|
|
params: BaseRequestParamsSchema.extend({
|
|
taskId: string3()
|
|
})
|
|
});
|
|
var GetTaskPayloadResultSchema = ResultSchema.loose();
|
|
var ListTasksRequestSchema = PaginatedRequestSchema.extend({
|
|
method: literal("tasks/list")
|
|
});
|
|
var ListTasksResultSchema = PaginatedResultSchema.extend({
|
|
tasks: array4(TaskSchema)
|
|
});
|
|
var CancelTaskRequestSchema = RequestSchema.extend({
|
|
method: literal("tasks/cancel"),
|
|
params: BaseRequestParamsSchema.extend({
|
|
taskId: string3()
|
|
})
|
|
});
|
|
var CancelTaskResultSchema = ResultSchema.merge(TaskSchema);
|
|
var ResourceContentsSchema = object2({
|
|
uri: string3(),
|
|
mimeType: optional2(string3()),
|
|
_meta: record2(string3(), unknown()).optional()
|
|
});
|
|
var TextResourceContentsSchema = ResourceContentsSchema.extend({
|
|
text: string3()
|
|
});
|
|
var Base64Schema = string3().refine((val) => {
|
|
try {
|
|
atob(val);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}, { message: "Invalid Base64 string" });
|
|
var BlobResourceContentsSchema = ResourceContentsSchema.extend({
|
|
blob: Base64Schema
|
|
});
|
|
var RoleSchema = _enum(["user", "assistant"]);
|
|
var AnnotationsSchema = object2({
|
|
audience: array4(RoleSchema).optional(),
|
|
priority: number5().min(0).max(1).optional(),
|
|
lastModified: datetime2({ offset: true }).optional()
|
|
});
|
|
var ResourceSchema = object2({
|
|
...BaseMetadataSchema.shape,
|
|
...IconsSchema.shape,
|
|
uri: string3(),
|
|
description: optional2(string3()),
|
|
mimeType: optional2(string3()),
|
|
size: optional2(number5()),
|
|
annotations: AnnotationsSchema.optional(),
|
|
_meta: optional2(looseObject({}))
|
|
});
|
|
var ResourceTemplateSchema = object2({
|
|
...BaseMetadataSchema.shape,
|
|
...IconsSchema.shape,
|
|
uriTemplate: string3(),
|
|
description: optional2(string3()),
|
|
mimeType: optional2(string3()),
|
|
annotations: AnnotationsSchema.optional(),
|
|
_meta: optional2(looseObject({}))
|
|
});
|
|
var ListResourcesRequestSchema = PaginatedRequestSchema.extend({
|
|
method: literal("resources/list")
|
|
});
|
|
var ListResourcesResultSchema = PaginatedResultSchema.extend({
|
|
resources: array4(ResourceSchema)
|
|
});
|
|
var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
|
|
method: literal("resources/templates/list")
|
|
});
|
|
var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
|
|
resourceTemplates: array4(ResourceTemplateSchema)
|
|
});
|
|
var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
uri: string3()
|
|
});
|
|
var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;
|
|
var ReadResourceRequestSchema = RequestSchema.extend({
|
|
method: literal("resources/read"),
|
|
params: ReadResourceRequestParamsSchema
|
|
});
|
|
var ReadResourceResultSchema = ResultSchema.extend({
|
|
contents: array4(union8([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({
|
|
uri: string3()
|
|
});
|
|
var ResourceUpdatedNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/resources/updated"),
|
|
params: ResourceUpdatedNotificationParamsSchema
|
|
});
|
|
var PromptArgumentSchema = object2({
|
|
name: string3(),
|
|
description: optional2(string3()),
|
|
required: optional2(boolean2())
|
|
});
|
|
var PromptSchema = object2({
|
|
...BaseMetadataSchema.shape,
|
|
...IconsSchema.shape,
|
|
description: optional2(string3()),
|
|
arguments: optional2(array4(PromptArgumentSchema)),
|
|
_meta: optional2(looseObject({}))
|
|
});
|
|
var ListPromptsRequestSchema = PaginatedRequestSchema.extend({
|
|
method: literal("prompts/list")
|
|
});
|
|
var ListPromptsResultSchema = PaginatedResultSchema.extend({
|
|
prompts: array4(PromptSchema)
|
|
});
|
|
var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
name: string3(),
|
|
arguments: record2(string3(), string3()).optional()
|
|
});
|
|
var GetPromptRequestSchema = RequestSchema.extend({
|
|
method: literal("prompts/get"),
|
|
params: GetPromptRequestParamsSchema
|
|
});
|
|
var TextContentSchema = object2({
|
|
type: literal("text"),
|
|
text: string3(),
|
|
annotations: AnnotationsSchema.optional(),
|
|
_meta: record2(string3(), unknown()).optional()
|
|
});
|
|
var ImageContentSchema = object2({
|
|
type: literal("image"),
|
|
data: Base64Schema,
|
|
mimeType: string3(),
|
|
annotations: AnnotationsSchema.optional(),
|
|
_meta: record2(string3(), unknown()).optional()
|
|
});
|
|
var AudioContentSchema = object2({
|
|
type: literal("audio"),
|
|
data: Base64Schema,
|
|
mimeType: string3(),
|
|
annotations: AnnotationsSchema.optional(),
|
|
_meta: record2(string3(), unknown()).optional()
|
|
});
|
|
var ToolUseContentSchema = object2({
|
|
type: literal("tool_use"),
|
|
name: string3(),
|
|
id: string3(),
|
|
input: record2(string3(), unknown()),
|
|
_meta: record2(string3(), unknown()).optional()
|
|
});
|
|
var EmbeddedResourceSchema = object2({
|
|
type: literal("resource"),
|
|
resource: union8([TextResourceContentsSchema, BlobResourceContentsSchema]),
|
|
annotations: AnnotationsSchema.optional(),
|
|
_meta: record2(string3(), unknown()).optional()
|
|
});
|
|
var ResourceLinkSchema = ResourceSchema.extend({
|
|
type: literal("resource_link")
|
|
});
|
|
var ContentBlockSchema = union8([
|
|
TextContentSchema,
|
|
ImageContentSchema,
|
|
AudioContentSchema,
|
|
ResourceLinkSchema,
|
|
EmbeddedResourceSchema
|
|
]);
|
|
var PromptMessageSchema = object2({
|
|
role: RoleSchema,
|
|
content: ContentBlockSchema
|
|
});
|
|
var GetPromptResultSchema = ResultSchema.extend({
|
|
description: string3().optional(),
|
|
messages: array4(PromptMessageSchema)
|
|
});
|
|
var PromptListChangedNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/prompts/list_changed"),
|
|
params: NotificationsParamsSchema.optional()
|
|
});
|
|
var ToolAnnotationsSchema = object2({
|
|
title: string3().optional(),
|
|
readOnlyHint: boolean2().optional(),
|
|
destructiveHint: boolean2().optional(),
|
|
idempotentHint: boolean2().optional(),
|
|
openWorldHint: boolean2().optional()
|
|
});
|
|
var ToolExecutionSchema = object2({
|
|
taskSupport: _enum(["required", "optional", "forbidden"]).optional()
|
|
});
|
|
var ToolSchema = object2({
|
|
...BaseMetadataSchema.shape,
|
|
...IconsSchema.shape,
|
|
description: string3().optional(),
|
|
inputSchema: object2({
|
|
type: literal("object"),
|
|
properties: record2(string3(), AssertObjectSchema).optional(),
|
|
required: array4(string3()).optional()
|
|
}).catchall(unknown()),
|
|
outputSchema: object2({
|
|
type: literal("object"),
|
|
properties: record2(string3(), AssertObjectSchema).optional(),
|
|
required: array4(string3()).optional()
|
|
}).catchall(unknown()).optional(),
|
|
annotations: ToolAnnotationsSchema.optional(),
|
|
execution: ToolExecutionSchema.optional(),
|
|
_meta: record2(string3(), unknown()).optional()
|
|
});
|
|
var ListToolsRequestSchema = PaginatedRequestSchema.extend({
|
|
method: literal("tools/list")
|
|
});
|
|
var ListToolsResultSchema = PaginatedResultSchema.extend({
|
|
tools: array4(ToolSchema)
|
|
});
|
|
var CallToolResultSchema = ResultSchema.extend({
|
|
content: array4(ContentBlockSchema).default([]),
|
|
structuredContent: record2(string3(), unknown()).optional(),
|
|
isError: boolean2().optional()
|
|
});
|
|
var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({
|
|
toolResult: unknown()
|
|
}));
|
|
var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
|
|
name: string3(),
|
|
arguments: record2(string3(), 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({
|
|
autoRefresh: boolean2().default(true),
|
|
debounceMs: number5().int().nonnegative().default(300)
|
|
});
|
|
var LoggingLevelSchema = _enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
|
|
var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
level: LoggingLevelSchema
|
|
});
|
|
var SetLevelRequestSchema = RequestSchema.extend({
|
|
method: literal("logging/setLevel"),
|
|
params: SetLevelRequestParamsSchema
|
|
});
|
|
var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({
|
|
level: LoggingLevelSchema,
|
|
logger: string3().optional(),
|
|
data: unknown()
|
|
});
|
|
var LoggingMessageNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/message"),
|
|
params: LoggingMessageNotificationParamsSchema
|
|
});
|
|
var ModelHintSchema = object2({
|
|
name: string3().optional()
|
|
});
|
|
var ModelPreferencesSchema = object2({
|
|
hints: array4(ModelHintSchema).optional(),
|
|
costPriority: number5().min(0).max(1).optional(),
|
|
speedPriority: number5().min(0).max(1).optional(),
|
|
intelligencePriority: number5().min(0).max(1).optional()
|
|
});
|
|
var ToolChoiceSchema = object2({
|
|
mode: _enum(["auto", "required", "none"]).optional()
|
|
});
|
|
var ToolResultContentSchema = object2({
|
|
type: literal("tool_result"),
|
|
toolUseId: string3().describe("The unique identifier for the corresponding tool call."),
|
|
content: array4(ContentBlockSchema).default([]),
|
|
structuredContent: object2({}).loose().optional(),
|
|
isError: boolean2().optional(),
|
|
_meta: record2(string3(), unknown()).optional()
|
|
});
|
|
var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);
|
|
var SamplingMessageContentBlockSchema = discriminatedUnion("type", [
|
|
TextContentSchema,
|
|
ImageContentSchema,
|
|
AudioContentSchema,
|
|
ToolUseContentSchema,
|
|
ToolResultContentSchema
|
|
]);
|
|
var SamplingMessageSchema = object2({
|
|
role: RoleSchema,
|
|
content: union8([SamplingMessageContentBlockSchema, array4(SamplingMessageContentBlockSchema)]),
|
|
_meta: record2(string3(), unknown()).optional()
|
|
});
|
|
var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
|
|
messages: array4(SamplingMessageSchema),
|
|
modelPreferences: ModelPreferencesSchema.optional(),
|
|
systemPrompt: string3().optional(),
|
|
includeContext: _enum(["none", "thisServer", "allServers"]).optional(),
|
|
temperature: number5().optional(),
|
|
maxTokens: number5().int(),
|
|
stopSequences: array4(string3()).optional(),
|
|
metadata: AssertObjectSchema.optional(),
|
|
tools: array4(ToolSchema).optional(),
|
|
toolChoice: ToolChoiceSchema.optional()
|
|
});
|
|
var CreateMessageRequestSchema = RequestSchema.extend({
|
|
method: literal("sampling/createMessage"),
|
|
params: CreateMessageRequestParamsSchema
|
|
});
|
|
var CreateMessageResultSchema = ResultSchema.extend({
|
|
model: string3(),
|
|
stopReason: optional2(_enum(["endTurn", "stopSequence", "maxTokens"]).or(string3())),
|
|
role: RoleSchema,
|
|
content: SamplingContentSchema
|
|
});
|
|
var CreateMessageResultWithToolsSchema = ResultSchema.extend({
|
|
model: string3(),
|
|
stopReason: optional2(_enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string3())),
|
|
role: RoleSchema,
|
|
content: union8([SamplingMessageContentBlockSchema, array4(SamplingMessageContentBlockSchema)])
|
|
});
|
|
var BooleanSchemaSchema = object2({
|
|
type: literal("boolean"),
|
|
title: string3().optional(),
|
|
description: string3().optional(),
|
|
default: boolean2().optional()
|
|
});
|
|
var StringSchemaSchema = object2({
|
|
type: literal("string"),
|
|
title: string3().optional(),
|
|
description: string3().optional(),
|
|
minLength: number5().optional(),
|
|
maxLength: number5().optional(),
|
|
format: _enum(["email", "uri", "date", "date-time"]).optional(),
|
|
default: string3().optional()
|
|
});
|
|
var NumberSchemaSchema = object2({
|
|
type: _enum(["number", "integer"]),
|
|
title: string3().optional(),
|
|
description: string3().optional(),
|
|
minimum: number5().optional(),
|
|
maximum: number5().optional(),
|
|
default: number5().optional()
|
|
});
|
|
var UntitledSingleSelectEnumSchemaSchema = object2({
|
|
type: literal("string"),
|
|
title: string3().optional(),
|
|
description: string3().optional(),
|
|
enum: array4(string3()),
|
|
default: string3().optional()
|
|
});
|
|
var TitledSingleSelectEnumSchemaSchema = object2({
|
|
type: literal("string"),
|
|
title: string3().optional(),
|
|
description: string3().optional(),
|
|
oneOf: array4(object2({
|
|
const: string3(),
|
|
title: string3()
|
|
})),
|
|
default: string3().optional()
|
|
});
|
|
var LegacyTitledEnumSchemaSchema = object2({
|
|
type: literal("string"),
|
|
title: string3().optional(),
|
|
description: string3().optional(),
|
|
enum: array4(string3()),
|
|
enumNames: array4(string3()).optional(),
|
|
default: string3().optional()
|
|
});
|
|
var SingleSelectEnumSchemaSchema = union8([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
|
|
var UntitledMultiSelectEnumSchemaSchema = object2({
|
|
type: literal("array"),
|
|
title: string3().optional(),
|
|
description: string3().optional(),
|
|
minItems: number5().optional(),
|
|
maxItems: number5().optional(),
|
|
items: object2({
|
|
type: literal("string"),
|
|
enum: array4(string3())
|
|
}),
|
|
default: array4(string3()).optional()
|
|
});
|
|
var TitledMultiSelectEnumSchemaSchema = object2({
|
|
type: literal("array"),
|
|
title: string3().optional(),
|
|
description: string3().optional(),
|
|
minItems: number5().optional(),
|
|
maxItems: number5().optional(),
|
|
items: object2({
|
|
anyOf: array4(object2({
|
|
const: string3(),
|
|
title: string3()
|
|
}))
|
|
}),
|
|
default: array4(string3()).optional()
|
|
});
|
|
var MultiSelectEnumSchemaSchema = union8([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
|
|
var EnumSchemaSchema = union8([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
|
|
var PrimitiveSchemaDefinitionSchema = union8([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
|
|
var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
|
|
mode: literal("form").optional(),
|
|
message: string3(),
|
|
requestedSchema: object2({
|
|
type: literal("object"),
|
|
properties: record2(string3(), PrimitiveSchemaDefinitionSchema),
|
|
required: array4(string3()).optional()
|
|
})
|
|
});
|
|
var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({
|
|
mode: literal("url"),
|
|
message: string3(),
|
|
elicitationId: string3(),
|
|
url: string3().url()
|
|
});
|
|
var ElicitRequestParamsSchema = union8([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
|
|
var ElicitRequestSchema = RequestSchema.extend({
|
|
method: literal("elicitation/create"),
|
|
params: ElicitRequestParamsSchema
|
|
});
|
|
var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({
|
|
elicitationId: string3()
|
|
});
|
|
var ElicitationCompleteNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/elicitation/complete"),
|
|
params: ElicitationCompleteNotificationParamsSchema
|
|
});
|
|
var ElicitResultSchema = ResultSchema.extend({
|
|
action: _enum(["accept", "decline", "cancel"]),
|
|
content: preprocess((val) => val === null ? undefined : val, record2(string3(), union8([string3(), number5(), boolean2(), array4(string3())])).optional())
|
|
});
|
|
var ResourceTemplateReferenceSchema = object2({
|
|
type: literal("ref/resource"),
|
|
uri: string3()
|
|
});
|
|
var PromptReferenceSchema = object2({
|
|
type: literal("ref/prompt"),
|
|
name: string3()
|
|
});
|
|
var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
|
|
ref: union8([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
|
|
argument: object2({
|
|
name: string3(),
|
|
value: string3()
|
|
}),
|
|
context: object2({
|
|
arguments: record2(string3(), string3()).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}`);
|
|
}
|
|
}
|
|
function assertCompleteRequestResourceTemplate(request) {
|
|
if (request.params.ref.type !== "ref/resource") {
|
|
throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);
|
|
}
|
|
}
|
|
var CompleteResultSchema = ResultSchema.extend({
|
|
completion: looseObject({
|
|
values: array4(string3()).max(100),
|
|
total: optional2(number5().int()),
|
|
hasMore: optional2(boolean2())
|
|
})
|
|
});
|
|
var RootSchema = object2({
|
|
uri: string3().startsWith("file://"),
|
|
name: string3().optional(),
|
|
_meta: record2(string3(), unknown()).optional()
|
|
});
|
|
var ListRootsRequestSchema = RequestSchema.extend({
|
|
method: literal("roots/list"),
|
|
params: BaseRequestParamsSchema.optional()
|
|
});
|
|
var ListRootsResultSchema = ResultSchema.extend({
|
|
roots: array4(RootSchema)
|
|
});
|
|
var RootsListChangedNotificationSchema = NotificationSchema.extend({
|
|
method: literal("notifications/roots/list_changed"),
|
|
params: NotificationsParamsSchema.optional()
|
|
});
|
|
var ClientRequestSchema = union8([
|
|
PingRequestSchema,
|
|
InitializeRequestSchema,
|
|
CompleteRequestSchema,
|
|
SetLevelRequestSchema,
|
|
GetPromptRequestSchema,
|
|
ListPromptsRequestSchema,
|
|
ListResourcesRequestSchema,
|
|
ListResourceTemplatesRequestSchema,
|
|
ReadResourceRequestSchema,
|
|
SubscribeRequestSchema,
|
|
UnsubscribeRequestSchema,
|
|
CallToolRequestSchema,
|
|
ListToolsRequestSchema,
|
|
GetTaskRequestSchema,
|
|
GetTaskPayloadRequestSchema,
|
|
ListTasksRequestSchema,
|
|
CancelTaskRequestSchema
|
|
]);
|
|
var ClientNotificationSchema = union8([
|
|
CancelledNotificationSchema,
|
|
ProgressNotificationSchema,
|
|
InitializedNotificationSchema,
|
|
RootsListChangedNotificationSchema,
|
|
TaskStatusNotificationSchema
|
|
]);
|
|
var ClientResultSchema = union8([
|
|
EmptyResultSchema,
|
|
CreateMessageResultSchema,
|
|
CreateMessageResultWithToolsSchema,
|
|
ElicitResultSchema,
|
|
ListRootsResultSchema,
|
|
GetTaskResultSchema,
|
|
ListTasksResultSchema,
|
|
CreateTaskResultSchema
|
|
]);
|
|
var ServerRequestSchema = union8([
|
|
PingRequestSchema,
|
|
CreateMessageRequestSchema,
|
|
ElicitRequestSchema,
|
|
ListRootsRequestSchema,
|
|
GetTaskRequestSchema,
|
|
GetTaskPayloadRequestSchema,
|
|
ListTasksRequestSchema,
|
|
CancelTaskRequestSchema
|
|
]);
|
|
var ServerNotificationSchema = union8([
|
|
CancelledNotificationSchema,
|
|
ProgressNotificationSchema,
|
|
LoggingMessageNotificationSchema,
|
|
ResourceUpdatedNotificationSchema,
|
|
ResourceListChangedNotificationSchema,
|
|
ToolListChangedNotificationSchema,
|
|
PromptListChangedNotificationSchema,
|
|
TaskStatusNotificationSchema,
|
|
ElicitationCompleteNotificationSchema
|
|
]);
|
|
var ServerResultSchema = union8([
|
|
EmptyResultSchema,
|
|
InitializeResultSchema,
|
|
CompleteResultSchema,
|
|
GetPromptResultSchema,
|
|
ListPromptsResultSchema,
|
|
ListResourcesResultSchema,
|
|
ListResourceTemplatesResultSchema,
|
|
ReadResourceResultSchema,
|
|
CallToolResultSchema,
|
|
ListToolsResultSchema,
|
|
GetTaskResultSchema,
|
|
ListTasksResultSchema,
|
|
CreateTaskResultSchema
|
|
]);
|
|
|
|
class McpError extends Error {
|
|
constructor(code, message, data) {
|
|
super(`MCP error ${code}: ${message}`);
|
|
this.code = code;
|
|
this.data = data;
|
|
this.name = "McpError";
|
|
}
|
|
static fromError(code, message, data) {
|
|
if (code === ErrorCode.UrlElicitationRequired && data) {
|
|
const errorData = data;
|
|
if (errorData.elicitations) {
|
|
return new UrlElicitationRequiredError(errorData.elicitations, message);
|
|
}
|
|
}
|
|
return new McpError(code, message, data);
|
|
}
|
|
}
|
|
|
|
class UrlElicitationRequiredError 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.30.0_@cfworker+json-schema@4.1.1_supports-color@10.2.2_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js
|
|
function isTerminal(status) {
|
|
return status === "completed" || status === "failed" || status === "cancelled";
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/Options.js
|
|
var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
|
|
var defaultOptions = {
|
|
name: undefined,
|
|
$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@4.4.3/node_modules/zod-to-json-schema/dist/esm/Refs.js
|
|
var getRefs = (options) => {
|
|
const _options = getDefaultOptions(options);
|
|
const currentPath = _options.name !== undefined ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
|
|
return {
|
|
..._options,
|
|
flags: { hasReferencedOpenAiAnyType: false },
|
|
currentPath,
|
|
propertyPath: undefined,
|
|
seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
|
|
def._def,
|
|
{
|
|
def: def._def,
|
|
path: [..._options.basePath, _options.definitionPath, name],
|
|
jsonSchema: undefined
|
|
}
|
|
]))
|
|
};
|
|
};
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/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 setResponseValueAndErrors(res, key, value, errorMessage, refs) {
|
|
res[key] = value;
|
|
addErrorMessage(res, key, errorMessage, refs);
|
|
}
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js
|
|
var getRelativePath = (pathA, pathB) => {
|
|
let i = 0;
|
|
for (;i < pathA.length && i < pathB.length; i++) {
|
|
if (pathA[i] !== pathB[i])
|
|
break;
|
|
}
|
|
return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
|
|
};
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/any.js
|
|
function parseAnyDef(refs) {
|
|
if (refs.target !== "openAi") {
|
|
return {};
|
|
}
|
|
const anyDefinitionPath = [
|
|
...refs.basePath,
|
|
refs.definitionPath,
|
|
refs.openAiAnyTypeName
|
|
];
|
|
refs.flags.hasReferencedOpenAiAnyType = true;
|
|
return {
|
|
$ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/")
|
|
};
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/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 (def.minLength) {
|
|
setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
|
|
}
|
|
if (def.maxLength) {
|
|
setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
|
|
}
|
|
if (def.exactLength) {
|
|
setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
|
|
setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
|
|
}
|
|
return res;
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/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 check of def.checks) {
|
|
switch (check.kind) {
|
|
case "min":
|
|
if (refs.target === "jsonSchema7") {
|
|
if (check.inclusive) {
|
|
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
|
|
} else {
|
|
setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
|
|
}
|
|
} else {
|
|
if (!check.inclusive) {
|
|
res.exclusiveMinimum = true;
|
|
}
|
|
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
|
|
}
|
|
break;
|
|
case "max":
|
|
if (refs.target === "jsonSchema7") {
|
|
if (check.inclusive) {
|
|
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
|
|
} else {
|
|
setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
|
|
}
|
|
} else {
|
|
if (!check.inclusive) {
|
|
res.exclusiveMaximum = true;
|
|
}
|
|
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
|
|
}
|
|
break;
|
|
case "multipleOf":
|
|
setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
|
|
break;
|
|
}
|
|
}
|
|
return res;
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
|
|
function parseBooleanDef() {
|
|
return {
|
|
type: "boolean"
|
|
};
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/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@4.4.3/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@4.4.3/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, i) => parseDateDef(def, refs, item))
|
|
};
|
|
}
|
|
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);
|
|
}
|
|
}
|
|
var integerDateParser = (def, refs) => {
|
|
const res = {
|
|
type: "integer",
|
|
format: "unix-time"
|
|
};
|
|
if (refs.target === "openApi3") {
|
|
return res;
|
|
}
|
|
for (const check of def.checks) {
|
|
switch (check.kind) {
|
|
case "min":
|
|
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
|
|
break;
|
|
case "max":
|
|
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
|
|
break;
|
|
}
|
|
}
|
|
return res;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/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@4.4.3/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@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
|
|
function parseEnumDef(def) {
|
|
return {
|
|
type: "string",
|
|
enum: Array.from(def.values)
|
|
};
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
|
|
var isJsonSchema7AllOfType = (type) => {
|
|
if ("type" in type && type.type === "string")
|
|
return false;
|
|
return "allOf" in type;
|
|
};
|
|
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 } : undefined;
|
|
const mergedAllOf = [];
|
|
allOf.forEach((schema) => {
|
|
if (isJsonSchema7AllOfType(schema)) {
|
|
mergedAllOf.push(...schema.allOf);
|
|
if (schema.unevaluatedProperties === undefined) {
|
|
unevaluatedProperties = undefined;
|
|
}
|
|
} else {
|
|
let nestedSchema = schema;
|
|
if ("additionalProperties" in schema && schema.additionalProperties === false) {
|
|
const { additionalProperties, ...rest } = schema;
|
|
nestedSchema = rest;
|
|
} else {
|
|
unevaluatedProperties = undefined;
|
|
}
|
|
mergedAllOf.push(nestedSchema);
|
|
}
|
|
});
|
|
return mergedAllOf.length ? {
|
|
allOf: mergedAllOf,
|
|
...unevaluatedProperties
|
|
} : undefined;
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
|
|
function parseLiteralDef(def, refs) {
|
|
const parsedType = typeof def.value;
|
|
if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
|
|
return {
|
|
type: Array.isArray(def.value) ? "array" : "object"
|
|
};
|
|
}
|
|
if (refs.target === "openApi3") {
|
|
return {
|
|
type: parsedType === "bigint" ? "integer" : parsedType,
|
|
enum: [def.value]
|
|
};
|
|
}
|
|
return {
|
|
type: parsedType === "bigint" ? "integer" : parsedType,
|
|
const: def.value
|
|
};
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/string.js
|
|
var emojiRegex2 = undefined;
|
|
var zodPatterns = {
|
|
cuid: /^[cC][^\s-]{8,}$/,
|
|
cuid2: /^[0-9a-z]+$/,
|
|
ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
|
|
email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
|
|
emoji: () => {
|
|
if (emojiRegex2 === undefined) {
|
|
emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
|
|
}
|
|
return emojiRegex2;
|
|
},
|
|
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}$/,
|
|
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])$/,
|
|
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 check of def.checks) {
|
|
switch (check.kind) {
|
|
case "min":
|
|
setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
|
|
break;
|
|
case "max":
|
|
setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
|
|
break;
|
|
case "email":
|
|
switch (refs.emailStrategy) {
|
|
case "format:email":
|
|
addFormat(res, "email", check.message, refs);
|
|
break;
|
|
case "format:idn-email":
|
|
addFormat(res, "idn-email", check.message, refs);
|
|
break;
|
|
case "pattern:zod":
|
|
addPattern(res, zodPatterns.email, check.message, refs);
|
|
break;
|
|
}
|
|
break;
|
|
case "url":
|
|
addFormat(res, "uri", check.message, refs);
|
|
break;
|
|
case "uuid":
|
|
addFormat(res, "uuid", check.message, refs);
|
|
break;
|
|
case "regex":
|
|
addPattern(res, check.regex, check.message, refs);
|
|
break;
|
|
case "cuid":
|
|
addPattern(res, zodPatterns.cuid, check.message, refs);
|
|
break;
|
|
case "cuid2":
|
|
addPattern(res, zodPatterns.cuid2, check.message, refs);
|
|
break;
|
|
case "startsWith":
|
|
addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
|
|
break;
|
|
case "endsWith":
|
|
addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
|
|
break;
|
|
case "datetime":
|
|
addFormat(res, "date-time", check.message, refs);
|
|
break;
|
|
case "date":
|
|
addFormat(res, "date", check.message, refs);
|
|
break;
|
|
case "time":
|
|
addFormat(res, "time", check.message, refs);
|
|
break;
|
|
case "duration":
|
|
addFormat(res, "duration", check.message, refs);
|
|
break;
|
|
case "length":
|
|
setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
|
|
setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
|
|
break;
|
|
case "includes": {
|
|
addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
|
|
break;
|
|
}
|
|
case "ip": {
|
|
if (check.version !== "v6") {
|
|
addFormat(res, "ipv4", check.message, refs);
|
|
}
|
|
if (check.version !== "v4") {
|
|
addFormat(res, "ipv6", check.message, refs);
|
|
}
|
|
break;
|
|
}
|
|
case "base64url":
|
|
addPattern(res, zodPatterns.base64url, check.message, refs);
|
|
break;
|
|
case "jwt":
|
|
addPattern(res, zodPatterns.jwt, check.message, refs);
|
|
break;
|
|
case "cidr": {
|
|
if (check.version !== "v6") {
|
|
addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
|
|
}
|
|
if (check.version !== "v4") {
|
|
addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
|
|
}
|
|
break;
|
|
}
|
|
case "emoji":
|
|
addPattern(res, zodPatterns.emoji(), check.message, refs);
|
|
break;
|
|
case "ulid": {
|
|
addPattern(res, zodPatterns.ulid, check.message, refs);
|
|
break;
|
|
}
|
|
case "base64": {
|
|
switch (refs.base64Strategy) {
|
|
case "format:binary": {
|
|
addFormat(res, "binary", check.message, refs);
|
|
break;
|
|
}
|
|
case "contentEncoding:base64": {
|
|
setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
|
|
break;
|
|
}
|
|
case "pattern:zod": {
|
|
addPattern(res, zodPatterns.base64, check.message, refs);
|
|
break;
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case "nanoid": {
|
|
addPattern(res, zodPatterns.nanoid, check.message, refs);
|
|
}
|
|
case "toLowerCase":
|
|
case "toUpperCase":
|
|
case "trim":
|
|
break;
|
|
default:
|
|
((_) => {})(check);
|
|
}
|
|
}
|
|
}
|
|
return res;
|
|
}
|
|
function escapeLiteralCheckValue(literal, refs) {
|
|
return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
|
|
}
|
|
var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
|
|
function escapeNonAlphaNumeric(source) {
|
|
let result = "";
|
|
for (let i = 0;i < source.length; i++) {
|
|
if (!ALPHA_NUMERIC.has(source[i])) {
|
|
result += "\\";
|
|
}
|
|
result += source[i];
|
|
}
|
|
return result;
|
|
}
|
|
function addFormat(schema, value, message, refs) {
|
|
if (schema.format || schema.anyOf?.some((x) => x.format)) {
|
|
if (!schema.anyOf) {
|
|
schema.anyOf = [];
|
|
}
|
|
if (schema.format) {
|
|
schema.anyOf.push({
|
|
format: schema.format,
|
|
...schema.errorMessage && refs.errorMessages && {
|
|
errorMessage: { format: schema.errorMessage.format }
|
|
}
|
|
});
|
|
delete schema.format;
|
|
if (schema.errorMessage) {
|
|
delete schema.errorMessage.format;
|
|
if (Object.keys(schema.errorMessage).length === 0) {
|
|
delete schema.errorMessage;
|
|
}
|
|
}
|
|
}
|
|
schema.anyOf.push({
|
|
format: value,
|
|
...message && refs.errorMessages && { errorMessage: { format: message } }
|
|
});
|
|
} else {
|
|
setResponseValueAndErrors(schema, "format", value, message, refs);
|
|
}
|
|
}
|
|
function addPattern(schema, regex, message, refs) {
|
|
if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
|
|
if (!schema.allOf) {
|
|
schema.allOf = [];
|
|
}
|
|
if (schema.pattern) {
|
|
schema.allOf.push({
|
|
pattern: schema.pattern,
|
|
...schema.errorMessage && refs.errorMessages && {
|
|
errorMessage: { pattern: schema.errorMessage.pattern }
|
|
}
|
|
});
|
|
delete schema.pattern;
|
|
if (schema.errorMessage) {
|
|
delete schema.errorMessage.pattern;
|
|
if (Object.keys(schema.errorMessage).length === 0) {
|
|
delete schema.errorMessage;
|
|
}
|
|
}
|
|
}
|
|
schema.allOf.push({
|
|
pattern: stringifyRegExpWithFlags(regex, refs),
|
|
...message && refs.errorMessages && { errorMessage: { pattern: message } }
|
|
});
|
|
} else {
|
|
setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
|
|
}
|
|
}
|
|
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")
|
|
};
|
|
const source = flags.i ? regex.source.toLowerCase() : regex.source;
|
|
let pattern = "";
|
|
let isEscaped = false;
|
|
let inCharGroup = false;
|
|
let inCharRange = false;
|
|
for (let i = 0;i < source.length; i++) {
|
|
if (isEscaped) {
|
|
pattern += source[i];
|
|
isEscaped = false;
|
|
continue;
|
|
}
|
|
if (flags.i) {
|
|
if (inCharGroup) {
|
|
if (source[i].match(/[a-z]/)) {
|
|
if (inCharRange) {
|
|
pattern += source[i];
|
|
pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
|
|
inCharRange = false;
|
|
} else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {
|
|
pattern += source[i];
|
|
inCharRange = true;
|
|
} else {
|
|
pattern += `${source[i]}${source[i].toUpperCase()}`;
|
|
}
|
|
continue;
|
|
}
|
|
} else if (source[i].match(/[a-z]/)) {
|
|
pattern += `[${source[i]}${source[i].toUpperCase()}]`;
|
|
continue;
|
|
}
|
|
}
|
|
if (flags.m) {
|
|
if (source[i] === "^") {
|
|
pattern += `(^|(?<=[\r
|
|
]))`;
|
|
continue;
|
|
} else if (source[i] === "$") {
|
|
pattern += `($|(?=[\r
|
|
]))`;
|
|
continue;
|
|
}
|
|
}
|
|
if (flags.s && source[i] === ".") {
|
|
pattern += inCharGroup ? `${source[i]}\r
|
|
` : `[${source[i]}\r
|
|
]`;
|
|
continue;
|
|
}
|
|
pattern += source[i];
|
|
if (source[i] === "\\") {
|
|
isEscaped = true;
|
|
} else if (inCharGroup && source[i] === "]") {
|
|
inCharGroup = false;
|
|
} else if (!inCharGroup && source[i] === "[") {
|
|
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;
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/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 schema = {
|
|
type: "object",
|
|
additionalProperties: parseDef(def.valueType._def, {
|
|
...refs,
|
|
currentPath: [...refs.currentPath, "additionalProperties"]
|
|
}) ?? refs.allowedAdditionalProperties
|
|
};
|
|
if (refs.target === "openApi3") {
|
|
return schema;
|
|
}
|
|
if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
|
|
const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
|
|
return {
|
|
...schema,
|
|
propertyNames: keyType
|
|
};
|
|
} else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
|
|
return {
|
|
...schema,
|
|
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, ...keyType } = parseBrandedDef(def.keyType._def, refs);
|
|
return {
|
|
...schema,
|
|
propertyNames: keyType
|
|
};
|
|
}
|
|
return schema;
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/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
|
|
}
|
|
};
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
|
|
function parseNativeEnumDef(def) {
|
|
const object = def.values;
|
|
const actualKeys = Object.keys(def.values).filter((key) => {
|
|
return typeof object[object[key]] !== "number";
|
|
});
|
|
const actualValues = actualKeys.map((key) => object[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@4.4.3/node_modules/zod-to-json-schema/dist/esm/parsers/never.js
|
|
function parseNeverDef(refs) {
|
|
return refs.target === "openAi" ? undefined : {
|
|
not: parseAnyDef({
|
|
...refs,
|
|
currentPath: [...refs.currentPath, "not"]
|
|
})
|
|
};
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/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@4.4.3/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((types, x) => {
|
|
const type = primitiveMappings[x._def.typeName];
|
|
return type && !types.includes(type) ? [...types, type] : types;
|
|
}, []);
|
|
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 type = typeof x._def.value;
|
|
switch (type) {
|
|
case "string":
|
|
case "number":
|
|
case "boolean":
|
|
return [...acc, type];
|
|
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, i, a) => a.indexOf(x) === i);
|
|
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((x) => !acc.includes(x))
|
|
], [])
|
|
};
|
|
}
|
|
return asAnyOf(def, refs);
|
|
}
|
|
var asAnyOf = (def, refs) => {
|
|
const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {
|
|
...refs,
|
|
currentPath: [...refs.currentPath, "anyOf", `${i}`]
|
|
})).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
|
|
return anyOf.length ? { anyOf } : undefined;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/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 base = parseDef(def.innerType._def, {
|
|
...refs,
|
|
currentPath: [...refs.currentPath]
|
|
});
|
|
if (base && "$ref" in base)
|
|
return { allOf: [base], nullable: true };
|
|
return base && { ...base, 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@4.4.3/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 check of def.checks) {
|
|
switch (check.kind) {
|
|
case "int":
|
|
res.type = "integer";
|
|
addErrorMessage(res, "type", check.message, refs);
|
|
break;
|
|
case "min":
|
|
if (refs.target === "jsonSchema7") {
|
|
if (check.inclusive) {
|
|
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
|
|
} else {
|
|
setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
|
|
}
|
|
} else {
|
|
if (!check.inclusive) {
|
|
res.exclusiveMinimum = true;
|
|
}
|
|
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
|
|
}
|
|
break;
|
|
case "max":
|
|
if (refs.target === "jsonSchema7") {
|
|
if (check.inclusive) {
|
|
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
|
|
} else {
|
|
setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
|
|
}
|
|
} else {
|
|
if (!check.inclusive) {
|
|
res.exclusiveMaximum = true;
|
|
}
|
|
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
|
|
}
|
|
break;
|
|
case "multipleOf":
|
|
setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
|
|
break;
|
|
}
|
|
}
|
|
return res;
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/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 required = [];
|
|
const shape = def.shape();
|
|
for (const propName in shape) {
|
|
let propDef = shape[propName];
|
|
if (propDef === undefined || propDef._def === undefined) {
|
|
continue;
|
|
}
|
|
let propOptional = safeIsOptional(propDef);
|
|
if (propOptional && forceOptionalIntoNullable) {
|
|
if (propDef._def.typeName === "ZodOptional") {
|
|
propDef = propDef._def.innerType;
|
|
}
|
|
if (!propDef.isNullable()) {
|
|
propDef = propDef.nullable();
|
|
}
|
|
propOptional = false;
|
|
}
|
|
const parsedDef = parseDef(propDef._def, {
|
|
...refs,
|
|
currentPath: [...refs.currentPath, "properties", propName],
|
|
propertyPath: [...refs.currentPath, "properties", propName]
|
|
});
|
|
if (parsedDef === undefined) {
|
|
continue;
|
|
}
|
|
result.properties[propName] = parsedDef;
|
|
if (!propOptional) {
|
|
required.push(propName);
|
|
}
|
|
}
|
|
if (required.length) {
|
|
result.required = required;
|
|
}
|
|
const additionalProperties = decideAdditionalProperties(def, refs);
|
|
if (additionalProperties !== undefined) {
|
|
result.additionalProperties = additionalProperties;
|
|
}
|
|
return result;
|
|
}
|
|
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;
|
|
}
|
|
}
|
|
function safeIsOptional(schema) {
|
|
try {
|
|
return schema.isOptional();
|
|
} catch {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/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"]
|
|
});
|
|
return innerSchema ? {
|
|
anyOf: [
|
|
{
|
|
not: parseAnyDef(refs)
|
|
},
|
|
innerSchema
|
|
]
|
|
} : parseAnyDef(refs);
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/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"]
|
|
});
|
|
const b = parseDef(def.out._def, {
|
|
...refs,
|
|
currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
|
|
});
|
|
return {
|
|
allOf: [a, b].filter((x) => x !== undefined)
|
|
};
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/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@4.4.3/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 schema = {
|
|
type: "array",
|
|
uniqueItems: true,
|
|
items
|
|
};
|
|
if (def.minSize) {
|
|
setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
|
|
}
|
|
if (def.maxSize) {
|
|
setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
|
|
}
|
|
return schema;
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/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, i) => parseDef(x._def, {
|
|
...refs,
|
|
currentPath: [...refs.currentPath, "items", `${i}`]
|
|
})).reduce((acc, x) => x === undefined ? 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, i) => parseDef(x._def, {
|
|
...refs,
|
|
currentPath: [...refs.currentPath, "items", `${i}`]
|
|
})).reduce((acc, x) => x === undefined ? acc : [...acc, x], [])
|
|
};
|
|
}
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/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@4.4.3/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@4.4.3/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@4.4.3/node_modules/zod-to-json-schema/dist/esm/selectParser.js
|
|
var selectParser2 = (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;
|
|
default:
|
|
return ((_) => {
|
|
return;
|
|
})(typeName);
|
|
}
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/zod-to-json-schema@3.25.2_zod@4.4.3/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 (seenItem && !forceResolution) {
|
|
const seenSchema = get$ref(seenItem, refs);
|
|
if (seenSchema !== undefined) {
|
|
return seenSchema;
|
|
}
|
|
}
|
|
const newItem = { def, path: refs.currentPath, jsonSchema: undefined };
|
|
refs.seen.set(def, newItem);
|
|
const jsonSchemaOrGetter = selectParser2(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, index) => refs.currentPath[index] === value)) {
|
|
console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
|
|
return parseAnyDef(refs);
|
|
}
|
|
return refs.$refStrategy === "seen" ? parseAnyDef(refs) : undefined;
|
|
}
|
|
}
|
|
};
|
|
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@4.4.3/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
|
|
var zodToJsonSchema = (schema, options) => {
|
|
const refs = getRefs(options);
|
|
let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({
|
|
...acc,
|
|
[name]: parseDef(schema._def, {
|
|
...refs,
|
|
currentPath: [...refs.basePath, refs.definitionPath, name]
|
|
}, true) ?? parseAnyDef(refs)
|
|
}), {}) : undefined;
|
|
const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? undefined : options?.name;
|
|
const main = parseDef(schema._def, name === undefined ? refs : {
|
|
...refs,
|
|
currentPath: [...refs.basePath, refs.definitionPath, name]
|
|
}, false) ?? parseAnyDef(refs);
|
|
const title = typeof options === "object" && options.name !== undefined && options.nameStrategy === "title" ? options.name : undefined;
|
|
if (title !== undefined) {
|
|
main.title = title;
|
|
}
|
|
if (refs.flags.hasReferencedOpenAiAnyType) {
|
|
if (!definitions) {
|
|
definitions = {};
|
|
}
|
|
if (!definitions[refs.openAiAnyTypeName]) {
|
|
definitions[refs.openAiAnyTypeName] = {
|
|
type: ["string", "number", "integer", "boolean", "array", "null"],
|
|
items: {
|
|
$ref: refs.$refStrategy === "relative" ? "1" : [
|
|
...refs.basePath,
|
|
refs.definitionPath,
|
|
refs.openAiAnyTypeName
|
|
].join("/")
|
|
}
|
|
};
|
|
}
|
|
}
|
|
const combined = name === undefined ? definitions ? {
|
|
...main,
|
|
[refs.definitionPath]: definitions
|
|
} : main : {
|
|
$ref: [
|
|
...refs.$refStrategy === "relative" ? [] : refs.basePath,
|
|
refs.definitionPath,
|
|
name
|
|
].join("/"),
|
|
[refs.definitionPath]: {
|
|
...definitions,
|
|
[name]: main
|
|
}
|
|
};
|
|
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.30.0_@cfworker+json-schema@4.1.1_supports-color@10.2.2_zod@4.4.3/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(schema, opts) {
|
|
if (isZ4Schema(schema)) {
|
|
return toJSONSchema(schema, {
|
|
target: mapMiniTarget(opts?.target),
|
|
io: opts?.pipeStrategy ?? "input"
|
|
});
|
|
}
|
|
return zodToJsonSchema(schema, {
|
|
strictUnions: opts?.strictUnions ?? true,
|
|
pipeStrategy: opts?.pipeStrategy ?? "input"
|
|
});
|
|
}
|
|
function getMethodLiteral(schema) {
|
|
const shape = getObjectShape(schema);
|
|
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(schema, data) {
|
|
const result = safeParse2(schema, data);
|
|
if (!result.success) {
|
|
throw result.error;
|
|
}
|
|
return result.data;
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_@cfworker+json-schema@4.1.1_supports-color@10.2.2_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
|
|
var DEFAULT_REQUEST_TIMEOUT_MSEC = 60000;
|
|
|
|
class Protocol {
|
|
constructor(_options) {
|
|
this._options = _options;
|
|
this._requestMessageId = 0;
|
|
this._requestHandlers = new Map;
|
|
this._requestHandlerAbortControllers = new Map;
|
|
this._notificationHandlers = new Map;
|
|
this._responseHandlers = new Map;
|
|
this._progressHandlers = new Map;
|
|
this._timeoutInfo = new Map;
|
|
this._pendingDebouncedNotifications = new Set;
|
|
this._taskProgressTokens = new Map;
|
|
this._requestResolvers = new Map;
|
|
this.setNotificationHandler(CancelledNotificationSchema, (notification) => {
|
|
this._oncancel(notification);
|
|
});
|
|
this.setNotificationHandler(ProgressNotificationSchema, (notification) => {
|
|
this._onprogress(notification);
|
|
});
|
|
this.setRequestHandler(PingRequestSchema, (_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 error = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
|
|
resolver(error);
|
|
}
|
|
} 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 (error) {
|
|
throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`);
|
|
}
|
|
});
|
|
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 (error) {
|
|
if (error instanceof McpError) {
|
|
throw error;
|
|
}
|
|
throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
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;
|
|
}
|
|
_cleanupTimeout(messageId) {
|
|
const info = this._timeoutInfo.get(messageId);
|
|
if (info) {
|
|
clearTimeout(info.timeoutId);
|
|
this._timeoutInfo.delete(messageId);
|
|
}
|
|
}
|
|
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 = (error) => {
|
|
_onerror?.(error);
|
|
this._onerror(error);
|
|
};
|
|
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 = 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 error = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");
|
|
this._transport = undefined;
|
|
this.onclose?.();
|
|
for (const handler of responseHandlers.values()) {
|
|
handler(error);
|
|
}
|
|
}
|
|
_onerror(error) {
|
|
this.onerror?.(error);
|
|
}
|
|
_onnotification(notification) {
|
|
const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;
|
|
if (handler === undefined) {
|
|
return;
|
|
}
|
|
Promise.resolve().then(() => handler(notification)).catch((error) => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));
|
|
}
|
|
_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 === undefined) {
|
|
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((error) => this._onerror(new Error(`Failed to enqueue error response: ${error}`)));
|
|
} else {
|
|
capturedTransport?.send(errorResponse).catch((error) => this._onerror(new Error(`Failed to send an error response: ${error}`)));
|
|
}
|
|
return;
|
|
}
|
|
const abortController = new AbortController;
|
|
this._requestHandlerAbortControllers.set(request.id, abortController);
|
|
const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : undefined;
|
|
const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : undefined;
|
|
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 (error) => {
|
|
if (abortController.signal.aborted) {
|
|
return;
|
|
}
|
|
const errorResponse = {
|
|
jsonrpc: "2.0",
|
|
id: request.id,
|
|
error: {
|
|
code: Number.isSafeInteger(error["code"]) ? error["code"] : ErrorCode.InternalError,
|
|
message: error.message ?? "Internal error",
|
|
...error["data"] !== undefined && { data: error["data"] }
|
|
}
|
|
};
|
|
if (relatedTaskId && this._taskMessageQueue) {
|
|
await this._enqueueTaskMessage(relatedTaskId, {
|
|
type: "error",
|
|
message: errorResponse,
|
|
timestamp: Date.now()
|
|
}, capturedTransport?.sessionId);
|
|
} else {
|
|
await capturedTransport?.send(errorResponse);
|
|
}
|
|
}).catch((error) => this._onerror(new Error(`Failed to send response: ${error}`))).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 (error) {
|
|
this._responseHandlers.delete(messageId);
|
|
this._progressHandlers.delete(messageId);
|
|
this._cleanupTimeout(messageId);
|
|
responseHandler(error);
|
|
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 error = new McpError(response.error.code, response.error.message, response.error.data);
|
|
resolver(error);
|
|
}
|
|
return;
|
|
}
|
|
const handler = this._responseHandlers.get(messageId);
|
|
if (handler === undefined) {
|
|
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 error = McpError.fromError(response.error.code, response.error.message, response.error.data);
|
|
handler(error);
|
|
}
|
|
}
|
|
get transport() {
|
|
return this._transport;
|
|
}
|
|
async close() {
|
|
await this._transport?.close();
|
|
}
|
|
async* requestStream(request, resultSchema, options) {
|
|
const { task } = options ?? {};
|
|
if (!task) {
|
|
try {
|
|
const result = await this.request(request, resultSchema, options);
|
|
yield { type: "result", result };
|
|
} catch (error) {
|
|
yield {
|
|
type: "error",
|
|
error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))
|
|
};
|
|
}
|
|
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 task = await this.getTask({ taskId }, options);
|
|
yield { type: "taskStatus", task };
|
|
if (isTerminal(task.status)) {
|
|
if (task.status === "completed") {
|
|
const result = await this.getTaskResult({ taskId }, resultSchema, options);
|
|
yield { type: "result", result };
|
|
} else if (task.status === "failed") {
|
|
yield {
|
|
type: "error",
|
|
error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)
|
|
};
|
|
} else if (task.status === "cancelled") {
|
|
yield {
|
|
type: "error",
|
|
error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)
|
|
};
|
|
}
|
|
return;
|
|
}
|
|
if (task.status === "input_required") {
|
|
const result = await this.getTaskResult({ taskId }, resultSchema, options);
|
|
yield { type: "result", result };
|
|
return;
|
|
}
|
|
const pollInterval = task.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1000;
|
|
await new Promise((resolve) => setTimeout(resolve, pollInterval));
|
|
options?.signal?.throwIfAborted();
|
|
}
|
|
} catch (error) {
|
|
yield {
|
|
type: "error",
|
|
error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))
|
|
};
|
|
}
|
|
}
|
|
request(request, resultSchema, options) {
|
|
const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
|
|
return new Promise((resolve, reject) => {
|
|
const earlyReject = (error) => {
|
|
reject(error);
|
|
};
|
|
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 (e) {
|
|
earlyReject(e);
|
|
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((error) => this._onerror(new Error(`Failed to send cancellation: ${error}`)));
|
|
const error = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));
|
|
reject(error);
|
|
};
|
|
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 {
|
|
resolve(parseResult.data);
|
|
}
|
|
} catch (error) {
|
|
reject(error);
|
|
}
|
|
});
|
|
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((error) => {
|
|
this._cleanupTimeout(messageId);
|
|
reject(error);
|
|
});
|
|
} else {
|
|
this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => {
|
|
this._cleanupTimeout(messageId);
|
|
reject(error);
|
|
});
|
|
}
|
|
});
|
|
}
|
|
async getTask(params, options) {
|
|
return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options);
|
|
}
|
|
async getTaskResult(params, resultSchema, options) {
|
|
return this.request({ method: "tasks/result", params }, resultSchema, options);
|
|
}
|
|
async listTasks(params, options) {
|
|
return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options);
|
|
}
|
|
async cancelTask(params, options) {
|
|
return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options);
|
|
}
|
|
async notification(notification, options) {
|
|
if (!this._transport) {
|
|
throw new Error("Not connected");
|
|
}
|
|
this.assertNotificationCapability(notification.method);
|
|
const relatedTaskId = options?.relatedTask?.taskId;
|
|
if (relatedTaskId) {
|
|
const jsonrpcNotification = {
|
|
...notification,
|
|
jsonrpc: "2.0",
|
|
params: {
|
|
...notification.params,
|
|
_meta: {
|
|
...notification.params?._meta || {},
|
|
[RELATED_TASK_META_KEY]: options.relatedTask
|
|
}
|
|
}
|
|
};
|
|
await this._enqueueTaskMessage(relatedTaskId, {
|
|
type: "notification",
|
|
message: jsonrpcNotification,
|
|
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 jsonrpcNotification = {
|
|
...notification,
|
|
jsonrpc: "2.0"
|
|
};
|
|
if (options?.relatedTask) {
|
|
jsonrpcNotification = {
|
|
...jsonrpcNotification,
|
|
params: {
|
|
...jsonrpcNotification.params,
|
|
_meta: {
|
|
...jsonrpcNotification.params?._meta || {},
|
|
[RELATED_TASK_META_KEY]: options.relatedTask
|
|
}
|
|
}
|
|
};
|
|
}
|
|
this._transport?.send(jsonrpcNotification, options).catch((error) => this._onerror(error));
|
|
});
|
|
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);
|
|
}
|
|
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));
|
|
});
|
|
}
|
|
removeRequestHandler(method) {
|
|
this._requestHandlers.delete(method);
|
|
}
|
|
assertCanSetRequestHandler(method) {
|
|
if (this._requestHandlers.has(method)) {
|
|
throw new Error(`A request handler for ${method} already exists, which would be overridden`);
|
|
}
|
|
}
|
|
setNotificationHandler(notificationSchema, handler) {
|
|
const method = getMethodLiteral(notificationSchema);
|
|
this._notificationHandlers.set(method, (notification) => {
|
|
const parsed = parseWithCompat(notificationSchema, notification);
|
|
return Promise.resolve(handler(parsed));
|
|
});
|
|
}
|
|
removeNotificationHandler(method) {
|
|
this._notificationHandlers.delete(method);
|
|
}
|
|
_cleanupTaskProgressHandler(taskId) {
|
|
const progressToken = this._taskProgressTokens.get(taskId);
|
|
if (progressToken !== undefined) {
|
|
this._progressHandlers.delete(progressToken);
|
|
this._taskProgressTokens.delete(taskId);
|
|
}
|
|
}
|
|
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);
|
|
}
|
|
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`));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
async _waitForTaskUpdate(taskId, signal) {
|
|
let interval = this._options?.defaultTaskPollInterval ?? 1000;
|
|
try {
|
|
const task = await this._taskStore?.getTask(taskId);
|
|
if (task?.pollInterval) {
|
|
interval = task.pollInterval;
|
|
}
|
|
} catch {}
|
|
return new Promise((resolve, reject) => {
|
|
if (signal.aborted) {
|
|
reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
|
|
return;
|
|
}
|
|
const timeoutId = setTimeout(resolve, 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 === undefined)
|
|
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.30.0_@cfworker+json-schema@4.1.1_supports-color@10.2.2_zod@4.4.3/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 ajv = new import_ajv.default({
|
|
strict: false,
|
|
validateFormats: true,
|
|
validateSchema: false,
|
|
allErrors: true
|
|
});
|
|
const addFormats = import_ajv_formats.default;
|
|
addFormats(ajv);
|
|
return ajv;
|
|
}
|
|
|
|
class AjvJsonSchemaValidator {
|
|
constructor(ajv) {
|
|
this._ajv = ajv ?? createDefaultAjvInstance();
|
|
}
|
|
getValidator(schema) {
|
|
const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema) : this._ajv.compile(schema);
|
|
return (input) => {
|
|
const valid = ajvValidator(input);
|
|
if (valid) {
|
|
return {
|
|
valid: true,
|
|
data: input,
|
|
errorMessage: undefined
|
|
};
|
|
} else {
|
|
return {
|
|
valid: false,
|
|
data: undefined,
|
|
errorMessage: this._ajv.errorsText(ajvValidator.errors)
|
|
};
|
|
}
|
|
};
|
|
}
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_@cfworker+json-schema@4.1.1_supports-color@10.2.2_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js
|
|
class ExperimentalServerTasks {
|
|
constructor(_server) {
|
|
this._server = _server;
|
|
}
|
|
requestStream(request, resultSchema, options) {
|
|
return this._server.requestStream(request, resultSchema, options);
|
|
}
|
|
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] : undefined;
|
|
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);
|
|
}
|
|
elicitInputStream(params, options) {
|
|
const clientCapabilities = this._server.getClientCapabilities();
|
|
const mode = params.mode ?? "form";
|
|
switch (mode) {
|
|
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 = mode === "form" && params.mode === undefined ? { ...params, mode: "form" } : params;
|
|
return this.requestStream({
|
|
method: "elicitation/create",
|
|
params: normalizedParams
|
|
}, ElicitResultSchema, options);
|
|
}
|
|
async getTask(taskId, options) {
|
|
return this._server.getTask({ taskId }, options);
|
|
}
|
|
async getTaskResult(taskId, resultSchema, options) {
|
|
return this._server.getTaskResult({ taskId }, resultSchema, options);
|
|
}
|
|
async listTasks(cursor, options) {
|
|
return this._server.listTasks(cursor ? { cursor } : undefined, options);
|
|
}
|
|
async cancelTask(taskId, options) {
|
|
return this._server.cancelTask({ taskId }, options);
|
|
}
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_@cfworker+json-schema@4.1.1_supports-color@10.2.2_zod@4.4.3/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.30.0_@cfworker+json-schema@4.1.1_supports-color@10.2.2_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js
|
|
class Server extends Protocol {
|
|
constructor(_serverInfo, options) {
|
|
super(options);
|
|
this._serverInfo = _serverInfo;
|
|
this._loggingLevels = new Map;
|
|
this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index]));
|
|
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"] || undefined;
|
|
const { level } = request.params;
|
|
const parseResult = LoggingLevelSchema.safeParse(level);
|
|
if (parseResult.success) {
|
|
this._loggingLevels.set(transportSessionId, parseResult.data);
|
|
}
|
|
return {};
|
|
});
|
|
}
|
|
}
|
|
get experimental() {
|
|
if (!this._experimental) {
|
|
this._experimental = {
|
|
tasks: new ExperimentalServerTasks(this)
|
|
};
|
|
}
|
|
return this._experimental;
|
|
}
|
|
registerCapabilities(capabilities) {
|
|
if (this.transport) {
|
|
throw new Error("Cannot register capabilities after connecting to transport");
|
|
}
|
|
this._capabilities = mergeCapabilities(this._capabilities, capabilities);
|
|
}
|
|
setRequestHandler(requestSchema, handler) {
|
|
const shape = getObjectShape(requestSchema);
|
|
const methodSchema = shape?.method;
|
|
if (!methodSchema) {
|
|
throw new Error("Schema is missing a method literal");
|
|
}
|
|
const methodValue = getLiteralValue(methodSchema);
|
|
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 }
|
|
};
|
|
}
|
|
getClientCapabilities() {
|
|
return this._clientCapabilities;
|
|
}
|
|
getClientVersion() {
|
|
return this._clientVersion;
|
|
}
|
|
getCapabilities() {
|
|
return this._capabilities;
|
|
}
|
|
async ping() {
|
|
return this.request({ method: "ping" }, EmptyResultSchema);
|
|
}
|
|
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] : undefined;
|
|
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);
|
|
}
|
|
async elicitInput(params, options) {
|
|
const mode = params.mode ?? "form";
|
|
switch (mode) {
|
|
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 (error) {
|
|
if (error instanceof McpError) {
|
|
throw error;
|
|
}
|
|
throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`);
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
}
|
|
}
|
|
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);
|
|
}
|
|
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.30.0_@cfworker+json-schema@4.1.1_supports-color@10.2.2_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js
|
|
var COMPLETABLE_SYMBOL = Symbol.for("mcp.completable");
|
|
function isCompletable(schema) {
|
|
return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema;
|
|
}
|
|
function getCompleter(schema) {
|
|
const meta = schema[COMPLETABLE_SYMBOL];
|
|
return meta?.complete;
|
|
}
|
|
var McpZodTypeKind;
|
|
(function(McpZodTypeKind) {
|
|
McpZodTypeKind["Completable"] = "McpCompletable";
|
|
})(McpZodTypeKind || (McpZodTypeKind = {}));
|
|
|
|
// ../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_@cfworker+json-schema@4.1.1_supports-color@10.2.2_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js
|
|
var TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/;
|
|
function validateToolName(name) {
|
|
const warnings = [];
|
|
if (name.length === 0) {
|
|
return {
|
|
isValid: false,
|
|
warnings: ["Tool name cannot be empty"]
|
|
};
|
|
}
|
|
if (name.length > 128) {
|
|
return {
|
|
isValid: false,
|
|
warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]
|
|
};
|
|
}
|
|
if (name.includes(" ")) {
|
|
warnings.push("Tool name contains spaces, which may cause parsing issues");
|
|
}
|
|
if (name.includes(",")) {
|
|
warnings.push("Tool name contains commas, which may cause parsing issues");
|
|
}
|
|
if (name.startsWith("-") || name.endsWith("-")) {
|
|
warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");
|
|
}
|
|
if (name.startsWith(".") || name.endsWith(".")) {
|
|
warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");
|
|
}
|
|
if (!TOOL_NAME_REGEX.test(name)) {
|
|
const invalidChars = name.split("").filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index);
|
|
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(name, warnings) {
|
|
if (warnings.length > 0) {
|
|
console.warn(`Tool name validation warning for "${name}":`);
|
|
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(name) {
|
|
const result = validateToolName(name);
|
|
issueToolNameWarning(name, result.warnings);
|
|
return result.isValid;
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_@cfworker+json-schema@4.1.1_supports-color@10.2.2_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js
|
|
class ExperimentalMcpServerTasks {
|
|
constructor(_mcpServer) {
|
|
this._mcpServer = _mcpServer;
|
|
}
|
|
registerToolTask(name, config, handler) {
|
|
const execution = { taskSupport: "required", ...config.execution };
|
|
if (execution.taskSupport === "forbidden") {
|
|
throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`);
|
|
}
|
|
const mcpServerInternal = this._mcpServer;
|
|
return mcpServerInternal._createRegisteredTool(name, config.title, config.description, config.inputSchema, config.outputSchema, config.annotations, execution, config._meta, handler);
|
|
}
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_@cfworker+json-schema@4.1.1_supports-color@10.2.2_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js
|
|
class McpServer {
|
|
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);
|
|
}
|
|
get experimental() {
|
|
if (!this._experimental) {
|
|
this._experimental = {
|
|
tasks: new ExperimentalMcpServerTasks(this)
|
|
};
|
|
}
|
|
return this._experimental;
|
|
}
|
|
async connect(transport) {
|
|
return await this.server.connect(transport);
|
|
}
|
|
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(([name, tool]) => {
|
|
const toolDefinition = {
|
|
name,
|
|
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 (error) {
|
|
if (error instanceof McpError) {
|
|
if (error.code === ErrorCode.UrlElicitationRequired) {
|
|
throw error;
|
|
}
|
|
}
|
|
return this.createToolError(error instanceof Error ? error.message : String(error));
|
|
}
|
|
});
|
|
this._toolHandlersInitialized = true;
|
|
}
|
|
createToolError(errorMessage) {
|
|
return {
|
|
content: [
|
|
{
|
|
type: "text",
|
|
text: errorMessage
|
|
}
|
|
],
|
|
isError: true
|
|
};
|
|
}
|
|
async validateToolInput(tool, args, toolName) {
|
|
if (!tool.inputSchema) {
|
|
return;
|
|
}
|
|
const inputObj = normalizeObjectSchema(tool.inputSchema);
|
|
const schemaToParse = inputObj ?? tool.inputSchema;
|
|
const parseResult = await safeParseAsync2(schemaToParse, args);
|
|
if (!parseResult.success) {
|
|
const error = "error" in parseResult ? parseResult.error : "Unknown error";
|
|
const errorMessage = getParseErrorMessage(error);
|
|
throw new McpError(ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`);
|
|
}
|
|
return parseResult.data;
|
|
}
|
|
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 error = "error" in parseResult ? parseResult.error : "Unknown error";
|
|
const errorMessage = getParseErrorMessage(error);
|
|
throw new McpError(ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`);
|
|
}
|
|
}
|
|
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));
|
|
}
|
|
}
|
|
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)) : await Promise.resolve(handler.createTask(taskExtra));
|
|
const taskId = createTaskResult.task.taskId;
|
|
let task = createTaskResult.task;
|
|
const pollInterval = task.pollInterval ?? 5000;
|
|
while (task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled") {
|
|
await new Promise((resolve) => setTimeout(resolve, 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,
|
|
...resource
|
|
});
|
|
}
|
|
}
|
|
return { resources: [...resources, ...templateResources] };
|
|
});
|
|
this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {
|
|
const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({
|
|
name,
|
|
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(([name, prompt]) => {
|
|
return {
|
|
name,
|
|
title: prompt.title,
|
|
description: prompt.description,
|
|
arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : undefined
|
|
};
|
|
})
|
|
}));
|
|
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 error = "error" in parseResult ? parseResult.error : "Unknown error";
|
|
const errorMessage = getParseErrorMessage(error);
|
|
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(name, 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(name, undefined, uriOrTemplate, metadata, readCallback);
|
|
this.setResourceRequestHandlers();
|
|
this.sendResourceListChanged();
|
|
return registeredResource;
|
|
} else {
|
|
if (this._registeredResourceTemplates[name]) {
|
|
throw new Error(`Resource template ${name} is already registered`);
|
|
}
|
|
const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, undefined, uriOrTemplate, metadata, readCallback);
|
|
this.setResourceRequestHandlers();
|
|
this.sendResourceListChanged();
|
|
return registeredResourceTemplate;
|
|
}
|
|
}
|
|
registerResource(name, uriOrTemplate, config, readCallback) {
|
|
if (typeof uriOrTemplate === "string") {
|
|
if (this._registeredResources[uriOrTemplate]) {
|
|
throw new Error(`Resource ${uriOrTemplate} is already registered`);
|
|
}
|
|
const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, config, readCallback);
|
|
this.setResourceRequestHandlers();
|
|
this.sendResourceListChanged();
|
|
return registeredResource;
|
|
} else {
|
|
if (this._registeredResourceTemplates[name]) {
|
|
throw new Error(`Resource template ${name} is already registered`);
|
|
}
|
|
const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, config, readCallback);
|
|
this.setResourceRequestHandlers();
|
|
this.sendResourceListChanged();
|
|
return registeredResourceTemplate;
|
|
}
|
|
}
|
|
_createRegisteredResource(name, title, uri, metadata, readCallback) {
|
|
const registeredResource = {
|
|
name,
|
|
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(name, 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 !== name) {
|
|
delete this._registeredResourceTemplates[name];
|
|
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[name] = registeredResourceTemplate;
|
|
const variableNames = template.uriTemplate.variableNames;
|
|
const hasCompleter = Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v));
|
|
if (hasCompleter) {
|
|
this.setCompletionRequestHandler();
|
|
}
|
|
return registeredResourceTemplate;
|
|
}
|
|
_createRegisteredPrompt(name, title, description, argsSchema, callback) {
|
|
const registeredPrompt = {
|
|
title,
|
|
description,
|
|
argsSchema: argsSchema === undefined ? undefined : 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 !== name) {
|
|
delete this._registeredPrompts[name];
|
|
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[name] = registeredPrompt;
|
|
if (argsSchema) {
|
|
const hasCompletable = Object.values(argsSchema).some((field) => {
|
|
const inner = field instanceof ZodOptional2 ? field._def?.innerType : field;
|
|
return isCompletable(inner);
|
|
});
|
|
if (hasCompletable) {
|
|
this.setCompletionRequestHandler();
|
|
}
|
|
}
|
|
return registeredPrompt;
|
|
}
|
|
_createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) {
|
|
validateAndWarnToolName(name);
|
|
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 !== name) {
|
|
if (typeof updates.name === "string") {
|
|
validateAndWarnToolName(updates.name);
|
|
}
|
|
delete this._registeredTools[name];
|
|
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[name] = registeredTool;
|
|
this.setToolRequestHandlers();
|
|
this.sendToolListChanged();
|
|
return registeredTool;
|
|
}
|
|
tool(name, ...rest) {
|
|
if (this._registeredTools[name]) {
|
|
throw new Error(`Tool ${name} 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 ${name} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);
|
|
}
|
|
annotations = rest.shift();
|
|
}
|
|
}
|
|
const callback = rest[0];
|
|
return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, undefined, callback);
|
|
}
|
|
registerTool(name, config, cb) {
|
|
if (this._registeredTools[name]) {
|
|
throw new Error(`Tool ${name} is already registered`);
|
|
}
|
|
const { title, description, inputSchema, outputSchema, annotations, _meta } = config;
|
|
return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, { taskSupport: "forbidden" }, _meta, cb);
|
|
}
|
|
prompt(name, ...rest) {
|
|
if (this._registeredPrompts[name]) {
|
|
throw new Error(`Prompt ${name} 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(name, undefined, description, argsSchema, cb);
|
|
this.setPromptRequestHandlers();
|
|
this.sendPromptListChanged();
|
|
return registeredPrompt;
|
|
}
|
|
registerPrompt(name, config, cb) {
|
|
if (this._registeredPrompts[name]) {
|
|
throw new Error(`Prompt ${name} is already registered`);
|
|
}
|
|
const { title, description, argsSchema } = config;
|
|
const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb);
|
|
this.setPromptRequestHandlers();
|
|
this.sendPromptListChanged();
|
|
return registeredPrompt;
|
|
}
|
|
isConnected() {
|
|
return this.server.transport !== undefined;
|
|
}
|
|
async sendLoggingMessage(params, sessionId) {
|
|
return this.server.sendLoggingMessage(params, sessionId);
|
|
}
|
|
sendResourceListChanged() {
|
|
if (this.isConnected()) {
|
|
this.server.sendResourceListChanged();
|
|
}
|
|
}
|
|
sendToolListChanged() {
|
|
if (this.isConnected()) {
|
|
this.server.sendToolListChanged();
|
|
}
|
|
}
|
|
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(schema) {
|
|
if (!schema) {
|
|
return;
|
|
}
|
|
if (isZodRawShapeCompat(schema)) {
|
|
return objectFromShape(schema);
|
|
}
|
|
if (!isZodSchemaInstance(schema)) {
|
|
throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");
|
|
}
|
|
return schema;
|
|
}
|
|
function promptArgumentsFromSchema(schema) {
|
|
const shape = getObjectShape(schema);
|
|
if (!shape)
|
|
return [];
|
|
return Object.entries(shape).map(([name, field]) => {
|
|
const description = getSchemaDescription(field);
|
|
const isOptional = isSchemaOptional(field);
|
|
return {
|
|
name,
|
|
description,
|
|
required: !isOptional
|
|
};
|
|
});
|
|
}
|
|
function getMethodValue(schema) {
|
|
const shape = getObjectShape(schema);
|
|
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.30.0_@cfworker+json-schema@4.1.1_supports-color@10.2.2_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
|
|
import process3 from "process";
|
|
|
|
// ../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_@cfworker+json-schema@4.1.1_supports-color@10.2.2_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
|
|
var STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;
|
|
|
|
class ReadBuffer {
|
|
constructor(options) {
|
|
this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE;
|
|
}
|
|
append(chunk) {
|
|
const newSize = (this._buffer?.length ?? 0) + chunk.length;
|
|
if (newSize > this._maxBufferSize) {
|
|
this.clear();
|
|
throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);
|
|
}
|
|
this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
|
|
}
|
|
readMessage() {
|
|
if (!this._buffer) {
|
|
return null;
|
|
}
|
|
const index = this._buffer.indexOf(`
|
|
`);
|
|
if (index === -1) {
|
|
return null;
|
|
}
|
|
const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");
|
|
this._buffer = this._buffer.subarray(index + 1);
|
|
return deserializeMessage(line);
|
|
}
|
|
clear() {
|
|
this._buffer = undefined;
|
|
}
|
|
}
|
|
function deserializeMessage(line) {
|
|
return JSONRPCMessageSchema.parse(JSON.parse(line));
|
|
}
|
|
function serializeMessage(message) {
|
|
return JSON.stringify(message) + `
|
|
`;
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.30.0_@cfworker+json-schema@4.1.1_supports-color@10.2.2_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
|
|
class StdioServerTransport {
|
|
constructor(_stdin = process3.stdin, _stdout = process3.stdout, options) {
|
|
this._stdin = _stdin;
|
|
this._stdout = _stdout;
|
|
this._started = false;
|
|
this._ondata = (chunk) => {
|
|
try {
|
|
this._readBuffer.append(chunk);
|
|
this.processReadBuffer();
|
|
} catch (error) {
|
|
this.onerror?.(error);
|
|
this.close().catch(() => {});
|
|
}
|
|
};
|
|
this._onerror = (error) => {
|
|
this.onerror?.(error);
|
|
};
|
|
this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize });
|
|
}
|
|
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 (error) {
|
|
this.onerror?.(error);
|
|
}
|
|
}
|
|
}
|
|
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((resolve) => {
|
|
const json = serializeMessage(message);
|
|
if (this._stdout.write(json)) {
|
|
resolve();
|
|
} else {
|
|
this._stdout.once("drain", resolve);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
// src/effects/json.ts
|
|
class JSONParseError extends TaggedError("effects/JSONParseError") {
|
|
}
|
|
var JsonRecordSchema = Record({ key: String$, value: Unknown });
|
|
|
|
// src/services/run-subagent-shared.ts
|
|
var ACP_STRUCTURED_OUTPUT_TOOL_NAME = "submit_structured_output";
|
|
var ACP_STRUCTURED_OUTPUT_WRAPPER_KEY = "value";
|
|
var decodeStructuredSchema = decodeUnknownSync(parseJson(JsonRecordSchema));
|
|
var decodeStructuredSchemaJson = (text) => decodeStructuredSchema(text);
|
|
var isStructuredObjectSchema = (structuredSchema) => {
|
|
if (!structuredSchema || Array.isArray(structuredSchema)) {
|
|
return false;
|
|
}
|
|
const schemaType = structuredSchema.type;
|
|
if (schemaType === "object") {
|
|
return true;
|
|
}
|
|
if (Array.isArray(schemaType) && schemaType.includes("object")) {
|
|
return true;
|
|
}
|
|
return "properties" in structuredSchema || "required" in structuredSchema || "additionalProperties" in structuredSchema;
|
|
};
|
|
var buildStructuredOutputToolSchema = (structuredSchema) => isStructuredObjectSchema(structuredSchema) ? structuredSchema : {
|
|
type: "object",
|
|
additionalProperties: false,
|
|
required: [ACP_STRUCTURED_OUTPUT_WRAPPER_KEY],
|
|
properties: {
|
|
[ACP_STRUCTURED_OUTPUT_WRAPPER_KEY]: structuredSchema
|
|
}
|
|
};
|
|
|
|
// src/services/terminal-ui.ts
|
|
import process4 from "process";
|
|
|
|
// ../../../node_modules/.pnpm/@clack+core@1.4.3/node_modules/@clack/core/dist/index.mjs
|
|
import { stdout, stdin } from "process";
|
|
import * as l from "readline";
|
|
import l__default from "readline";
|
|
|
|
// ../../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/utils.js
|
|
var getCodePointsLength = (() => {
|
|
const SURROGATE_PAIR_RE = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
|
|
return (input) => {
|
|
let surrogatePairsNr = 0;
|
|
SURROGATE_PAIR_RE.lastIndex = 0;
|
|
while (SURROGATE_PAIR_RE.test(input)) {
|
|
surrogatePairsNr += 1;
|
|
}
|
|
return input.length - surrogatePairsNr;
|
|
};
|
|
})();
|
|
var isFullWidth = (x) => {
|
|
return x === 12288 || x >= 65281 && x <= 65376 || x >= 65504 && x <= 65510;
|
|
};
|
|
var isWideNotCJKTNotEmoji = (x) => {
|
|
return x === 8987 || x === 9001 || x >= 12272 && x <= 12287 || x >= 12289 && x <= 12350 || x >= 12441 && x <= 12543 || x >= 12549 && x <= 12591 || x >= 12593 && x <= 12686 || x >= 12688 && x <= 12771 || x >= 12783 && x <= 12830 || x >= 12832 && x <= 12871 || x >= 12880 && x <= 19903 || x >= 65040 && x <= 65049 || x >= 65072 && x <= 65106 || x >= 65108 && x <= 65126 || x >= 65128 && x <= 65131 || x >= 127488 && x <= 127490 || x >= 127504 && x <= 127547 || x >= 127552 && x <= 127560 || x >= 131072 && x <= 196605 || x >= 196608 && x <= 262141;
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/index.js
|
|
var ANSI_RE = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y;
|
|
var CONTROL_RE = /[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y;
|
|
var CJKT_WIDE_RE = /(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu;
|
|
var TAB_RE = /\t{1,1000}/y;
|
|
var EMOJI_RE = /[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu;
|
|
var LATIN_RE = /(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y;
|
|
var MODIFIER_RE = /\p{M}+/gu;
|
|
var NO_TRUNCATION = { limit: Infinity, ellipsis: "" };
|
|
var getStringTruncatedWidth = (input, truncationOptions = {}, widthOptions = {}) => {
|
|
const LIMIT = truncationOptions.limit ?? Infinity;
|
|
const ELLIPSIS = truncationOptions.ellipsis ?? "";
|
|
const ELLIPSIS_WIDTH = truncationOptions?.ellipsisWidth ?? (ELLIPSIS ? getStringTruncatedWidth(ELLIPSIS, NO_TRUNCATION, widthOptions).width : 0);
|
|
const ANSI_WIDTH = 0;
|
|
const CONTROL_WIDTH = widthOptions.controlWidth ?? 0;
|
|
const TAB_WIDTH = widthOptions.tabWidth ?? 8;
|
|
const EMOJI_WIDTH = widthOptions.emojiWidth ?? 2;
|
|
const FULL_WIDTH_WIDTH = 2;
|
|
const REGULAR_WIDTH = widthOptions.regularWidth ?? 1;
|
|
const WIDE_WIDTH = widthOptions.wideWidth ?? FULL_WIDTH_WIDTH;
|
|
const PARSE_BLOCKS = [
|
|
[LATIN_RE, REGULAR_WIDTH],
|
|
[ANSI_RE, ANSI_WIDTH],
|
|
[CONTROL_RE, CONTROL_WIDTH],
|
|
[TAB_RE, TAB_WIDTH],
|
|
[EMOJI_RE, EMOJI_WIDTH],
|
|
[CJKT_WIDE_RE, WIDE_WIDTH]
|
|
];
|
|
let indexPrev = 0;
|
|
let index = 0;
|
|
let length = input.length;
|
|
let lengthExtra = 0;
|
|
let truncationEnabled = false;
|
|
let truncationIndex = length;
|
|
let truncationLimit = Math.max(0, LIMIT - ELLIPSIS_WIDTH);
|
|
let unmatchedStart = 0;
|
|
let unmatchedEnd = 0;
|
|
let width = 0;
|
|
let widthExtra = 0;
|
|
outer:
|
|
while (true) {
|
|
if (unmatchedEnd > unmatchedStart || index >= length && index > indexPrev) {
|
|
const unmatched = input.slice(unmatchedStart, unmatchedEnd) || input.slice(indexPrev, index);
|
|
lengthExtra = 0;
|
|
for (const char of unmatched.replaceAll(MODIFIER_RE, "")) {
|
|
const codePoint = char.codePointAt(0) || 0;
|
|
if (isFullWidth(codePoint)) {
|
|
widthExtra = FULL_WIDTH_WIDTH;
|
|
} else if (isWideNotCJKTNotEmoji(codePoint)) {
|
|
widthExtra = WIDE_WIDTH;
|
|
} else {
|
|
widthExtra = REGULAR_WIDTH;
|
|
}
|
|
if (width + widthExtra > truncationLimit) {
|
|
truncationIndex = Math.min(truncationIndex, Math.max(unmatchedStart, indexPrev) + lengthExtra);
|
|
}
|
|
if (width + widthExtra > LIMIT) {
|
|
truncationEnabled = true;
|
|
break outer;
|
|
}
|
|
lengthExtra += char.length;
|
|
width += widthExtra;
|
|
}
|
|
unmatchedStart = unmatchedEnd = 0;
|
|
}
|
|
if (index >= length) {
|
|
break outer;
|
|
}
|
|
for (let i = 0, l = PARSE_BLOCKS.length;i < l; i++) {
|
|
const [BLOCK_RE, BLOCK_WIDTH] = PARSE_BLOCKS[i];
|
|
BLOCK_RE.lastIndex = index;
|
|
if (BLOCK_RE.test(input)) {
|
|
lengthExtra = BLOCK_RE === CJKT_WIDE_RE ? getCodePointsLength(input.slice(index, BLOCK_RE.lastIndex)) : BLOCK_RE === EMOJI_RE ? 1 : BLOCK_RE.lastIndex - index;
|
|
widthExtra = lengthExtra * BLOCK_WIDTH;
|
|
if (width + widthExtra > truncationLimit) {
|
|
truncationIndex = Math.min(truncationIndex, index + Math.floor((truncationLimit - width) / BLOCK_WIDTH));
|
|
}
|
|
if (width + widthExtra > LIMIT) {
|
|
truncationEnabled = true;
|
|
break outer;
|
|
}
|
|
width += widthExtra;
|
|
unmatchedStart = indexPrev;
|
|
unmatchedEnd = index;
|
|
index = indexPrev = BLOCK_RE.lastIndex;
|
|
continue outer;
|
|
}
|
|
}
|
|
index += 1;
|
|
}
|
|
return {
|
|
width: truncationEnabled ? truncationLimit : width,
|
|
index: truncationEnabled ? truncationIndex : length,
|
|
truncated: truncationEnabled,
|
|
ellipsed: truncationEnabled && LIMIT >= ELLIPSIS_WIDTH
|
|
};
|
|
};
|
|
var dist_default = getStringTruncatedWidth;
|
|
|
|
// ../../../node_modules/.pnpm/fast-string-width@3.0.2/node_modules/fast-string-width/dist/index.js
|
|
var NO_TRUNCATION2 = {
|
|
limit: Infinity,
|
|
ellipsis: "",
|
|
ellipsisWidth: 0
|
|
};
|
|
var fastStringWidth = (input, options = {}) => {
|
|
return dist_default(input, NO_TRUNCATION2, options).width;
|
|
};
|
|
var dist_default2 = fastStringWidth;
|
|
|
|
// ../../../node_modules/.pnpm/fast-wrap-ansi@0.2.2/node_modules/fast-wrap-ansi/lib/main.js
|
|
var ESC = "\x1B";
|
|
var CSI = "\x9B";
|
|
var END_CODE = 39;
|
|
var ANSI_ESCAPE_BELL = "\x07";
|
|
var ANSI_CSI = "[";
|
|
var ANSI_OSC = "]";
|
|
var ANSI_SGR_TERMINATOR = "m";
|
|
var ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
|
|
var GROUP_REGEX = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`, "y");
|
|
var getClosingCode = (openingCode) => {
|
|
if (openingCode >= 30 && openingCode <= 37)
|
|
return 39;
|
|
if (openingCode >= 90 && openingCode <= 97)
|
|
return 39;
|
|
if (openingCode >= 40 && openingCode <= 47)
|
|
return 49;
|
|
if (openingCode >= 100 && openingCode <= 107)
|
|
return 49;
|
|
if (openingCode === 1 || openingCode === 2)
|
|
return 22;
|
|
if (openingCode === 3)
|
|
return 23;
|
|
if (openingCode === 4)
|
|
return 24;
|
|
if (openingCode === 7)
|
|
return 27;
|
|
if (openingCode === 8)
|
|
return 28;
|
|
if (openingCode === 9)
|
|
return 29;
|
|
if (openingCode === 0)
|
|
return 0;
|
|
return;
|
|
};
|
|
var wrapAnsiCode = (code) => `${ESC}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
|
|
var wrapAnsiHyperlink = (url) => `${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`;
|
|
var wrapWord = (rows, word, columns) => {
|
|
const characters = word[Symbol.iterator]();
|
|
let isInsideEscape = false;
|
|
let isInsideLinkEscape = false;
|
|
let lastRow = rows.at(-1);
|
|
let visible = lastRow === undefined ? 0 : dist_default2(lastRow);
|
|
let currentCharacter = characters.next();
|
|
let nextCharacter = characters.next();
|
|
let rawCharacterIndex = 0;
|
|
while (!currentCharacter.done) {
|
|
const character = currentCharacter.value;
|
|
const characterLength = dist_default2(character);
|
|
if (visible + characterLength <= columns) {
|
|
rows[rows.length - 1] += character;
|
|
} else {
|
|
rows.push(character);
|
|
visible = 0;
|
|
}
|
|
if (character === ESC || character === CSI) {
|
|
isInsideEscape = true;
|
|
isInsideLinkEscape = word.startsWith(ANSI_ESCAPE_LINK, rawCharacterIndex + 1);
|
|
}
|
|
if (isInsideEscape) {
|
|
if (isInsideLinkEscape) {
|
|
if (character === ANSI_ESCAPE_BELL) {
|
|
isInsideEscape = false;
|
|
isInsideLinkEscape = false;
|
|
}
|
|
} else if (character === ANSI_SGR_TERMINATOR) {
|
|
isInsideEscape = false;
|
|
}
|
|
} else {
|
|
visible += characterLength;
|
|
if (visible === columns && !nextCharacter.done) {
|
|
rows.push("");
|
|
visible = 0;
|
|
}
|
|
}
|
|
currentCharacter = nextCharacter;
|
|
nextCharacter = characters.next();
|
|
rawCharacterIndex += character.length;
|
|
}
|
|
lastRow = rows.at(-1);
|
|
if (!visible && lastRow !== undefined && lastRow.length && rows.length > 1) {
|
|
rows[rows.length - 2] += rows.pop();
|
|
}
|
|
};
|
|
var stringVisibleTrimSpacesRight = (string) => {
|
|
const words = string.split(" ");
|
|
let last = words.length;
|
|
while (last) {
|
|
if (dist_default2(words[last - 1])) {
|
|
break;
|
|
}
|
|
last--;
|
|
}
|
|
if (last === words.length) {
|
|
return string;
|
|
}
|
|
return words.slice(0, last).join(" ") + words.slice(last).join("");
|
|
};
|
|
var exec = (string, columns, options = {}) => {
|
|
if (options.trim !== false && string.trim() === "") {
|
|
return "";
|
|
}
|
|
let returnValue = "";
|
|
let escapeCode;
|
|
let escapeUrl;
|
|
const words = string.split(" ");
|
|
let rows = [""];
|
|
let rowLength = 0;
|
|
for (let index = 0;index < words.length; index++) {
|
|
const word = words[index];
|
|
if (options.trim !== false) {
|
|
const row = rows.at(-1) ?? "";
|
|
const trimmed = row.trimStart();
|
|
if (row.length !== trimmed.length) {
|
|
rows[rows.length - 1] = trimmed;
|
|
rowLength = dist_default2(trimmed);
|
|
}
|
|
}
|
|
if (index !== 0) {
|
|
if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
|
|
rows.push("");
|
|
rowLength = 0;
|
|
}
|
|
if (rowLength || options.trim === false) {
|
|
rows[rows.length - 1] += " ";
|
|
rowLength++;
|
|
}
|
|
}
|
|
const wordLength = dist_default2(word);
|
|
if (options.hard && wordLength > columns) {
|
|
const remainingColumns = columns - rowLength;
|
|
const breaksStartingThisLine = 1 + Math.floor((wordLength - remainingColumns - 1) / columns);
|
|
const breaksStartingNextLine = Math.floor((wordLength - 1) / columns);
|
|
if (breaksStartingNextLine < breaksStartingThisLine) {
|
|
rows.push("");
|
|
}
|
|
wrapWord(rows, word, columns);
|
|
rowLength = dist_default2(rows.at(-1) ?? "");
|
|
continue;
|
|
}
|
|
if (rowLength + wordLength > columns && rowLength && wordLength) {
|
|
if (options.wordWrap === false && rowLength < columns) {
|
|
wrapWord(rows, word, columns);
|
|
rowLength = dist_default2(rows.at(-1) ?? "");
|
|
continue;
|
|
}
|
|
rows.push("");
|
|
rowLength = 0;
|
|
}
|
|
if (rowLength + wordLength > columns && options.wordWrap === false) {
|
|
wrapWord(rows, word, columns);
|
|
rowLength = dist_default2(rows.at(-1) ?? "");
|
|
continue;
|
|
}
|
|
rows[rows.length - 1] += word;
|
|
rowLength += wordLength;
|
|
}
|
|
if (options.trim !== false) {
|
|
rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
|
|
}
|
|
const preString = rows.join(`
|
|
`);
|
|
let inSurrogate = false;
|
|
for (let i = 0;i < preString.length; i++) {
|
|
const character = preString[i];
|
|
returnValue += character;
|
|
if (!inSurrogate) {
|
|
inSurrogate = character >= "\uD800" && character <= "\uDBFF";
|
|
if (inSurrogate) {
|
|
continue;
|
|
}
|
|
} else {
|
|
inSurrogate = false;
|
|
}
|
|
if (character === ESC || character === CSI) {
|
|
GROUP_REGEX.lastIndex = i + 1;
|
|
const groupsResult = GROUP_REGEX.exec(preString);
|
|
const groups = groupsResult?.groups;
|
|
if (groups?.code !== undefined) {
|
|
const code = Number.parseFloat(groups.code);
|
|
escapeCode = code === END_CODE ? undefined : code;
|
|
} else if (groups?.uri !== undefined) {
|
|
escapeUrl = groups.uri.length === 0 ? undefined : groups.uri;
|
|
}
|
|
}
|
|
if (preString[i + 1] === `
|
|
`) {
|
|
if (escapeUrl) {
|
|
returnValue += wrapAnsiHyperlink("");
|
|
}
|
|
const closingCode = escapeCode ? getClosingCode(escapeCode) : undefined;
|
|
if (escapeCode && closingCode) {
|
|
returnValue += wrapAnsiCode(closingCode);
|
|
}
|
|
} else if (character === `
|
|
`) {
|
|
if (escapeCode && getClosingCode(escapeCode)) {
|
|
returnValue += wrapAnsiCode(escapeCode);
|
|
}
|
|
if (escapeUrl) {
|
|
returnValue += wrapAnsiHyperlink(escapeUrl);
|
|
}
|
|
}
|
|
}
|
|
return returnValue;
|
|
};
|
|
var CRLF_OR_LF = /\r?\n/;
|
|
function wrapAnsi(string, columns, options) {
|
|
return String(string).normalize().split(CRLF_OR_LF).map((line) => exec(line, columns, options)).join(`
|
|
`);
|
|
}
|
|
|
|
// ../../../node_modules/.pnpm/@clack+core@1.4.3/node_modules/@clack/core/dist/index.mjs
|
|
var import_sisteransi = __toESM(require_src(), 1);
|
|
import { ReadStream } from "tty";
|
|
function findCursor(s, o, l) {
|
|
if (!l.some((r) => !r.disabled))
|
|
return s;
|
|
const t = s + o, n = Math.max(l.length - 1, 0), e = t < 0 ? n : t > n ? 0 : t;
|
|
return l[e]?.disabled ? findCursor(e, o < 0 ? -1 : 1, l) : e;
|
|
}
|
|
var a$1 = ["up", "down", "left", "right", "space", "enter", "cancel"];
|
|
var t = [
|
|
"January",
|
|
"February",
|
|
"March",
|
|
"April",
|
|
"May",
|
|
"June",
|
|
"July",
|
|
"August",
|
|
"September",
|
|
"October",
|
|
"November",
|
|
"December"
|
|
];
|
|
var settings = {
|
|
actions: new Set(a$1),
|
|
aliases: /* @__PURE__ */ new Map([
|
|
["k", "up"],
|
|
["j", "down"],
|
|
["h", "left"],
|
|
["l", "right"],
|
|
["\x03", "cancel"],
|
|
["escape", "cancel"]
|
|
]),
|
|
messages: {
|
|
cancel: "Canceled",
|
|
error: "Something went wrong"
|
|
},
|
|
withGuide: true,
|
|
date: {
|
|
monthNames: [...t],
|
|
messages: {
|
|
required: "Please enter a valid date",
|
|
invalidMonth: "There are only 12 months in a year",
|
|
invalidDay: (n, e) => `There are only ${n} days in ${e}`,
|
|
afterMin: (n) => `Date must be on or after ${n.toISOString().slice(0, 10)}`,
|
|
beforeMax: (n) => `Date must be on or before ${n.toISOString().slice(0, 10)}`
|
|
}
|
|
}
|
|
};
|
|
function isActionKey(n, e) {
|
|
if (typeof n == "string")
|
|
return settings.aliases.get(n) === e;
|
|
for (const s of n)
|
|
if (s !== undefined && isActionKey(s, e))
|
|
return true;
|
|
return false;
|
|
}
|
|
function diffLines(i, s) {
|
|
if (i === s)
|
|
return;
|
|
const e = i.split(`
|
|
`), t = s.split(`
|
|
`), r = Math.max(e.length, t.length), f = [];
|
|
for (let n = 0;n < r; n++)
|
|
e[n] !== t[n] && f.push(n);
|
|
return {
|
|
lines: f,
|
|
numLinesBefore: e.length,
|
|
numLinesAfter: t.length,
|
|
numLines: r
|
|
};
|
|
}
|
|
var R = globalThis.process.platform.startsWith("win");
|
|
var CANCEL_SYMBOL = Symbol("clack:cancel");
|
|
function isCancel(e) {
|
|
return e === CANCEL_SYMBOL;
|
|
}
|
|
function setRawMode(e, r) {
|
|
const o = e;
|
|
o.isTTY && o.setRawMode(r);
|
|
}
|
|
function block({
|
|
input: e = stdin,
|
|
output: r = stdout,
|
|
overwrite: o = true,
|
|
hideCursor: t = true
|
|
} = {}) {
|
|
const s = l.createInterface({
|
|
input: e,
|
|
output: r,
|
|
prompt: "",
|
|
tabSize: 1
|
|
});
|
|
l.emitKeypressEvents(e, s), e instanceof ReadStream && e.isTTY && e.setRawMode(true);
|
|
const n = (f, { name: a, sequence: p }) => {
|
|
const c = String(f);
|
|
if (isActionKey([c, a, p], "cancel")) {
|
|
t && r.write(import_sisteransi.cursor.show), process.exit(0);
|
|
return;
|
|
}
|
|
if (!o)
|
|
return;
|
|
const i = a === "return" ? 0 : -1, m = a === "return" ? -1 : 0;
|
|
l.moveCursor(r, i, m, () => {
|
|
l.clearLine(r, 1, () => {
|
|
e.once("keypress", n);
|
|
});
|
|
});
|
|
};
|
|
return t && r.write(import_sisteransi.cursor.hide), e.once("keypress", n), () => {
|
|
e.off("keypress", n), t && r.write(import_sisteransi.cursor.show), e instanceof ReadStream && e.isTTY && !R && e.setRawMode(false), s.terminal = false, s.close();
|
|
};
|
|
}
|
|
var getColumns = (e) => ("columns" in e) && typeof e.columns == "number" ? e.columns : 80;
|
|
var getRows = (e) => ("rows" in e) && typeof e.rows == "number" ? e.rows : 20;
|
|
function wrapTextWithPrefix(e, r, o, t = o, s = o, n) {
|
|
const f = getColumns(e ?? stdout);
|
|
return wrapAnsi(r, f - o.length, {
|
|
hard: true,
|
|
trim: false
|
|
}).split(`
|
|
`).map((c, i, m) => {
|
|
const d = n ? n(c, i) : c;
|
|
return i === 0 ? `${t}${d}` : i === m.length - 1 ? `${s}${d}` : `${o}${d}`;
|
|
}).join(`
|
|
`);
|
|
}
|
|
function runValidation(e, n) {
|
|
if ("~standard" in e) {
|
|
const a = e["~standard"].validate(n);
|
|
if (a instanceof Promise)
|
|
throw new TypeError("Schema validation must be synchronous. Update `validate()` and remove any asynchronous logic.");
|
|
return a.issues?.at(0)?.message;
|
|
}
|
|
return e(n);
|
|
}
|
|
|
|
class V {
|
|
input;
|
|
output;
|
|
_abortSignal;
|
|
rl;
|
|
opts;
|
|
_render;
|
|
_track = false;
|
|
_prevFrame = "";
|
|
_subscribers = /* @__PURE__ */ new Map;
|
|
_cursor = 0;
|
|
state = "initial";
|
|
error = "";
|
|
value;
|
|
userInput = "";
|
|
constructor(t, e = true) {
|
|
const { input: i = stdin, output: n = stdout, render: s, signal: r, ...o } = t;
|
|
this.opts = o, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = s.bind(this), this._track = e, this._abortSignal = r, this.input = i, this.output = n;
|
|
}
|
|
unsubscribe() {
|
|
this._subscribers.clear();
|
|
}
|
|
setSubscriber(t, e) {
|
|
const i = this._subscribers.get(t) ?? [];
|
|
i.push(e), this._subscribers.set(t, i);
|
|
}
|
|
on(t, e) {
|
|
this.setSubscriber(t, { cb: e });
|
|
}
|
|
once(t, e) {
|
|
this.setSubscriber(t, { cb: e, once: true });
|
|
}
|
|
emit(t, ...e) {
|
|
const i = this._subscribers.get(t) ?? [], n = [];
|
|
for (const s of i)
|
|
s.cb(...e), s.once && n.push(() => i.splice(i.indexOf(s), 1));
|
|
for (const s of n)
|
|
s();
|
|
}
|
|
prompt() {
|
|
return new Promise((t) => {
|
|
if (this._abortSignal) {
|
|
if (this._abortSignal.aborted)
|
|
return this.state = "cancel", this.close(), t(CANCEL_SYMBOL);
|
|
this._abortSignal.addEventListener("abort", () => {
|
|
this.state = "cancel", this.close();
|
|
}, { once: true });
|
|
}
|
|
this.rl = l__default.createInterface({
|
|
input: this.input,
|
|
tabSize: 2,
|
|
prompt: "",
|
|
escapeCodeTimeout: 50,
|
|
terminal: true
|
|
}), this.rl.prompt(), this.opts.initialUserInput !== undefined && this._setUserInput(this.opts.initialUserInput, true), this.input.on("keypress", this.onKeypress), setRawMode(this.input, true), this.output.on("resize", this.render), this.render(), this.once("submit", () => {
|
|
this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t(this.value);
|
|
}), this.once("cancel", () => {
|
|
this.output.write(import_sisteransi.cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t(CANCEL_SYMBOL);
|
|
});
|
|
});
|
|
}
|
|
_isActionKey(t, e) {
|
|
return t === "\t";
|
|
}
|
|
_shouldSubmit(t, e) {
|
|
return true;
|
|
}
|
|
_setValue(t) {
|
|
this.value = t, this.emit("value", this.value);
|
|
}
|
|
_setUserInput(t, e) {
|
|
this.userInput = t ?? "", this.emit("userInput", this.userInput), e && this._track && this.rl && (this.rl.write(this.userInput), this._cursor = this.rl.cursor);
|
|
}
|
|
_clearUserInput() {
|
|
this.rl?.write(null, { ctrl: true, name: "u" }), this._setUserInput("");
|
|
}
|
|
onKeypress(t, e) {
|
|
if (this._track && e.name !== "return" && (e.name && this._isActionKey(t, e) && this.rl?.write(null, { ctrl: true, name: "h" }), this._cursor = this.rl?.cursor ?? 0, this._setUserInput(this.rl?.line)), this.state === "error" && (this.state = "active"), e?.name && (!this._track && settings.aliases.has(e.name) && this.emit("cursor", settings.aliases.get(e.name)), settings.actions.has(e.name) && this.emit("cursor", e.name)), t && (t.toLowerCase() === "y" || t.toLowerCase() === "n") && this.emit("confirm", t.toLowerCase() === "y"), this.emit("key", t, e), e?.name === "return" && this._shouldSubmit(t, e)) {
|
|
if (this.opts.validate) {
|
|
const i = runValidation(this.opts.validate, this.value);
|
|
i && (this.error = i instanceof Error ? i.message : i, this.state = "error", this.rl?.write(this.userInput));
|
|
}
|
|
this.state !== "error" && (this.state = "submit");
|
|
}
|
|
isActionKey([t, e?.name, e?.sequence], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
|
|
}
|
|
close() {
|
|
this.input.unpipe(), this.input.removeListener("keypress", this.onKeypress), this.output.write(`
|
|
`), setRawMode(this.input, false), this.rl?.close(), this.rl = undefined, this.emit(`${this.state}`, this.value), this.unsubscribe();
|
|
}
|
|
restoreCursor() {
|
|
const t = wrapAnsi(this._prevFrame, process.stdout.columns, { hard: true, trim: false }).split(`
|
|
`).length - 1;
|
|
this.output.write(import_sisteransi.cursor.move(-999, t * -1));
|
|
}
|
|
render() {
|
|
const t = wrapAnsi(this._render(this) ?? "", process.stdout.columns, {
|
|
hard: true,
|
|
trim: false
|
|
});
|
|
if (t !== this._prevFrame) {
|
|
if (this.state === "initial")
|
|
this.output.write(import_sisteransi.cursor.hide);
|
|
else {
|
|
const e = diffLines(this._prevFrame, t), i = getRows(this.output);
|
|
if (this.restoreCursor(), e) {
|
|
const n = Math.max(0, e.numLinesAfter - i), s = Math.max(0, e.numLinesBefore - i);
|
|
let r = e.lines.find((o) => o >= n);
|
|
if (r === undefined) {
|
|
this._prevFrame = t;
|
|
return;
|
|
}
|
|
if (e.lines.length === 1) {
|
|
this.output.write(import_sisteransi.cursor.move(0, r - s)), this.output.write(import_sisteransi.erase.lines(1));
|
|
const o = t.split(`
|
|
`);
|
|
this.output.write(o[r]), this._prevFrame = t, this.output.write(import_sisteransi.cursor.move(0, o.length - r - 1));
|
|
return;
|
|
} else if (e.lines.length > 1) {
|
|
if (n < s)
|
|
r = n;
|
|
else {
|
|
const h = r - s;
|
|
h > 0 && this.output.write(import_sisteransi.cursor.move(0, h));
|
|
}
|
|
this.output.write(import_sisteransi.erase.down());
|
|
const f = t.split(`
|
|
`).slice(r);
|
|
this.output.write(f.join(`
|
|
`)), this._prevFrame = t;
|
|
return;
|
|
}
|
|
}
|
|
this.output.write(import_sisteransi.erase.down());
|
|
}
|
|
this.output.write(t), this.state === "initial" && (this.state = "active"), this._prevFrame = t;
|
|
}
|
|
}
|
|
}
|
|
class r extends V {
|
|
get cursor() {
|
|
return this.value ? 0 : 1;
|
|
}
|
|
get _value() {
|
|
return this.cursor === 0;
|
|
}
|
|
constructor(t) {
|
|
super(t, false), this.value = !!t.initialValue, this.on("userInput", () => {
|
|
this.value = this._value;
|
|
}), this.on("confirm", (i) => {
|
|
this.output.write(import_sisteransi.cursor.move(0, -1)), this.value = i, this.state = "submit", this.close();
|
|
}), this.on("cursor", () => {
|
|
this.value = !this.value;
|
|
});
|
|
}
|
|
}
|
|
var n$1 = class n extends V {
|
|
options;
|
|
cursor = 0;
|
|
get _selectedValue() {
|
|
return this.options[this.cursor];
|
|
}
|
|
changeValue() {
|
|
const e = this._selectedValue;
|
|
this.value = e === undefined ? undefined : e.value;
|
|
}
|
|
constructor(e) {
|
|
super(e, false), this.options = e.options;
|
|
const o = this.options.findIndex(({ value: s }) => s === e.initialValue), t = o === -1 ? 0 : o;
|
|
this.cursor = this.options[t]?.disabled ? findCursor(t, 1, this.options) : t, this.changeValue(), this.on("cursor", (s) => {
|
|
switch (s) {
|
|
case "left":
|
|
case "up":
|
|
this.cursor = findCursor(this.cursor, -1, this.options);
|
|
break;
|
|
case "down":
|
|
case "right":
|
|
this.cursor = findCursor(this.cursor, 1, this.options);
|
|
break;
|
|
}
|
|
this.changeValue();
|
|
});
|
|
}
|
|
};
|
|
|
|
// ../../../node_modules/.pnpm/@clack+prompts@1.7.0/node_modules/@clack/prompts/dist/index.mjs
|
|
import { styleText, stripVTControlCharacters } from "util";
|
|
import process$1 from "process";
|
|
var import_sisteransi2 = __toESM(require_src(), 1);
|
|
function isUnicodeSupported() {
|
|
if (process$1.platform !== "win32") {
|
|
return process$1.env.TERM !== "linux";
|
|
}
|
|
return Boolean(process$1.env.CI) || Boolean(process$1.env.WT_SESSION) || Boolean(process$1.env.TERMINUS_SUBLIME) || process$1.env.ConEmuTask === "{cmd::Cmder}" || process$1.env.TERM_PROGRAM === "Terminus-Sublime" || process$1.env.TERM_PROGRAM === "vscode" || process$1.env.TERM === "xterm-256color" || process$1.env.TERM === "alacritty" || process$1.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
|
|
}
|
|
var unicode = isUnicodeSupported();
|
|
var isCI = () => process.env.CI === "true";
|
|
var unicodeOr = (o, e) => unicode ? o : e;
|
|
var S_STEP_ACTIVE = unicodeOr("\u25C6", "*");
|
|
var S_STEP_CANCEL = unicodeOr("\u25A0", "x");
|
|
var S_STEP_ERROR = unicodeOr("\u25B2", "x");
|
|
var S_STEP_SUBMIT = unicodeOr("\u25C7", "o");
|
|
var S_BAR_START = unicodeOr("\u250C", "T");
|
|
var S_BAR = unicodeOr("\u2502", "|");
|
|
var S_BAR_END = unicodeOr("\u2514", "\u2014");
|
|
var S_BAR_START_RIGHT = unicodeOr("\u2510", "T");
|
|
var S_BAR_END_RIGHT = unicodeOr("\u2518", "\u2014");
|
|
var S_RADIO_ACTIVE = unicodeOr("\u25CF", ">");
|
|
var S_RADIO_INACTIVE = unicodeOr("\u25CB", " ");
|
|
var S_CHECKBOX_ACTIVE = unicodeOr("\u25FB", "[\u2022]");
|
|
var S_CHECKBOX_SELECTED = unicodeOr("\u25FC", "[+]");
|
|
var S_CHECKBOX_INACTIVE = unicodeOr("\u25FB", "[ ]");
|
|
var S_PASSWORD_MASK = unicodeOr("\u25AA", "\u2022");
|
|
var S_BAR_H = unicodeOr("\u2500", "-");
|
|
var S_CORNER_TOP_RIGHT = unicodeOr("\u256E", "+");
|
|
var S_CONNECT_LEFT = unicodeOr("\u251C", "+");
|
|
var S_CORNER_BOTTOM_RIGHT = unicodeOr("\u256F", "+");
|
|
var S_CORNER_BOTTOM_LEFT = unicodeOr("\u2570", "+");
|
|
var S_CORNER_TOP_LEFT = unicodeOr("\u256D", "+");
|
|
var S_INFO = unicodeOr("\u25CF", "\u2022");
|
|
var S_SUCCESS = unicodeOr("\u25C6", "*");
|
|
var S_WARN = unicodeOr("\u25B2", "!");
|
|
var S_ERROR = unicodeOr("\u25A0", "x");
|
|
var symbol3 = (o) => {
|
|
switch (o) {
|
|
case "initial":
|
|
case "active":
|
|
return styleText("cyan", S_STEP_ACTIVE);
|
|
case "cancel":
|
|
return styleText("red", S_STEP_CANCEL);
|
|
case "error":
|
|
return styleText("yellow", S_STEP_ERROR);
|
|
case "submit":
|
|
return styleText("green", S_STEP_SUBMIT);
|
|
}
|
|
};
|
|
var symbolBar = (o) => {
|
|
switch (o) {
|
|
case "initial":
|
|
case "active":
|
|
return styleText("cyan", S_BAR);
|
|
case "cancel":
|
|
return styleText("red", S_BAR);
|
|
case "error":
|
|
return styleText("yellow", S_BAR);
|
|
case "submit":
|
|
return styleText("green", S_BAR);
|
|
}
|
|
};
|
|
function formatInstructionFooter(o, e) {
|
|
const r = [`${e ? `${styleText("cyan", S_BAR)} ` : ""}${o.join(" \u2022 ")}`];
|
|
return e && r.push(styleText("cyan", S_BAR_END)), r;
|
|
}
|
|
var I = (l, e, w, p, b, C = false) => {
|
|
let r = e, O = 0;
|
|
if (C)
|
|
for (let i = p - 1;i >= w; i--) {
|
|
const m = l[i];
|
|
if (m && (r -= m.length), O++, r <= b)
|
|
break;
|
|
}
|
|
else
|
|
for (let i = w;i < p; i++) {
|
|
const m = l[i];
|
|
if (m && (r -= m.length), O++, r <= b)
|
|
break;
|
|
}
|
|
return { lineCount: r, removals: O };
|
|
};
|
|
var limitOptions = ({
|
|
cursor: l,
|
|
options: e,
|
|
style: w,
|
|
output: p = process.stdout,
|
|
maxItems: b = Number.POSITIVE_INFINITY,
|
|
columnPadding: C = 0,
|
|
rowPadding: r = 4
|
|
}) => {
|
|
const i = getColumns(p) - C, m = getRows(p), M = styleText("dim", "..."), v = Math.max(m - r, 0), a = Math.max(Math.min(b, v), 5);
|
|
let f = 0;
|
|
l >= a - 3 && (f = Math.max(Math.min(l - a + 3, e.length - a), 0));
|
|
let d = a < e.length && f > 0, c = a < e.length && f + a < e.length;
|
|
const W = Math.min(f + a, e.length), s = [];
|
|
let g = 0;
|
|
d && g++, c && g++;
|
|
const T = f + (d ? 1 : 0), y = W - (c ? 1 : 0);
|
|
for (let t = T;t < y; t++) {
|
|
const n = e[t], o = n ? w(n, t === l) : "", h = wrapAnsi(o, i, {
|
|
hard: true,
|
|
trim: false
|
|
}).split(`
|
|
`);
|
|
s.push(h), g += h.length;
|
|
}
|
|
if (g > v) {
|
|
let t = 0, n = 0, o = g;
|
|
const h = l - T;
|
|
let u = v;
|
|
const L = () => I(s, o, 0, h, u), E = () => I(s, o, h + 1, s.length, u, true);
|
|
d ? ({ lineCount: o, removals: t } = L(), o > u && (c || (u -= 1), { lineCount: o, removals: n } = E())) : (c || (u -= 1), { lineCount: o, removals: n } = E(), o > u && (u -= 1, { lineCount: o, removals: t } = L())), t > 0 && (d = true, s.splice(0, t)), n > 0 && (c = true, s.splice(s.length - n, n));
|
|
}
|
|
const x = [];
|
|
d && x.push(M);
|
|
for (const t of s)
|
|
for (const n of t)
|
|
x.push(n);
|
|
return c && x.push(M), x;
|
|
};
|
|
var confirm = (i) => {
|
|
const a = i.active ?? "Yes", s = i.inactive ?? "No";
|
|
return new r({
|
|
active: a,
|
|
inactive: s,
|
|
signal: i.signal,
|
|
input: i.input,
|
|
output: i.output,
|
|
initialValue: i.initialValue ?? true,
|
|
render() {
|
|
const e = i.withGuide ?? settings.withGuide, u = `${symbol3(this.state)} `, l = e ? `${styleText("gray", S_BAR)} ` : "", f = wrapTextWithPrefix(i.output, i.message, l, u), o = `${e ? `${styleText("gray", S_BAR)}
|
|
` : ""}${f}
|
|
`, c = this.value ? a : s;
|
|
switch (this.state) {
|
|
case "submit": {
|
|
const r = e ? `${styleText("gray", S_BAR)} ` : "";
|
|
return `${o}${r}${styleText("dim", c)}`;
|
|
}
|
|
case "cancel": {
|
|
const r = e ? `${styleText("gray", S_BAR)} ` : "";
|
|
return `${o}${r}${styleText(["strikethrough", "dim"], c)}${e ? `
|
|
${styleText("gray", S_BAR)}` : ""}`;
|
|
}
|
|
default: {
|
|
const r = e ? `${styleText("cyan", S_BAR)} ` : "", g = e ? styleText("cyan", S_BAR_END) : "";
|
|
return `${o}${r}${this.value ? `${styleText("green", S_RADIO_ACTIVE)} ${a}` : `${styleText("dim", S_RADIO_INACTIVE)} ${styleText("dim", a)}`}${i.vertical ? e ? `
|
|
${styleText("cyan", S_BAR)} ` : `
|
|
` : ` ${styleText("dim", "/")} `}${this.value ? `${styleText("dim", S_RADIO_INACTIVE)} ${styleText("dim", s)}` : `${styleText("green", S_RADIO_ACTIVE)} ${s}`}
|
|
${g}
|
|
`;
|
|
}
|
|
}
|
|
}
|
|
}).prompt();
|
|
};
|
|
var MULTISELECT_INSTRUCTIONS = [
|
|
`${styleText("dim", "\u2191/\u2193")} to navigate`,
|
|
`${styleText("dim", "Space:")} select`,
|
|
`${styleText("dim", "Enter:")} confirm`
|
|
];
|
|
var log2 = {
|
|
message: (s = [], {
|
|
symbol: e = styleText("gray", S_BAR),
|
|
secondarySymbol: r = styleText("gray", S_BAR),
|
|
output: m = process.stdout,
|
|
spacing: l = 1,
|
|
withGuide: c
|
|
} = {}) => {
|
|
const t = [], o = c ?? settings.withGuide, f = o ? r : "", O = o ? `${e} ` : "", u = o ? `${r} ` : "";
|
|
for (let i = 0;i < l; i++)
|
|
t.push(f);
|
|
const g = Array.isArray(s) ? s : s.split(`
|
|
`);
|
|
if (g.length > 0) {
|
|
const [i, ...y] = g;
|
|
i.length > 0 ? t.push(`${O}${i}`) : t.push(o ? e : "");
|
|
for (const p of y)
|
|
p.length > 0 ? t.push(`${u}${p}`) : t.push(o ? r : "");
|
|
}
|
|
m.write(`${t.join(`
|
|
`)}
|
|
`);
|
|
},
|
|
info: (s, e) => {
|
|
log2.message(s, { ...e, symbol: styleText("blue", S_INFO) });
|
|
},
|
|
success: (s, e) => {
|
|
log2.message(s, { ...e, symbol: styleText("green", S_SUCCESS) });
|
|
},
|
|
step: (s, e) => {
|
|
log2.message(s, { ...e, symbol: styleText("green", S_STEP_SUBMIT) });
|
|
},
|
|
warn: (s, e) => {
|
|
log2.message(s, { ...e, symbol: styleText("yellow", S_WARN) });
|
|
},
|
|
warning: (s, e) => {
|
|
log2.warn(s, e);
|
|
},
|
|
error: (s, e) => {
|
|
log2.message(s, { ...e, symbol: styleText("red", S_ERROR) });
|
|
}
|
|
};
|
|
var intro = (o = "", t) => {
|
|
const i = t?.output ?? process.stdout, e = t?.withGuide ?? settings.withGuide ? `${styleText("gray", S_BAR_START)} ` : "";
|
|
i.write(`${e}${o}
|
|
`);
|
|
};
|
|
var outro = (o = "", t) => {
|
|
const i = t?.output ?? process.stdout, e = t?.withGuide ?? settings.withGuide ? `${styleText("gray", S_BAR)}
|
|
${styleText("gray", S_BAR_END)} ` : "";
|
|
i.write(`${e}${o}
|
|
|
|
`);
|
|
};
|
|
var W$1 = (o) => o;
|
|
var C = (o, e, s) => {
|
|
const a = {
|
|
hard: true,
|
|
trim: false
|
|
}, i = wrapAnsi(o, e, a).split(`
|
|
`), c = i.reduce((n, t) => Math.max(dist_default2(t), n), 0), u = i.map(s).reduce((n, t) => Math.max(dist_default2(t), n), 0), g = e - (u - c);
|
|
return wrapAnsi(o, g, a);
|
|
};
|
|
var note = (o = "", e = "", s) => {
|
|
const a = s?.output ?? process$1.stdout, i = s?.withGuide ?? settings.withGuide, c = s?.format ?? W$1, g = ["", ...C(o, getColumns(a) - 6, c).split(`
|
|
`).map(c), ""], n = dist_default2(e), t = Math.max(g.reduce((m, F) => {
|
|
const O = dist_default2(F);
|
|
return O > m ? O : m;
|
|
}, 0), n) + 2, h = g.map((m) => `${styleText("gray", S_BAR)} ${m}${" ".repeat(t - dist_default2(m))}${styleText("gray", S_BAR)}`).join(`
|
|
`), T = i ? `${styleText("gray", S_BAR)}
|
|
` : "", l$1 = i ? S_CONNECT_LEFT : S_CORNER_BOTTOM_LEFT;
|
|
a.write(`${T}${styleText("green", S_STEP_SUBMIT)} ${styleText("reset", e)} ${styleText("gray", S_BAR_H.repeat(Math.max(t - n - 1, 1)) + S_CORNER_TOP_RIGHT)}
|
|
${h}
|
|
${styleText("gray", l$1 + S_BAR_H.repeat(t + 2) + S_CORNER_BOTTOM_RIGHT)}
|
|
`);
|
|
};
|
|
var W = (l) => styleText("magenta", l);
|
|
var spinner = ({
|
|
indicator: l = "dots",
|
|
onCancel: h,
|
|
output: n = process.stdout,
|
|
cancelMessage: G,
|
|
errorMessage: O,
|
|
frames: E = unicode ? ["\u25D2", "\u25D0", "\u25D3", "\u25D1"] : ["\u2022", "o", "O", "0"],
|
|
delay: F = unicode ? 80 : 120,
|
|
signal: m,
|
|
...I
|
|
} = {}) => {
|
|
const u = isCI();
|
|
let M, T, d = false, S = false, s = "", p, w = performance.now();
|
|
const x = getColumns(n), k = I?.styleFrame ?? W, g = (e) => {
|
|
const r = e > 1 ? O ?? settings.messages.error : G ?? settings.messages.cancel;
|
|
S = e === 1, d && (a(r, e), S && typeof h == "function" && h());
|
|
}, f = () => g(2), i = () => g(1), A = () => {
|
|
process.on("uncaughtExceptionMonitor", f), process.on("unhandledRejection", f), process.on("SIGINT", i), process.on("SIGTERM", i), process.on("exit", g), m && m.addEventListener("abort", i);
|
|
}, H = () => {
|
|
process.removeListener("uncaughtExceptionMonitor", f), process.removeListener("unhandledRejection", f), process.removeListener("SIGINT", i), process.removeListener("SIGTERM", i), process.removeListener("exit", g), m && m.removeEventListener("abort", i);
|
|
}, y = () => {
|
|
if (p === undefined)
|
|
return;
|
|
u && n.write(`
|
|
`);
|
|
const r = wrapAnsi(p, x, {
|
|
hard: true,
|
|
trim: false
|
|
}).split(`
|
|
`);
|
|
r.length > 1 && n.write(import_sisteransi2.cursor.up(r.length - 1)), n.write(import_sisteransi2.cursor.to(0)), n.write(import_sisteransi2.erase.down());
|
|
}, C = (e) => e.replace(/\.+$/, ""), _ = (e) => {
|
|
const r = (performance.now() - e) / 1000, t = Math.floor(r / 60), o = Math.floor(r % 60);
|
|
return t > 0 ? `[${t}m ${o}s]` : `[${o}s]`;
|
|
}, N = I.withGuide ?? settings.withGuide, P = (e = "") => {
|
|
d = true, M = block({ output: n }), s = C(e), w = performance.now(), N && n.write(`${styleText("gray", S_BAR)}
|
|
`);
|
|
let r = 0, t = 0;
|
|
A(), T = setInterval(() => {
|
|
if (u && s === p)
|
|
return;
|
|
y(), p = s;
|
|
const o = k(E[r]);
|
|
let v;
|
|
if (u)
|
|
v = `${o} ${s}...`;
|
|
else if (l === "timer")
|
|
v = `${o} ${s} ${_(w)}`;
|
|
else {
|
|
const B = ".".repeat(Math.floor(t)).slice(0, 3);
|
|
v = `${o} ${s}${B}`;
|
|
}
|
|
const j = wrapAnsi(v, x, {
|
|
hard: true,
|
|
trim: false
|
|
});
|
|
n.write(j), r = r + 1 < E.length ? r + 1 : 0, t = t < 4 ? t + 0.125 : 0;
|
|
}, F);
|
|
}, a = (e = "", r = 0, t = false) => {
|
|
if (!d)
|
|
return;
|
|
d = false, clearInterval(T), y();
|
|
const o = r === 0 ? styleText("green", S_STEP_SUBMIT) : r === 1 ? styleText("red", S_STEP_CANCEL) : styleText("red", S_STEP_ERROR);
|
|
s = e ?? s, t || (l === "timer" ? n.write(`${o} ${s} ${_(w)}
|
|
`) : n.write(`${o} ${s}
|
|
`)), H(), M();
|
|
};
|
|
return {
|
|
start: P,
|
|
stop: (e = "") => a(e, 0),
|
|
message: (e = "") => {
|
|
s = C(e ?? s);
|
|
},
|
|
cancel: (e = "") => a(e, 1),
|
|
error: (e = "") => a(e, 2),
|
|
clear: () => a("", 0, true),
|
|
get isCancelled() {
|
|
return S;
|
|
}
|
|
};
|
|
};
|
|
var u2 = {
|
|
light: unicodeOr("\u2500", "-"),
|
|
heavy: unicodeOr("\u2501", "="),
|
|
block: unicodeOr("\u2588", "#")
|
|
};
|
|
var SELECT_INSTRUCTIONS = [
|
|
`${styleText("dim", "\u2191/\u2193")} to navigate`,
|
|
`${styleText("dim", "Enter:")} confirm`
|
|
];
|
|
var c = (t, o) => t.includes(`
|
|
`) ? t.split(`
|
|
`).map((d) => o(d)).join(`
|
|
`) : o(t);
|
|
var select = (t) => {
|
|
const o = (n, m) => {
|
|
if (n === undefined)
|
|
return "";
|
|
const s = n.label ?? String(n.value);
|
|
switch (m) {
|
|
case "disabled":
|
|
return `${styleText("gray", S_RADIO_INACTIVE)} ${c(s, (i) => styleText("gray", i))}${n.hint ? ` ${styleText("dim", `(${n.hint ?? "disabled"})`)}` : ""}`;
|
|
case "selected":
|
|
return `${c(s, (i) => styleText("dim", i))}`;
|
|
case "active":
|
|
return `${styleText("green", S_RADIO_ACTIVE)} ${s}${n.hint ? ` ${styleText("dim", `(${n.hint})`)}` : ""}`;
|
|
case "cancelled":
|
|
return `${c(s, (i) => styleText(["strikethrough", "dim"], i))}`;
|
|
default:
|
|
return `${styleText("dim", S_RADIO_INACTIVE)} ${c(s, (i) => styleText("dim", i))}`;
|
|
}
|
|
}, d = t.showInstructions ?? true;
|
|
return new n$1({
|
|
options: t.options,
|
|
signal: t.signal,
|
|
input: t.input,
|
|
output: t.output,
|
|
initialValue: t.initialValue,
|
|
render() {
|
|
const n = t.withGuide ?? settings.withGuide, m = `${symbol3(this.state)} `, s = `${symbolBar(this.state)} `, i = wrapTextWithPrefix(t.output, t.message, s, m), u = `${n ? `${styleText("gray", S_BAR)}
|
|
` : ""}${i}
|
|
`;
|
|
switch (this.state) {
|
|
case "submit": {
|
|
const r = n ? `${styleText("gray", S_BAR)} ` : "", a = wrapTextWithPrefix(t.output, o(this.options[this.cursor], "selected"), r);
|
|
return `${u}${a}`;
|
|
}
|
|
case "cancel": {
|
|
const r = n ? `${styleText("gray", S_BAR)} ` : "", a = wrapTextWithPrefix(t.output, o(this.options[this.cursor], "cancelled"), r);
|
|
return `${u}${a}${n ? `
|
|
${styleText("gray", S_BAR)}` : ""}`;
|
|
}
|
|
default: {
|
|
const r = n ? `${styleText("cyan", S_BAR)} ` : "", a = u.split(`
|
|
`).length, p = d ? formatInstructionFooter(SELECT_INSTRUCTIONS, n) : n ? [styleText("cyan", S_BAR_END)] : [], b = p.join(`
|
|
`), f = p.length + 1;
|
|
return `${u}${r}${limitOptions({
|
|
output: t.output,
|
|
cursor: this.cursor,
|
|
options: this.options,
|
|
maxItems: t.maxItems,
|
|
columnPadding: r.length,
|
|
rowPadding: a + f,
|
|
style: (g, x) => o(g, g.disabled ? "disabled" : x ? "active" : "inactive")
|
|
}).join(`
|
|
${r}`)}
|
|
${b}
|
|
`;
|
|
}
|
|
}
|
|
}
|
|
}).prompt();
|
|
};
|
|
var i = `${styleText("gray", S_BAR)} `;
|
|
|
|
// src/services/terminal-ui.ts
|
|
var getTerminalCapabilities = (stdio) => {
|
|
const stdinIsTTY = Boolean(stdio.stdin.isTTY);
|
|
const stdoutIsTTY = Boolean(stdio.stdout.isTTY);
|
|
const stderrIsTTY = Boolean(stdio.stderr.isTTY);
|
|
return {
|
|
stdinIsTTY,
|
|
stdoutIsTTY,
|
|
stderrIsTTY,
|
|
canPrompt: stdinIsTTY && stderrIsTTY,
|
|
canDecorate: stderrIsTTY
|
|
};
|
|
};
|
|
var TerminalUI = GenericTag("services/TerminalUI");
|
|
var SPINNER_RENDER_OVERHEAD = 7;
|
|
var graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
|
|
var clampSpinnerMessage = (columns, message) => {
|
|
const singleLine = message.replace(/\s*\r?\n\s*/g, " ");
|
|
if (singleLine.includes("\x1B")) {
|
|
return singleLine;
|
|
}
|
|
const budget = Math.max(columns - SPINNER_RENDER_OVERHEAD, 1);
|
|
if (dist_default2(singleLine) <= budget) {
|
|
return singleLine;
|
|
}
|
|
let clamped = "";
|
|
let width = 0;
|
|
for (const { segment } of graphemeSegmenter.segment(singleLine)) {
|
|
const segmentWidth = dist_default2(segment);
|
|
if (width + segmentWidth > budget - 1) {
|
|
break;
|
|
}
|
|
clamped += segment;
|
|
width += segmentWidth;
|
|
}
|
|
return `${clamped}\u2026`;
|
|
};
|
|
function createClackSpinnerHandle(spinner, defaultMessage) {
|
|
let stopped = false;
|
|
return {
|
|
handle: {
|
|
message: (msg) => sync3(() => spinner.updateMessage(msg)),
|
|
stop: (msg) => sync3(() => {
|
|
stopped = true;
|
|
spinner.raw.stop(msg ?? defaultMessage);
|
|
}),
|
|
error: (msg) => sync3(() => {
|
|
stopped = true;
|
|
spinner.raw.error(msg ?? defaultMessage);
|
|
})
|
|
},
|
|
isStopped: () => stopped
|
|
};
|
|
}
|
|
var silentSpinnerHandle = {
|
|
message: () => _void,
|
|
stop: () => _void,
|
|
error: () => _void
|
|
};
|
|
var makeTerminalUI = (streams) => {
|
|
const capabilities = getTerminalCapabilities(streams);
|
|
const { canPrompt, canDecorate, stdoutIsTTY } = capabilities;
|
|
const stderr = streams.stderr;
|
|
const decorate = (render) => {
|
|
if (!canDecorate) {
|
|
return _void;
|
|
}
|
|
return sync3(render);
|
|
};
|
|
const startSpinner = (message) => {
|
|
const initialColumns = getColumns(stderr);
|
|
const raw = spinner({ output: stderr });
|
|
raw.start(clampSpinnerMessage(initialColumns, message));
|
|
return {
|
|
raw,
|
|
updateMessage: (msg) => raw.message(clampSpinnerMessage(Math.min(initialColumns, getColumns(stderr)), msg))
|
|
};
|
|
};
|
|
return {
|
|
capabilities: succeed7(capabilities),
|
|
output: (data, options) => sync3(() => {
|
|
if (options?.force || !stdoutIsTTY) {
|
|
streams.stdout.write(`${data}
|
|
`);
|
|
}
|
|
}),
|
|
error: (data) => sync3(() => stderr.write(`${data}
|
|
`)),
|
|
intro: (title) => decorate(() => intro(title, { output: stderr })),
|
|
outro: (message) => decorate(() => outro(message, { output: stderr })),
|
|
log: {
|
|
info: (message) => decorate(() => log2.info(message, { output: stderr })),
|
|
success: (message) => decorate(() => log2.success(message, { output: stderr })),
|
|
warn: (message) => decorate(() => log2.warn(message, { output: stderr })),
|
|
error: (message) => decorate(() => log2.error(message, { output: stderr })),
|
|
step: (message) => decorate(() => log2.step(message, { output: stderr })),
|
|
message: (message) => decorate(() => log2.message(message, { output: stderr }))
|
|
},
|
|
note: (message, title) => decorate(() => note(message, title ?? "", { format: (line) => line, output: stderr })),
|
|
select: (message, options) => {
|
|
if (!canPrompt) {
|
|
return succeed7(options[0].value);
|
|
}
|
|
return promise2(async () => {
|
|
const result = await select({
|
|
message,
|
|
options: [...options],
|
|
output: stderr
|
|
});
|
|
if (typeof result === "symbol")
|
|
return options[0].value;
|
|
return result;
|
|
});
|
|
},
|
|
confirm: (message, options) => {
|
|
if (!canPrompt) {
|
|
return succeed7(options?.defaultValue ?? true);
|
|
}
|
|
return promise2(async () => {
|
|
const result = await confirm({
|
|
message,
|
|
initialValue: options?.defaultValue ?? true,
|
|
output: stderr
|
|
});
|
|
if (isCancel(result))
|
|
return false;
|
|
return result;
|
|
});
|
|
},
|
|
withSpinner: (message, effect, options) => {
|
|
if (!canDecorate) {
|
|
return effect;
|
|
}
|
|
return acquireUseRelease2(sync3(() => startSpinner(message)), () => effect, (spinner, exit) => sync3(() => {
|
|
if (isSuccess(exit)) {
|
|
let successMessage = message;
|
|
const configuredSuccessMessage = options?.successMessage;
|
|
if (typeof configuredSuccessMessage === "function") {
|
|
successMessage = configuredSuccessMessage(exit.value);
|
|
} else if (configuredSuccessMessage !== undefined) {
|
|
successMessage = configuredSuccessMessage;
|
|
}
|
|
spinner.raw.stop(successMessage);
|
|
} else {
|
|
spinner.raw.error(options?.errorMessage ?? message);
|
|
}
|
|
}));
|
|
},
|
|
useMakeSpinner: (message, use) => {
|
|
if (!canDecorate) {
|
|
return use(silentSpinnerHandle);
|
|
}
|
|
return acquireUseRelease2(sync3(() => {
|
|
const spinner = startSpinner(message);
|
|
const { handle, isStopped } = createClackSpinnerHandle(spinner, message);
|
|
return { raw: spinner.raw, handle, isStopped };
|
|
}), ({ handle }) => use(handle), ({ raw, isStopped }, exit) => sync3(() => {
|
|
if (isFailure2(exit) && !isStopped()) {
|
|
raw.error(message);
|
|
}
|
|
}));
|
|
}
|
|
};
|
|
};
|
|
var TerminalUILive = succeed8(TerminalUI, makeTerminalUI({
|
|
stdin: process4.stdin,
|
|
stdout: process4.stdout,
|
|
stderr: process4.stderr
|
|
}));
|
|
|
|
// src/services/run-subagent-output-mcp.ts
|
|
var readFlag = (name) => {
|
|
const index = process5.argv.indexOf(name);
|
|
const value = index >= 0 ? process5.argv[index + 1] : undefined;
|
|
if (!value) {
|
|
throw new Error(`Missing required flag: ${name}`);
|
|
}
|
|
return value;
|
|
};
|
|
var main = async () => {
|
|
const fs = runSync(FileSystem.pipe(provide2(layer3)));
|
|
const schemaFilePath = readFlag("--schema-file");
|
|
const resultFilePath = readFlag("--result-file");
|
|
const schemaText = await runPromise(fs.readFileString(schemaFilePath));
|
|
const structuredSchema = decodeStructuredSchemaJson(schemaText);
|
|
const toolInputSchema = jsonSchemaToZod(buildStructuredOutputToolSchema(structuredSchema));
|
|
const server = new McpServer({
|
|
name: "composio-subagent-output",
|
|
version: "1.0.0"
|
|
});
|
|
server.registerTool(ACP_STRUCTURED_OUTPUT_TOOL_NAME, {
|
|
title: "Submit structured output",
|
|
description: "Submit the final structured experimental_subAgent output. Call this exactly once when the task is complete.",
|
|
inputSchema: toolInputSchema
|
|
}, async (payload) => {
|
|
await runPromise(fs.writeFileString(resultFilePath, JSON.stringify(payload)));
|
|
return {
|
|
content: [
|
|
{
|
|
type: "text",
|
|
text: "Structured output captured."
|
|
}
|
|
]
|
|
};
|
|
});
|
|
const transport = new StdioServerTransport;
|
|
await server.connect(transport);
|
|
};
|
|
main().catch((error) => {
|
|
const message = error instanceof Error ? error.stack ?? error.message : String(error);
|
|
gen2(function* () {
|
|
const ui = yield* TerminalUI;
|
|
yield* ui.error(message);
|
|
}).pipe(provide2(TerminalUILive), runSync);
|
|
process5.exit(1);
|
|
});
|