var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __commonJS = (cb, mod2) => function __require() { return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports; }; var __export = (target, all) => { for (var name2 in all) __defProp(target, name2, { get: all[name2], enumerable: true }); }; var __copyProps = (to, from3, except, desc) => { if (from3 && typeof from3 === "object" || typeof from3 === "function") { for (let key of __getOwnPropNames(from3)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from3[key], enumerable: !(desc = __getOwnPropDesc(from3, key)) || desc.enumerable }); } return to; }; var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. 1 ? __defProp(target, "default", { value: mod2, enumerable: true }) : target, mod2 )); // ../../../../../node_modules/.deno/iso-datestring-validator@2.2.2/node_modules/iso-datestring-validator/dist/index.js var require_dist = __commonJS({ "../../../../../node_modules/.deno/iso-datestring-validator@2.2.2/node_modules/iso-datestring-validator/dist/index.js"(exports) { (() => { "use strict"; var e = { d: (t2, r2) => { for (var n2 in r2) e.o(r2, n2) && !e.o(t2, n2) && Object.defineProperty(t2, n2, { enumerable: true, get: r2[n2] }); }, o: (e2, t2) => Object.prototype.hasOwnProperty.call(e2, t2), r: (e2) => { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e2, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e2, "__esModule", { value: true }); } }, t = {}; function r(e2, t2) { return void 0 === t2 && (t2 = "-"), new RegExp("^(?!0{4}" + t2 + "0{2}" + t2 + "0{2})((?=[0-9]{4}" + t2 + "(((0[^2])|1[0-2])|02(?=" + t2 + "(([0-1][0-9])|2[0-8])))" + t2 + "[0-9]{2})|(?=((([13579][26])|([2468][048])|(0[48]))0{2})|([0-9]{2}((((0|[2468])[48])|[2468][048])|([13579][26])))" + t2 + "02" + t2 + "29))([0-9]{4})" + t2 + "(?!((0[469])|11)" + t2 + "31)((0[1,3-9]|1[0-2])|(02(?!" + t2 + "3)))" + t2 + "(0[1-9]|[1-2][0-9]|3[0-1])$").test(e2); } function n(e2) { var t2 = /\D/.exec(e2); return t2 ? t2[0] : ""; } function i(e2, t2, r2) { void 0 === t2 && (t2 = ":"), void 0 === r2 && (r2 = false); var i2 = new RegExp("^([0-1]|2(?=([0-3])|4" + t2 + "00))[0-9]" + t2 + "[0-5][0-9](" + t2 + "([0-5]|6(?=0))[0-9])?(.[0-9]{1,9})?$"); if (!r2 || !/[Z+\-]/.test(e2)) return i2.test(e2); if (/Z$/.test(e2)) return i2.test(e2.replace("Z", "")); var o2 = e2.includes("+"), a2 = e2.split(/[+-]/), u2 = a2[0], d2 = a2[1]; return i2.test(u2) && function(e3, t3, r3) { return void 0 === r3 && (r3 = ":"), new RegExp(t3 ? "^(0(?!(2" + r3 + "4)|0" + r3 + "3)|1(?=([0-1]|2(?=" + r3 + "[04])|[34](?=" + r3 + "0))))([03469](?=" + r3 + "[03])|[17](?=" + r3 + "0)|2(?=" + r3 + "[04])|5(?=" + r3 + "[034])|8(?=" + r3 + "[04]))" + r3 + "([03](?=0)|4(?=5))[05]$" : "^(0(?=[^0])|1(?=[0-2]))([39](?=" + r3 + "[03])|[0-24-8](?=" + r3 + "00))" + r3 + "[03]0$").test(e3); }(d2, o2, n(d2)); } function o(e2) { var t2 = e2.split("T"), o2 = t2[0], a2 = t2[1], u2 = r(o2, n(o2)); if (!a2) return false; var d2, s = (d2 = a2.match(/([^Z+\-\d])(?=\d+\1)/), Array.isArray(d2) ? d2[0] : ""); return u2 && i(a2, s, true); } function a(e2, t2) { return void 0 === t2 && (t2 = "-"), new RegExp("^[0-9]{4}" + t2 + "(0(?=[^0])|1(?=[0-2]))[0-9]$").test(e2); } e.r(t), e.d(t, { isValidDate: () => r, isValidISODateString: () => o, isValidTime: () => i, isValidYearMonth: () => a }); var u = exports; for (var d in t) u[d] = t[d]; t.__esModule && Object.defineProperty(u, "__esModule", { value: true }); })(); } }); // ../deno-typescript-shared/constants.ts function splitAtUri(uri) { const parts = uri.replace(/^at:\/\//, "").split("/"); return { repo: parts[0] ?? "", collection: parts[1] ?? "", rkey: parts[2] ?? "" }; } // ../deno-typescript-shared/cache.ts function createCacheStore(initial, opts = {}) { const maxEntries = opts.maxEntries ?? 512; let cache2 = initial && typeof initial === "object" ? initial : {}; const order = Object.keys(cache2); const ghCachePath = Deno.env.get("GITHUB_CACHE"); if (ghCachePath) { try { const parsed = JSON.parse(Deno.readTextFileSync(ghCachePath)); if (parsed && typeof parsed === "object") { cache2 = parsed; order.length = 0; order.push(...Object.keys(cache2)); } } catch { } } function touch(key) { const i = order.indexOf(key); if (i >= 0) order.splice(i, 1); order.push(key); } function evict() { while (order.length > maxEntries) { const oldest = order.shift(); if (oldest === void 0) break; delete cache2[oldest]; } } function persist() { if (ghCachePath) { try { Deno.writeTextFileSync(ghCachePath, JSON.stringify(cache2)); } catch { } } } return { read() { return cache2; }, write(next) { cache2 = next; order.length = 0; order.push(...Object.keys(next)); evict(); persist(); }, get(key) { const entry = cache2[key]; if (entry !== void 0) touch(key); return entry; }, set(key, entry) { cache2[key] = entry; touch(key); evict(); persist(); }, has(key) { return key in cache2; }, delete(key) { if (key in cache2) { delete cache2[key]; const i = order.indexOf(key); if (i >= 0) order.splice(i, 1); } } }; } function recordCacheKey(ref) { return `rec/${ref.uri}/${ref.cid}`; } var RECORD_VALUE_FILE = "value.json"; var POLICY_RESULT_FILE = "result.json"; var POLICY_META_FILE = "meta.json"; function hashString(s) { let h = 5381; for (let i = 0; i < s.length; i++) { h = (h << 5) + h + s.charCodeAt(i) | 0; } return (h >>> 0).toString(36); } function recPart(r) { return r && r.uri ? `${r.uri}/${r.cid ?? ""}` : ""; } function policyCacheKey(policyName, records, args) { const argSuffix = args && Object.keys(args).length > 0 ? `:${hashString(JSON.stringify(args))}` : ""; return `policy/${policyName}/${recPart(records.rfp)}|${recPart(records.bid)}|${recPart(records.accept)}${argSuffix}`; } function readPolicyResult(store, key, now = Date.now()) { const entry = store.get(key); if (!entry) return void 0; const meta = entry[POLICY_META_FILE]; if (meta) { try { const m = JSON.parse(meta.data); if (now - m.cachedAt > m.ttlMs) { store.delete(key); return void 0; } } catch { } } const file = entry[POLICY_RESULT_FILE]; if (!file) return void 0; try { const parsed = JSON.parse(file.data); return parsed && typeof parsed === "object" && typeof parsed.allow === "boolean" ? parsed : void 0; } catch { return void 0; } } function writePolicyResult(store, key, result, ttlMs = 3e4) { store.set(key, { [POLICY_RESULT_FILE]: { data: JSON.stringify(result), encoding: "text" }, [POLICY_META_FILE]: { data: JSON.stringify({ cachedAt: Date.now(), ttlMs }), encoding: "text" } }); } // ../../../../../node_modules/.deno/@atproto+common-web@0.5.14/node_modules/@atproto/common-web/dist/check.js var check_exports = {}; __export(check_exports, { assure: () => assure, create: () => create, is: () => is, isObject: () => isObject }); var is = (obj, def2) => { return def2.safeParse(obj).success; }; var create = (def2) => (v) => def2.safeParse(v).success; var assure = (def2, obj) => { return def2.parse(obj); }; var isObject = (obj) => { return typeof obj === "object" && obj !== null; }; // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base32.js var base32_exports = {}; __export(base32_exports, { base32: () => base32, base32hex: () => base32hex, base32hexpad: () => base32hexpad, base32hexpadupper: () => base32hexpadupper, base32hexupper: () => base32hexupper, base32pad: () => base32pad, base32padupper: () => base32padupper, base32upper: () => base32upper, base32z: () => base32z }); // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/bytes.js var empty = new Uint8Array(0); function equals(aa, bb) { if (aa === bb) { return true; } if (aa.byteLength !== bb.byteLength) { return false; } for (let ii = 0; ii < aa.byteLength; ii++) { if (aa[ii] !== bb[ii]) { return false; } } return true; } function coerce(o) { if (o instanceof Uint8Array && o.constructor.name === "Uint8Array") { return o; } if (o instanceof ArrayBuffer) { return new Uint8Array(o); } if (ArrayBuffer.isView(o)) { return new Uint8Array(o.buffer, o.byteOffset, o.byteLength); } throw new Error("Unknown type, must be binary type"); } function fromString(str) { return new TextEncoder().encode(str); } function toString(b) { return new TextDecoder().decode(b); } // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/vendor/base-x.js function base(ALPHABET, name2) { if (ALPHABET.length >= 255) { throw new TypeError("Alphabet too long"); } var BASE_MAP = new Uint8Array(256); for (var j = 0; j < BASE_MAP.length; j++) { BASE_MAP[j] = 255; } for (var i = 0; i < ALPHABET.length; i++) { var x = ALPHABET.charAt(i); var xc = x.charCodeAt(0); if (BASE_MAP[xc] !== 255) { throw new TypeError(x + " is ambiguous"); } BASE_MAP[xc] = i; } var BASE = ALPHABET.length; var LEADER = ALPHABET.charAt(0); var FACTOR = Math.log(BASE) / Math.log(256); var iFACTOR = Math.log(256) / Math.log(BASE); function encode5(source) { if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) { source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength); } else if (Array.isArray(source)) { source = Uint8Array.from(source); } if (!(source instanceof Uint8Array)) { throw new TypeError("Expected Uint8Array"); } if (source.length === 0) { return ""; } var zeroes = 0; var length2 = 0; var pbegin = 0; var pend = source.length; while (pbegin !== pend && source[pbegin] === 0) { pbegin++; zeroes++; } var size = (pend - pbegin) * iFACTOR + 1 >>> 0; var b58 = new Uint8Array(size); while (pbegin !== pend) { var carry = source[pbegin]; var i2 = 0; for (var it1 = size - 1; (carry !== 0 || i2 < length2) && it1 !== -1; it1--, i2++) { carry += 256 * b58[it1] >>> 0; b58[it1] = carry % BASE >>> 0; carry = carry / BASE >>> 0; } if (carry !== 0) { throw new Error("Non-zero carry"); } length2 = i2; pbegin++; } var it2 = size - length2; while (it2 !== size && b58[it2] === 0) { it2++; } var str = LEADER.repeat(zeroes); for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); } return str; } function decodeUnsafe(source) { if (typeof source !== "string") { throw new TypeError("Expected String"); } if (source.length === 0) { return new Uint8Array(); } var psz = 0; if (source[psz] === " ") { return; } var zeroes = 0; var length2 = 0; while (source[psz] === LEADER) { zeroes++; psz++; } var size = (source.length - psz) * FACTOR + 1 >>> 0; var b256 = new Uint8Array(size); while (source[psz]) { var carry = BASE_MAP[source.charCodeAt(psz)]; if (carry === 255) { return; } var i2 = 0; for (var it3 = size - 1; (carry !== 0 || i2 < length2) && it3 !== -1; it3--, i2++) { carry += BASE * b256[it3] >>> 0; b256[it3] = carry % 256 >>> 0; carry = carry / 256 >>> 0; } if (carry !== 0) { throw new Error("Non-zero carry"); } length2 = i2; psz++; } if (source[psz] === " ") { return; } var it4 = size - length2; while (it4 !== size && b256[it4] === 0) { it4++; } var vch = new Uint8Array(zeroes + (size - it4)); var j2 = zeroes; while (it4 !== size) { vch[j2++] = b256[it4++]; } return vch; } function decode6(string2) { var buffer = decodeUnsafe(string2); if (buffer) { return buffer; } throw new Error(`Non-${name2} character`); } return { encode: encode5, decodeUnsafe, decode: decode6 }; } var src = base; var _brrp__multiformats_scope_baseX = src; var base_x_default = _brrp__multiformats_scope_baseX; // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base.js var Encoder = class { name; prefix; baseEncode; constructor(name2, prefix, baseEncode) { this.name = name2; this.prefix = prefix; this.baseEncode = baseEncode; } encode(bytes) { if (bytes instanceof Uint8Array) { return `${this.prefix}${this.baseEncode(bytes)}`; } else { throw Error("Unknown type, must be binary type"); } } }; var Decoder = class { name; prefix; baseDecode; prefixCodePoint; constructor(name2, prefix, baseDecode) { this.name = name2; this.prefix = prefix; const prefixCodePoint = prefix.codePointAt(0); if (prefixCodePoint === void 0) { throw new Error("Invalid prefix character"); } this.prefixCodePoint = prefixCodePoint; this.baseDecode = baseDecode; } decode(text) { if (typeof text === "string") { if (text.codePointAt(0) !== this.prefixCodePoint) { throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`); } return this.baseDecode(text.slice(this.prefix.length)); } else { throw Error("Can only multibase decode strings"); } } or(decoder) { return or(this, decoder); } }; var ComposedDecoder = class { decoders; constructor(decoders) { this.decoders = decoders; } or(decoder) { return or(this, decoder); } decode(input2) { const prefix = input2[0]; const decoder = this.decoders[prefix]; if (decoder != null) { return decoder.decode(input2); } else { throw RangeError(`Unable to decode multibase string ${JSON.stringify(input2)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); } } }; function or(left, right) { return new ComposedDecoder({ ...left.decoders ?? { [left.prefix]: left }, ...right.decoders ?? { [right.prefix]: right } }); } var Codec = class { name; prefix; baseEncode; baseDecode; encoder; decoder; constructor(name2, prefix, baseEncode, baseDecode) { this.name = name2; this.prefix = prefix; this.baseEncode = baseEncode; this.baseDecode = baseDecode; this.encoder = new Encoder(name2, prefix, baseEncode); this.decoder = new Decoder(name2, prefix, baseDecode); } encode(input2) { return this.encoder.encode(input2); } decode(input2) { return this.decoder.decode(input2); } }; function from({ name: name2, prefix, encode: encode5, decode: decode6 }) { return new Codec(name2, prefix, encode5, decode6); } function baseX({ name: name2, prefix, alphabet: alphabet2 }) { const { encode: encode5, decode: decode6 } = base_x_default(alphabet2, name2); return from({ prefix, name: name2, encode: encode5, decode: (text) => coerce(decode6(text)) }); } function decode(string2, alphabetIdx, bitsPerChar, name2) { let end = string2.length; while (string2[end - 1] === "=") { --end; } const out = new Uint8Array(end * bitsPerChar / 8 | 0); let bits = 0; let buffer = 0; let written = 0; for (let i = 0; i < end; ++i) { const value = alphabetIdx[string2[i]]; if (value === void 0) { throw new SyntaxError(`Non-${name2} character`); } buffer = buffer << bitsPerChar | value; bits += bitsPerChar; if (bits >= 8) { bits -= 8; out[written++] = 255 & buffer >> bits; } } if (bits >= bitsPerChar || (255 & buffer << 8 - bits) !== 0) { throw new SyntaxError("Unexpected end of data"); } return out; } function encode(data, alphabet2, bitsPerChar) { const pad = alphabet2[alphabet2.length - 1] === "="; const mask = (1 << bitsPerChar) - 1; let out = ""; let bits = 0; let buffer = 0; for (let i = 0; i < data.length; ++i) { buffer = buffer << 8 | data[i]; bits += 8; while (bits > bitsPerChar) { bits -= bitsPerChar; out += alphabet2[mask & buffer >> bits]; } } if (bits !== 0) { out += alphabet2[mask & buffer << bitsPerChar - bits]; } if (pad) { while ((out.length * bitsPerChar & 7) !== 0) { out += "="; } } return out; } function createAlphabetIdx(alphabet2) { const alphabetIdx = {}; for (let i = 0; i < alphabet2.length; ++i) { alphabetIdx[alphabet2[i]] = i; } return alphabetIdx; } function rfc4648({ name: name2, prefix, bitsPerChar, alphabet: alphabet2 }) { const alphabetIdx = createAlphabetIdx(alphabet2); return from({ prefix, name: name2, encode(input2) { return encode(input2, alphabet2, bitsPerChar); }, decode(input2) { return decode(input2, alphabetIdx, bitsPerChar, name2); } }); } // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base32.js var base32 = rfc4648({ prefix: "b", name: "base32", alphabet: "abcdefghijklmnopqrstuvwxyz234567", bitsPerChar: 5 }); var base32upper = rfc4648({ prefix: "B", name: "base32upper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", bitsPerChar: 5 }); var base32pad = rfc4648({ prefix: "c", name: "base32pad", alphabet: "abcdefghijklmnopqrstuvwxyz234567=", bitsPerChar: 5 }); var base32padupper = rfc4648({ prefix: "C", name: "base32padupper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", bitsPerChar: 5 }); var base32hex = rfc4648({ prefix: "v", name: "base32hex", alphabet: "0123456789abcdefghijklmnopqrstuv", bitsPerChar: 5 }); var base32hexupper = rfc4648({ prefix: "V", name: "base32hexupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", bitsPerChar: 5 }); var base32hexpad = rfc4648({ prefix: "t", name: "base32hexpad", alphabet: "0123456789abcdefghijklmnopqrstuv=", bitsPerChar: 5 }); var base32hexpadupper = rfc4648({ prefix: "T", name: "base32hexpadupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", bitsPerChar: 5 }); var base32z = rfc4648({ prefix: "h", name: "base32z", alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", bitsPerChar: 5 }); // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base36.js var base36_exports = {}; __export(base36_exports, { base36: () => base36, base36upper: () => base36upper }); var base36 = baseX({ prefix: "k", name: "base36", alphabet: "0123456789abcdefghijklmnopqrstuvwxyz" }); var base36upper = baseX({ prefix: "K", name: "base36upper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" }); // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base58.js var base58_exports = {}; __export(base58_exports, { base58btc: () => base58btc, base58flickr: () => base58flickr }); var base58btc = baseX({ name: "base58btc", prefix: "z", alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" }); var base58flickr = baseX({ name: "base58flickr", prefix: "Z", alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" }); // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/vendor/varint.js var encode_1 = encode2; var MSB = 128; var REST = 127; var MSBALL = ~REST; var INT = Math.pow(2, 31); function encode2(num, out, offset) { out = out || []; offset = offset || 0; var oldOffset = offset; while (num >= INT) { out[offset++] = num & 255 | MSB; num /= 128; } while (num & MSBALL) { out[offset++] = num & 255 | MSB; num >>>= 7; } out[offset] = num | 0; encode2.bytes = offset - oldOffset + 1; return out; } var decode2 = read; var MSB$1 = 128; var REST$1 = 127; function read(buf, offset) { var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length; do { if (counter >= l) { read.bytes = 0; throw new RangeError("Could not decode varint"); } b = buf[counter++]; res += shift < 28 ? (b & REST$1) << shift : (b & REST$1) * Math.pow(2, shift); shift += 7; } while (b >= MSB$1); read.bytes = counter - offset; return res; } var N1 = Math.pow(2, 7); var N2 = Math.pow(2, 14); var N3 = Math.pow(2, 21); var N4 = Math.pow(2, 28); var N5 = Math.pow(2, 35); var N6 = Math.pow(2, 42); var N7 = Math.pow(2, 49); var N8 = Math.pow(2, 56); var N9 = Math.pow(2, 63); var length = function(value) { return value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10; }; var varint = { encode: encode_1, decode: decode2, encodingLength: length }; var _brrp_varint = varint; var varint_default = _brrp_varint; // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/varint.js function decode3(data, offset = 0) { const code2 = varint_default.decode(data, offset); return [ code2, varint_default.decode.bytes ]; } function encodeTo(int, target, offset = 0) { varint_default.encode(int, target, offset); return target; } function encodingLength(int) { return varint_default.encodingLength(int); } // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/hashes/digest.js function create2(code2, digest2) { const size = digest2.byteLength; const sizeOffset = encodingLength(code2); const digestOffset = sizeOffset + encodingLength(size); const bytes = new Uint8Array(digestOffset + size); encodeTo(code2, bytes, 0); encodeTo(size, bytes, sizeOffset); bytes.set(digest2, digestOffset); return new Digest(code2, size, digest2, bytes); } function decode4(multihash) { const bytes = coerce(multihash); const [code2, sizeOffset] = decode3(bytes); const [size, digestOffset] = decode3(bytes.subarray(sizeOffset)); const digest2 = bytes.subarray(sizeOffset + digestOffset); if (digest2.byteLength !== size) { throw new Error("Incorrect length"); } return new Digest(code2, size, digest2, bytes); } function equals2(a, b) { if (a === b) { return true; } else { const data = b; return a.code === data.code && a.size === data.size && data.bytes instanceof Uint8Array && equals(a.bytes, data.bytes); } } var Digest = class { code; size; digest; bytes; /** * Creates a multihash digest. */ constructor(code2, size, digest2, bytes) { this.code = code2; this.size = size; this.digest = digest2; this.bytes = bytes; } }; // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/cid.js function format(link, base3) { const { bytes, version } = link; switch (version) { case 0: return toStringV0(bytes, baseCache(link), base3 ?? base58btc.encoder); default: return toStringV1(bytes, baseCache(link), base3 ?? base32.encoder); } } var cache = /* @__PURE__ */ new WeakMap(); function baseCache(cid) { const baseCache2 = cache.get(cid); if (baseCache2 == null) { const baseCache3 = /* @__PURE__ */ new Map(); cache.set(cid, baseCache3); return baseCache3; } return baseCache2; } var CID = class _CID { code; version; multihash; bytes; "/"; /** * @param version - Version of the CID * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv * @param multihash - (Multi)hash of the of the content. */ constructor(version, code2, multihash, bytes) { this.code = code2; this.version = version; this.multihash = multihash; this.bytes = bytes; this["/"] = bytes; } /** * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes` * please either use `CID.asCID(cid)` or switch to new signalling mechanism * * @deprecated */ get asCID() { return this; } // ArrayBufferView get byteOffset() { return this.bytes.byteOffset; } // ArrayBufferView get byteLength() { return this.bytes.byteLength; } toV0() { switch (this.version) { case 0: { return this; } case 1: { const { code: code2, multihash } = this; if (code2 !== DAG_PB_CODE) { throw new Error("Cannot convert a non dag-pb CID to CIDv0"); } if (multihash.code !== SHA_256_CODE) { throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0"); } return _CID.createV0(multihash); } default: { throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`); } } } toV1() { switch (this.version) { case 0: { const { code: code2, digest: digest2 } = this.multihash; const multihash = create2(code2, digest2); return _CID.createV1(this.code, multihash); } case 1: { return this; } default: { throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`); } } } equals(other) { return _CID.equals(this, other); } static equals(self, other) { const unknown = other; return unknown != null && self.code === unknown.code && self.version === unknown.version && equals2(self.multihash, unknown.multihash); } toString(base3) { return format(this, base3); } toJSON() { return { "/": format(this) }; } link() { return this; } [Symbol.toStringTag] = "CID"; // Legacy [Symbol.for("nodejs.util.inspect.custom")]() { return `CID(${this.toString()})`; } /** * Takes any input `value` and returns a `CID` instance if it was * a `CID` otherwise returns `null`. If `value` is instanceof `CID` * it will return value back. If `value` is not instance of this CID * class, but is compatible CID it will return new instance of this * `CID` class. Otherwise returns null. * * This allows two different incompatible versions of CID library to * co-exist and interop as long as binary interface is compatible. */ static asCID(input2) { if (input2 == null) { return null; } const value = input2; if (value instanceof _CID) { return value; } else if (value["/"] != null && value["/"] === value.bytes || value.asCID === value) { const { version, code: code2, multihash, bytes } = value; return new _CID(version, code2, multihash, bytes ?? encodeCID(version, code2, multihash.bytes)); } else if (value[cidSymbol] === true) { const { version, multihash, code: code2 } = value; const digest2 = decode4(multihash); return _CID.create(version, code2, digest2); } else { return null; } } /** * @param version - Version of the CID * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv * @param digest - (Multi)hash of the of the content. */ static create(version, code2, digest2) { if (typeof code2 !== "number") { throw new Error("String codecs are no longer supported"); } if (!(digest2.bytes instanceof Uint8Array)) { throw new Error("Invalid digest"); } switch (version) { case 0: { if (code2 !== DAG_PB_CODE) { throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`); } else { return new _CID(version, code2, digest2, digest2.bytes); } } case 1: { const bytes = encodeCID(version, code2, digest2.bytes); return new _CID(version, code2, digest2, bytes); } default: { throw new Error("Invalid version"); } } } /** * Simplified version of `create` for CIDv0. */ static createV0(digest2) { return _CID.create(0, DAG_PB_CODE, digest2); } /** * Simplified version of `create` for CIDv1. * * @param code - Content encoding format code. * @param digest - Multihash of the content. */ static createV1(code2, digest2) { return _CID.create(1, code2, digest2); } /** * Decoded a CID from its binary representation. The byte array must contain * only the CID with no additional bytes. * * An error will be thrown if the bytes provided do not contain a valid * binary representation of a CID. */ static decode(bytes) { const [cid, remainder] = _CID.decodeFirst(bytes); if (remainder.length !== 0) { throw new Error("Incorrect length"); } return cid; } /** * Decoded a CID from its binary representation at the beginning of a byte * array. * * Returns an array with the first element containing the CID and the second * element containing the remainder of the original byte array. The remainder * will be a zero-length byte array if the provided bytes only contained a * binary CID representation. */ static decodeFirst(bytes) { const specs = _CID.inspectBytes(bytes); const prefixSize = specs.size - specs.multihashSize; const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize)); if (multihashBytes.byteLength !== specs.multihashSize) { throw new Error("Incorrect length"); } const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize); const digest2 = new Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes); const cid = specs.version === 0 ? _CID.createV0(digest2) : _CID.createV1(specs.codec, digest2); return [ cid, bytes.subarray(specs.size) ]; } /** * Inspect the initial bytes of a CID to determine its properties. * * Involves decoding up to 4 varints. Typically this will require only 4 to 6 * bytes but for larger multicodec code values and larger multihash digest * lengths these varints can be quite large. It is recommended that at least * 10 bytes be made available in the `initialBytes` argument for a complete * inspection. */ static inspectBytes(initialBytes) { let offset = 0; const next = () => { const [i, length2] = decode3(initialBytes.subarray(offset)); offset += length2; return i; }; let version = next(); let codec = DAG_PB_CODE; if (version === 18) { version = 0; offset = 0; } else { codec = next(); } if (version !== 0 && version !== 1) { throw new RangeError(`Invalid CID version ${version}`); } const prefixSize = offset; const multihashCode = next(); const digestSize = next(); const size = offset + digestSize; const multihashSize = size - prefixSize; return { version, codec, multihashCode, digestSize, multihashSize, size }; } /** * Takes cid in a string representation and creates an instance. If `base` * decoder is not provided will use a default from the configuration. It will * throw an error if encoding of the CID is not compatible with supplied (or * a default decoder). */ static parse(source, base3) { const [prefix, bytes] = parseCIDtoBytes(source, base3); const cid = _CID.decode(bytes); if (cid.version === 0 && source[0] !== "Q") { throw Error("Version 0 CID string must not include multibase prefix"); } baseCache(cid).set(prefix, source); return cid; } }; function parseCIDtoBytes(source, base3) { switch (source[0]) { // CIDv0 is parsed differently case "Q": { const decoder = base3 ?? base58btc; return [ base58btc.prefix, decoder.decode(`${base58btc.prefix}${source}`) ]; } case base58btc.prefix: { const decoder = base3 ?? base58btc; return [ base58btc.prefix, decoder.decode(source) ]; } case base32.prefix: { const decoder = base3 ?? base32; return [ base32.prefix, decoder.decode(source) ]; } case base36.prefix: { const decoder = base3 ?? base36; return [ base36.prefix, decoder.decode(source) ]; } default: { if (base3 == null) { throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided"); } return [ source[0], base3.decode(source) ]; } } } function toStringV0(bytes, cache2, base3) { const { prefix } = base3; if (prefix !== base58btc.prefix) { throw Error(`Cannot string encode V0 in ${base3.name} encoding`); } const cid = cache2.get(prefix); if (cid == null) { const cid2 = base3.encode(bytes).slice(1); cache2.set(prefix, cid2); return cid2; } else { return cid; } } function toStringV1(bytes, cache2, base3) { const { prefix } = base3; const cid = cache2.get(prefix); if (cid == null) { const cid2 = base3.encode(bytes); cache2.set(prefix, cid2); return cid2; } else { return cid; } } var DAG_PB_CODE = 112; var SHA_256_CODE = 18; function encodeCID(version, code2, multihash) { const codeOffset = encodingLength(version); const hashOffset = codeOffset + encodingLength(code2); const bytes = new Uint8Array(hashOffset + multihash.byteLength); encodeTo(version, bytes, 0); encodeTo(code2, bytes, codeOffset); bytes.set(multihash, hashOffset); return bytes; } var cidSymbol = Symbol.for("@ipld/js-cid/CID"); // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/hashes/sha2.js var sha2_exports = {}; __export(sha2_exports, { sha256: () => sha256, sha512: () => sha512 }); import crypto from "node:crypto"; // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/hashes/hasher.js var DEFAULT_MIN_DIGEST_LENGTH = 20; function from2({ name: name2, code: code2, encode: encode5, minDigestLength, maxDigestLength }) { return new Hasher(name2, code2, encode5, minDigestLength, maxDigestLength); } var Hasher = class { name; code; encode; minDigestLength; maxDigestLength; constructor(name2, code2, encode5, minDigestLength, maxDigestLength) { this.name = name2; this.code = code2; this.encode = encode5; this.minDigestLength = minDigestLength ?? DEFAULT_MIN_DIGEST_LENGTH; this.maxDigestLength = maxDigestLength; } digest(input2, options) { if (options?.truncate != null) { if (options.truncate < this.minDigestLength) { throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`); } if (this.maxDigestLength != null && options.truncate > this.maxDigestLength) { throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`); } } if (input2 instanceof Uint8Array) { const result = this.encode(input2); if (result instanceof Uint8Array) { return createDigest(result, this.code, options?.truncate); } return result.then((digest2) => createDigest(digest2, this.code, options?.truncate)); } else { throw Error("Unknown type, must be binary type"); } } }; function createDigest(digest2, code2, truncate) { if (truncate != null && truncate !== digest2.byteLength) { if (truncate > digest2.byteLength) { throw new Error(`Invalid truncate option, must be less than or equal to ${digest2.byteLength}`); } digest2 = digest2.subarray(0, truncate); } return create2(code2, digest2); } // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/hashes/sha2.js var sha256 = from2({ name: "sha2-256", code: 18, encode: (input2) => coerce(crypto.createHash("sha256").update(input2).digest()) }); var sha512 = from2({ name: "sha2-512", code: 19, encode: (input2) => coerce(crypto.createHash("sha512").update(input2).digest()) }); // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base64.js var base64_exports = {}; __export(base64_exports, { base64: () => base64, base64pad: () => base64pad, base64url: () => base64url, base64urlpad: () => base64urlpad }); var base64 = rfc4648({ prefix: "m", name: "base64", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", bitsPerChar: 6 }); var base64pad = rfc4648({ prefix: "M", name: "base64pad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", bitsPerChar: 6 }); var base64url = rfc4648({ prefix: "u", name: "base64url", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", bitsPerChar: 6 }); var base64urlpad = rfc4648({ prefix: "U", name: "base64urlpad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=", bitsPerChar: 6 }); // ../../../../../node_modules/.deno/@atproto+lex-data@0.1.8/node_modules/@atproto/lex-data/dist/cid.js var SHA256_HASH_CODE = sha256.code; var SHA512_HASH_CODE = sha512.code; // ../../../../../node_modules/.deno/zod@3.25.76/node_modules/zod/v3/external.js var external_exports = {}; __export(external_exports, { BRAND: () => BRAND, DIRTY: () => DIRTY, EMPTY_PATH: () => EMPTY_PATH, INVALID: () => INVALID, NEVER: () => NEVER, OK: () => OK, ParseStatus: () => ParseStatus, Schema: () => ZodType, ZodAny: () => ZodAny, ZodArray: () => ZodArray, ZodBigInt: () => ZodBigInt, ZodBoolean: () => ZodBoolean, ZodBranded: () => ZodBranded, ZodCatch: () => ZodCatch, ZodDate: () => ZodDate, ZodDefault: () => ZodDefault, ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, ZodEffects: () => ZodEffects, ZodEnum: () => ZodEnum, ZodError: () => ZodError, ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, ZodFunction: () => ZodFunction, ZodIntersection: () => ZodIntersection, ZodIssueCode: () => ZodIssueCode, ZodLazy: () => ZodLazy, ZodLiteral: () => ZodLiteral, ZodMap: () => ZodMap, ZodNaN: () => ZodNaN, ZodNativeEnum: () => ZodNativeEnum, ZodNever: () => ZodNever, ZodNull: () => ZodNull, ZodNullable: () => ZodNullable, ZodNumber: () => ZodNumber, ZodObject: () => ZodObject, ZodOptional: () => ZodOptional, ZodParsedType: () => ZodParsedType, ZodPipeline: () => ZodPipeline, ZodPromise: () => ZodPromise, ZodReadonly: () => ZodReadonly, ZodRecord: () => ZodRecord, ZodSchema: () => ZodType, ZodSet: () => ZodSet, ZodString: () => ZodString, ZodSymbol: () => ZodSymbol, ZodTransformer: () => ZodEffects, ZodTuple: () => ZodTuple, ZodType: () => ZodType, ZodUndefined: () => ZodUndefined, ZodUnion: () => ZodUnion, ZodUnknown: () => ZodUnknown, ZodVoid: () => ZodVoid, addIssueToContext: () => addIssueToContext, any: () => anyType, array: () => arrayType, bigint: () => bigIntType, boolean: () => booleanType, coerce: () => coerce2, custom: () => custom, date: () => dateType, datetimeRegex: () => datetimeRegex, defaultErrorMap: () => en_default, discriminatedUnion: () => discriminatedUnionType, effect: () => effectsType, enum: () => enumType, function: () => functionType, getErrorMap: () => getErrorMap, getParsedType: () => getParsedType, instanceof: () => instanceOfType, intersection: () => intersectionType, isAborted: () => isAborted, isAsync: () => isAsync, isDirty: () => isDirty, isValid: () => isValid, late: () => late, lazy: () => lazyType, literal: () => literalType, makeIssue: () => makeIssue, map: () => mapType, nan: () => nanType, nativeEnum: () => nativeEnumType, never: () => neverType, null: () => nullType, nullable: () => nullableType, number: () => numberType, object: () => objectType, objectUtil: () => objectUtil, oboolean: () => oboolean, onumber: () => onumber, optional: () => optionalType, ostring: () => ostring, pipeline: () => pipelineType, preprocess: () => preprocessType, promise: () => promiseType, quotelessJson: () => quotelessJson, record: () => recordType, set: () => setType, setErrorMap: () => setErrorMap, strictObject: () => strictObjectType, string: () => stringType, symbol: () => symbolType, transformer: () => effectsType, tuple: () => tupleType, undefined: () => undefinedType, union: () => unionType, unknown: () => unknownType, util: () => util, void: () => voidType }); // ../../../../../node_modules/.deno/zod@3.25.76/node_modules/zod/v3/helpers/util.js var util; (function(util2) { util2.assertEqual = (_) => { }; function assertIs(_arg) { } util2.assertIs = assertIs; function assertNever(_x) { throw new Error(); } util2.assertNever = assertNever; util2.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util2.getValidEnumValues = (obj) => { const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); const filtered = {}; for (const k of validKeys) { filtered[k] = obj[k]; } return util2.objectValues(filtered); }; util2.objectValues = (obj) => { return util2.objectKeys(obj).map(function(e) { return obj[e]; }); }; util2.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; }; util2.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return void 0; }; util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; function joinValues(array, separator = " | ") { return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); } util2.joinValues = joinValues; util2.jsonStringifyReplacer = (_, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util || (util = {})); var objectUtil; (function(objectUtil2) { objectUtil2.mergeShapes = (first, second) => { return { ...first, ...second }; }; })(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/.deno/zod@3.25.76/node_modules/zod/v3/ZodError.js var ZodIssueCode = util.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite" ]); var quotelessJson = (obj) => { const json = JSON.stringify(obj, null, 2); return json.replace(/"([^"]+)":/g, "$1:"); }; var ZodError = 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 = {}; 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/.deno/zod@3.25.76/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/.deno/zod@3.25.76/node_modules/zod/v3/errors.js var overrideErrorMap = en_default; function setErrorMap(map) { overrideErrorMap = map; } function getErrorMap() { return overrideErrorMap; } // ../../../../../node_modules/.deno/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js var makeIssue = (params) => { const { data, path, errorMaps, issueData } = params; const fullPath = [ ...path, ...issueData.path || [] ]; const fullIssue = { ...issueData, path: fullPath }; if (issueData.message !== void 0) { return { ...issueData, path: fullPath, message: issueData.message }; } 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 }; }; var EMPTY_PATH = []; 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 ? void 0 : en_default ].filter((x) => !!x) }); ctx.common.issues.push(issue); } var ParseStatus = class _ParseStatus { constructor() { this.value = "valid"; } dirty() { if (this.value === "valid") this.value = "dirty"; } abort() { if (this.value !== "aborted") this.value = "aborted"; } static mergeArray(status, results) { const arrayValue = []; for (const s of results) { if (s.status === "aborted") return INVALID; if (s.status === "dirty") status.dirty(); arrayValue.push(s.value); } return { status: status.value, value: arrayValue }; } 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/.deno/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js var errorUtil; (function(errorUtil2) { errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; })(errorUtil || (errorUtil = {})); // ../../../../../node_modules/.deno/zod@3.25.76/node_modules/zod/v3/types.js var ParseInputLazyPath = class { constructor(parent, value, path, key) { this._cachedPath = []; this.parent = parent; this.data = value; this._path = path; this._key = key; } get path() { if (!this._cachedPath.length) { if (Array.isArray(this._key)) { this._cachedPath.push(...this._path, ...this._key); } else { this._cachedPath.push(...this._path, this._key); } } return this._cachedPath; } }; 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: errorMap2, invalid_type_error, required_error, description } = params; if (errorMap2 && (invalid_type_error || required_error)) { throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } if (errorMap2) return { errorMap: errorMap2, description }; const customMap = (iss, ctx) => { const { message } = params; if (iss.code === "invalid_enum_value") { return { message: message ?? ctx.defaultError }; } if (typeof ctx.data === "undefined") { return { message: message ?? required_error ?? ctx.defaultError }; } if (iss.code !== "invalid_type") return { message: ctx.defaultError }; return { message: message ?? invalid_type_error ?? ctx.defaultError }; }; return { errorMap: customMap, description }; } var ZodType = class { get description() { return this._def.description; } _getType(input2) { return getParsedType(input2.data); } _getOrReturnCtx(input2, ctx) { return ctx || { common: input2.parent.common, data: input2.data, parsedType: getParsedType(input2.data), schemaErrorMap: this._def.errorMap, path: input2.path, parent: input2.parent }; } _processInputParams(input2) { return { status: new ParseStatus(), ctx: { common: input2.parent.common, data: input2.data, parsedType: getParsedType(input2.data), schemaErrorMap: this._def.errorMap, path: input2.path, parent: input2.parent } }; } _parseSync(input2) { const result = this._parse(input2); if (isAsync(result)) { throw new Error("Synchronous parse encountered promise."); } return result; } _parseAsync(input2) { const result = this._parse(input2); 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(def2) { this.spa = this.safeParseAsync; this._def = def2; 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(def2) { const defaultValueFunc = typeof def2 === "function" ? def2 : () => def2; 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(def2) { const catchValueFunc = typeof def2 === "function" ? def2 : () => def2; 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(void 0).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 base642 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); const decoded = JSON.parse(atob(base642)); if (typeof decoded !== "object" || decoded === null) return false; if ("typ" in decoded && decoded?.typ !== "JWT") return false; if (!decoded.alg) return false; if (alg && decoded.alg !== alg) return false; return true; } catch { return false; } } function isValidCidr(ip, version) { if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { return true; } if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { return true; } return false; } var ZodString = class _ZodString extends ZodType { _parse(input2) { if (this._def.coerce) { input2.data = String(input2.data); } const parsedType = this._getType(input2); if (parsedType !== ZodParsedType.string) { const ctx2 = this._getOrReturnCtx(input2); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.string, received: ctx2.parsedType }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const check of this._def.checks) { if (check.kind === "min") { if (input2.data.length < check.value) { ctx = this._getOrReturnCtx(input2, 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 (input2.data.length > check.value) { ctx = this._getOrReturnCtx(input2, 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 = input2.data.length > check.value; const tooSmall = input2.data.length < check.value; if (tooBig || tooSmall) { ctx = this._getOrReturnCtx(input2, 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(input2.data)) { ctx = this._getOrReturnCtx(input2, 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(input2.data)) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { validation: "emoji", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "uuid") { if (!uuidRegex.test(input2.data)) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { validation: "uuid", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "nanoid") { if (!nanoidRegex.test(input2.data)) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { validation: "nanoid", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "cuid") { if (!cuidRegex.test(input2.data)) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { validation: "cuid", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "cuid2") { if (!cuid2Regex.test(input2.data)) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { validation: "cuid2", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "ulid") { if (!ulidRegex.test(input2.data)) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { validation: "ulid", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "url") { try { new URL(input2.data); } catch { ctx = this._getOrReturnCtx(input2, 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(input2.data); if (!testResult) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { validation: "regex", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "trim") { input2.data = input2.data.trim(); } else if (check.kind === "includes") { if (!input2.data.includes(check.value, check.position)) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { includes: check.value, position: check.position }, message: check.message }); status.dirty(); } } else if (check.kind === "toLowerCase") { input2.data = input2.data.toLowerCase(); } else if (check.kind === "toUpperCase") { input2.data = input2.data.toUpperCase(); } else if (check.kind === "startsWith") { if (!input2.data.startsWith(check.value)) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: { startsWith: check.value }, message: check.message }); status.dirty(); } } else if (check.kind === "endsWith") { if (!input2.data.endsWith(check.value)) { ctx = this._getOrReturnCtx(input2, 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(input2.data)) { ctx = this._getOrReturnCtx(input2, 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(input2.data)) { ctx = this._getOrReturnCtx(input2, 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(input2.data)) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { code: ZodIssueCode.invalid_string, validation: "time", message: check.message }); status.dirty(); } } else if (check.kind === "duration") { if (!durationRegex.test(input2.data)) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { validation: "duration", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "ip") { if (!isValidIP(input2.data, check.version)) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { validation: "ip", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "jwt") { if (!isValidJWT(input2.data, check.alg)) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { validation: "jwt", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "cidr") { if (!isValidCidr(input2.data, check.version)) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { validation: "cidr", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "base64") { if (!base64Regex.test(input2.data)) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { validation: "base64", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "base64url") { if (!base64urlRegex.test(input2.data)) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { validation: "base64url", code: ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: input2.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) }); } /** * Equivalent to `.min(1)` */ 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; } var ZodNumber = class _ZodNumber extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; this.step = this.multipleOf; } _parse(input2) { if (this._def.coerce) { input2.data = Number(input2.data); } const parsedType = this._getType(input2); if (parsedType !== ZodParsedType.number) { const ctx2 = this._getOrReturnCtx(input2); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.number, received: ctx2.parsedType }); return INVALID; } let ctx = void 0; const status = new ParseStatus(); for (const check of this._def.checks) { if (check.kind === "int") { if (!util.isInteger(input2.data)) { ctx = this._getOrReturnCtx(input2, 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 ? input2.data < check.value : input2.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input2, 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 ? input2.data > check.value : input2.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input2, 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(input2.data, check.value) !== 0) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message }); status.dirty(); } } else if (check.kind === "finite") { if (!Number.isFinite(input2.data)) { ctx = this._getOrReturnCtx(input2, ctx); addIssueToContext(ctx, { code: ZodIssueCode.not_finite, message: check.message }); status.dirty(); } } else { util.assertNever(check); } } return { status: status.value, value: input2.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) }); }; var ZodBigInt = class _ZodBigInt extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; } _parse(input2) { if (this._def.coerce) { try { input2.data = BigInt(input2.data); } catch { return this._getInvalidInput(input2); } } const parsedType = this._getType(input2); if (parsedType !== ZodParsedType.bigint) { return this._getInvalidInput(input2); } let ctx = void 0; const status = new ParseStatus(); for (const check of this._def.checks) { if (check.kind === "min") { const tooSmall = check.inclusive ? input2.data < check.value : input2.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input2, 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 ? input2.data > check.value : input2.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input2, 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 (input2.data % check.value !== BigInt(0)) { ctx = this._getOrReturnCtx(input2, 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: input2.data }; } _getInvalidInput(input2) { const ctx = this._getOrReturnCtx(input2); 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) }); }; var ZodBoolean = class extends ZodType { _parse(input2) { if (this._def.coerce) { input2.data = Boolean(input2.data); } const parsedType = this._getType(input2); if (parsedType !== ZodParsedType.boolean) { const ctx = this._getOrReturnCtx(input2); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.boolean, received: ctx.parsedType }); return INVALID; } return OK(input2.data); } }; ZodBoolean.create = (params) => { return new ZodBoolean({ typeName: ZodFirstPartyTypeKind.ZodBoolean, coerce: params?.coerce || false, ...processCreateParams(params) }); }; var ZodDate = class _ZodDate extends ZodType { _parse(input2) { if (this._def.coerce) { input2.data = new Date(input2.data); } const parsedType = this._getType(input2); if (parsedType !== ZodParsedType.date) { const ctx2 = this._getOrReturnCtx(input2); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.date, received: ctx2.parsedType }); return INVALID; } if (Number.isNaN(input2.data.getTime())) { const ctx2 = this._getOrReturnCtx(input2); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_date }); return INVALID; } const status = new ParseStatus(); let ctx = void 0; for (const check of this._def.checks) { if (check.kind === "min") { if (input2.data.getTime() < check.value) { ctx = this._getOrReturnCtx(input2, 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 (input2.data.getTime() > check.value) { ctx = this._getOrReturnCtx(input2, 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(input2.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) }); }; var ZodSymbol = class extends ZodType { _parse(input2) { const parsedType = this._getType(input2); if (parsedType !== ZodParsedType.symbol) { const ctx = this._getOrReturnCtx(input2); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.symbol, received: ctx.parsedType }); return INVALID; } return OK(input2.data); } }; ZodSymbol.create = (params) => { return new ZodSymbol({ typeName: ZodFirstPartyTypeKind.ZodSymbol, ...processCreateParams(params) }); }; var ZodUndefined = class extends ZodType { _parse(input2) { const parsedType = this._getType(input2); if (parsedType !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input2); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.undefined, received: ctx.parsedType }); return INVALID; } return OK(input2.data); } }; ZodUndefined.create = (params) => { return new ZodUndefined({ typeName: ZodFirstPartyTypeKind.ZodUndefined, ...processCreateParams(params) }); }; var ZodNull = class extends ZodType { _parse(input2) { const parsedType = this._getType(input2); if (parsedType !== ZodParsedType.null) { const ctx = this._getOrReturnCtx(input2); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.null, received: ctx.parsedType }); return INVALID; } return OK(input2.data); } }; ZodNull.create = (params) => { return new ZodNull({ typeName: ZodFirstPartyTypeKind.ZodNull, ...processCreateParams(params) }); }; var ZodAny = class extends ZodType { constructor() { super(...arguments); this._any = true; } _parse(input2) { return OK(input2.data); } }; ZodAny.create = (params) => { return new ZodAny({ typeName: ZodFirstPartyTypeKind.ZodAny, ...processCreateParams(params) }); }; var ZodUnknown = class extends ZodType { constructor() { super(...arguments); this._unknown = true; } _parse(input2) { return OK(input2.data); } }; ZodUnknown.create = (params) => { return new ZodUnknown({ typeName: ZodFirstPartyTypeKind.ZodUnknown, ...processCreateParams(params) }); }; var ZodNever = class extends ZodType { _parse(input2) { const ctx = this._getOrReturnCtx(input2); 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) }); }; var ZodVoid = class extends ZodType { _parse(input2) { const parsedType = this._getType(input2); if (parsedType !== ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input2); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.void, received: ctx.parsedType }); return INVALID; } return OK(input2.data); } }; ZodVoid.create = (params) => { return new ZodVoid({ typeName: ZodFirstPartyTypeKind.ZodVoid, ...processCreateParams(params) }); }; var ZodArray = class _ZodArray extends ZodType { _parse(input2) { const { ctx, status } = this._processInputParams(input2); const def2 = this._def; if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType }); return INVALID; } if (def2.exactLength !== null) { const tooBig = ctx.data.length > def2.exactLength.value; const tooSmall = ctx.data.length < def2.exactLength.value; if (tooBig || tooSmall) { addIssueToContext(ctx, { code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, minimum: tooSmall ? def2.exactLength.value : void 0, maximum: tooBig ? def2.exactLength.value : void 0, type: "array", inclusive: true, exact: true, message: def2.exactLength.message }); status.dirty(); } } if (def2.minLength !== null) { if (ctx.data.length < def2.minLength.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def2.minLength.value, type: "array", inclusive: true, exact: false, message: def2.minLength.message }); status.dirty(); } } if (def2.maxLength !== null) { if (ctx.data.length > def2.maxLength.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def2.maxLength.value, type: "array", inclusive: true, exact: false, message: def2.maxLength.message }); status.dirty(); } } if (ctx.common.async) { return Promise.all([ ...ctx.data ].map((item, i) => { return def2.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); })).then((result2) => { return ParseStatus.mergeArray(status, result2); }); } const result = [ ...ctx.data ].map((item, i) => { return def2.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 = (schema2, params) => { return new ZodArray({ type: schema2, minLength: null, maxLength: null, exactLength: null, typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(params) }); }; function deepPartialify(schema2) { if (schema2 instanceof ZodObject) { const newShape = {}; for (const key in schema2.shape) { const fieldSchema = schema2.shape[key]; newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); } return new ZodObject({ ...schema2._def, shape: () => newShape }); } else if (schema2 instanceof ZodArray) { return new ZodArray({ ...schema2._def, type: deepPartialify(schema2.element) }); } else if (schema2 instanceof ZodOptional) { return ZodOptional.create(deepPartialify(schema2.unwrap())); } else if (schema2 instanceof ZodNullable) { return ZodNullable.create(deepPartialify(schema2.unwrap())); } else if (schema2 instanceof ZodTuple) { return ZodTuple.create(schema2.items.map((item) => deepPartialify(item))); } else { return schema2; } } var ZodObject = class _ZodObject extends ZodType { constructor() { super(...arguments); this._cached = null; this.nonstrict = this.passthrough; this.augment = this.extend; } _getCached() { if (this._cached !== null) return this._cached; const shape = this._def.shape(); const keys = util.objectKeys(shape); this._cached = { shape, keys }; return this._cached; } _parse(input2) { const parsedType = this._getType(input2); if (parsedType !== ZodParsedType.object) { const ctx2 = this._getOrReturnCtx(input2); addIssueToContext(ctx2, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.object, received: ctx2.parsedType }); return INVALID; } const { status, ctx } = this._processInputParams(input2); 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) //, ctx.child(key), value, getParsedType(value) ), alwaysSet: key in ctx.data }); } } if (ctx.common.async) { return Promise.resolve().then(async () => { const syncPairs = []; for (const pair of 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 !== void 0 ? { 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" }); } // const AugmentFactory = // (def: Def) => // ( // augmentation: Augmentation // ): ZodObject< // extendShape, Augmentation>, // Def["unknownKeys"], // Def["catchall"] // > => { // return new ZodObject({ // ...def, // shape: () => ({ // ...def.shape(), // ...augmentation, // }), // }) as any; // }; extend(augmentation) { return new _ZodObject({ ...this._def, shape: () => ({ ...this._def.shape(), ...augmentation }) }); } /** * Prior to zod@1.0.12 there was a bug in the * inferred type of merged objects. Please * upgrade if you are experiencing issues. */ merge(merging) { const merged = new _ZodObject({ unknownKeys: merging._def.unknownKeys, catchall: merging._def.catchall, shape: () => ({ ...this._def.shape(), ...merging._def.shape() }), typeName: ZodFirstPartyTypeKind.ZodObject }); return merged; } // merge< // Incoming extends AnyZodObject, // Augmentation extends Incoming["shape"], // NewOutput extends { // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation // ? Augmentation[k]["_output"] // : k extends keyof Output // ? Output[k] // : never; // }, // NewInput extends { // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation // ? Augmentation[k]["_input"] // : k extends keyof Input // ? Input[k] // : never; // } // >( // merging: Incoming // ): ZodObject< // extendShape>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"], // NewOutput, // NewInput // > { // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } setKey(key, schema2) { return this.augment({ [key]: schema2 }); } // merge( // merging: Incoming // ): //ZodObject = (merging) => { // ZodObject< // extendShape>, // Incoming["_def"]["unknownKeys"], // Incoming["_def"]["catchall"] // > { // // const mergedShape = objectUtil.mergeShapes( // // this._def.shape(), // // merging._def.shape() // // ); // const merged: any = new ZodObject({ // unknownKeys: merging._def.unknownKeys, // catchall: merging._def.catchall, // shape: () => // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), // typeName: ZodFirstPartyTypeKind.ZodObject, // }) as any; // return merged; // } catchall(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 }); } /** * @deprecated */ deepPartial() { return deepPartialify(this); } partial(mask) { const newShape = {}; for (const key of util.objectKeys(this.shape)) { const fieldSchema = this.shape[key]; if (mask && !mask[key]) { newShape[key] = fieldSchema; } else { newShape[key] = fieldSchema.optional(); } } return new _ZodObject({ ...this._def, shape: () => newShape }); } 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) }); }; var ZodUnion = class extends ZodType { _parse(input2) { const { ctx } = this._processInputParams(input2); const options = this._def.options; function handleResults(results) { for (const result of results) { if (result.result.status === "valid") { return result.result; } } for (const result of results) { if (result.result.status === "dirty") { ctx.common.issues.push(...result.ctx.common.issues); return result.result; } } const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors }); return INVALID; } if (ctx.common.async) { return Promise.all(options.map(async (option) => { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; return { result: await option._parseAsync({ data: ctx.data, path: ctx.path, parent: childCtx }), ctx: childCtx }; })).then(handleResults); } else { let dirty = void 0; const issues = []; for (const option of options) { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; const result = option._parseSync({ data: ctx.data, path: ctx.path, parent: childCtx }); if (result.status === "valid") { return result; } else if (result.status === "dirty" && !dirty) { dirty = { result, ctx: childCtx }; } if (childCtx.common.issues.length) { issues.push(childCtx.common.issues); } } if (dirty) { ctx.common.issues.push(...dirty.ctx.common.issues); return dirty.result; } const unionErrors = issues.map((issues2) => new ZodError(issues2)); addIssueToContext(ctx, { code: ZodIssueCode.invalid_union, unionErrors }); return INVALID; } } 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 [ void 0 ]; } else if (type instanceof ZodNull) { return [ null ]; } else if (type instanceof ZodOptional) { return [ void 0, ...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 []; } }; var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { _parse(input2) { const { ctx } = this._processInputParams(input2); 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; } /** * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. * However, it only allows a union of objects, all of which need to share a discriminator property. This property must * have a different value for each object in the union. * @param discriminator the name of the discriminator property * @param types an array of object schemas * @param params */ static create(discriminator, options, params) { const optionsMap = /* @__PURE__ */ new Map(); for (const 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 }; } } var ZodIntersection = class extends ZodType { _parse(input2) { const { status, ctx } = this._processInputParams(input2); 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) }); }; var ZodTuple = class _ZodTuple extends ZodType { _parse(input2) { const { status, ctx } = this._processInputParams(input2); if (ctx.parsedType !== ZodParsedType.array) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.array, received: ctx.parsedType }); return INVALID; } if (ctx.data.length < this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array" }); return INVALID; } const rest = this._def.rest; if (!rest && ctx.data.length > this._def.items.length) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array" }); status.dirty(); } const items = [ ...ctx.data ].map((item, itemIndex) => { const schema2 = this._def.items[itemIndex] || this._def.rest; if (!schema2) return null; return schema2._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); }).filter((x) => !!x); if (ctx.common.async) { return Promise.all(items).then((results) => { return ParseStatus.mergeArray(status, results); }); } else { return ParseStatus.mergeArray(status, items); } } get items() { return this._def.items; } rest(rest) { return new _ZodTuple({ ...this._def, rest }); } }; ZodTuple.create = (schemas, params) => { if (!Array.isArray(schemas)) { throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } return new ZodTuple({ items: schemas, typeName: ZodFirstPartyTypeKind.ZodTuple, rest: null, ...processCreateParams(params) }); }; var ZodRecord = class _ZodRecord extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input2) { const { status, ctx } = this._processInputParams(input2); 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) }); } }; var ZodMap = class extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input2) { const { status, ctx } = this._processInputParams(input2); 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 = /* @__PURE__ */ 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 = /* @__PURE__ */ 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) }); }; var ZodSet = class _ZodSet extends ZodType { _parse(input2) { const { status, ctx } = this._processInputParams(input2); if (ctx.parsedType !== ZodParsedType.set) { addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.set, received: ctx.parsedType }); return INVALID; } const def2 = this._def; if (def2.minSize !== null) { if (ctx.data.size < def2.minSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_small, minimum: def2.minSize.value, type: "set", inclusive: true, exact: false, message: def2.minSize.message }); status.dirty(); } } if (def2.maxSize !== null) { if (ctx.data.size > def2.maxSize.value) { addIssueToContext(ctx, { code: ZodIssueCode.too_big, maximum: def2.maxSize.value, type: "set", inclusive: true, exact: false, message: def2.maxSize.message }); status.dirty(); } } const valueType = this._def.valueType; function finalizeSet(elements2) { const parsedSet = /* @__PURE__ */ new Set(); for (const element of elements2) { if (element.status === "aborted") return INVALID; if (element.status === "dirty") status.dirty(); parsedSet.add(element.value); } return { status: status.value, value: parsedSet }; } const elements = [ ...ctx.data.values() ].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); if (ctx.common.async) { return Promise.all(elements).then((elements2) => finalizeSet(elements2)); } 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) }); }; var ZodFunction = class _ZodFunction extends ZodType { constructor() { super(...arguments); this.validate = this.implement; } _parse(input2) { const { ctx } = this._processInputParams(input2); 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) }); } }; var ZodLazy = class extends ZodType { get schema() { return this._def.getter(); } _parse(input2) { const { ctx } = this._processInputParams(input2); const lazySchema = this._def.getter(); return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } }; ZodLazy.create = (getter, params) => { return new ZodLazy({ getter, typeName: ZodFirstPartyTypeKind.ZodLazy, ...processCreateParams(params) }); }; var ZodLiteral = class extends ZodType { _parse(input2) { if (input2.data !== this._def.value) { const ctx = this._getOrReturnCtx(input2); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_literal, expected: this._def.value }); return INVALID; } return { status: "valid", value: input2.data }; } get value() { return this._def.value; } }; ZodLiteral.create = (value, params) => { return new ZodLiteral({ value, typeName: ZodFirstPartyTypeKind.ZodLiteral, ...processCreateParams(params) }); }; function createZodEnum(values, params) { return new ZodEnum({ values, typeName: ZodFirstPartyTypeKind.ZodEnum, ...processCreateParams(params) }); } var ZodEnum = class _ZodEnum extends ZodType { _parse(input2) { if (typeof input2.data !== "string") { const ctx = this._getOrReturnCtx(input2); 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(input2.data)) { const ctx = this._getOrReturnCtx(input2); const expectedValues = this._def.values; addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input2.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; var ZodNativeEnum = class extends ZodType { _parse(input2) { const nativeEnumValues = util.getValidEnumValues(this._def.values); const ctx = this._getOrReturnCtx(input2); 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(input2.data)) { const expectedValues = util.objectValues(nativeEnumValues); addIssueToContext(ctx, { received: ctx.data, code: ZodIssueCode.invalid_enum_value, options: expectedValues }); return INVALID; } return OK(input2.data); } get enum() { return this._def.values; } }; ZodNativeEnum.create = (values, params) => { return new ZodNativeEnum({ values, typeName: ZodFirstPartyTypeKind.ZodNativeEnum, ...processCreateParams(params) }); }; var ZodPromise = class extends ZodType { unwrap() { return this._def.type; } _parse(input2) { const { ctx } = this._processInputParams(input2); 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 = (schema2, params) => { return new ZodPromise({ type: schema2, typeName: ZodFirstPartyTypeKind.ZodPromise, ...processCreateParams(params) }); }; var ZodEffects = class extends ZodType { innerType() { return this._def.schema; } sourceType() { return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; } _parse(input2) { const { status, ctx } = this._processInputParams(input2); 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 (processed2) => { if (status.value === "aborted") return INVALID; const result = await this._def.schema._parseAsync({ data: processed2, path: ctx.path, parent: ctx }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; }); } else { if (status.value === "aborted") return INVALID; const result = this._def.schema._parseSync({ data: processed, path: ctx.path, parent: ctx }); if (result.status === "aborted") return INVALID; if (result.status === "dirty") return DIRTY(result.value); if (status.value === "dirty") return DIRTY(result.value); return result; } } if (effect.type === "refinement") { const executeRefinement = (acc) => { const result = effect.refinement(acc, checkCtx); if (ctx.common.async) { return Promise.resolve(result); } if (result instanceof Promise) { throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); } return acc; }; if (ctx.common.async === false) { const inner = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); executeRefinement(inner.value); return { status: status.value, value: inner.value }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { if (inner.status === "aborted") return INVALID; if (inner.status === "dirty") status.dirty(); return executeRefinement(inner.value).then(() => { return { status: status.value, value: inner.value }; }); }); } } if (effect.type === "transform") { if (ctx.common.async === false) { const base3 = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (!isValid(base3)) return INVALID; const result = effect.transform(base3.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((base3) => { if (!isValid(base3)) return INVALID; return Promise.resolve(effect.transform(base3.value, checkCtx)).then((result) => ({ status: status.value, value: result })); }); } } util.assertNever(effect); } }; ZodEffects.create = (schema2, effect, params) => { return new ZodEffects({ schema: schema2, typeName: ZodFirstPartyTypeKind.ZodEffects, effect, ...processCreateParams(params) }); }; ZodEffects.createWithPreprocess = (preprocess, schema2, params) => { return new ZodEffects({ schema: schema2, effect: { type: "preprocess", transform: preprocess }, typeName: ZodFirstPartyTypeKind.ZodEffects, ...processCreateParams(params) }); }; var ZodOptional = class extends ZodType { _parse(input2) { const parsedType = this._getType(input2); if (parsedType === ZodParsedType.undefined) { return OK(void 0); } return this._def.innerType._parse(input2); } unwrap() { return this._def.innerType; } }; ZodOptional.create = (type, params) => { return new ZodOptional({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(params) }); }; var ZodNullable = class extends ZodType { _parse(input2) { const parsedType = this._getType(input2); if (parsedType === ZodParsedType.null) { return OK(null); } return this._def.innerType._parse(input2); } unwrap() { return this._def.innerType; } }; ZodNullable.create = (type, params) => { return new ZodNullable({ innerType: type, typeName: ZodFirstPartyTypeKind.ZodNullable, ...processCreateParams(params) }); }; var ZodDefault = class extends ZodType { _parse(input2) { const { ctx } = this._processInputParams(input2); 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) }); }; var ZodCatch = class extends ZodType { _parse(input2) { const { ctx } = this._processInputParams(input2); const newCtx = { ...ctx, common: { ...ctx.common, issues: [] } }; const result = this._def.innerType._parse({ data: newCtx.data, path: newCtx.path, parent: { ...newCtx } }); if (isAsync(result)) { return result.then((result2) => { return { status: "valid", value: result2.status === "valid" ? result2.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data }) }; }); } else { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError(newCtx.common.issues); }, input: newCtx.data }) }; } } 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) }); }; var ZodNaN = class extends ZodType { _parse(input2) { const parsedType = this._getType(input2); if (parsedType !== ZodParsedType.nan) { const ctx = this._getOrReturnCtx(input2); addIssueToContext(ctx, { code: ZodIssueCode.invalid_type, expected: ZodParsedType.nan, received: ctx.parsedType }); return INVALID; } return { status: "valid", value: input2.data }; } }; ZodNaN.create = (params) => { return new ZodNaN({ typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(params) }); }; var BRAND = Symbol("zod_brand"); var ZodBranded = class extends ZodType { _parse(input2) { const { ctx } = this._processInputParams(input2); const data = ctx.data; return this._def.type._parse({ data, path: ctx.path, parent: ctx }); } unwrap() { return this._def.type; } }; var ZodPipeline = class _ZodPipeline extends ZodType { _parse(input2) { const { status, ctx } = this._processInputParams(input2); 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 }); } }; var ZodReadonly = class extends ZodType { _parse(input2) { const result = this._def.innerType._parse(input2); 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((r2) => { if (!r2) { 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(ZodFirstPartyTypeKind2) { ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); var instanceOfType = (cls, params = { message: `Input not instance of ${cls.name}` }) => custom((data) => data instanceof cls, params); var stringType = ZodString.create; var numberType = ZodNumber.create; var nanType = ZodNaN.create; var bigIntType = ZodBigInt.create; var booleanType = ZodBoolean.create; var dateType = ZodDate.create; var symbolType = ZodSymbol.create; var undefinedType = ZodUndefined.create; var nullType = ZodNull.create; var anyType = ZodAny.create; var unknownType = ZodUnknown.create; var neverType = ZodNever.create; var voidType = ZodVoid.create; var arrayType = ZodArray.create; var objectType = ZodObject.create; var strictObjectType = ZodObject.strictCreate; var unionType = ZodUnion.create; var discriminatedUnionType = ZodDiscriminatedUnion.create; var intersectionType = ZodIntersection.create; var tupleType = ZodTuple.create; var recordType = ZodRecord.create; var mapType = ZodMap.create; var setType = ZodSet.create; var functionType = ZodFunction.create; var lazyType = ZodLazy.create; var literalType = ZodLiteral.create; var enumType = ZodEnum.create; var nativeEnumType = ZodNativeEnum.create; var promiseType = ZodPromise.create; var effectsType = ZodEffects.create; var optionalType = ZodOptional.create; var nullableType = ZodNullable.create; var preprocessType = ZodEffects.createWithPreprocess; var pipelineType = ZodPipeline.create; var ostring = () => stringType().optional(); var onumber = () => numberType().optional(); var oboolean = () => booleanType().optional(); var coerce2 = { string: (arg) => ZodString.create({ ...arg, coerce: true }), number: (arg) => ZodNumber.create({ ...arg, coerce: true }), boolean: (arg) => ZodBoolean.create({ ...arg, coerce: true }), bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }), date: (arg) => ZodDate.create({ ...arg, coerce: true }) }; var NEVER = INVALID; // ../../../../../node_modules/.deno/@atproto+common-web@0.5.14/node_modules/@atproto/common-web/dist/types.js var cidSchema = external_exports.unknown().transform((obj, ctx) => { const cid = CID.asCID(obj); if (cid == null) { ctx.addIssue({ code: external_exports.ZodIssueCode.custom, message: "Not a valid CID" }); return external_exports.NEVER; } return cid; }); var carHeader = external_exports.object({ version: external_exports.literal(1), roots: external_exports.array(cidSchema) }); var schema = { cid: cidSchema, carHeader, bytes: external_exports.instanceof(Uint8Array), string: external_exports.string(), array: external_exports.array(external_exports.unknown()), map: external_exports.record(external_exports.string(), external_exports.unknown()), unknown: external_exports.unknown() }; var def = { cid: { name: "cid", schema: schema.cid }, carHeader: { name: "CAR header", schema: schema.carHeader }, bytes: { name: "bytes", schema: schema.bytes }, string: { name: "string", schema: schema.string }, map: { name: "map", schema: schema.map }, unknown: { name: "unknown", schema: schema.unknown } }; // ../../../../../node_modules/.deno/@atproto+common-web@0.5.14/node_modules/@atproto/common-web/dist/times.js var SECOND = 1e3; var MINUTE = SECOND * 60; var HOUR = MINUTE * 60; var DAY = HOUR * 24; // ../../../../../node_modules/.deno/@atproto+syntax@0.7.6/node_modules/@atproto/syntax/dist/datetime.js var isoDatestringValidator = __toESM(require_dist()); var { isValidISODateString } = ((m) => m.default ?? m)(isoDatestringValidator); // ../../../../../node_modules/.deno/@atproto+common-web@0.5.14/node_modules/@atproto/common-web/dist/did-doc.js var getDid = (doc) => { const id = doc.id; if (typeof id !== "string") { throw new Error("No `id` on document"); } return id; }; var getHandle = (doc) => { const aka = doc.alsoKnownAs; if (aka) { for (let i = 0; i < aka.length; i++) { const alias = aka[i]; if (alias.startsWith("at://")) { return alias.slice(5); } } } return void 0; }; var getSigningKey = (doc) => { return getVerificationMaterial(doc, "atproto"); }; var getVerificationMaterial = (doc, keyId) => { const key = findItemById(doc, "verificationMethod", `#${keyId}`); if (!key) { return void 0; } if (!key.publicKeyMultibase) { return void 0; } return { type: key.type, publicKeyMultibase: key.publicKeyMultibase }; }; var getPdsEndpoint = (doc) => { return getServiceEndpoint(doc, { id: "#atproto_pds", type: "AtprotoPersonalDataServer" }); }; var getServiceEndpoint = (doc, opts) => { const service2 = findItemById(doc, "service", opts.id); if (!service2) { return void 0; } if (opts.type && service2.type !== opts.type) { return void 0; } if (typeof service2.serviceEndpoint !== "string") { return void 0; } return validateUrl(service2.serviceEndpoint); }; function findItemById(doc, type, id) { const items = doc[type]; if (items) { for (let i = 0; i < items.length; i++) { const item = items[i]; const itemId = item.id; if (itemId[0] === "#" ? itemId === id : itemId.length === doc.id.length + id.length && itemId[doc.id.length] === "#" && itemId.endsWith(id) && itemId.startsWith(doc.id)) { return item; } } } return void 0; } var validateUrl = (urlStr) => { if (!urlStr.startsWith("http://") && !urlStr.startsWith("https://")) { return void 0; } if (!canParseUrl(urlStr)) { return void 0; } return urlStr; }; var canParseUrl = URL.canParse ?? // URL.canParse is not available in Node.js < 18.17.0 ((urlStr) => { try { new URL(urlStr); return true; } catch { return false; } }); var verificationMethod = external_exports.object({ id: external_exports.string(), type: external_exports.string(), controller: external_exports.string(), publicKeyJwk: external_exports.record(external_exports.string(), external_exports.unknown()).optional(), publicKeyMultibase: external_exports.string().optional() }); var service = external_exports.object({ id: external_exports.string(), type: external_exports.string(), serviceEndpoint: external_exports.union([ external_exports.string(), external_exports.record(external_exports.unknown()) ]) }); var didDocument = external_exports.object({ "@context": external_exports.union([ external_exports.literal("https://www.w3.org/ns/did/v1"), external_exports.array(external_exports.string().url()) ]).optional(), id: external_exports.string(), alsoKnownAs: external_exports.array(external_exports.string()).optional(), verificationMethod: external_exports.array(verificationMethod).optional(), authentication: external_exports.array(external_exports.union([ external_exports.string(), verificationMethod ])).optional(), service: external_exports.array(service).optional() }); // ../../../../../node_modules/.deno/@atproto+identity@0.5.6/node_modules/@atproto/identity/dist/errors.js var DidNotFoundError = class extends Error { constructor(did) { super(`Could not resolve DID: ${did}`); this.did = did; } }; var PoorlyFormattedDidError = class extends Error { constructor(did) { super(`Poorly formatted DID: ${did}`); this.did = did; } }; var UnsupportedDidMethodError = class extends Error { constructor(did) { super(`Unsupported DID method: ${did}`); this.did = did; } }; var PoorlyFormattedDidDocumentError = class extends Error { constructor(did, doc) { super(`Poorly formatted DID Document: ${doc}`); this.did = did; this.doc = doc; } }; var UnsupportedDidWebPathError = class extends Error { constructor(did) { super(`Unsupported did:web paths: ${did}`); this.did = did; } }; // ../../../../../node_modules/.deno/@atproto+crypto@0.5.7/node_modules/@atproto/crypto/dist/const.js var P256_DID_PREFIX = new Uint8Array([ 128, 36 ]); var SECP256K1_DID_PREFIX = new Uint8Array([ 231, 1 ]); var BASE58_MULTIBASE_PREFIX = "z"; var DID_KEY_PREFIX = "did:key:"; var P256_JWT_ALG = "ES256"; var SECP256K1_JWT_ALG = "ES256K"; // ../../../../../node_modules/.deno/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/equals.js function equals3(a, b) { if (a === b) { return true; } if (a.byteLength !== b.byteLength) { return false; } for (let i = 0; i < a.byteLength; i++) { if (a[i] !== b[i]) { return false; } } return true; } // ../../../../../node_modules/.deno/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/alloc.node.js import { Buffer as Buffer2 } from "node:buffer"; // ../../../../../node_modules/.deno/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/util/as-uint8array.node.js function asUint8Array(buf) { return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); } // ../../../../../node_modules/.deno/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/alloc.node.js function allocUnsafe(size = 0) { return asUint8Array(Buffer2.allocUnsafe(size)); } // ../../../../../node_modules/.deno/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/compare.node.js import { Buffer as Buffer3 } from "node:buffer"; // ../../../../../node_modules/.deno/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/concat.node.js import { Buffer as Buffer4 } from "node:buffer"; function concat(arrays, length2) { return asUint8Array(Buffer4.concat(arrays, length2)); } // ../../../../../node_modules/.deno/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/from-string.node.js import { Buffer as Buffer5 } from "node:buffer"; // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base10.js var base10_exports = {}; __export(base10_exports, { base10: () => base10 }); var base10 = baseX({ prefix: "9", name: "base10", alphabet: "0123456789" }); // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base16.js var base16_exports = {}; __export(base16_exports, { base16: () => base16, base16upper: () => base16upper }); var base16 = rfc4648({ prefix: "f", name: "base16", alphabet: "0123456789abcdef", bitsPerChar: 4 }); var base16upper = rfc4648({ prefix: "F", name: "base16upper", alphabet: "0123456789ABCDEF", bitsPerChar: 4 }); // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base2.js var base2_exports = {}; __export(base2_exports, { base2: () => base2 }); var base2 = rfc4648({ prefix: "0", name: "base2", alphabet: "01", bitsPerChar: 1 }); // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base256emoji.js var base256emoji_exports = {}; __export(base256emoji_exports, { base256emoji: () => base256emoji }); var alphabet = Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"); var alphabetBytesToChars = alphabet.reduce((p, c, i) => { p[i] = c; return p; }, []); var alphabetCharsToBytes = alphabet.reduce((p, c, i) => { const codePoint = c.codePointAt(0); if (codePoint == null) { throw new Error(`Invalid character: ${c}`); } p[codePoint] = i; return p; }, []); function encode3(data) { return data.reduce((p, c) => { p += alphabetBytesToChars[c]; return p; }, ""); } function decode5(str) { const byts = []; for (const char of str) { const codePoint = char.codePointAt(0); if (codePoint == null) { throw new Error(`Invalid character: ${char}`); } const byt = alphabetCharsToBytes[codePoint]; if (byt == null) { throw new Error(`Non-base256emoji character: ${char}`); } byts.push(byt); } return new Uint8Array(byts); } var base256emoji = from({ prefix: "\u{1F680}", name: "base256emoji", encode: encode3, decode: decode5 }); // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/base8.js var base8_exports = {}; __export(base8_exports, { base8: () => base8 }); var base8 = rfc4648({ prefix: "7", name: "base8", alphabet: "01234567", bitsPerChar: 3 }); // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/bases/identity.js var identity_exports = {}; __export(identity_exports, { identity: () => identity }); var identity = from({ prefix: "\0", name: "identity", encode: (buf) => toString(buf), decode: (str) => fromString(str) }); // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/codecs/json.js var textEncoder = new TextEncoder(); var textDecoder = new TextDecoder(); // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/hashes/identity.js var identity_exports2 = {}; __export(identity_exports2, { identity: () => identity2 }); var code = 0; var name = "identity"; var encode4 = coerce; function digest(input2, options) { if (options?.truncate != null && options.truncate !== input2.byteLength) { if (options.truncate < 0 || options.truncate > input2.byteLength) { throw new Error(`Invalid truncate option, must be less than or equal to ${input2.byteLength}`); } input2 = input2.subarray(0, options.truncate); } return create2(code, encode4(input2)); } var identity2 = { code, name, encode: encode4, digest }; // ../../../../../node_modules/.deno/multiformats@13.4.2/node_modules/multiformats/dist/src/basics.js var bases = { ...identity_exports, ...base2_exports, ...base8_exports, ...base10_exports, ...base16_exports, ...base32_exports, ...base36_exports, ...base58_exports, ...base64_exports, ...base256emoji_exports }; var hashes = { ...sha2_exports, ...identity_exports2 }; // ../../../../../node_modules/.deno/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/util/bases.js function createCodec(name2, prefix, encode5, decode6) { return { name: name2, prefix, encoder: { name: name2, prefix, encode: encode5 }, decoder: { decode: decode6 } }; } var string = createCodec("utf8", "u", (buf) => { const decoder = new TextDecoder("utf8"); return "u" + decoder.decode(buf); }, (str) => { const encoder = new TextEncoder(); return encoder.encode(str.substring(1)); }); var ascii = createCodec("ascii", "a", (buf) => { let string2 = "a"; for (let i = 0; i < buf.length; i++) { string2 += String.fromCharCode(buf[i]); } return string2; }, (str) => { str = str.substring(1); const buf = allocUnsafe(str.length); for (let i = 0; i < str.length; i++) { buf[i] = str.charCodeAt(i); } return buf; }); var BASES = { utf8: string, "utf-8": string, hex: bases.base16, latin1: ascii, ascii, binary: ascii, ...bases }; var bases_default = BASES; // ../../../../../node_modules/.deno/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/from-string.node.js function fromString2(string2, encoding = "utf8") { const base3 = bases_default[encoding]; if (base3 == null) { throw new Error(`Unsupported encoding "${encoding}"`); } if (encoding === "utf8" || encoding === "utf-8") { return asUint8Array(Buffer5.from(string2, "utf-8")); } return base3.decoder.decode(`${base3.prefix}${string2}`); } // ../../../../../node_modules/.deno/uint8arrays@5.1.1/node_modules/uint8arrays/dist/src/to-string.node.js import { Buffer as Buffer6 } from "node:buffer"; function toString2(array, encoding = "utf8") { const base3 = bases_default[encoding]; if (base3 == null) { throw new Error(`Unsupported encoding "${encoding}"`); } if (encoding === "utf8" || encoding === "utf-8") { return Buffer6.from(array.buffer, array.byteOffset, array.byteLength).toString("utf8"); } return base3.encoder.encode(array).substring(1); } // ../../../../../node_modules/.deno/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/cryptoNode.js import * as nc from "node:crypto"; var crypto2 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0; // ../../../../../node_modules/.deno/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js function isBytes(a) { return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; } function anumber(n) { if (!Number.isSafeInteger(n) || n < 0) throw new Error("positive integer expected, got " + n); } function abytes(b, ...lengths) { if (!isBytes(b)) throw new Error("Uint8Array expected"); if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length); } function ahash(h) { if (typeof h !== "function" || typeof h.create !== "function") throw new Error("Hash should be wrapped by utils.createHasher"); anumber(h.outputLen); anumber(h.blockLen); } function aexists(instance, checkFinished = true) { if (instance.destroyed) throw new Error("Hash instance has been destroyed"); if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called"); } function aoutput(out, instance) { abytes(out); const min = instance.outputLen; if (out.length < min) { throw new Error("digestInto() expects output buffer of length at least " + min); } } function clean(...arrays) { for (let i = 0; i < arrays.length; i++) { arrays[i].fill(0); } } function createView(arr) { return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); } function rotr(word, shift) { return word << 32 - shift | word >>> shift; } var hasHexBuiltin = /* @__PURE__ */ (() => ( // @ts-ignore typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" ))(); var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); function bytesToHex(bytes) { abytes(bytes); if (hasHexBuiltin) return bytes.toHex(); let hex = ""; for (let i = 0; i < bytes.length; i++) { hex += hexes[bytes[i]]; } return hex; } var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; function asciiToBase16(ch) { if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); return; } function hexToBytes(hex) { if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex); if (hasHexBuiltin) return Uint8Array.fromHex(hex); const hl = hex.length; const al = hl / 2; if (hl % 2) throw new Error("hex string expected, got unpadded hex of length " + hl); const array = new Uint8Array(al); for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { const n1 = asciiToBase16(hex.charCodeAt(hi)); const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); if (n1 === void 0 || n2 === void 0) { const char = hex[hi] + hex[hi + 1]; throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); } array[ai] = n1 * 16 + n2; } return array; } function utf8ToBytes(str) { if (typeof str !== "string") throw new Error("string expected"); return new Uint8Array(new TextEncoder().encode(str)); } function toBytes(data) { if (typeof data === "string") data = utf8ToBytes(data); abytes(data); return data; } function concatBytes(...arrays) { let sum = 0; for (let i = 0; i < arrays.length; i++) { const a = arrays[i]; abytes(a); sum += a.length; } const res = new Uint8Array(sum); for (let i = 0, pad = 0; i < arrays.length; i++) { const a = arrays[i]; res.set(a, pad); pad += a.length; } return res; } var Hash = class { }; function createHasher(hashCons) { const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); const tmp = hashCons(); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.create = () => hashCons(); return hashC; } function randomBytes(bytesLength = 32) { if (crypto2 && typeof crypto2.getRandomValues === "function") { return crypto2.getRandomValues(new Uint8Array(bytesLength)); } if (crypto2 && typeof crypto2.randomBytes === "function") { return Uint8Array.from(crypto2.randomBytes(bytesLength)); } throw new Error("crypto.getRandomValues must be defined"); } // ../../../../../node_modules/.deno/@noble+curves@1.9.7/node_modules/@noble/curves/esm/utils.js var _0n = /* @__PURE__ */ BigInt(0); var _1n = /* @__PURE__ */ BigInt(1); function _abool2(value, title = "") { if (typeof value !== "boolean") { const prefix = title && `"${title}"`; throw new Error(prefix + "expected boolean, got type=" + typeof value); } return value; } function _abytes2(value, length2, title = "") { const bytes = isBytes(value); const len = value?.length; const needsLen = length2 !== void 0; if (!bytes || needsLen && len !== length2) { const prefix = title && `"${title}" `; const ofLen = needsLen ? ` of length ${length2}` : ""; const got = bytes ? `length=${len}` : `type=${typeof value}`; throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got); } return value; } function numberToHexUnpadded(num) { const hex = num.toString(16); return hex.length & 1 ? "0" + hex : hex; } function hexToNumber(hex) { if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex); return hex === "" ? _0n : BigInt("0x" + hex); } function bytesToNumberBE(bytes) { return hexToNumber(bytesToHex(bytes)); } function bytesToNumberLE(bytes) { abytes(bytes); return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); } function numberToBytesBE(n, len) { return hexToBytes(n.toString(16).padStart(len * 2, "0")); } function numberToBytesLE(n, len) { return numberToBytesBE(n, len).reverse(); } function ensureBytes(title, hex, expectedLength) { let res; if (typeof hex === "string") { try { res = hexToBytes(hex); } catch (e) { throw new Error(title + " must be hex string or Uint8Array, cause: " + e); } } else if (isBytes(hex)) { res = Uint8Array.from(hex); } else { throw new Error(title + " must be hex string or Uint8Array"); } const len = res.length; if (typeof expectedLength === "number" && len !== expectedLength) throw new Error(title + " of length " + expectedLength + " expected, got " + len); return res; } var isPosBig = (n) => typeof n === "bigint" && _0n <= n; function inRange(n, min, max) { return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; } function aInRange(title, n, min, max) { if (!inRange(n, min, max)) throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n); } function bitLen(n) { let len; for (len = 0; n > _0n; n >>= _1n, len += 1) ; return len; } var bitMask = (n) => (_1n << BigInt(n)) - _1n; function createHmacDrbg(hashLen, qByteLen, hmacFn) { if (typeof hashLen !== "number" || hashLen < 2) throw new Error("hashLen must be a number"); if (typeof qByteLen !== "number" || qByteLen < 2) throw new Error("qByteLen must be a number"); if (typeof hmacFn !== "function") throw new Error("hmacFn must be a function"); const u8n = (len) => new Uint8Array(len); const u8of = (byte) => Uint8Array.of(byte); let v = u8n(hashLen); let k = u8n(hashLen); let i = 0; const reset = () => { v.fill(1); k.fill(0); i = 0; }; const h = (...b) => hmacFn(k, v, ...b); const reseed = (seed = u8n(0)) => { k = h(u8of(0), seed); v = h(); if (seed.length === 0) return; k = h(u8of(1), seed); v = h(); }; const gen = () => { if (i++ >= 1e3) throw new Error("drbg: tried 1000 values"); let len = 0; const out = []; while (len < qByteLen) { v = h(); const sl = v.slice(); out.push(sl); len += v.length; } return concatBytes(...out); }; const genUntil = (seed, pred) => { reset(); reseed(seed); let res = void 0; while (!(res = pred(gen()))) reseed(); reset(); return res; }; return genUntil; } function _validateObject(object, fields, optFields = {}) { if (!object || typeof object !== "object") throw new Error("expected valid options object"); function checkField(fieldName, expectedType, isOpt) { const val = object[fieldName]; if (isOpt && val === void 0) return; const current = typeof val; if (current !== expectedType || val === null) throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`); } Object.entries(fields).forEach(([k, v]) => checkField(k, v, false)); Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true)); } function memoized(fn) { const map = /* @__PURE__ */ new WeakMap(); return (arg, ...args) => { const val = map.get(arg); if (val !== void 0) return val; const computed = fn(arg, ...args); map.set(arg, computed); return computed; }; } // ../../../../../node_modules/.deno/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/modular.js var _0n2 = BigInt(0); var _1n2 = BigInt(1); var _2n = /* @__PURE__ */ BigInt(2); var _3n = /* @__PURE__ */ BigInt(3); var _4n = /* @__PURE__ */ BigInt(4); var _5n = /* @__PURE__ */ BigInt(5); var _7n = /* @__PURE__ */ BigInt(7); var _8n = /* @__PURE__ */ BigInt(8); var _9n = /* @__PURE__ */ BigInt(9); var _16n = /* @__PURE__ */ BigInt(16); function mod(a, b) { const result = a % b; return result >= _0n2 ? result : b + result; } function pow2(x, power, modulo) { let res = x; while (power-- > _0n2) { res *= res; res %= modulo; } return res; } function invert(number, modulo) { if (number === _0n2) throw new Error("invert: expected non-zero number"); if (modulo <= _0n2) throw new Error("invert: expected positive modulus, got " + modulo); let a = mod(number, modulo); let b = modulo; let x = _0n2, y = _1n2, u = _1n2, v = _0n2; while (a !== _0n2) { const q = b / a; const r = b % a; const m = x - u * q; const n = y - v * q; b = a, a = r, x = u, y = v, u = m, v = n; } const gcd = b; if (gcd !== _1n2) throw new Error("invert: does not exist"); return mod(x, modulo); } function assertIsSquare(Fp, root, n) { if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root"); } function sqrt3mod4(Fp, n) { const p1div4 = (Fp.ORDER + _1n2) / _4n; const root = Fp.pow(n, p1div4); assertIsSquare(Fp, root, n); return root; } function sqrt5mod8(Fp, n) { const p5div8 = (Fp.ORDER - _5n) / _8n; const n2 = Fp.mul(n, _2n); const v = Fp.pow(n2, p5div8); const nv = Fp.mul(n, v); const i = Fp.mul(Fp.mul(nv, _2n), v); const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); assertIsSquare(Fp, root, n); return root; } function sqrt9mod16(P) { const Fp_ = Field(P); const tn = tonelliShanks(P); const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); const c2 = tn(Fp_, c1); const c3 = tn(Fp_, Fp_.neg(c1)); const c4 = (P + _7n) / _16n; return (Fp, n) => { let tv1 = Fp.pow(n, c4); let tv2 = Fp.mul(tv1, c1); const tv3 = Fp.mul(tv1, c2); const tv4 = Fp.mul(tv1, c3); const e1 = Fp.eql(Fp.sqr(tv2), n); const e2 = Fp.eql(Fp.sqr(tv3), n); tv1 = Fp.cmov(tv1, tv2, e1); tv2 = Fp.cmov(tv4, tv3, e2); const e3 = Fp.eql(Fp.sqr(tv2), n); const root = Fp.cmov(tv1, tv2, e3); assertIsSquare(Fp, root, n); return root; }; } function tonelliShanks(P) { if (P < _3n) throw new Error("sqrt is not defined for small field"); let Q = P - _1n2; let S = 0; while (Q % _2n === _0n2) { Q /= _2n; S++; } let Z = _2n; const _Fp = Field(P); while (FpLegendre(_Fp, Z) === 1) { if (Z++ > 1e3) throw new Error("Cannot find square root: probably non-prime P"); } if (S === 1) return sqrt3mod4; let cc = _Fp.pow(Z, Q); const Q1div2 = (Q + _1n2) / _2n; return function tonelliSlow(Fp, n) { if (Fp.is0(n)) return n; if (FpLegendre(Fp, n) !== 1) throw new Error("Cannot find square root"); let M = S; let c = Fp.mul(Fp.ONE, cc); let t = Fp.pow(n, Q); let R = Fp.pow(n, Q1div2); while (!Fp.eql(t, Fp.ONE)) { if (Fp.is0(t)) return Fp.ZERO; let i = 1; let t_tmp = Fp.sqr(t); while (!Fp.eql(t_tmp, Fp.ONE)) { i++; t_tmp = Fp.sqr(t_tmp); if (i === M) throw new Error("Cannot find square root"); } const exponent = _1n2 << BigInt(M - i - 1); const b = Fp.pow(c, exponent); M = i; c = Fp.sqr(b); t = Fp.mul(t, c); R = Fp.mul(R, b); } return R; }; } function FpSqrt(P) { if (P % _4n === _3n) return sqrt3mod4; if (P % _8n === _5n) return sqrt5mod8; if (P % _16n === _9n) return sqrt9mod16(P); return tonelliShanks(P); } var FIELD_FIELDS = [ "create", "isValid", "is0", "neg", "inv", "sqrt", "sqr", "eql", "add", "sub", "mul", "pow", "div", "addN", "subN", "mulN", "sqrN" ]; function validateField(field) { const initial = { ORDER: "bigint", MASK: "bigint", BYTES: "number", BITS: "number" }; const opts = FIELD_FIELDS.reduce((map, val) => { map[val] = "function"; return map; }, initial); _validateObject(field, opts); return field; } function FpPow(Fp, num, power) { if (power < _0n2) throw new Error("invalid exponent, negatives unsupported"); if (power === _0n2) return Fp.ONE; if (power === _1n2) return num; let p = Fp.ONE; let d = num; while (power > _0n2) { if (power & _1n2) p = Fp.mul(p, d); d = Fp.sqr(d); power >>= _1n2; } return p; } function FpInvertBatch(Fp, nums, passZero = false) { const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0); const multipliedAcc = nums.reduce((acc, num, i) => { if (Fp.is0(num)) return acc; inverted[i] = acc; return Fp.mul(acc, num); }, Fp.ONE); const invertedAcc = Fp.inv(multipliedAcc); nums.reduceRight((acc, num, i) => { if (Fp.is0(num)) return acc; inverted[i] = Fp.mul(acc, inverted[i]); return Fp.mul(acc, num); }, invertedAcc); return inverted; } function FpLegendre(Fp, n) { const p1mod2 = (Fp.ORDER - _1n2) / _2n; const powered = Fp.pow(n, p1mod2); const yes = Fp.eql(powered, Fp.ONE); const zero = Fp.eql(powered, Fp.ZERO); const no = Fp.eql(powered, Fp.neg(Fp.ONE)); if (!yes && !zero && !no) throw new Error("invalid Legendre symbol result"); return yes ? 1 : zero ? 0 : -1; } function nLength(n, nBitLength) { if (nBitLength !== void 0) anumber(nBitLength); const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; const nByteLength = Math.ceil(_nBitLength / 8); return { nBitLength: _nBitLength, nByteLength }; } function Field(ORDER, bitLenOrOpts, isLE = false, opts = {}) { if (ORDER <= _0n2) throw new Error("invalid field: expected ORDER > 0, got " + ORDER); let _nbitLength = void 0; let _sqrt = void 0; let modFromBytes = false; let allowedLengths = void 0; if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) { if (opts.sqrt || isLE) throw new Error("cannot specify opts in two arguments"); const _opts = bitLenOrOpts; if (_opts.BITS) _nbitLength = _opts.BITS; if (_opts.sqrt) _sqrt = _opts.sqrt; if (typeof _opts.isLE === "boolean") isLE = _opts.isLE; if (typeof _opts.modFromBytes === "boolean") modFromBytes = _opts.modFromBytes; allowedLengths = _opts.allowedLengths; } else { if (typeof bitLenOrOpts === "number") _nbitLength = bitLenOrOpts; if (opts.sqrt) _sqrt = opts.sqrt; } const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength); if (BYTES > 2048) throw new Error("invalid field: expected ORDER of <= 2048 bytes"); let sqrtP; const f = Object.freeze({ ORDER, isLE, BITS, BYTES, MASK: bitMask(BITS), ZERO: _0n2, ONE: _1n2, allowedLengths, create: (num) => mod(num, ORDER), isValid: (num) => { if (typeof num !== "bigint") throw new Error("invalid field element: expected bigint, got " + typeof num); return _0n2 <= num && num < ORDER; }, is0: (num) => num === _0n2, // is valid and invertible isValidNot0: (num) => !f.is0(num) && f.isValid(num), isOdd: (num) => (num & _1n2) === _1n2, neg: (num) => mod(-num, ORDER), eql: (lhs, rhs) => lhs === rhs, sqr: (num) => mod(num * num, ORDER), add: (lhs, rhs) => mod(lhs + rhs, ORDER), sub: (lhs, rhs) => mod(lhs - rhs, ORDER), mul: (lhs, rhs) => mod(lhs * rhs, ORDER), pow: (num, power) => FpPow(f, num, power), div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), // Same as above, but doesn't normalize sqrN: (num) => num * num, addN: (lhs, rhs) => lhs + rhs, subN: (lhs, rhs) => lhs - rhs, mulN: (lhs, rhs) => lhs * rhs, inv: (num) => invert(num, ORDER), sqrt: _sqrt || ((n) => { if (!sqrtP) sqrtP = FpSqrt(ORDER); return sqrtP(f, n); }), toBytes: (num) => isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES), fromBytes: (bytes, skipValidation = true) => { if (allowedLengths) { if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) { throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length); } const padded = new Uint8Array(BYTES); padded.set(bytes, isLE ? 0 : padded.length - bytes.length); bytes = padded; } if (bytes.length !== BYTES) throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length); let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); if (modFromBytes) scalar = mod(scalar, ORDER); if (!skipValidation) { if (!f.isValid(scalar)) throw new Error("invalid field element: outside of range 0..ORDER"); } return scalar; }, // TODO: we don't need it here, move out to separate fn invertBatch: (lst) => FpInvertBatch(f, lst), // We can't move this out because Fp6, Fp12 implement it // and it's unclear what to return in there. cmov: (a, b, c) => c ? b : a }); return Object.freeze(f); } function getFieldBytesLength(fieldOrder) { if (typeof fieldOrder !== "bigint") throw new Error("field order must be bigint"); const bitLength = fieldOrder.toString(2).length; return Math.ceil(bitLength / 8); } function getMinHashLength(fieldOrder) { const length2 = getFieldBytesLength(fieldOrder); return length2 + Math.ceil(length2 / 2); } function mapHashToField(key, fieldOrder, isLE = false) { const len = key.length; const fieldLen = getFieldBytesLength(fieldOrder); const minLen = getMinHashLength(fieldOrder); if (len < 16 || len < minLen || len > 1024) throw new Error("expected " + minLen + "-1024 bytes of input, got " + len); const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key); const reduced = mod(num, fieldOrder - _1n2) + _1n2; return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); } // ../../../../../node_modules/.deno/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js function setBigUint64(view, byteOffset, value, isLE) { if (typeof view.setBigUint64 === "function") return view.setBigUint64(byteOffset, value, isLE); const _32n2 = BigInt(32); const _u32_max = BigInt(4294967295); const wh = Number(value >> _32n2 & _u32_max); const wl = Number(value & _u32_max); const h = isLE ? 4 : 0; const l = isLE ? 0 : 4; view.setUint32(byteOffset + h, wh, isLE); view.setUint32(byteOffset + l, wl, isLE); } function Chi(a, b, c) { return a & b ^ ~a & c; } function Maj(a, b, c) { return a & b ^ a & c ^ b & c; } var HashMD = class extends Hash { constructor(blockLen, outputLen, padOffset, isLE) { super(); this.finished = false; this.length = 0; this.pos = 0; this.destroyed = false; this.blockLen = blockLen; this.outputLen = outputLen; this.padOffset = padOffset; this.isLE = isLE; this.buffer = new Uint8Array(blockLen); this.view = createView(this.buffer); } update(data) { aexists(this); data = toBytes(data); abytes(data); const { view, buffer, blockLen } = this; const len = data.length; for (let pos = 0; pos < len; ) { const take = Math.min(blockLen - this.pos, len - pos); if (take === blockLen) { const dataView = createView(data); for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos); continue; } buffer.set(data.subarray(pos, pos + take), this.pos); this.pos += take; pos += take; if (this.pos === blockLen) { this.process(view, 0); this.pos = 0; } } this.length += data.length; this.roundClean(); return this; } digestInto(out) { aexists(this); aoutput(out, this); this.finished = true; const { buffer, view, blockLen, isLE } = this; let { pos } = this; buffer[pos++] = 128; clean(this.buffer.subarray(pos)); if (this.padOffset > blockLen - pos) { this.process(view, 0); pos = 0; } for (let i = pos; i < blockLen; i++) buffer[i] = 0; setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); this.process(view, 0); const oview = createView(out); const len = this.outputLen; if (len % 4) throw new Error("_sha2: outputLen should be aligned to 32bit"); const outLen = len / 4; const state = this.get(); if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state"); for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE); } digest() { const { buffer, outputLen } = this; this.digestInto(buffer); const res = buffer.slice(0, outputLen); this.destroy(); return res; } _cloneInto(to) { to || (to = new this.constructor()); to.set(...this.get()); const { blockLen, buffer, length: length2, finished, destroyed, pos } = this; to.destroyed = destroyed; to.finished = finished; to.length = length2; to.pos = pos; if (length2 % blockLen) to.buffer.set(buffer); return to; } clone() { return this._cloneInto(); } }; var SHA256_IV = /* @__PURE__ */ Uint32Array.from([ 1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225 ]); var SHA384_IV = /* @__PURE__ */ Uint32Array.from([ 3418070365, 3238371032, 1654270250, 914150663, 2438529370, 812702999, 355462360, 4144912697, 1731405415, 4290775857, 2394180231, 1750603025, 3675008525, 1694076839, 1203062813, 3204075428 ]); var SHA512_IV = /* @__PURE__ */ Uint32Array.from([ 1779033703, 4089235720, 3144134277, 2227873595, 1013904242, 4271175723, 2773480762, 1595750129, 1359893119, 2917565137, 2600822924, 725511199, 528734635, 4215389547, 1541459225, 327033209 ]); // ../../../../../node_modules/.deno/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_u64.js var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); var _32n = /* @__PURE__ */ BigInt(32); function fromBig(n, le = false) { if (le) return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) }; return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; } function split(lst, le = false) { const len = lst.length; let Ah = new Uint32Array(len); let Al = new Uint32Array(len); for (let i = 0; i < len; i++) { const { h, l } = fromBig(lst[i], le); [Ah[i], Al[i]] = [ h, l ]; } return [ Ah, Al ]; } var shrSH = (h, _l, s) => h >>> s; var shrSL = (h, l, s) => h << 32 - s | l >>> s; var rotrSH = (h, l, s) => h >>> s | l << 32 - s; var rotrSL = (h, l, s) => h << 32 - s | l >>> s; var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32; var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s; function add(Ah, Al, Bh, Bl) { const l = (Al >>> 0) + (Bl >>> 0); return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 }; } var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0; var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0; var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0; // ../../../../../node_modules/.deno/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js var SHA256_K = /* @__PURE__ */ Uint32Array.from([ 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 ]); var SHA256_W = /* @__PURE__ */ new Uint32Array(64); var SHA256 = class extends HashMD { constructor(outputLen = 32) { super(64, outputLen, 8, false); this.A = SHA256_IV[0] | 0; this.B = SHA256_IV[1] | 0; this.C = SHA256_IV[2] | 0; this.D = SHA256_IV[3] | 0; this.E = SHA256_IV[4] | 0; this.F = SHA256_IV[5] | 0; this.G = SHA256_IV[6] | 0; this.H = SHA256_IV[7] | 0; } get() { const { A, B, C, D, E, F, G, H } = this; return [ A, B, C, D, E, F, G, H ]; } // prettier-ignore set(A, B, C, D, E, F, G, H) { this.A = A | 0; this.B = B | 0; this.C = C | 0; this.D = D | 0; this.E = E | 0; this.F = F | 0; this.G = G | 0; this.H = H | 0; } process(view, offset) { for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false); for (let i = 16; i < 64; i++) { const W15 = SHA256_W[i - 15]; const W2 = SHA256_W[i - 2]; const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; } let { A, B, C, D, E, F, G, H } = this; for (let i = 0; i < 64; i++) { const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0; const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); const T2 = sigma0 + Maj(A, B, C) | 0; H = G; G = F; F = E; E = D + T1 | 0; D = C; C = B; B = A; A = T1 + T2 | 0; } A = A + this.A | 0; B = B + this.B | 0; C = C + this.C | 0; D = D + this.D | 0; E = E + this.E | 0; F = F + this.F | 0; G = G + this.G | 0; H = H + this.H | 0; this.set(A, B, C, D, E, F, G, H); } roundClean() { clean(SHA256_W); } destroy() { this.set(0, 0, 0, 0, 0, 0, 0, 0); clean(this.buffer); } }; var K512 = /* @__PURE__ */ (() => split([ "0x428a2f98d728ae22", "0x7137449123ef65cd", "0xb5c0fbcfec4d3b2f", "0xe9b5dba58189dbbc", "0x3956c25bf348b538", "0x59f111f1b605d019", "0x923f82a4af194f9b", "0xab1c5ed5da6d8118", "0xd807aa98a3030242", "0x12835b0145706fbe", "0x243185be4ee4b28c", "0x550c7dc3d5ffb4e2", "0x72be5d74f27b896f", "0x80deb1fe3b1696b1", "0x9bdc06a725c71235", "0xc19bf174cf692694", "0xe49b69c19ef14ad2", "0xefbe4786384f25e3", "0x0fc19dc68b8cd5b5", "0x240ca1cc77ac9c65", "0x2de92c6f592b0275", "0x4a7484aa6ea6e483", "0x5cb0a9dcbd41fbd4", "0x76f988da831153b5", "0x983e5152ee66dfab", "0xa831c66d2db43210", "0xb00327c898fb213f", "0xbf597fc7beef0ee4", "0xc6e00bf33da88fc2", "0xd5a79147930aa725", "0x06ca6351e003826f", "0x142929670a0e6e70", "0x27b70a8546d22ffc", "0x2e1b21385c26c926", "0x4d2c6dfc5ac42aed", "0x53380d139d95b3df", "0x650a73548baf63de", "0x766a0abb3c77b2a8", "0x81c2c92e47edaee6", "0x92722c851482353b", "0xa2bfe8a14cf10364", "0xa81a664bbc423001", "0xc24b8b70d0f89791", "0xc76c51a30654be30", "0xd192e819d6ef5218", "0xd69906245565a910", "0xf40e35855771202a", "0x106aa07032bbd1b8", "0x19a4c116b8d2d0c8", "0x1e376c085141ab53", "0x2748774cdf8eeb99", "0x34b0bcb5e19b48a8", "0x391c0cb3c5c95a63", "0x4ed8aa4ae3418acb", "0x5b9cca4f7763e373", "0x682e6ff3d6b2b8a3", "0x748f82ee5defb2fc", "0x78a5636f43172f60", "0x84c87814a1f0ab72", "0x8cc702081a6439ec", "0x90befffa23631e28", "0xa4506cebde82bde9", "0xbef9a3f7b2c67915", "0xc67178f2e372532b", "0xca273eceea26619c", "0xd186b8c721c0c207", "0xeada7dd6cde0eb1e", "0xf57d4f7fee6ed178", "0x06f067aa72176fba", "0x0a637dc5a2c898a6", "0x113f9804bef90dae", "0x1b710b35131c471b", "0x28db77f523047d84", "0x32caab7b40c72493", "0x3c9ebe0a15c9bebc", "0x431d67c49c100d4c", "0x4cc5d4becb3e42b6", "0x597f299cfc657e2a", "0x5fcb6fab3ad6faec", "0x6c44198c4a475817" ].map((n) => BigInt(n))))(); var SHA512_Kh = /* @__PURE__ */ (() => K512[0])(); var SHA512_Kl = /* @__PURE__ */ (() => K512[1])(); var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); var SHA512 = class extends HashMD { constructor(outputLen = 64) { super(128, outputLen, 16, false); this.Ah = SHA512_IV[0] | 0; this.Al = SHA512_IV[1] | 0; this.Bh = SHA512_IV[2] | 0; this.Bl = SHA512_IV[3] | 0; this.Ch = SHA512_IV[4] | 0; this.Cl = SHA512_IV[5] | 0; this.Dh = SHA512_IV[6] | 0; this.Dl = SHA512_IV[7] | 0; this.Eh = SHA512_IV[8] | 0; this.El = SHA512_IV[9] | 0; this.Fh = SHA512_IV[10] | 0; this.Fl = SHA512_IV[11] | 0; this.Gh = SHA512_IV[12] | 0; this.Gl = SHA512_IV[13] | 0; this.Hh = SHA512_IV[14] | 0; this.Hl = SHA512_IV[15] | 0; } // prettier-ignore get() { const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; return [ Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl ]; } // prettier-ignore set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { this.Ah = Ah | 0; this.Al = Al | 0; this.Bh = Bh | 0; this.Bl = Bl | 0; this.Ch = Ch | 0; this.Cl = Cl | 0; this.Dh = Dh | 0; this.Dl = Dl | 0; this.Eh = Eh | 0; this.El = El | 0; this.Fh = Fh | 0; this.Fl = Fl | 0; this.Gh = Gh | 0; this.Gl = Gl | 0; this.Hh = Hh | 0; this.Hl = Hl | 0; } process(view, offset) { for (let i = 0; i < 16; i++, offset += 4) { SHA512_W_H[i] = view.getUint32(offset); SHA512_W_L[i] = view.getUint32(offset += 4); } for (let i = 16; i < 80; i++) { const W15h = SHA512_W_H[i - 15] | 0; const W15l = SHA512_W_L[i - 15] | 0; const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7); const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7); const W2h = SHA512_W_H[i - 2] | 0; const W2l = SHA512_W_L[i - 2] | 0; const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6); const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6); const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); SHA512_W_H[i] = SUMh | 0; SHA512_W_L[i] = SUMl | 0; } let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; for (let i = 0; i < 80; i++) { const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41); const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41); const CHIh = Eh & Fh ^ ~Eh & Gh; const CHIl = El & Fl ^ ~El & Gl; const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); const T1l = T1ll | 0; const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39); const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39); const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch; const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; Hh = Gh | 0; Hl = Gl | 0; Gh = Fh | 0; Gl = Fl | 0; Fh = Eh | 0; Fl = El | 0; ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); Dh = Ch | 0; Dl = Cl | 0; Ch = Bh | 0; Cl = Bl | 0; Bh = Ah | 0; Bl = Al | 0; const All = add3L(T1l, sigma0l, MAJl); Ah = add3H(All, T1h, sigma0h, MAJh); Al = All | 0; } ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); } roundClean() { clean(SHA512_W_H, SHA512_W_L); } destroy() { clean(this.buffer); this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } }; var SHA384 = class extends SHA512 { constructor() { super(48); this.Ah = SHA384_IV[0] | 0; this.Al = SHA384_IV[1] | 0; this.Bh = SHA384_IV[2] | 0; this.Bl = SHA384_IV[3] | 0; this.Ch = SHA384_IV[4] | 0; this.Cl = SHA384_IV[5] | 0; this.Dh = SHA384_IV[6] | 0; this.Dl = SHA384_IV[7] | 0; this.Eh = SHA384_IV[8] | 0; this.El = SHA384_IV[9] | 0; this.Fh = SHA384_IV[10] | 0; this.Fl = SHA384_IV[11] | 0; this.Gh = SHA384_IV[12] | 0; this.Gl = SHA384_IV[13] | 0; this.Hh = SHA384_IV[14] | 0; this.Hl = SHA384_IV[15] | 0; } }; var sha2562 = /* @__PURE__ */ createHasher(() => new SHA256()); var sha5122 = /* @__PURE__ */ createHasher(() => new SHA512()); var sha384 = /* @__PURE__ */ createHasher(() => new SHA384()); // ../../../../../node_modules/.deno/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js var HMAC = class extends Hash { constructor(hash, _key) { super(); this.finished = false; this.destroyed = false; ahash(hash); const key = toBytes(_key); this.iHash = hash.create(); if (typeof this.iHash.update !== "function") throw new Error("Expected instance of class which extends utils.Hash"); this.blockLen = this.iHash.blockLen; this.outputLen = this.iHash.outputLen; const blockLen = this.blockLen; const pad = new Uint8Array(blockLen); pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); for (let i = 0; i < pad.length; i++) pad[i] ^= 54; this.iHash.update(pad); this.oHash = hash.create(); for (let i = 0; i < pad.length; i++) pad[i] ^= 54 ^ 92; this.oHash.update(pad); clean(pad); } update(buf) { aexists(this); this.iHash.update(buf); return this; } digestInto(out) { aexists(this); abytes(out, this.outputLen); this.finished = true; this.iHash.digestInto(out); this.oHash.update(out); this.oHash.digestInto(out); this.destroy(); } digest() { const out = new Uint8Array(this.oHash.outputLen); this.digestInto(out); return out; } _cloneInto(to) { to || (to = Object.create(Object.getPrototypeOf(this), {})); const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; to = to; to.finished = finished; to.destroyed = destroyed; to.blockLen = blockLen; to.outputLen = outputLen; to.oHash = oHash._cloneInto(to.oHash); to.iHash = iHash._cloneInto(to.iHash); return to; } clone() { return this._cloneInto(); } destroy() { this.destroyed = true; this.oHash.destroy(); this.iHash.destroy(); } }; var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); hmac.create = (hash, key) => new HMAC(hash, key); // ../../../../../node_modules/.deno/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/curve.js var _0n3 = BigInt(0); var _1n3 = BigInt(1); function negateCt(condition, item) { const neg = item.negate(); return condition ? neg : item; } function normalizeZ(c, points) { const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z)); return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i]))); } function validateW(W, bits) { if (!Number.isSafeInteger(W) || W <= 0 || W > bits) throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W); } function calcWOpts(W, scalarBits) { validateW(W, scalarBits); const windows = Math.ceil(scalarBits / W) + 1; const windowSize = 2 ** (W - 1); const maxNumber = 2 ** W; const mask = bitMask(W); const shiftBy = BigInt(W); return { windows, windowSize, mask, maxNumber, shiftBy }; } function calcOffsets(n, window, wOpts) { const { windowSize, mask, maxNumber, shiftBy } = wOpts; let wbits = Number(n & mask); let nextN = n >> shiftBy; if (wbits > windowSize) { wbits -= maxNumber; nextN += _1n3; } const offsetStart = window * windowSize; const offset = offsetStart + Math.abs(wbits) - 1; const isZero = wbits === 0; const isNeg = wbits < 0; const isNegF = window % 2 !== 0; const offsetF = offsetStart; return { nextN, offset, isZero, isNeg, isNegF, offsetF }; } function validateMSMPoints(points, c) { if (!Array.isArray(points)) throw new Error("array expected"); points.forEach((p, i) => { if (!(p instanceof c)) throw new Error("invalid point at index " + i); }); } function validateMSMScalars(scalars, field) { if (!Array.isArray(scalars)) throw new Error("array of scalars expected"); scalars.forEach((s, i) => { if (!field.isValid(s)) throw new Error("invalid scalar at index " + i); }); } var pointPrecomputes = /* @__PURE__ */ new WeakMap(); var pointWindowSizes = /* @__PURE__ */ new WeakMap(); function getW(P) { return pointWindowSizes.get(P) || 1; } function assert0(n) { if (n !== _0n3) throw new Error("invalid wNAF"); } var wNAF = class { // Parametrized with a given Point class (not individual point) constructor(Point, bits) { this.BASE = Point.BASE; this.ZERO = Point.ZERO; this.Fn = Point.Fn; this.bits = bits; } // non-const time multiplication ladder _unsafeLadder(elm, n, p = this.ZERO) { let d = elm; while (n > _0n3) { if (n & _1n3) p = p.add(d); d = d.double(); n >>= _1n3; } return p; } /** * Creates a wNAF precomputation window. Used for caching. * Default window size is set by `utils.precompute()` and is equal to 8. * Number of precomputed points depends on the curve size: * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: * - 𝑊 is the window size * - 𝑛 is the bitlength of the curve order. * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. * @param point Point instance * @param W window size * @returns precomputed point tables flattened to a single array */ precomputeWindow(point, W) { const { windows, windowSize } = calcWOpts(W, this.bits); const points = []; let p = point; let base3 = p; for (let window = 0; window < windows; window++) { base3 = p; points.push(base3); for (let i = 1; i < windowSize; i++) { base3 = base3.add(p); points.push(base3); } p = base3.double(); } return points; } /** * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. * More compact implementation: * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541 * @returns real and fake (for const-time) points */ wNAF(W, precomputes, n) { if (!this.Fn.isValid(n)) throw new Error("invalid scalar"); let p = this.ZERO; let f = this.BASE; const wo = calcWOpts(W, this.bits); for (let window = 0; window < wo.windows; window++) { const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo); n = nextN; if (isZero) { f = f.add(negateCt(isNegF, precomputes[offsetF])); } else { p = p.add(negateCt(isNeg, precomputes[offset])); } } assert0(n); return { p, f }; } /** * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form. * @param acc accumulator point to add result of multiplication * @returns point */ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) { const wo = calcWOpts(W, this.bits); for (let window = 0; window < wo.windows; window++) { if (n === _0n3) break; const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo); n = nextN; if (isZero) { continue; } else { const item = precomputes[offset]; acc = acc.add(isNeg ? item.negate() : item); } } assert0(n); return acc; } getPrecomputes(W, point, transform) { let comp = pointPrecomputes.get(point); if (!comp) { comp = this.precomputeWindow(point, W); if (W !== 1) { if (typeof transform === "function") comp = transform(comp); pointPrecomputes.set(point, comp); } } return comp; } cached(point, scalar, transform) { const W = getW(point); return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar); } unsafe(point, scalar, transform, prev) { const W = getW(point); if (W === 1) return this._unsafeLadder(point, scalar, prev); return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev); } // We calculate precomputes for elliptic curve point multiplication // using windowed method. This specifies window size and // stores precomputed values. Usually only base point would be precomputed. createCache(P, W) { validateW(W, this.bits); pointWindowSizes.set(P, W); pointPrecomputes.delete(P); } hasCache(elm) { return getW(elm) !== 1; } }; function mulEndoUnsafe(Point, point, k1, k2) { let acc = point; let p1 = Point.ZERO; let p2 = Point.ZERO; while (k1 > _0n3 || k2 > _0n3) { if (k1 & _1n3) p1 = p1.add(acc); if (k2 & _1n3) p2 = p2.add(acc); acc = acc.double(); k1 >>= _1n3; k2 >>= _1n3; } return { p1, p2 }; } function pippenger(c, fieldN, points, scalars) { validateMSMPoints(points, c); validateMSMScalars(scalars, fieldN); const plength = points.length; const slength = scalars.length; if (plength !== slength) throw new Error("arrays of points and scalars must have equal length"); const zero = c.ZERO; const wbits = bitLen(BigInt(plength)); let windowSize = 1; if (wbits > 12) windowSize = wbits - 3; else if (wbits > 4) windowSize = wbits - 2; else if (wbits > 0) windowSize = 2; const MASK = bitMask(windowSize); const buckets = new Array(Number(MASK) + 1).fill(zero); const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize; let sum = zero; for (let i = lastBits; i >= 0; i -= windowSize) { buckets.fill(zero); for (let j = 0; j < slength; j++) { const scalar = scalars[j]; const wbits2 = Number(scalar >> BigInt(i) & MASK); buckets[wbits2] = buckets[wbits2].add(points[j]); } let resI = zero; for (let j = buckets.length - 1, sumI = zero; j > 0; j--) { sumI = sumI.add(buckets[j]); resI = resI.add(sumI); } sum = sum.add(resI); if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double(); } return sum; } function createField(order, field, isLE) { if (field) { if (field.ORDER !== order) throw new Error("Field.ORDER must match order: Fp == p, Fn == n"); validateField(field); return field; } else { return Field(order, { isLE }); } } function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) { if (FpFnLE === void 0) FpFnLE = type === "edwards"; if (!CURVE || typeof CURVE !== "object") throw new Error(`expected valid ${type} CURVE object`); for (const p of [ "p", "n", "h" ]) { const val = CURVE[p]; if (!(typeof val === "bigint" && val > _0n3)) throw new Error(`CURVE.${p} must be positive bigint`); } const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE); const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE); const _b = type === "weierstrass" ? "b" : "d"; const params = [ "Gx", "Gy", "a", _b ]; for (const p of params) { if (!Fp.isValid(CURVE[p])) throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`); } CURVE = Object.freeze(Object.assign({}, CURVE)); return { CURVE, Fp, Fn }; } // ../../../../../node_modules/.deno/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/weierstrass.js var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den; function _splitEndoScalar(k, basis, n) { const [[a1, b1], [a2, b2]] = basis; const c1 = divNearest(b2 * k, n); const c2 = divNearest(-b1 * k, n); let k1 = k - c1 * a1 - c2 * a2; let k2 = -c1 * b1 - c2 * b2; const k1neg = k1 < _0n4; const k2neg = k2 < _0n4; if (k1neg) k1 = -k1; if (k2neg) k2 = -k2; const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4; if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) { throw new Error("splitScalar (endomorphism): failed, k=" + k); } return { k1neg, k1, k2neg, k2 }; } function validateSigFormat(format2) { if (![ "compact", "recovered", "der" ].includes(format2)) throw new Error('Signature format must be "compact", "recovered", or "der"'); return format2; } function validateSigOpts(opts, def2) { const optsn = {}; for (let optName of Object.keys(def2)) { optsn[optName] = opts[optName] === void 0 ? def2[optName] : opts[optName]; } _abool2(optsn.lowS, "lowS"); _abool2(optsn.prehash, "prehash"); if (optsn.format !== void 0) validateSigFormat(optsn.format); return optsn; } var DERErr = class extends Error { constructor(m = "") { super(m); } }; var DER = { // asn.1 DER encoding utils Err: DERErr, // Basic building block is TLV (Tag-Length-Value) _tlv: { encode: (tag, data) => { const { Err: E } = DER; if (tag < 0 || tag > 256) throw new E("tlv.encode: wrong tag"); if (data.length & 1) throw new E("tlv.encode: unpadded data"); const dataLen = data.length / 2; const len = numberToHexUnpadded(dataLen); if (len.length / 2 & 128) throw new E("tlv.encode: long form length too big"); const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : ""; const t = numberToHexUnpadded(tag); return t + lenLen + len + data; }, // v - value, l - left bytes (unparsed) decode(tag, data) { const { Err: E } = DER; let pos = 0; if (tag < 0 || tag > 256) throw new E("tlv.encode: wrong tag"); if (data.length < 2 || data[pos++] !== tag) throw new E("tlv.decode: wrong tlv"); const first = data[pos++]; const isLong = !!(first & 128); let length2 = 0; if (!isLong) length2 = first; else { const lenLen = first & 127; if (!lenLen) throw new E("tlv.decode(long): indefinite length not supported"); if (lenLen > 4) throw new E("tlv.decode(long): byte length is too big"); const lengthBytes = data.subarray(pos, pos + lenLen); if (lengthBytes.length !== lenLen) throw new E("tlv.decode: length bytes not complete"); if (lengthBytes[0] === 0) throw new E("tlv.decode(long): zero leftmost byte"); for (const b of lengthBytes) length2 = length2 << 8 | b; pos += lenLen; if (length2 < 128) throw new E("tlv.decode(long): not minimal encoding"); } const v = data.subarray(pos, pos + length2); if (v.length !== length2) throw new E("tlv.decode: wrong value length"); return { v, l: data.subarray(pos + length2) }; } }, // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, // since we always use positive integers here. It must always be empty: // - add zero byte if exists // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) _int: { encode(num) { const { Err: E } = DER; if (num < _0n4) throw new E("integer: negative integers are not allowed"); let hex = numberToHexUnpadded(num); if (Number.parseInt(hex[0], 16) & 8) hex = "00" + hex; if (hex.length & 1) throw new E("unexpected DER parsing assertion: unpadded hex"); return hex; }, decode(data) { const { Err: E } = DER; if (data[0] & 128) throw new E("invalid signature integer: negative"); if (data[0] === 0 && !(data[1] & 128)) throw new E("invalid signature integer: unnecessary leading zero"); return bytesToNumberBE(data); } }, toSig(hex) { const { Err: E, _int: int, _tlv: tlv } = DER; const data = ensureBytes("signature", hex); const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data); if (seqLeftBytes.length) throw new E("invalid signature: left bytes after parsing"); const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes); const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes); if (sLeftBytes.length) throw new E("invalid signature: left bytes after parsing"); return { r: int.decode(rBytes), s: int.decode(sBytes) }; }, hexFromSig(sig) { const { _tlv: tlv, _int: int } = DER; const rs = tlv.encode(2, int.encode(sig.r)); const ss = tlv.encode(2, int.encode(sig.s)); const seq = rs + ss; return tlv.encode(48, seq); } }; var _0n4 = BigInt(0); var _1n4 = BigInt(1); var _2n2 = BigInt(2); var _3n2 = BigInt(3); var _4n2 = BigInt(4); function _normFnElement(Fn, key) { const { BYTES: expected } = Fn; let num; if (typeof key === "bigint") { num = key; } else { let bytes = ensureBytes("private key", key); try { num = Fn.fromBytes(bytes); } catch (error) { throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`); } } if (!Fn.isValidNot0(num)) throw new Error("invalid private key: out of range [1..N-1]"); return num; } function weierstrassN(params, extraOpts = {}) { const validated = _createCurveFields("weierstrass", params, extraOpts); const { Fp, Fn } = validated; let CURVE = validated.CURVE; const { h: cofactor, n: CURVE_ORDER } = CURVE; _validateObject(extraOpts, {}, { allowInfinityPoint: "boolean", clearCofactor: "function", isTorsionFree: "function", fromBytes: "function", toBytes: "function", endo: "object", wrapPrivateKey: "boolean" }); const { endo } = extraOpts; if (endo) { if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) { throw new Error('invalid endo: expected "beta": bigint and "basises": array'); } } const lengths = getWLengths(Fp, Fn); function assertCompressionIsSupported() { if (!Fp.isOdd) throw new Error("compression is not supported: Field does not have .isOdd()"); } function pointToBytes(_c, point, isCompressed) { const { x, y } = point.toAffine(); const bx = Fp.toBytes(x); _abool2(isCompressed, "isCompressed"); if (isCompressed) { assertCompressionIsSupported(); const hasEvenY = !Fp.isOdd(y); return concatBytes(pprefix(hasEvenY), bx); } else { return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y)); } } function pointFromBytes(bytes) { _abytes2(bytes, void 0, "Point"); const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; const length2 = bytes.length; const head = bytes[0]; const tail = bytes.subarray(1); if (length2 === comp && (head === 2 || head === 3)) { const x = Fp.fromBytes(tail); if (!Fp.isValid(x)) throw new Error("bad point: is not on curve, wrong x"); const y2 = weierstrassEquation(x); let y; try { y = Fp.sqrt(y2); } catch (sqrtError) { const err = sqrtError instanceof Error ? ": " + sqrtError.message : ""; throw new Error("bad point: is not on curve, sqrt error" + err); } assertCompressionIsSupported(); const isYOdd = Fp.isOdd(y); const isHeadOdd = (head & 1) === 1; if (isHeadOdd !== isYOdd) y = Fp.neg(y); return { x, y }; } else if (length2 === uncomp && head === 4) { const L = Fp.BYTES; const x = Fp.fromBytes(tail.subarray(0, L)); const y = Fp.fromBytes(tail.subarray(L, L * 2)); if (!isValidXY(x, y)) throw new Error("bad point: is not on curve"); return { x, y }; } else { throw new Error(`bad point: got length ${length2}, expected compressed=${comp} or uncompressed=${uncomp}`); } } const encodePoint = extraOpts.toBytes || pointToBytes; const decodePoint = extraOpts.fromBytes || pointFromBytes; function weierstrassEquation(x) { const x2 = Fp.sqr(x); const x3 = Fp.mul(x2, x); return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); } function isValidXY(x, y) { const left = Fp.sqr(y); const right = weierstrassEquation(x); return Fp.eql(left, right); } if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error("bad curve params: generator point"); const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2); const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27)); if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error("bad curve params: a or b"); function acoord(title, n, banZero = false) { if (!Fp.isValid(n) || banZero && Fp.is0(n)) throw new Error(`bad point coordinate ${title}`); return n; } function aprjpoint(other) { if (!(other instanceof Point)) throw new Error("ProjectivePoint expected"); } function splitEndoScalarN(k) { if (!endo || !endo.basises) throw new Error("no endo"); return _splitEndoScalar(k, endo.basises, Fn.ORDER); } const toAffineMemo = memoized((p, iz) => { const { X, Y, Z } = p; if (Fp.eql(Z, Fp.ONE)) return { x: X, y: Y }; const is0 = p.is0(); if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(Z); const x = Fp.mul(X, iz); const y = Fp.mul(Y, iz); const zz = Fp.mul(Z, iz); if (is0) return { x: Fp.ZERO, y: Fp.ZERO }; if (!Fp.eql(zz, Fp.ONE)) throw new Error("invZ was invalid"); return { x, y }; }); const assertValidMemo = memoized((p) => { if (p.is0()) { if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y)) return; throw new Error("bad point: ZERO"); } const { x, y } = p.toAffine(); if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error("bad point: x or y not field elements"); if (!isValidXY(x, y)) throw new Error("bad point: equation left != right"); if (!p.isTorsionFree()) throw new Error("bad point: not in prime-order subgroup"); return true; }); function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) { k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z); k1p = negateCt(k1neg, k1p); k2p = negateCt(k2neg, k2p); return k1p.add(k2p); } class Point { /** Does NOT validate if the point is valid. Use `.assertValidity()`. */ constructor(X, Y, Z) { this.X = acoord("x", X); this.Y = acoord("y", Y, true); this.Z = acoord("z", Z); Object.freeze(this); } static CURVE() { return CURVE; } /** Does NOT validate if the point is valid. Use `.assertValidity()`. */ static fromAffine(p) { const { x, y } = p || {}; if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error("invalid affine point"); if (p instanceof Point) throw new Error("projective point not allowed"); if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO; return new Point(x, y, Fp.ONE); } static fromBytes(bytes) { const P = Point.fromAffine(decodePoint(_abytes2(bytes, void 0, "point"))); P.assertValidity(); return P; } static fromHex(hex) { return Point.fromBytes(ensureBytes("pointHex", hex)); } get x() { return this.toAffine().x; } get y() { return this.toAffine().y; } /** * * @param windowSize * @param isLazy true will defer table computation until the first multiplication * @returns */ precompute(windowSize = 8, isLazy = true) { wnaf.createCache(this, windowSize); if (!isLazy) this.multiply(_3n2); return this; } // TODO: return `this` /** A point on curve is valid if it conforms to equation. */ assertValidity() { assertValidMemo(this); } hasEvenY() { const { y } = this.toAffine(); if (!Fp.isOdd) throw new Error("Field doesn't support isOdd"); return !Fp.isOdd(y); } /** Compare one point to another. */ equals(other) { aprjpoint(other); const { X: X1, Y: Y1, Z: Z1 } = this; const { X: X2, Y: Y2, Z: Z2 } = other; const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); return U1 && U2; } /** Flips point to one corresponding to (x, -y) in Affine coordinates. */ negate() { return new Point(this.X, Fp.neg(this.Y), this.Z); } // Renes-Costello-Batina exception-free doubling formula. // There is 30% faster Jacobian formula, but it is not complete. // https://eprint.iacr.org/2015/1060, algorithm 3 // Cost: 8M + 3S + 3*a + 2*b3 + 15add. double() { const { a, b } = CURVE; const b3 = Fp.mul(b, _3n2); const { X: X1, Y: Y1, Z: Z1 } = this; let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; let t0 = Fp.mul(X1, X1); let t1 = Fp.mul(Y1, Y1); let t2 = Fp.mul(Z1, Z1); let t3 = Fp.mul(X1, Y1); t3 = Fp.add(t3, t3); Z3 = Fp.mul(X1, Z1); Z3 = Fp.add(Z3, Z3); X3 = Fp.mul(a, Z3); Y3 = Fp.mul(b3, t2); Y3 = Fp.add(X3, Y3); X3 = Fp.sub(t1, Y3); Y3 = Fp.add(t1, Y3); Y3 = Fp.mul(X3, Y3); X3 = Fp.mul(t3, X3); Z3 = Fp.mul(b3, Z3); t2 = Fp.mul(a, t2); t3 = Fp.sub(t0, t2); t3 = Fp.mul(a, t3); t3 = Fp.add(t3, Z3); Z3 = Fp.add(t0, t0); t0 = Fp.add(Z3, t0); t0 = Fp.add(t0, t2); t0 = Fp.mul(t0, t3); Y3 = Fp.add(Y3, t0); t2 = Fp.mul(Y1, Z1); t2 = Fp.add(t2, t2); t0 = Fp.mul(t2, t3); X3 = Fp.sub(X3, t0); Z3 = Fp.mul(t2, t1); Z3 = Fp.add(Z3, Z3); Z3 = Fp.add(Z3, Z3); return new Point(X3, Y3, Z3); } // Renes-Costello-Batina exception-free addition formula. // There is 30% faster Jacobian formula, but it is not complete. // https://eprint.iacr.org/2015/1060, algorithm 1 // Cost: 12M + 0S + 3*a + 3*b3 + 23add. add(other) { aprjpoint(other); const { X: X1, Y: Y1, Z: Z1 } = this; const { X: X2, Y: Y2, Z: Z2 } = other; let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; const a = CURVE.a; const b3 = Fp.mul(CURVE.b, _3n2); let t0 = Fp.mul(X1, X2); let t1 = Fp.mul(Y1, Y2); let t2 = Fp.mul(Z1, Z2); let t3 = Fp.add(X1, Y1); let t4 = Fp.add(X2, Y2); t3 = Fp.mul(t3, t4); t4 = Fp.add(t0, t1); t3 = Fp.sub(t3, t4); t4 = Fp.add(X1, Z1); let t5 = Fp.add(X2, Z2); t4 = Fp.mul(t4, t5); t5 = Fp.add(t0, t2); t4 = Fp.sub(t4, t5); t5 = Fp.add(Y1, Z1); X3 = Fp.add(Y2, Z2); t5 = Fp.mul(t5, X3); X3 = Fp.add(t1, t2); t5 = Fp.sub(t5, X3); Z3 = Fp.mul(a, t4); X3 = Fp.mul(b3, t2); Z3 = Fp.add(X3, Z3); X3 = Fp.sub(t1, Z3); Z3 = Fp.add(t1, Z3); Y3 = Fp.mul(X3, Z3); t1 = Fp.add(t0, t0); t1 = Fp.add(t1, t0); t2 = Fp.mul(a, t2); t4 = Fp.mul(b3, t4); t1 = Fp.add(t1, t2); t2 = Fp.sub(t0, t2); t2 = Fp.mul(a, t2); t4 = Fp.add(t4, t2); t0 = Fp.mul(t1, t4); Y3 = Fp.add(Y3, t0); t0 = Fp.mul(t5, t4); X3 = Fp.mul(t3, X3); X3 = Fp.sub(X3, t0); t0 = Fp.mul(t3, t1); Z3 = Fp.mul(t5, Z3); Z3 = Fp.add(Z3, t0); return new Point(X3, Y3, Z3); } subtract(other) { return this.add(other.negate()); } is0() { return this.equals(Point.ZERO); } /** * Constant time multiplication. * Uses wNAF method. Windowed method may be 10% faster, * but takes 2x longer to generate and consumes 2x memory. * Uses precomputes when available. * Uses endomorphism for Koblitz curves. * @param scalar by which the point would be multiplied * @returns New point */ multiply(scalar) { const { endo: endo2 } = extraOpts; if (!Fn.isValidNot0(scalar)) throw new Error("invalid scalar: out of range"); let point, fake; const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p)); if (endo2) { const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar); const { p: k1p, f: k1f } = mul(k1); const { p: k2p, f: k2f } = mul(k2); fake = k1f.add(k2f); point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg); } else { const { p, f } = mul(scalar); point = p; fake = f; } return normalizeZ(Point, [ point, fake ])[0]; } /** * Non-constant-time multiplication. Uses double-and-add algorithm. * It's faster, but should only be used when you don't care about * an exposed secret key e.g. sig verification, which works over *public* keys. */ multiplyUnsafe(sc) { const { endo: endo2 } = extraOpts; const p = this; if (!Fn.isValid(sc)) throw new Error("invalid scalar: out of range"); if (sc === _0n4 || p.is0()) return Point.ZERO; if (sc === _1n4) return p; if (wnaf.hasCache(this)) return this.multiply(sc); if (endo2) { const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc); const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); return finishEndo(endo2.beta, p1, p2, k1neg, k2neg); } else { return wnaf.unsafe(p, sc); } } multiplyAndAddUnsafe(Q, a, b) { const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b)); return sum.is0() ? void 0 : sum; } /** * Converts Projective point to affine (x, y) coordinates. * @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch */ toAffine(invertedZ) { return toAffineMemo(this, invertedZ); } /** * Checks whether Point is free of torsion elements (is in prime subgroup). * Always torsion-free for cofactor=1 curves. */ isTorsionFree() { const { isTorsionFree } = extraOpts; if (cofactor === _1n4) return true; if (isTorsionFree) return isTorsionFree(Point, this); return wnaf.unsafe(this, CURVE_ORDER).is0(); } clearCofactor() { const { clearCofactor } = extraOpts; if (cofactor === _1n4) return this; if (clearCofactor) return clearCofactor(Point, this); return this.multiplyUnsafe(cofactor); } isSmallOrder() { return this.multiplyUnsafe(cofactor).is0(); } toBytes(isCompressed = true) { _abool2(isCompressed, "isCompressed"); this.assertValidity(); return encodePoint(Point, this, isCompressed); } toHex(isCompressed = true) { return bytesToHex(this.toBytes(isCompressed)); } toString() { return ``; } // TODO: remove get px() { return this.X; } get py() { return this.X; } get pz() { return this.Z; } toRawBytes(isCompressed = true) { return this.toBytes(isCompressed); } _setWindowSize(windowSize) { this.precompute(windowSize); } static normalizeZ(points) { return normalizeZ(Point, points); } static msm(points, scalars) { return pippenger(Point, Fn, points, scalars); } static fromPrivateKey(privateKey) { return Point.BASE.multiply(_normFnElement(Fn, privateKey)); } } Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); Point.Fp = Fp; Point.Fn = Fn; const bits = Fn.BITS; const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits); Point.BASE.precompute(8); return Point; } function pprefix(hasEvenY) { return Uint8Array.of(hasEvenY ? 2 : 3); } function getWLengths(Fp, Fn) { return { secretKey: Fn.BYTES, publicKey: 1 + Fp.BYTES, publicKeyUncompressed: 1 + 2 * Fp.BYTES, publicKeyHasPrefix: true, signature: 2 * Fn.BYTES }; } function ecdh(Point, ecdhOpts = {}) { const { Fn } = Point; const randomBytes_ = ecdhOpts.randomBytes || randomBytes; const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) }); function isValidSecretKey(secretKey) { try { return !!_normFnElement(Fn, secretKey); } catch (error) { return false; } } function isValidPublicKey(publicKey, isCompressed) { const { publicKey: comp, publicKeyUncompressed } = lengths; try { const l = publicKey.length; if (isCompressed === true && l !== comp) return false; if (isCompressed === false && l !== publicKeyUncompressed) return false; return !!Point.fromBytes(publicKey); } catch (error) { return false; } } function randomSecretKey(seed = randomBytes_(lengths.seed)) { return mapHashToField(_abytes2(seed, lengths.seed, "seed"), Fn.ORDER); } function getPublicKey(secretKey, isCompressed = true) { return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed); } function keygen(seed) { const secretKey = randomSecretKey(seed); return { secretKey, publicKey: getPublicKey(secretKey) }; } function isProbPub(item) { if (typeof item === "bigint") return false; if (item instanceof Point) return true; const { secretKey, publicKey, publicKeyUncompressed } = lengths; if (Fn.allowedLengths || secretKey === publicKey) return void 0; const l = ensureBytes("key", item).length; return l === publicKey || l === publicKeyUncompressed; } function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) { if (isProbPub(secretKeyA) === true) throw new Error("first arg must be private key"); if (isProbPub(publicKeyB) === false) throw new Error("second arg must be public key"); const s = _normFnElement(Fn, secretKeyA); const b = Point.fromHex(publicKeyB); return b.multiply(s).toBytes(isCompressed); } const utils = { isValidSecretKey, isValidPublicKey, randomSecretKey, // TODO: remove isValidPrivateKey: isValidSecretKey, randomPrivateKey: randomSecretKey, normPrivateKeyToScalar: (key) => _normFnElement(Fn, key), precompute(windowSize = 8, point = Point.BASE) { return point.precompute(windowSize, false); } }; return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths }); } function ecdsa(Point, hash, ecdsaOpts = {}) { ahash(hash); _validateObject(ecdsaOpts, {}, { hmac: "function", lowS: "boolean", randomBytes: "function", bits2int: "function", bits2int_modN: "function" }); const randomBytes2 = ecdsaOpts.randomBytes || randomBytes; const hmac2 = ecdsaOpts.hmac || ((key, ...msgs) => hmac(hash, key, concatBytes(...msgs))); const { Fp, Fn } = Point; const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn; const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts); const defaultSigOpts = { prehash: false, lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : false, format: void 0, extraEntropy: false }; const defaultSigOpts_format = "compact"; function isBiggerThanHalfOrder(number) { const HALF = CURVE_ORDER >> _1n4; return number > HALF; } function validateRS(title, num) { if (!Fn.isValidNot0(num)) throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`); return num; } function validateSigLength(bytes, format2) { validateSigFormat(format2); const size = lengths.signature; const sizer = format2 === "compact" ? size : format2 === "recovered" ? size + 1 : void 0; return _abytes2(bytes, sizer, `${format2} signature`); } class Signature { constructor(r, s, recovery) { this.r = validateRS("r", r); this.s = validateRS("s", s); if (recovery != null) this.recovery = recovery; Object.freeze(this); } static fromBytes(bytes, format2 = defaultSigOpts_format) { validateSigLength(bytes, format2); let recid; if (format2 === "der") { const { r: r2, s: s2 } = DER.toSig(_abytes2(bytes)); return new Signature(r2, s2); } if (format2 === "recovered") { recid = bytes[0]; format2 = "compact"; bytes = bytes.subarray(1); } const L = Fn.BYTES; const r = bytes.subarray(0, L); const s = bytes.subarray(L, L * 2); return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid); } static fromHex(hex, format2) { return this.fromBytes(hexToBytes(hex), format2); } addRecoveryBit(recovery) { return new Signature(this.r, this.s, recovery); } recoverPublicKey(messageHash) { const FIELD_ORDER = Fp.ORDER; const { r, s, recovery: rec } = this; if (rec == null || ![ 0, 1, 2, 3 ].includes(rec)) throw new Error("recovery id invalid"); const hasCofactor = CURVE_ORDER * _2n2 < FIELD_ORDER; if (hasCofactor && rec > 1) throw new Error("recovery id is ambiguous for h>1 curve"); const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r; if (!Fp.isValid(radj)) throw new Error("recovery id 2 or 3 invalid"); const x = Fp.toBytes(radj); const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x)); const ir = Fn.inv(radj); const h = bits2int_modN(ensureBytes("msgHash", messageHash)); const u1 = Fn.create(-h * ir); const u2 = Fn.create(s * ir); const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2)); if (Q.is0()) throw new Error("point at infinify"); Q.assertValidity(); return Q; } // Signatures should be low-s, to prevent malleability. hasHighS() { return isBiggerThanHalfOrder(this.s); } toBytes(format2 = defaultSigOpts_format) { validateSigFormat(format2); if (format2 === "der") return hexToBytes(DER.hexFromSig(this)); const r = Fn.toBytes(this.r); const s = Fn.toBytes(this.s); if (format2 === "recovered") { if (this.recovery == null) throw new Error("recovery bit must be present"); return concatBytes(Uint8Array.of(this.recovery), r, s); } return concatBytes(r, s); } toHex(format2) { return bytesToHex(this.toBytes(format2)); } // TODO: remove assertValidity() { } static fromCompact(hex) { return Signature.fromBytes(ensureBytes("sig", hex), "compact"); } static fromDER(hex) { return Signature.fromBytes(ensureBytes("sig", hex), "der"); } normalizeS() { return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this; } toDERRawBytes() { return this.toBytes("der"); } toDERHex() { return bytesToHex(this.toBytes("der")); } toCompactRawBytes() { return this.toBytes("compact"); } toCompactHex() { return bytesToHex(this.toBytes("compact")); } } const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) { if (bytes.length > 8192) throw new Error("input is too large"); const num = bytesToNumberBE(bytes); const delta = bytes.length * 8 - fnBits; return delta > 0 ? num >> BigInt(delta) : num; }; const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) { return Fn.create(bits2int(bytes)); }; const ORDER_MASK = bitMask(fnBits); function int2octets(num) { aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK); return Fn.toBytes(num); } function validateMsgAndHash(message, prehash) { _abytes2(message, void 0, "message"); return prehash ? _abytes2(hash(message), void 0, "prehashed message") : message; } function prepSig(message, privateKey, opts) { if ([ "recovered", "canonical" ].some((k) => k in opts)) throw new Error("sign() legacy options not supported"); const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts); message = validateMsgAndHash(message, prehash); const h1int = bits2int_modN(message); const d = _normFnElement(Fn, privateKey); const seedArgs = [ int2octets(d), int2octets(h1int) ]; if (extraEntropy != null && extraEntropy !== false) { const e = extraEntropy === true ? randomBytes2(lengths.secretKey) : extraEntropy; seedArgs.push(ensureBytes("extraEntropy", e)); } const seed = concatBytes(...seedArgs); const m = h1int; function k2sig(kBytes) { const k = bits2int(kBytes); if (!Fn.isValidNot0(k)) return; const ik = Fn.inv(k); const q = Point.BASE.multiply(k).toAffine(); const r = Fn.create(q.x); if (r === _0n4) return; const s = Fn.create(ik * Fn.create(m + r * d)); if (s === _0n4) return; let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4); let normS = s; if (lowS && isBiggerThanHalfOrder(s)) { normS = Fn.neg(s); recovery ^= 1; } return new Signature(r, normS, recovery); } return { seed, k2sig }; } function sign(message, secretKey, opts = {}) { message = ensureBytes("message", message); const { seed, k2sig } = prepSig(message, secretKey, opts); const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2); const sig = drbg(seed, k2sig); return sig; } function tryParsingSig(sg) { let sig = void 0; const isHex = typeof sg === "string" || isBytes(sg); const isObj = !isHex && sg !== null && typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint"; if (!isHex && !isObj) throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance"); if (isObj) { sig = new Signature(sg.r, sg.s); } else if (isHex) { try { sig = Signature.fromBytes(ensureBytes("sig", sg), "der"); } catch (derError) { if (!(derError instanceof DER.Err)) throw derError; } if (!sig) { try { sig = Signature.fromBytes(ensureBytes("sig", sg), "compact"); } catch (error) { return false; } } } if (!sig) return false; return sig; } function verify(signature, message, publicKey, opts = {}) { const { lowS, prehash, format: format2 } = validateSigOpts(opts, defaultSigOpts); publicKey = ensureBytes("publicKey", publicKey); message = validateMsgAndHash(ensureBytes("message", message), prehash); if ("strict" in opts) throw new Error("options.strict was renamed to lowS"); const sig = format2 === void 0 ? tryParsingSig(signature) : Signature.fromBytes(ensureBytes("sig", signature), format2); if (sig === false) return false; try { const P = Point.fromBytes(publicKey); if (lowS && sig.hasHighS()) return false; const { r, s } = sig; const h = bits2int_modN(message); const is2 = Fn.inv(s); const u1 = Fn.create(h * is2); const u2 = Fn.create(r * is2); const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); if (R.is0()) return false; const v = Fn.create(R.x); return v === r; } catch (e) { return false; } } function recoverPublicKey(signature, message, opts = {}) { const { prehash } = validateSigOpts(opts, defaultSigOpts); message = validateMsgAndHash(message, prehash); return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes(); } return Object.freeze({ keygen, getPublicKey, getSharedSecret, utils, lengths, Point, sign, verify, recoverPublicKey, Signature, hash }); } function _weierstrass_legacy_opts_to_new(c) { const CURVE = { a: c.a, b: c.b, p: c.Fp.ORDER, n: c.n, h: c.h, Gx: c.Gx, Gy: c.Gy }; const Fp = c.Fp; let allowedLengths = c.allowedPrivateKeyLengths ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2)))) : void 0; const Fn = Field(CURVE.n, { BITS: c.nBitLength, allowedLengths, modFromBytes: c.wrapPrivateKey }); const curveOpts = { Fp, Fn, allowInfinityPoint: c.allowInfinityPoint, endo: c.endo, isTorsionFree: c.isTorsionFree, clearCofactor: c.clearCofactor, fromBytes: c.fromBytes, toBytes: c.toBytes }; return { CURVE, curveOpts }; } function _ecdsa_legacy_opts_to_new(c) { const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c); const ecdsaOpts = { hmac: c.hmac, randomBytes: c.randomBytes, lowS: c.lowS, bits2int: c.bits2int, bits2int_modN: c.bits2int_modN }; return { CURVE, curveOpts, hash: c.hash, ecdsaOpts }; } function _ecdsa_new_output_to_legacy(c, _ecdsa) { const Point = _ecdsa.Point; return Object.assign({}, _ecdsa, { ProjectivePoint: Point, CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS)) }); } function weierstrass(c) { const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c); const Point = weierstrassN(CURVE, curveOpts); const signs = ecdsa(Point, hash, ecdsaOpts); return _ecdsa_new_output_to_legacy(c, signs); } // ../../../../../node_modules/.deno/@noble+curves@1.9.7/node_modules/@noble/curves/esm/_shortw_utils.js function createCurve(curveDef, defHash) { const create3 = (hash) => weierstrass({ ...curveDef, hash }); return { ...create3(defHash), create: create3 }; } // ../../../../../node_modules/.deno/@noble+curves@1.9.7/node_modules/@noble/curves/esm/nist.js var p256_CURVE = { p: BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"), n: BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"), h: BigInt(1), a: BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"), b: BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"), Gx: BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"), Gy: BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5") }; var p384_CURVE = { p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"), n: BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"), h: BigInt(1), a: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"), b: BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"), Gx: BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"), Gy: BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f") }; var p521_CURVE = { p: BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), n: BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"), h: BigInt(1), a: BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"), b: BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"), Gx: BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"), Gy: BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650") }; var Fp256 = Field(p256_CURVE.p); var Fp384 = Field(p384_CURVE.p); var Fp521 = Field(p521_CURVE.p); var p256 = createCurve({ ...p256_CURVE, Fp: Fp256, lowS: false }, sha2562); var p384 = createCurve({ ...p384_CURVE, Fp: Fp384, lowS: false }, sha384); var p521 = createCurve({ ...p521_CURVE, Fp: Fp521, lowS: false, allowedPrivateKeyLengths: [ 130, 131, 132 ] }, sha5122); // ../../../../../node_modules/.deno/@noble+curves@1.9.7/node_modules/@noble/curves/esm/p256.js var p2562 = p256; // ../../../../../node_modules/.deno/@atproto+crypto@0.5.7/node_modules/@atproto/crypto/dist/p256/encoding.js var compressPubkey = (pubkeyBytes) => { const point = p2562.ProjectivePoint.fromHex(pubkeyBytes); return point.toRawBytes(true); }; var decompressPubkey = (compressed) => { if (compressed.length !== 33) { throw new Error("Expected 33 byte compress pubkey"); } const point = p2562.ProjectivePoint.fromHex(compressed); return point.toRawBytes(false); }; // ../../../../../node_modules/.deno/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha256.js var sha2563 = sha2562; // ../../../../../node_modules/.deno/@atproto+crypto@0.5.7/node_modules/@atproto/crypto/dist/utils.js var extractMultikey = (did) => { if (!did.startsWith(DID_KEY_PREFIX)) { throw new Error(`Incorrect prefix for did:key: ${did}`); } return did.slice(DID_KEY_PREFIX.length); }; var MAX_BASE58_KEY_LENGTH = 128; var base58ToKeyBytes = (str) => { if (str.length > MAX_BASE58_KEY_LENGTH) { throw new Error(`base58btc key too long (${str.length} > ${MAX_BASE58_KEY_LENGTH})`); } return fromString2(str, "base58btc"); }; var extractPrefixedBytes = (multikey) => { if (!multikey.startsWith(BASE58_MULTIBASE_PREFIX)) { throw new Error(`Incorrect prefix for multikey: ${multikey}`); } return base58ToKeyBytes(multikey.slice(BASE58_MULTIBASE_PREFIX.length)); }; var hasPrefix = (bytes, prefix) => { return equals3(prefix, bytes.subarray(0, prefix.byteLength)); }; // ../../../../../node_modules/.deno/@atproto+crypto@0.5.7/node_modules/@atproto/crypto/dist/p256/operations.js var verifyDidSig = async (did, data, sig, opts) => { const prefixedBytes = extractPrefixedBytes(extractMultikey(did)); if (!hasPrefix(prefixedBytes, P256_DID_PREFIX)) { throw new Error(`Not a P-256 did:key: ${did}`); } const keyBytes = prefixedBytes.slice(P256_DID_PREFIX.length); return verifySig(keyBytes, data, sig, opts); }; var verifySig = async (publicKey, data, sig, opts) => { const allowMalleable = opts?.allowMalleableSig ?? false; const msgHash = await sha2563(data); return p2562.verify(sig, msgHash, publicKey, { format: allowMalleable ? void 0 : "compact", lowS: !allowMalleable }); }; // ../../../../../node_modules/.deno/@atproto+crypto@0.5.7/node_modules/@atproto/crypto/dist/p256/plugin.js var p256Plugin = { prefix: P256_DID_PREFIX, jwtAlg: P256_JWT_ALG, verifySignature: verifyDidSig, compressPubkey, decompressPubkey }; // ../../../../../node_modules/.deno/@noble+curves@1.9.7/node_modules/@noble/curves/esm/secp256k1.js var secp256k1_CURVE = { p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"), n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"), h: BigInt(1), a: BigInt(0), b: BigInt(7), Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"), Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8") }; var secp256k1_ENDO = { beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), basises: [ [ BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3") ], [ BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15") ] ] }; var _2n3 = /* @__PURE__ */ BigInt(2); function sqrtMod(y) { const P = secp256k1_CURVE.p; const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); const b2 = y * y * y % P; const b3 = b2 * b2 * y % P; const b6 = pow2(b3, _3n3, P) * b3 % P; const b9 = pow2(b6, _3n3, P) * b3 % P; const b11 = pow2(b9, _2n3, P) * b2 % P; const b22 = pow2(b11, _11n, P) * b11 % P; const b44 = pow2(b22, _22n, P) * b22 % P; const b88 = pow2(b44, _44n, P) * b44 % P; const b176 = pow2(b88, _88n, P) * b88 % P; const b220 = pow2(b176, _44n, P) * b44 % P; const b223 = pow2(b220, _3n3, P) * b3 % P; const t1 = pow2(b223, _23n, P) * b22 % P; const t2 = pow2(t1, _6n, P) * b2 % P; const root = pow2(t2, _2n3, P); if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error("Cannot find square root"); return root; } var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod }); var secp256k1 = createCurve({ ...secp256k1_CURVE, Fp: Fpk1, lowS: true, endo: secp256k1_ENDO }, sha2562); // ../../../../../node_modules/.deno/@atproto+crypto@0.5.7/node_modules/@atproto/crypto/dist/secp256k1/encoding.js var compressPubkey2 = (pubkeyBytes) => { const point = secp256k1.ProjectivePoint.fromHex(pubkeyBytes); return point.toRawBytes(true); }; var decompressPubkey2 = (compressed) => { if (compressed.length !== 33) { throw new Error("Expected 33 byte compress pubkey"); } const point = secp256k1.ProjectivePoint.fromHex(compressed); return point.toRawBytes(false); }; // ../../../../../node_modules/.deno/@atproto+crypto@0.5.7/node_modules/@atproto/crypto/dist/secp256k1/operations.js var verifyDidSig2 = async (did, data, sig, opts) => { const prefixedBytes = extractPrefixedBytes(extractMultikey(did)); if (!hasPrefix(prefixedBytes, SECP256K1_DID_PREFIX)) { throw new Error(`Not a secp256k1 did:key: ${did}`); } const keyBytes = prefixedBytes.slice(SECP256K1_DID_PREFIX.length); return verifySig2(keyBytes, data, sig, opts); }; var verifySig2 = async (publicKey, data, sig, opts) => { const allowMalleable = opts?.allowMalleableSig ?? false; const msgHash = await sha2563(data); return secp256k1.verify(sig, msgHash, publicKey, { format: allowMalleable ? void 0 : "compact", lowS: !allowMalleable }); }; // ../../../../../node_modules/.deno/@atproto+crypto@0.5.7/node_modules/@atproto/crypto/dist/secp256k1/plugin.js var secp256k1Plugin = { prefix: SECP256K1_DID_PREFIX, jwtAlg: SECP256K1_JWT_ALG, verifySignature: verifyDidSig2, compressPubkey: compressPubkey2, decompressPubkey: decompressPubkey2 }; // ../../../../../node_modules/.deno/@atproto+crypto@0.5.7/node_modules/@atproto/crypto/dist/plugins.js var plugins = [ p256Plugin, secp256k1Plugin ]; // ../../../../../node_modules/.deno/@atproto+crypto@0.5.7/node_modules/@atproto/crypto/dist/did.js var parseMultikey = (multikey) => { const prefixedBytes = extractPrefixedBytes(multikey); const plugin = plugins.find((p) => hasPrefix(prefixedBytes, p.prefix)); if (!plugin) { throw new Error("Unsupported key type"); } const keyBytes = plugin.decompressPubkey(prefixedBytes.slice(plugin.prefix.length)); return { jwtAlg: plugin.jwtAlg, keyBytes }; }; var formatMultikey = (jwtAlg, keyBytes) => { const plugin = plugins.find((p) => p.jwtAlg === jwtAlg); if (!plugin) { throw new Error("Unsupported key type"); } const prefixedBytes = concat([ plugin.prefix, plugin.compressPubkey(keyBytes) ]); return BASE58_MULTIBASE_PREFIX + toString2(prefixedBytes, "base58btc"); }; var parseDidKey = (did) => { const multikey = extractMultikey(did); return parseMultikey(multikey); }; function formatDidKey(jwtAlg, keyBytes) { return `${DID_KEY_PREFIX}${formatMultikey(jwtAlg, keyBytes)}`; } // ../../../../../node_modules/.deno/@atproto+crypto@0.5.7/node_modules/@atproto/crypto/dist/multibase.js var multibaseToBytes = (mb) => { const base3 = mb[0]; const key = mb.slice(1); switch (base3) { case "f": return fromString2(key, "base16"); case "F": return fromString2(key, "base16upper"); case "b": return fromString2(key, "base32"); case "B": return fromString2(key, "base32upper"); case "z": return base58ToKeyBytes(key); case "m": return fromString2(key, "base64"); case "u": return fromString2(key, "base64url"); case "U": return fromString2(key, "base64urlpad"); default: throw new Error(`Unsupported multibase: :${mb}`); } }; // ../../../../../node_modules/.deno/@atproto+crypto@0.5.7/node_modules/@atproto/crypto/dist/verify.js var verifySignature = (didKey, data, sig, opts) => { const parsed = parseDidKey(didKey); if (opts?.jwtAlg && opts.jwtAlg !== parsed.jwtAlg) { throw new Error(`Expected key alg ${opts.jwtAlg}, got ${parsed.jwtAlg}`); } const plugin = plugins.find((p) => p.jwtAlg === parsed.jwtAlg); if (!plugin) { throw new Error(`Unsupported signature alg: ${parsed.jwtAlg}`); } return plugin.verifySignature(didKey, data, sig, opts); }; // ../../../../../node_modules/.deno/@atproto+identity@0.5.6/node_modules/@atproto/identity/dist/did/atproto-data.js var getKey = (doc) => { const key = getSigningKey(doc); if (!key) return void 0; return getDidKeyFromMultibase(key); }; var getDidKeyFromMultibase = (key) => { const keyBytes = multibaseToBytes(key.publicKeyMultibase); let didKey = void 0; if (key.type === "EcdsaSecp256r1VerificationKey2019") { didKey = formatDidKey(P256_JWT_ALG, keyBytes); } else if (key.type === "EcdsaSecp256k1VerificationKey2019") { didKey = formatDidKey(SECP256K1_JWT_ALG, keyBytes); } else if (key.type === "Multikey") { const parsed = parseMultikey(key.publicKeyMultibase); didKey = formatDidKey(parsed.jwtAlg, parsed.keyBytes); } return didKey; }; var parseToAtprotoDocument = (doc) => { const did = getDid(doc); return { did, signingKey: getKey(doc), handle: getHandle(doc), pds: getPdsEndpoint(doc) }; }; var ensureAtpDocument = (doc) => { const { did, signingKey, handle, pds } = parseToAtprotoDocument(doc); if (!did) { throw new Error(`Could not parse id from doc: ${doc}`); } if (!signingKey) { throw new Error(`Could not parse signingKey from doc: ${doc}`); } if (!handle) { throw new Error(`Could not parse handle from doc: ${doc}`); } if (!pds) { throw new Error(`Could not parse pds from doc: ${doc}`); } return { did, signingKey, handle, pds }; }; var ensureAtprotoKey = (doc) => { const { signingKey } = parseToAtprotoDocument(doc); if (!signingKey) { throw new Error(`Could not parse signingKey from doc: ${doc}`); } return signingKey; }; // ../../../../../node_modules/.deno/@atproto+identity@0.5.6/node_modules/@atproto/identity/dist/did/base-resolver.js var BaseResolver = class { constructor(cache2) { this.cache = cache2; } validateDidDoc(did, val) { if (!check_exports.is(val, didDocument)) { throw new PoorlyFormattedDidDocumentError(did, val); } if (val.id !== did) { throw new PoorlyFormattedDidDocumentError(did, val); } return val; } async resolveNoCache(did) { const got = await this.resolveNoCheck(did); if (got === null) return null; return this.validateDidDoc(did, got); } async refreshCache(did, prevResult) { await this.cache?.refreshCache(did, () => this.resolveNoCache(did), prevResult); } async resolve(did, forceRefresh = false) { let fromCache = null; if (this.cache && !forceRefresh) { fromCache = await this.cache.checkCache(did); if (fromCache && !fromCache.expired) { if (fromCache?.stale) { await this.refreshCache(did, fromCache); } return fromCache.doc; } } const got = await this.resolveNoCache(did); if (got === null) { await this.cache?.clearEntry(did); return null; } await this.cache?.cacheDid(did, got, fromCache ?? void 0); return got; } async ensureResolve(did, forceRefresh = false) { const result = await this.resolve(did, forceRefresh); if (result === null) { throw new DidNotFoundError(did); } return result; } async resolveAtprotoData(did, forceRefresh = false) { const didDocument2 = await this.ensureResolve(did, forceRefresh); return ensureAtpDocument(didDocument2); } async resolveAtprotoKey(did, forceRefresh = false) { if (did.startsWith("did:key:")) { return did; } else { const didDocument2 = await this.ensureResolve(did, forceRefresh); return ensureAtprotoKey(didDocument2); } } async verifySignature(did, data, sig, forceRefresh = false) { const signingKey = await this.resolveAtprotoKey(did, forceRefresh); return verifySignature(signingKey, data, sig); } }; // ../../../../../node_modules/.deno/@atproto+identity@0.5.6/node_modules/@atproto/identity/dist/did/util.js async function timed(ms, fn) { const abortController = new AbortController(); const timer = setTimeout(() => abortController.abort(), ms); const signal = abortController.signal; try { return await fn(signal); } finally { clearTimeout(timer); abortController.abort(); } } // ../../../../../node_modules/.deno/@atproto+identity@0.5.6/node_modules/@atproto/identity/dist/did/web-resolver.js var DOC_PATH = "/.well-known/did.json"; var DidWebResolver = class extends BaseResolver { constructor(timeout, cache2) { super(cache2); this.timeout = timeout; this.cache = cache2; } async resolveNoCheck(did) { const parsedId = did.split(":").slice(2).join(":"); const parts = parsedId.split(":").map(decodeURIComponent); let path; if (parts.length < 1) { throw new PoorlyFormattedDidError(did); } else if (parts.length === 1) { path = parts[0] + DOC_PATH; } else { throw new UnsupportedDidWebPathError(did); } const url = new URL(`https://${path}`); if (url.hostname === "localhost") { url.protocol = "http"; } return timed(this.timeout, async (signal) => { const res = await fetch(url, { signal, redirect: "error", headers: { accept: "application/did+ld+json,application/json" } }); if (!res.ok) return null; return res.json(); }); } }; // ../../../../../node_modules/.deno/@atproto+identity@0.5.6/node_modules/@atproto/identity/dist/did/plc-resolver.js var DidPlcResolver = class extends BaseResolver { constructor(plcUrl, timeout, cache2) { super(cache2); this.plcUrl = plcUrl; this.timeout = timeout; this.cache = cache2; } async resolveNoCheck(did) { return timed(this.timeout, async (signal) => { const url = new URL(`/${encodeURIComponent(did)}`, this.plcUrl); const res = await fetch(url, { redirect: "error", headers: { accept: "application/did+ld+json,application/json" }, signal }); if (res.status === 404) return null; if (!res.ok) { throw Object.assign(new Error(res.statusText), { status: res.status }); } return res.json(); }); } }; // ../../../../../node_modules/.deno/@atproto+identity@0.5.6/node_modules/@atproto/identity/dist/did/did-resolver.js var DidResolver = class extends BaseResolver { constructor(opts) { super(opts.didCache); const { timeout = 3e3, plcUrl = "https://plc.directory" } = opts; this.methods = /* @__PURE__ */ new Map([ [ "plc", new DidPlcResolver(plcUrl, timeout) ], [ "web", new DidWebResolver(timeout) ] ]); } async resolveNoCheck(did) { if (!did.startsWith("did:")) { throw new PoorlyFormattedDidError(did); } const methodSepIdx = did.indexOf(":", 4); if (methodSepIdx === -1) { throw new PoorlyFormattedDidError(did); } const methodName = did.slice(4, methodSepIdx); const method = this.methods.get(methodName); if (!method) { throw new UnsupportedDidMethodError(did); } return method.resolveNoCheck(did); } }; // ../../../../../node_modules/.deno/@atproto+identity@0.5.6/node_modules/@atproto/identity/dist/handle/index.js import * as dns from "node:dns/promises"; var SUBDOMAIN = "_atproto"; var PREFIX = "did="; var HandleResolver = class { constructor(opts = {}) { this.timeout = opts.timeout ?? 3e3; this.backupNameservers = opts.backupNameservers; } async resolve(handle) { const dnsPromise = this.resolveDns(handle); const httpAbort = new AbortController(); const httpPromise = this.resolveHttp(handle, httpAbort.signal).catch(() => void 0); const dnsRes = await dnsPromise; if (dnsRes) { httpAbort.abort(); return dnsRes; } const res = await httpPromise; if (res) { return res; } return this.resolveDnsBackup(handle); } async resolveDns(handle) { let chunkedResults; try { chunkedResults = await dns.resolveTxt(`${SUBDOMAIN}.${handle}`); } catch (err) { return void 0; } return this.parseDnsResult(chunkedResults); } async resolveHttp(handle, signal) { const url = new URL("/.well-known/atproto-did", `https://${handle}`); try { const res = await fetch(url, { signal }); const did = (await res.text()).split("\n")[0].trim(); if (typeof did === "string" && did.startsWith("did:")) { return did; } return void 0; } catch (err) { return void 0; } } async resolveDnsBackup(handle) { let chunkedResults; try { const backupIps = await this.getBackupNameserverIps(); if (!backupIps || backupIps.length < 1) return void 0; const resolver = new dns.Resolver(); resolver.setServers(backupIps); chunkedResults = await resolver.resolveTxt(`${SUBDOMAIN}.${handle}`); } catch (err) { return void 0; } return this.parseDnsResult(chunkedResults); } parseDnsResult(chunkedResults) { const results = chunkedResults.map((chunks) => chunks.join("")); const found = results.filter((i) => i.startsWith(PREFIX)); if (found.length !== 1) { return void 0; } return found[0].slice(PREFIX.length); } async getBackupNameserverIps() { if (!this.backupNameservers) { return void 0; } else if (!this.backupNameserverIps) { const responses = await Promise.allSettled(this.backupNameservers.map((h) => dns.lookup(h))); for (const res of responses) { if (res.status === "fulfilled") { this.backupNameserverIps ??= []; this.backupNameserverIps.push(res.value.address); } } } return this.backupNameserverIps; } }; // ../../../../../node_modules/.deno/@atproto+identity@0.5.6/node_modules/@atproto/identity/dist/id-resolver.js var IdResolver = class { constructor(opts = {}) { const { timeout = 3e3, plcUrl, didCache } = opts; this.handle = new HandleResolver({ timeout, backupNameservers: opts.backupNameservers }); this.did = new DidResolver({ timeout, plcUrl, didCache }); } }; // ../deno-typescript-shared/ctx.ts function noTrustSnapshot(did) { return Promise.reject(new Error(`no trust snapshot is seeded for ${did}: operator and vouch lookups come only from the host snapshot`)); } var PolicyEvalCtxImpl = class { policyName; args; perspective; selfDid; counterpartyDid; subjectDid; rootRequesterDid; policyRef; demand; offer; rfp; bid; accept; #resolver; #store; #resolve; #resolveOperatorDid; #getVouchedDids; #log; constructor(opts) { const self = opts.selfDid; this.policyName = opts.policyName ?? "unset"; this.args = opts.args ?? {}; this.perspective = opts.perspective ?? "requester"; this.selfDid = self; this.subjectDid = opts.subjectDid ?? ""; this.counterpartyDid = opts.counterpartyDid ?? opts.subjectDid ?? self; this.rootRequesterDid = opts.rootRequesterDid ?? ""; this.policyRef = opts.policyRef; this.demand = opts.demand; this.offer = opts.offer; this.rfp = opts.rfp; this.bid = opts.bid; this.accept = opts.accept; this.#resolver = new IdResolver({ plcUrl: opts.plcUrl ?? "https://plc.directory" }); this.#store = opts.store; this.#log = opts.log; this.#resolve = opts.resolve ?? ((ref) => this.#resolveCached(ref)); this.#resolveOperatorDid = opts.resolveOperatorDid ?? noTrustSnapshot; this.#getVouchedDids = opts.getVouchedDids ?? noTrustSnapshot; } /** Satisfies PolicyEvalCtx.resolve — getRecord on the strongRef, cached under rec// when a store is present. */ async resolve(ref) { return this.#resolve(ref); } /** Satisfies PolicyEvalCtx.resolveOperatorDid from the injected snapshot. */ async resolveOperatorDid(did) { return this.#resolveOperatorDid(did); } /** Satisfies PolicyEvalCtx.getVouchedDids from the injected snapshot. */ async getVouchedDids(did) { return this.#getVouchedDids(did); } /** Satisfies PolicyEvalCtx.log — JSON structured, always stderr so callers * (the raw-deno CLI, the gha-lite actions) keep stdout for their machine * readable output. In the gha-lite net-only worker console.* are shimmed to * the same channel, so the distinction is harmless there. */ log(level, msg, meta) { this.#emit(level, msg, meta); } /** Run any policy factory (the sibling ${policyName}.ts files) against this ctx. */ async evaluate(policy) { return policy.evaluate(this); } /** Route through the injected logger when present, else JSON-stderr. */ #emit(level, msg, meta) { if (this.#log) { this.#log(level, msg, meta); return; } const line = JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), level, msg, ...meta ?? {} }); console.error(line); } // ── Live ATProto reads (plain HTTP, DID→PDS resolved per repo) ──────────── /** Resolve a DID to its PDS service endpoint via the PLC directory. */ async #pdsFor(did) { const doc = await this.#resolver.did.resolve(did); const pds = doc ? getPdsEndpoint(doc) : void 0; if (!pds) throw new Error(`no PDS endpoint for ${did}`); return pds; } /** getRecord against the repo's PDS, memoized in the store under rec//. */ async #resolveCached(ref) { const store = this.#store; if (store) { const key = recordCacheKey(ref); const entry = store.get(key); const file = entry?.[RECORD_VALUE_FILE]; if (file) { try { return JSON.parse(file.data); } catch { } } const value = await this.#getRecord(ref); store.set(key, { [RECORD_VALUE_FILE]: { data: JSON.stringify(value), encoding: "text" } }); return value; } return this.#getRecord(ref); } /** com.atproto.repo.getRecord via the repo's PDS. */ async #getRecord(ref) { const { repo, collection, rkey } = splitAtUri(ref.uri); const pds = await this.#pdsFor(repo); const url = new URL(`${pds}/xrpc/com.atproto.repo.getRecord`); url.searchParams.set("repo", repo); url.searchParams.set("collection", collection); url.searchParams.set("rkey", rkey); const res = await fetch(url); if (!res.ok) throw new Error(`getRecord ${ref.uri} failed: ${res.status}`); const data = await res.json(); return data.value ?? {}; } toJSON() { return { policyName: this.policyName, args: this.args, perspective: this.perspective, selfDid: this.selfDid, counterpartyDid: this.counterpartyDid, subjectDid: this.subjectDid, rootRequesterDid: this.rootRequesterDid, policyRef: this.policyRef, demand: this.demand, offer: this.offer, rfp: this.rfp, bid: this.bid, accept: this.accept }; } }; function authorOf(r) { return r ? splitAtUri(r.uri).repo : ""; } function deriveSubject(perspective, rfp, bid, accept) { if (perspective === "requester") return authorOf(bid); return authorOf(rfp ?? accept); } function deriveRootRequester(perspective, selfDid, subjectDid) { return perspective === "requester" ? selfDid : subjectDid; } function deriveDemand(rfp) { if (!rfp) return void 0; const payload = rfp.value?.payload; if (!payload || !payload.uri || !payload.cid) return void 0; return { rfpRef: { uri: rfp.uri, cid: rfp.cid }, payloadRef: payload, payloadNsid: splitAtUri(payload.uri).collection, payload: rfp.payload }; } function deriveOffer(bid) { if (!bid) return void 0; const payload = bid.value?.payload; if (!payload || !payload.uri || !payload.cid) return void 0; return { bidRef: { uri: bid.uri, cid: bid.cid }, payloadRef: payload, payloadNsid: splitAtUri(payload.uri).collection, payload: bid.payload }; } async function createPolicyCtx(input2) { const scratch = new PolicyEvalCtxImpl({ policyName: input2.policyName, args: input2.args, perspective: input2.perspective, selfDid: input2.selfDid, plcUrl: input2.plcUrl, store: input2.store, resolve: input2.resolve, resolveOperatorDid: input2.resolveOperatorDid, getVouchedDids: input2.getVouchedDids, log: input2.log }); const hydrate = async (r) => { if (!r) return void 0; if (r.value) return r; try { return { ...r, value: await scratch.resolve({ uri: r.uri, cid: r.cid }) }; } catch { return r; } }; const rfp = await hydrate(input2.rfp); const bid = await hydrate(input2.bid); const accept = await hydrate(input2.accept); const subjectDid = input2.subjectDid ?? deriveSubject(input2.perspective, rfp, bid, accept); const rootRequesterDid = input2.rootRequesterDid ?? deriveRootRequester(input2.perspective, input2.selfDid, subjectDid); return new PolicyEvalCtxImpl({ policyName: input2.policyName, args: input2.args, perspective: input2.perspective, selfDid: input2.selfDid, subjectDid, rootRequesterDid, counterpartyDid: input2.counterpartyDid ?? subjectDid, policyRef: input2.policyRef, demand: deriveDemand(rfp), offer: deriveOffer(bid), rfp, bid, accept, plcUrl: input2.plcUrl, store: input2.store, resolve: input2.resolve, resolveOperatorDid: input2.resolveOperatorDid, getVouchedDids: input2.getVouchedDids, log: input2.log }); } // ../deno-typescript-shared/evaluate.ts var DEFAULT_TTL_MS = 3e4; function ttlMsOf(args) { const sec = args?.cacheTtlSec; return typeof sec === "number" && Number.isFinite(sec) && sec > 0 ? sec * 1e3 : DEFAULT_TTL_MS; } async function runPolicy(store, policy, ctx, opts = {}) { const key = opts.cacheKey ?? policyCacheKey(policy.name, { rfp: ctx.rfp, bid: ctx.bid, accept: ctx.accept }, ctx.args); const hit = readPolicyResult(store, key); if (hit) { ctx.log("debug", "policy cache hit", { key }); return { result: hit, fromCache: true, cacheKey: key }; } const result = await policy.evaluate(ctx); writePolicyResult(store, key, result, opts.ttlMs ?? ttlMsOf(ctx.args)); ctx.log("info", "policy evaluated", { key, allow: result.allow }); return { result, fromCache: false, cacheKey: key }; } // ../deno-typescript-shared/scope.ts var LEGACY_TRUST_NAMES = [ "only-me", "tangled-vouch", "mutuals" ]; function tryResolvePolicyName(registry, name2, perspective) { if (registry.get(name2)) return name2; if (LEGACY_TRUST_NAMES.includes(name2)) { const canonical = `${perspective}-${name2}`; if (registry.get(canonical)) return canonical; } return void 0; } async function buildTrustSnapshot(resolveOperatorDid, getVouchedDids, selfDid, counterpartyDid) { const selfOp = await resolveOperatorDid(selfDid) ?? selfDid; const coOp = await resolveOperatorDid(counterpartyDid); const vouchSets = /* @__PURE__ */ new Map(); const vouches = async (did) => { let s = vouchSets.get(did); if (!s) { s = await getVouchedDids(did); vouchSets.set(did, s); } return s; }; const trustedOps = /* @__PURE__ */ new Set([ selfDid, selfOp ]); await vouches(selfDid); await vouches(selfOp); if (coOp && coOp !== selfDid && coOp !== selfOp) await vouches(coOp); if (counterpartyDid && !trustedOps.has(counterpartyDid)) await vouches(counterpartyDid); const operatorOf = /* @__PURE__ */ new Map([ [ selfDid, selfOp ] ]); if (coOp) operatorOf.set(counterpartyDid, coOp); return { operatorOf: (did) => operatorOf.get(did), sameOperator: (a, b) => { if (a === b) return true; const oa = operatorOf.get(a); const ob = operatorOf.get(b); if (oa === void 0 || ob === void 0) return void 0; return oa === ob; }, isVouched: (voucher, vouchee) => vouchSets.get(voucher)?.has(vouchee) ?? false, vouchedBy: (voucher) => vouchSets.get(voucher) ?? /* @__PURE__ */ new Set(), trustedOperators: () => trustedOps, associatedWith: () => /* @__PURE__ */ new Set() }; } function flatVouched(query) { const out = /* @__PURE__ */ new Set(); for (const op of query.trustedOperators()) { for (const d of query.vouchedBy(op)) out.add(d); } return out; } async function scopeDecide(opts) { const { registry, named, perspective, selfDid, counterpartyDid, resolveOperatorDid, getVouchedDids } = opts; if (!Array.isArray(named) || named.length === 0) return void 0; let snapshot; let abstained = false; let firstDeny; for (const raw of named) { const entry = raw; if (!entry || typeof entry !== "object") { abstained = true; continue; } const name2 = typeof entry.name === "string" ? entry.name : ""; if (!name2) { abstained = true; continue; } const args = entry.args ?? {}; const canonical = tryResolvePolicyName(registry, name2, perspective); const policy = canonical !== void 0 ? registry.get(canonical) : void 0; if (!policy || policy.kind !== "trust" || typeof policy.decide !== "function") { abstained = true; continue; } const needsSnapshot = policy.needsTrustSnapshot === true || policy.needsVouchSet === true; if (needsSnapshot && !snapshot) { try { snapshot = await buildTrustSnapshot(resolveOperatorDid, getVouchedDids, selfDid, counterpartyDid); } catch (err) { firstDeny ??= { allow: false, violations: [ { msg: `scope denied by ${name2}: ${String(err)}`, policyId: name2 } ] }; continue; } } const verdict = policy.decide({ did: counterpartyDid, selfDid, vouchedDids: needsSnapshot && snapshot ? flatVouched(snapshot) : void 0, args, query: needsSnapshot ? snapshot : void 0 }); if (verdict === void 0) { abstained = true; continue; } if (!verdict) { firstDeny ??= { allow: false, violations: [ { msg: `scope denied by ${name2}`, policyId: name2 } ] }; } } if (firstDeny) return firstDeny; if (abstained) return void 0; return { allow: true, violations: [] }; } // ../deno-typescript-shared/trust.ts function operatedByTrusted(query, did) { const op = query.operatorOf(did); return op !== void 0 && query.trustedOperators().has(op); } function trustVouched(query, did) { const op = query.operatorOf(did); for (const trusted of query.trustedOperators()) { const vouched = query.vouchedBy(trusted); if (vouched.has(did) || op !== void 0 && vouched.has(op)) return true; } return false; } var tangledVouchAllows = (query, selfDid, did) => did === selfDid || operatedByTrusted(query, did) || trustVouched(query, did); function deny(ctx, msg) { return { allow: false, violations: [ { msg, policyId: ctx.policyName } ] }; } async function evaluateTrust(ctx, label, allows, msg) { const did = ctx.counterpartyDid; ctx.log("info", label + " evaluate", { counterpartyDid: did, subjectDid: ctx.subjectDid, selfDid: ctx.selfDid }); if (!did) return deny(ctx, "no counterparty to evaluate"); if (ctx.subjectDid && ctx.subjectDid !== did) return deny(ctx, "the subject and the counterparty differ"); try { const query = await buildTrustSnapshot((d) => ctx.resolveOperatorDid(d), (d) => ctx.getVouchedDids(d), ctx.selfDid, did); if (allows(query, ctx.selfDid, did)) return { allow: true, violations: [] }; ctx.log("info", label + ": " + msg, { counterpartyDid: did, selfDid: ctx.selfDid }); return deny(ctx, msg); } catch (err) { return deny(ctx, String(err)); } } // ../deno-typescript/tangled-vouch.ts var BIDDER_TANGLED_VOUCH_POLICY_NAME = "bidder-tangled-vouch"; function decide({ did, selfDid, query }) { if (!query) return void 0; return tangledVouchAllows(query, selfDid, did); } function evaluateTangledVouch(ctx) { return evaluateTrust(ctx, "tangled-vouch", tangledVouchAllows, "not vouched"); } function createBidderTangledVouchPolicy() { return { kind: "trust", name: BIDDER_TANGLED_VOUCH_POLICY_NAME, description: "Only bid on RFPs from a requester whose operator appears in the bidder's Tangled vouch graph.", needsVouchSet: true, needsTrustSnapshot: true, decide, evaluate: evaluateTangledVouch }; } // action-common.ts function input(name2) { return Deno.env.get("INPUT_" + name2.toUpperCase()) ?? ""; } function inputJson(name2) { const raw = input(name2); if (!raw) return void 0; try { return JSON.parse(raw); } catch { console.error(`::error::policy action: input ${name2} is not valid JSON: ${raw}`); Deno.exit(1); } } function policyPerspective(policy) { if (policy.kind === "work") return policy.perspectives[0] ?? "requester"; return policy.name.startsWith("bidder-") ? "bidder" : "requester"; } async function writeOutputs(o) { const outputPath = Deno.env.get("GITHUB_OUTPUT"); if (outputPath) { const lines = [ `allow=${o.allow}`, `violations=${JSON.stringify(o.violations)}`, `from-cache=${o.fromCache}`, `cache-key=${o.cacheKey}` ]; for (const line of lines) { await Deno.writeTextFile(outputPath, `${line} `, { append: true }); } } } function onePolicyRegistry(policy) { return { get: (name2) => name2 === policy.name ? policy : void 0, names: () => [ policy.name ] }; } function trustResolvers(store, counterpartyDid) { const entry = store.get(`trust/${counterpartyDid}`); if (!entry) return void 0; const parse = (file) => { const f = entry[file]; return f ? JSON.parse(f.data) : void 0; }; const operatorOf = parse("operatorOf.json"); const vouchedBy = parse("vouchedBy.json"); if (!operatorOf || !vouchedBy) return void 0; return { resolveOperatorDid: async (did) => operatorOf[did] ?? null, getVouchedDids: async (did) => new Set(vouchedBy[did] ?? []) }; } function needsTrustSnapshot(policy) { return policy.kind === "trust" && policy.needsTrustSnapshot === true; } async function denyUnseeded(policy, counterpartyDid, mode) { const violations = [ { msg: `no trust snapshot is seeded for the counterparty ${counterpartyDid || "(none)"}`, policyId: policy.name } ]; await writeOutputs({ allow: false, violations, fromCache: false, cacheKey: "" }); console.log(JSON.stringify({ policy: policy.name, allow: false, violations, mode })); } async function evaluateScope(policy, opts) { const { selfDid, perspective, args, store } = opts; const counterpartyDid = input("counterparty-did"); if (!counterpartyDid) { console.error("::error::policy action: scope mode requires counterparty-did"); Deno.exit(1); } const subjectDid = counterpartyDid; const rootRequesterDid = perspective === "requester" ? selfDid : counterpartyDid; const tr = trustResolvers(store, counterpartyDid); if (needsTrustSnapshot(policy) && !tr) { await denyUnseeded(policy, counterpartyDid, "scope"); return; } const ctx = new PolicyEvalCtxImpl({ policyName: policy.name, args, perspective, selfDid, subjectDid, rootRequesterDid, resolveOperatorDid: tr?.resolveOperatorDid, getVouchedDids: tr?.getVouchedDids, store }); const verdict = await scopeDecide({ registry: onePolicyRegistry(policy), named: [ { name: policy.name, args } ], perspective, selfDid, counterpartyDid, resolveOperatorDid: (did) => ctx.resolveOperatorDid(did), getVouchedDids: (did) => ctx.getVouchedDids(did) }); if (verdict !== void 0) { await writeOutputs({ allow: verdict.allow, violations: verdict.violations, fromCache: false, cacheKey: "" }); console.log(JSON.stringify({ policy: policy.name, allow: verdict.allow, violations: verdict.violations, mode: "scope" })); return; } const { result, fromCache, cacheKey } = await runPolicy(store, policy, ctx, { cacheKey: input("cache-key") || void 0 }); await writeOutputs({ allow: result.allow, violations: result.violations, fromCache, cacheKey }); console.log(JSON.stringify({ policy: policy.name, allow: result.allow, violations: result.violations, fromCache, cacheKey, mode: "scope-fallback" })); } async function evaluatePolicyAction(policy) { const selfDid = input("self-did"); if (!selfDid) { console.error("::error::policy action: self-did is required (the evaluator's own DID)"); Deno.exit(1); } const perspective = input("perspective") || policyPerspective(policy); const store = createCacheStore(); const args = inputJson("policy-args") ?? {}; if (input("mode") === "scope") { await evaluateScope(policy, { selfDid, perspective, args, store }); return; } const tr = trustResolvers(store, input("counterparty-did") || ""); if (needsTrustSnapshot(policy) && !tr) { await denyUnseeded(policy, input("counterparty-did"), "full"); return; } const ctx = await createPolicyCtx({ policyName: policy.name, args, perspective, selfDid, // The engine passes the caller's explicit DID context when the workflow is // evaluated against known parties (e.g. the bidder checking an RFP's policy // before any bid exists); these win over record-derived fields. subjectDid: input("subject-did") || void 0, rootRequesterDid: input("root-requester-did") || void 0, counterpartyDid: input("counterparty-did") || void 0, // The host's trust snapshot (operators + vouch sets) when provided — the // action answers trust queries from it instead of re-reading the network. resolveOperatorDid: tr?.resolveOperatorDid, getVouchedDids: tr?.getVouchedDids, rfp: inputJson("rfp"), bid: inputJson("bid"), accept: inputJson("accept"), store }); const { result, fromCache, cacheKey } = await runPolicy(store, policy, ctx, { cacheKey: input("cache-key") || void 0 }); await writeOutputs({ allow: result.allow, violations: result.violations, fromCache, cacheKey }); console.log(JSON.stringify({ policy: policy.name, allow: result.allow, violations: result.violations, fromCache, cacheKey })); } // bundled-actions/tangy/policy-bidder-tangled-vouch/index.ts await evaluatePolicyAction(createBidderTangledVouchPolicy()); /*! Bundled license information: @noble/hashes/esm/utils.js: (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/utils.js: @noble/curves/esm/abstract/modular.js: @noble/curves/esm/abstract/curve.js: @noble/curves/esm/abstract/weierstrass.js: @noble/curves/esm/_shortw_utils.js: @noble/curves/esm/nist.js: @noble/curves/esm/p256.js: @noble/curves/esm/secp256k1.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) */