"use strict"; 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, mod5) => function __require() { return mod5 || (0, cb[__getOwnPropNames(cb)[0]])((mod5 = { exports: {} }).exports, mod5), mod5.exports; }; var __export = (target, all) => { for (var name5 in all) __defProp(target, name5, { get: all[name5], enumerable: true }); }; var __copyProps = (to, from7, except, desc) => { if (from7 && typeof from7 === "object" || typeof from7 === "function") { for (let key of __getOwnPropNames(from7)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from7[key], enumerable: !(desc = __getOwnPropDesc(from7, key)) || desc.enumerable }); } return to; }; var __toESM = (mod5, isNodeMode, target) => (target = mod5 != null ? __create(__getProtoOf(mod5)) : {}, __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. isNodeMode || !mod5 || !mod5.__esModule ? __defProp(target, "default", { value: mod5, enumerable: true }) : target, mod5 )); var __toCommonJS = (mod5) => __copyProps(__defProp({}, "__esModule", { value: true }), mod5); // node_modules/err-code/index.js var require_err_code = __commonJS({ "node_modules/err-code/index.js"(exports2, module2) { "use strict"; function assign(obj, props) { for (const key in props) { Object.defineProperty(obj, key, { value: props[key], enumerable: true, configurable: true }); } return obj; } function createError(err3, code5, props) { if (!err3 || typeof err3 === "string") { throw new TypeError("Please pass an Error to err-code"); } if (!props) { props = {}; } if (typeof code5 === "object") { props = code5; code5 = ""; } if (code5) { props.code = code5; } try { return assign(err3, props); } catch (_) { props.message = err3.message; props.stack = err3.stack; const ErrClass = function() { }; ErrClass.prototype = Object.create(Object.getPrototypeOf(err3)); const output2 = assign(new ErrClass(), props); return output2; } } module2.exports = createError; } }); // node_modules/@protobufjs/aspromise/index.js var require_aspromise = __commonJS({ "node_modules/@protobufjs/aspromise/index.js"(exports2, module2) { "use strict"; module2.exports = asPromise; function asPromise(fn, ctx) { var params = new Array(arguments.length - 1), offset = 0, index = 2, pending = true; while (index < arguments.length) params[offset++] = arguments[index++]; return new Promise(function executor(resolve5, reject) { params[offset] = function callback(err3) { if (pending) { pending = false; if (err3) reject(err3); else { var params2 = new Array(arguments.length - 1), offset2 = 0; while (offset2 < params2.length) params2[offset2++] = arguments[offset2]; resolve5.apply(null, params2); } } }; try { fn.apply(ctx || null, params); } catch (err3) { if (pending) { pending = false; reject(err3); } } }); } } }); // node_modules/@protobufjs/base64/index.js var require_base64 = __commonJS({ "node_modules/@protobufjs/base64/index.js"(exports2) { "use strict"; var base642 = exports2; base642.length = function length5(string2) { var p = string2.length; if (!p) return 0; var n = 0; while (--p % 4 > 1 && string2.charAt(p) === "=") ++n; return Math.ceil(string2.length * 3) / 4 - n; }; var b64 = new Array(64); var s64 = new Array(123); for (i = 0; i < 64; ) s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; var i; base642.encode = function encode16(buffer2, start, end) { var parts = null, chunk = []; var i2 = 0, j = 0, t; while (start < end) { var b = buffer2[start++]; switch (j) { case 0: chunk[i2++] = b64[b >> 2]; t = (b & 3) << 4; j = 1; break; case 1: chunk[i2++] = b64[t | b >> 4]; t = (b & 15) << 2; j = 2; break; case 2: chunk[i2++] = b64[t | b >> 6]; chunk[i2++] = b64[b & 63]; j = 0; break; } if (i2 > 8191) { (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); i2 = 0; } } if (j) { chunk[i2++] = b64[t]; chunk[i2++] = 61; if (j === 1) chunk[i2++] = 61; } if (parts) { if (i2) parts.push(String.fromCharCode.apply(String, chunk.slice(0, i2))); return parts.join(""); } return String.fromCharCode.apply(String, chunk.slice(0, i2)); }; var invalidEncoding = "invalid encoding"; base642.decode = function decode23(string2, buffer2, offset) { var start = offset; var j = 0, t; for (var i2 = 0; i2 < string2.length; ) { var c = string2.charCodeAt(i2++); if (c === 61 && j > 1) break; if ((c = s64[c]) === void 0) throw Error(invalidEncoding); switch (j) { case 0: t = c; j = 1; break; case 1: buffer2[offset++] = t << 2 | (c & 48) >> 4; t = c; j = 2; break; case 2: buffer2[offset++] = (t & 15) << 4 | (c & 60) >> 2; t = c; j = 3; break; case 3: buffer2[offset++] = (t & 3) << 6 | c; j = 0; break; } } if (j === 1) throw Error(invalidEncoding); return offset - start; }; base642.test = function test(string2) { return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string2); }; } }); // node_modules/@protobufjs/eventemitter/index.js var require_eventemitter = __commonJS({ "node_modules/@protobufjs/eventemitter/index.js"(exports2, module2) { "use strict"; module2.exports = EventEmitter3; function EventEmitter3() { this._listeners = {}; } EventEmitter3.prototype.on = function on(evt, fn, ctx) { (this._listeners[evt] || (this._listeners[evt] = [])).push({ fn, ctx: ctx || this }); return this; }; EventEmitter3.prototype.off = function off(evt, fn) { if (evt === void 0) this._listeners = {}; else { if (fn === void 0) this._listeners[evt] = []; else { var listeners = this._listeners[evt]; for (var i = 0; i < listeners.length; ) if (listeners[i].fn === fn) listeners.splice(i, 1); else ++i; } } return this; }; EventEmitter3.prototype.emit = function emit(evt) { var listeners = this._listeners[evt]; if (listeners) { var args = [], i = 1; for (; i < arguments.length; ) args.push(arguments[i++]); for (i = 0; i < listeners.length; ) listeners[i].fn.apply(listeners[i++].ctx, args); } return this; }; } }); // node_modules/@protobufjs/float/index.js var require_float = __commonJS({ "node_modules/@protobufjs/float/index.js"(exports2, module2) { "use strict"; module2.exports = factory(factory); function factory(exports3) { if (typeof Float32Array !== "undefined") (function() { var f32 = new Float32Array([-0]), f8b = new Uint8Array(f32.buffer), le = f8b[3] === 128; function writeFloat_f32_cpy(val, buf2, pos) { f32[0] = val; buf2[pos] = f8b[0]; buf2[pos + 1] = f8b[1]; buf2[pos + 2] = f8b[2]; buf2[pos + 3] = f8b[3]; } function writeFloat_f32_rev(val, buf2, pos) { f32[0] = val; buf2[pos] = f8b[3]; buf2[pos + 1] = f8b[2]; buf2[pos + 2] = f8b[1]; buf2[pos + 3] = f8b[0]; } exports3.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; exports3.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; function readFloat_f32_cpy(buf2, pos) { f8b[0] = buf2[pos]; f8b[1] = buf2[pos + 1]; f8b[2] = buf2[pos + 2]; f8b[3] = buf2[pos + 3]; return f32[0]; } function readFloat_f32_rev(buf2, pos) { f8b[3] = buf2[pos]; f8b[2] = buf2[pos + 1]; f8b[1] = buf2[pos + 2]; f8b[0] = buf2[pos + 3]; return f32[0]; } exports3.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; exports3.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; })(); else (function() { function writeFloat_ieee754(writeUint, val, buf2, pos) { var sign = val < 0 ? 1 : 0; if (sign) val = -val; if (val === 0) writeUint(1 / val > 0 ? ( /* positive */ 0 ) : ( /* negative 0 */ 2147483648 ), buf2, pos); else if (isNaN(val)) writeUint(2143289344, buf2, pos); else if (val > 34028234663852886e22) writeUint((sign << 31 | 2139095040) >>> 0, buf2, pos); else if (val < 11754943508222875e-54) writeUint((sign << 31 | Math.round(val / 1401298464324817e-60)) >>> 0, buf2, pos); else { var exponent = Math.floor(Math.log(val) / Math.LN2), mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf2, pos); } } exports3.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); exports3.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); function readFloat_ieee754(readUint, buf2, pos) { var uint = readUint(buf2, pos), sign = (uint >> 31) * 2 + 1, exponent = uint >>> 23 & 255, mantissa = uint & 8388607; return exponent === 255 ? mantissa ? NaN : sign * Infinity : exponent === 0 ? sign * 1401298464324817e-60 * mantissa : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); } exports3.readFloatLE = readFloat_ieee754.bind(null, readUintLE); exports3.readFloatBE = readFloat_ieee754.bind(null, readUintBE); })(); if (typeof Float64Array !== "undefined") (function() { var f64 = new Float64Array([-0]), f8b = new Uint8Array(f64.buffer), le = f8b[7] === 128; function writeDouble_f64_cpy(val, buf2, pos) { f64[0] = val; buf2[pos] = f8b[0]; buf2[pos + 1] = f8b[1]; buf2[pos + 2] = f8b[2]; buf2[pos + 3] = f8b[3]; buf2[pos + 4] = f8b[4]; buf2[pos + 5] = f8b[5]; buf2[pos + 6] = f8b[6]; buf2[pos + 7] = f8b[7]; } function writeDouble_f64_rev(val, buf2, pos) { f64[0] = val; buf2[pos] = f8b[7]; buf2[pos + 1] = f8b[6]; buf2[pos + 2] = f8b[5]; buf2[pos + 3] = f8b[4]; buf2[pos + 4] = f8b[3]; buf2[pos + 5] = f8b[2]; buf2[pos + 6] = f8b[1]; buf2[pos + 7] = f8b[0]; } exports3.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; exports3.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; function readDouble_f64_cpy(buf2, pos) { f8b[0] = buf2[pos]; f8b[1] = buf2[pos + 1]; f8b[2] = buf2[pos + 2]; f8b[3] = buf2[pos + 3]; f8b[4] = buf2[pos + 4]; f8b[5] = buf2[pos + 5]; f8b[6] = buf2[pos + 6]; f8b[7] = buf2[pos + 7]; return f64[0]; } function readDouble_f64_rev(buf2, pos) { f8b[7] = buf2[pos]; f8b[6] = buf2[pos + 1]; f8b[5] = buf2[pos + 2]; f8b[4] = buf2[pos + 3]; f8b[3] = buf2[pos + 4]; f8b[2] = buf2[pos + 5]; f8b[1] = buf2[pos + 6]; f8b[0] = buf2[pos + 7]; return f64[0]; } exports3.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; exports3.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; })(); else (function() { function writeDouble_ieee754(writeUint, off0, off1, val, buf2, pos) { var sign = val < 0 ? 1 : 0; if (sign) val = -val; if (val === 0) { writeUint(0, buf2, pos + off0); writeUint(1 / val > 0 ? ( /* positive */ 0 ) : ( /* negative 0 */ 2147483648 ), buf2, pos + off1); } else if (isNaN(val)) { writeUint(0, buf2, pos + off0); writeUint(2146959360, buf2, pos + off1); } else if (val > 17976931348623157e292) { writeUint(0, buf2, pos + off0); writeUint((sign << 31 | 2146435072) >>> 0, buf2, pos + off1); } else { var mantissa; if (val < 22250738585072014e-324) { mantissa = val / 5e-324; writeUint(mantissa >>> 0, buf2, pos + off0); writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf2, pos + off1); } else { var exponent = Math.floor(Math.log(val) / Math.LN2); if (exponent === 1024) exponent = 1023; mantissa = val * Math.pow(2, -exponent); writeUint(mantissa * 4503599627370496 >>> 0, buf2, pos + off0); writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf2, pos + off1); } } } exports3.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); exports3.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); function readDouble_ieee754(readUint, off0, off1, buf2, pos) { var lo = readUint(buf2, pos + off0), hi = readUint(buf2, pos + off1); var sign = (hi >> 31) * 2 + 1, exponent = hi >>> 20 & 2047, mantissa = 4294967296 * (hi & 1048575) + lo; return exponent === 2047 ? mantissa ? NaN : sign * Infinity : exponent === 0 ? sign * 5e-324 * mantissa : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); } exports3.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); exports3.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); })(); return exports3; } function writeUintLE(val, buf2, pos) { buf2[pos] = val & 255; buf2[pos + 1] = val >>> 8 & 255; buf2[pos + 2] = val >>> 16 & 255; buf2[pos + 3] = val >>> 24; } function writeUintBE(val, buf2, pos) { buf2[pos] = val >>> 24; buf2[pos + 1] = val >>> 16 & 255; buf2[pos + 2] = val >>> 8 & 255; buf2[pos + 3] = val & 255; } function readUintLE(buf2, pos) { return (buf2[pos] | buf2[pos + 1] << 8 | buf2[pos + 2] << 16 | buf2[pos + 3] << 24) >>> 0; } function readUintBE(buf2, pos) { return (buf2[pos] << 24 | buf2[pos + 1] << 16 | buf2[pos + 2] << 8 | buf2[pos + 3]) >>> 0; } } }); // node_modules/@protobufjs/inquire/index.js var require_inquire = __commonJS({ "node_modules/@protobufjs/inquire/index.js"(exports, module) { "use strict"; module.exports = inquire; function inquire(moduleName) { try { var mod = eval("quire".replace(/^/, "re"))(moduleName); if (mod && (mod.length || Object.keys(mod).length)) return mod; } catch (e) { } return null; } } }); // node_modules/@protobufjs/utf8/index.js var require_utf8 = __commonJS({ "node_modules/@protobufjs/utf8/index.js"(exports2) { "use strict"; var utf8 = exports2; utf8.length = function utf8_length(string2) { var len = 0, c = 0; for (var i = 0; i < string2.length; ++i) { c = string2.charCodeAt(i); if (c < 128) len += 1; else if (c < 2048) len += 2; else if ((c & 64512) === 55296 && (string2.charCodeAt(i + 1) & 64512) === 56320) { ++i; len += 4; } else len += 3; } return len; }; utf8.read = function utf8_read(buffer2, start, end) { var len = end - start; if (len < 1) return ""; var parts = null, chunk = [], i = 0, t; while (start < end) { t = buffer2[start++]; if (t < 128) chunk[i++] = t; else if (t > 191 && t < 224) chunk[i++] = (t & 31) << 6 | buffer2[start++] & 63; else if (t > 239 && t < 365) { t = ((t & 7) << 18 | (buffer2[start++] & 63) << 12 | (buffer2[start++] & 63) << 6 | buffer2[start++] & 63) - 65536; chunk[i++] = 55296 + (t >> 10); chunk[i++] = 56320 + (t & 1023); } else chunk[i++] = (t & 15) << 12 | (buffer2[start++] & 63) << 6 | buffer2[start++] & 63; if (i > 8191) { (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); i = 0; } } if (parts) { if (i) parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); return parts.join(""); } return String.fromCharCode.apply(String, chunk.slice(0, i)); }; utf8.write = function utf8_write(string2, buffer2, offset) { var start = offset, c1, c2; for (var i = 0; i < string2.length; ++i) { c1 = string2.charCodeAt(i); if (c1 < 128) { buffer2[offset++] = c1; } else if (c1 < 2048) { buffer2[offset++] = c1 >> 6 | 192; buffer2[offset++] = c1 & 63 | 128; } else if ((c1 & 64512) === 55296 && ((c2 = string2.charCodeAt(i + 1)) & 64512) === 56320) { c1 = 65536 + ((c1 & 1023) << 10) + (c2 & 1023); ++i; buffer2[offset++] = c1 >> 18 | 240; buffer2[offset++] = c1 >> 12 & 63 | 128; buffer2[offset++] = c1 >> 6 & 63 | 128; buffer2[offset++] = c1 & 63 | 128; } else { buffer2[offset++] = c1 >> 12 | 224; buffer2[offset++] = c1 >> 6 & 63 | 128; buffer2[offset++] = c1 & 63 | 128; } } return offset - start; }; } }); // node_modules/@protobufjs/pool/index.js var require_pool = __commonJS({ "node_modules/@protobufjs/pool/index.js"(exports2, module2) { "use strict"; module2.exports = pool; function pool(alloc3, slice2, size) { var SIZE = size || 8192; var MAX = SIZE >>> 1; var slab = null; var offset = SIZE; return function pool_alloc(size2) { if (size2 < 1 || size2 > MAX) return alloc3(size2); if (offset + size2 > SIZE) { slab = alloc3(SIZE); offset = 0; } var buf2 = slice2.call(slab, offset, offset += size2); if (offset & 7) offset = (offset | 7) + 1; return buf2; }; } } }); // node_modules/protobufjs/src/util/longbits.js var require_longbits = __commonJS({ "node_modules/protobufjs/src/util/longbits.js"(exports2, module2) { "use strict"; module2.exports = LongBits; var util2 = require_minimal(); function LongBits(lo, hi) { this.lo = lo >>> 0; this.hi = hi >>> 0; } var zero = LongBits.zero = new LongBits(0, 0); zero.toNumber = function() { return 0; }; zero.zzEncode = zero.zzDecode = function() { return this; }; zero.length = function() { return 1; }; var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; LongBits.fromNumber = function fromNumber(value) { if (value === 0) return zero; var sign = value < 0; if (sign) value = -value; var lo = value >>> 0, hi = (value - lo) / 4294967296 >>> 0; if (sign) { hi = ~hi >>> 0; lo = ~lo >>> 0; if (++lo > 4294967295) { lo = 0; if (++hi > 4294967295) hi = 0; } } return new LongBits(lo, hi); }; LongBits.from = function from7(value) { if (typeof value === "number") return LongBits.fromNumber(value); if (util2.isString(value)) { if (util2.Long) value = util2.Long.fromString(value); else return LongBits.fromNumber(parseInt(value, 10)); } return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; }; LongBits.prototype.toNumber = function toNumber(unsigned) { if (!unsigned && this.hi >>> 31) { var lo = ~this.lo + 1 >>> 0, hi = ~this.hi >>> 0; if (!lo) hi = hi + 1 >>> 0; return -(lo + hi * 4294967296); } return this.lo + this.hi * 4294967296; }; LongBits.prototype.toLong = function toLong(unsigned) { return util2.Long ? new util2.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; }; var charCodeAt = String.prototype.charCodeAt; LongBits.fromHash = function fromHash(hash2) { if (hash2 === zeroHash) return zero; return new LongBits( (charCodeAt.call(hash2, 0) | charCodeAt.call(hash2, 1) << 8 | charCodeAt.call(hash2, 2) << 16 | charCodeAt.call(hash2, 3) << 24) >>> 0, (charCodeAt.call(hash2, 4) | charCodeAt.call(hash2, 5) << 8 | charCodeAt.call(hash2, 6) << 16 | charCodeAt.call(hash2, 7) << 24) >>> 0 ); }; LongBits.prototype.toHash = function toHash() { return String.fromCharCode( this.lo & 255, this.lo >>> 8 & 255, this.lo >>> 16 & 255, this.lo >>> 24, this.hi & 255, this.hi >>> 8 & 255, this.hi >>> 16 & 255, this.hi >>> 24 ); }; LongBits.prototype.zzEncode = function zzEncode() { var mask = this.hi >> 31; this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; this.lo = (this.lo << 1 ^ mask) >>> 0; return this; }; LongBits.prototype.zzDecode = function zzDecode() { var mask = -(this.lo & 1); this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; this.hi = (this.hi >>> 1 ^ mask) >>> 0; return this; }; LongBits.prototype.length = function length5() { var part0 = this.lo, part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, part2 = this.hi >>> 24; return part2 === 0 ? part1 === 0 ? part0 < 16384 ? part0 < 128 ? 1 : 2 : part0 < 2097152 ? 3 : 4 : part1 < 16384 ? part1 < 128 ? 5 : 6 : part1 < 2097152 ? 7 : 8 : part2 < 128 ? 9 : 10; }; } }); // node_modules/protobufjs/src/util/minimal.js var require_minimal = __commonJS({ "node_modules/protobufjs/src/util/minimal.js"(exports2) { "use strict"; var util2 = exports2; util2.asPromise = require_aspromise(); util2.base64 = require_base64(); util2.EventEmitter = require_eventemitter(); util2.float = require_float(); util2.inquire = require_inquire(); util2.utf8 = require_utf8(); util2.pool = require_pool(); util2.LongBits = require_longbits(); util2.isNode = Boolean(typeof global !== "undefined" && global && global.process && global.process.versions && global.process.versions.node); util2.global = util2.isNode && global || typeof window !== "undefined" && window || typeof self !== "undefined" && self || exports2; util2.emptyArray = Object.freeze ? Object.freeze([]) : ( /* istanbul ignore next */ [] ); util2.emptyObject = Object.freeze ? Object.freeze({}) : ( /* istanbul ignore next */ {} ); util2.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) { return typeof value === "number" && isFinite(value) && Math.floor(value) === value; }; util2.isString = function isString(value) { return typeof value === "string" || value instanceof String; }; util2.isObject = function isObject(value) { return value && typeof value === "object"; }; util2.isset = /** * Checks if a property on a message is considered to be present. * @param {Object} obj Plain object or message instance * @param {string} prop Property name * @returns {boolean} `true` if considered to be present, otherwise `false` */ util2.isSet = function isSet(obj, prop) { var value = obj[prop]; if (value != null && obj.hasOwnProperty(prop)) return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; return false; }; util2.Buffer = function() { try { var Buffer2 = util2.inquire("buffer").Buffer; return Buffer2.prototype.utf8Write ? Buffer2 : ( /* istanbul ignore next */ null ); } catch (e) { return null; } }(); util2._Buffer_from = null; util2._Buffer_allocUnsafe = null; util2.newBuffer = function newBuffer(sizeOrArray) { return typeof sizeOrArray === "number" ? util2.Buffer ? util2._Buffer_allocUnsafe(sizeOrArray) : new util2.Array(sizeOrArray) : util2.Buffer ? util2._Buffer_from(sizeOrArray) : typeof Uint8Array === "undefined" ? sizeOrArray : new Uint8Array(sizeOrArray); }; util2.Array = typeof Uint8Array !== "undefined" ? Uint8Array : Array; util2.Long = /* istanbul ignore next */ util2.global.dcodeIO && /* istanbul ignore next */ util2.global.dcodeIO.Long || /* istanbul ignore next */ util2.global.Long || util2.inquire("long"); util2.key2Re = /^true|false|0|1$/; util2.key32Re = /^-?(?:0|[1-9][0-9]*)$/; util2.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; util2.longToHash = function longToHash(value) { return value ? util2.LongBits.from(value).toHash() : util2.LongBits.zeroHash; }; util2.longFromHash = function longFromHash(hash2, unsigned) { var bits = util2.LongBits.fromHash(hash2); if (util2.Long) return util2.Long.fromBits(bits.lo, bits.hi, unsigned); return bits.toNumber(Boolean(unsigned)); }; function merge2(dst, src5, ifNotSet) { for (var keys = Object.keys(src5), i = 0; i < keys.length; ++i) if (dst[keys[i]] === void 0 || !ifNotSet) dst[keys[i]] = src5[keys[i]]; return dst; } util2.merge = merge2; util2.lcFirst = function lcFirst(str3) { return str3.charAt(0).toLowerCase() + str3.substring(1); }; function newError(name5) { function CustomError(message2, properties) { if (!(this instanceof CustomError)) return new CustomError(message2, properties); Object.defineProperty(this, "message", { get: function() { return message2; } }); if (Error.captureStackTrace) Error.captureStackTrace(this, CustomError); else Object.defineProperty(this, "stack", { value: new Error().stack || "" }); if (properties) merge2(this, properties); } CustomError.prototype = Object.create(Error.prototype, { constructor: { value: CustomError, writable: true, enumerable: false, configurable: true }, name: { get: function get2() { return name5; }, set: void 0, enumerable: false, // configurable: false would accurately preserve the behavior of // the original, but I'm guessing that was not intentional. // For an actual error subclass, this property would // be configurable. configurable: true }, toString: { value: function value() { return this.name + ": " + this.message; }, writable: true, enumerable: false, configurable: true } }); return CustomError; } util2.newError = newError; util2.ProtocolError = newError("ProtocolError"); util2.oneOfGetter = function getOneOf(fieldNames) { var fieldMap = {}; for (var i = 0; i < fieldNames.length; ++i) fieldMap[fieldNames[i]] = 1; return function() { for (var keys = Object.keys(this), i2 = keys.length - 1; i2 > -1; --i2) if (fieldMap[keys[i2]] === 1 && this[keys[i2]] !== void 0 && this[keys[i2]] !== null) return keys[i2]; }; }; util2.oneOfSetter = function setOneOf(fieldNames) { return function(name5) { for (var i = 0; i < fieldNames.length; ++i) if (fieldNames[i] !== name5) delete this[fieldNames[i]]; }; }; util2.toJSONOptions = { longs: String, enums: String, bytes: String, json: true }; util2._configure = function() { var Buffer2 = util2.Buffer; if (!Buffer2) { util2._Buffer_from = util2._Buffer_allocUnsafe = null; return; } util2._Buffer_from = Buffer2.from !== Uint8Array.from && Buffer2.from || /* istanbul ignore next */ function Buffer_from(value, encoding) { return new Buffer2(value, encoding); }; util2._Buffer_allocUnsafe = Buffer2.allocUnsafe || /* istanbul ignore next */ function Buffer_allocUnsafe(size) { return new Buffer2(size); }; }; } }); // node_modules/protobufjs/src/reader.js var require_reader = __commonJS({ "node_modules/protobufjs/src/reader.js"(exports2, module2) { "use strict"; module2.exports = Reader; var util2 = require_minimal(); var BufferReader; var LongBits = util2.LongBits; var utf8 = util2.utf8; function indexOutOfRange(reader2, writeLength) { return RangeError("index out of range: " + reader2.pos + " + " + (writeLength || 1) + " > " + reader2.len); } function Reader(buffer2) { this.buf = buffer2; this.pos = 0; this.len = buffer2.length; } var create_array = typeof Uint8Array !== "undefined" ? function create_typed_array(buffer2) { if (buffer2 instanceof Uint8Array || Array.isArray(buffer2)) return new Reader(buffer2); throw Error("illegal buffer"); } : function create_array2(buffer2) { if (Array.isArray(buffer2)) return new Reader(buffer2); throw Error("illegal buffer"); }; var create5 = function create6() { return util2.Buffer ? function create_buffer_setup(buffer2) { return (Reader.create = function create_buffer(buffer3) { return util2.Buffer.isBuffer(buffer3) ? new BufferReader(buffer3) : create_array(buffer3); })(buffer2); } : create_array; }; Reader.create = create5(); Reader.prototype._slice = util2.Array.prototype.subarray || /* istanbul ignore next */ util2.Array.prototype.slice; Reader.prototype.uint32 = function read_uint32_setup() { var value = 4294967295; return function read_uint32() { value = (this.buf[this.pos] & 127) >>> 0; if (this.buf[this.pos++] < 128) return value; value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value; value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value; value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value; value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value; if ((this.pos += 5) > this.len) { this.pos = this.len; throw indexOutOfRange(this, 10); } return value; }; }(); Reader.prototype.int32 = function read_int32() { return this.uint32() | 0; }; Reader.prototype.sint32 = function read_sint32() { var value = this.uint32(); return value >>> 1 ^ -(value & 1) | 0; }; function readLongVarint() { var bits = new LongBits(0, 0); var i = 0; if (this.len - this.pos > 4) { for (; i < 4; ++i) { bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; if (this.buf[this.pos++] < 128) return bits; } bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; if (this.buf[this.pos++] < 128) return bits; i = 0; } else { for (; i < 3; ++i) { if (this.pos >= this.len) throw indexOutOfRange(this); bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; if (this.buf[this.pos++] < 128) return bits; } bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; return bits; } if (this.len - this.pos > 4) { for (; i < 5; ++i) { bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; if (this.buf[this.pos++] < 128) return bits; } } else { for (; i < 5; ++i) { if (this.pos >= this.len) throw indexOutOfRange(this); bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; if (this.buf[this.pos++] < 128) return bits; } } throw Error("invalid varint encoding"); } Reader.prototype.bool = function read_bool() { return this.uint32() !== 0; }; function readFixed32_end(buf2, end) { return (buf2[end - 4] | buf2[end - 3] << 8 | buf2[end - 2] << 16 | buf2[end - 1] << 24) >>> 0; } Reader.prototype.fixed32 = function read_fixed32() { if (this.pos + 4 > this.len) throw indexOutOfRange(this, 4); return readFixed32_end(this.buf, this.pos += 4); }; Reader.prototype.sfixed32 = function read_sfixed32() { if (this.pos + 4 > this.len) throw indexOutOfRange(this, 4); return readFixed32_end(this.buf, this.pos += 4) | 0; }; function readFixed64() { if (this.pos + 8 > this.len) throw indexOutOfRange(this, 8); return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); } Reader.prototype.float = function read_float() { if (this.pos + 4 > this.len) throw indexOutOfRange(this, 4); var value = util2.float.readFloatLE(this.buf, this.pos); this.pos += 4; return value; }; Reader.prototype.double = function read_double() { if (this.pos + 8 > this.len) throw indexOutOfRange(this, 4); var value = util2.float.readDoubleLE(this.buf, this.pos); this.pos += 8; return value; }; Reader.prototype.bytes = function read_bytes() { var length5 = this.uint32(), start = this.pos, end = this.pos + length5; if (end > this.len) throw indexOutOfRange(this, length5); this.pos += length5; if (Array.isArray(this.buf)) return this.buf.slice(start, end); if (start === end) { var nativeBuffer = util2.Buffer; return nativeBuffer ? nativeBuffer.alloc(0) : new this.buf.constructor(0); } return this._slice.call(this.buf, start, end); }; Reader.prototype.string = function read_string() { var bytes2 = this.bytes(); return utf8.read(bytes2, 0, bytes2.length); }; Reader.prototype.skip = function skip(length5) { if (typeof length5 === "number") { if (this.pos + length5 > this.len) throw indexOutOfRange(this, length5); this.pos += length5; } else { do { if (this.pos >= this.len) throw indexOutOfRange(this); } while (this.buf[this.pos++] & 128); } return this; }; Reader.prototype.skipType = function(wireType) { switch (wireType) { case 0: this.skip(); break; case 1: this.skip(8); break; case 2: this.skip(this.uint32()); break; case 3: while ((wireType = this.uint32() & 7) !== 4) { this.skipType(wireType); } break; case 5: this.skip(4); break; default: throw Error("invalid wire type " + wireType + " at offset " + this.pos); } return this; }; Reader._configure = function(BufferReader_) { BufferReader = BufferReader_; Reader.create = create5(); BufferReader._configure(); var fn = util2.Long ? "toLong" : ( /* istanbul ignore next */ "toNumber" ); util2.merge(Reader.prototype, { int64: function read_int64() { return readLongVarint.call(this)[fn](false); }, uint64: function read_uint64() { return readLongVarint.call(this)[fn](true); }, sint64: function read_sint64() { return readLongVarint.call(this).zzDecode()[fn](false); }, fixed64: function read_fixed64() { return readFixed64.call(this)[fn](true); }, sfixed64: function read_sfixed64() { return readFixed64.call(this)[fn](false); } }); }; } }); // node_modules/protobufjs/src/reader_buffer.js var require_reader_buffer = __commonJS({ "node_modules/protobufjs/src/reader_buffer.js"(exports2, module2) { "use strict"; module2.exports = BufferReader; var Reader = require_reader(); (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; var util2 = require_minimal(); function BufferReader(buffer2) { Reader.call(this, buffer2); } BufferReader._configure = function() { if (util2.Buffer) BufferReader.prototype._slice = util2.Buffer.prototype.slice; }; BufferReader.prototype.string = function read_string_buffer() { var len = this.uint32(); return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); }; BufferReader._configure(); } }); // node_modules/protobufjs/src/writer.js var require_writer = __commonJS({ "node_modules/protobufjs/src/writer.js"(exports2, module2) { "use strict"; module2.exports = Writer; var util2 = require_minimal(); var BufferWriter; var LongBits = util2.LongBits; var base642 = util2.base64; var utf8 = util2.utf8; function Op(fn, len, val) { this.fn = fn; this.len = len; this.next = void 0; this.val = val; } function noop() { } function State(writer2) { this.head = writer2.head; this.tail = writer2.tail; this.len = writer2.len; this.next = writer2.states; } function Writer() { this.len = 0; this.head = new Op(noop, 0, 0); this.tail = this.head; this.states = null; } var create5 = function create6() { return util2.Buffer ? function create_buffer_setup() { return (Writer.create = function create_buffer() { return new BufferWriter(); })(); } : function create_array() { return new Writer(); }; }; Writer.create = create5(); Writer.alloc = function alloc3(size) { return new util2.Array(size); }; if (util2.Array !== Array) Writer.alloc = util2.pool(Writer.alloc, util2.Array.prototype.subarray); Writer.prototype._push = function push(fn, len, val) { this.tail = this.tail.next = new Op(fn, len, val); this.len += len; return this; }; function writeByte(val, buf2, pos) { buf2[pos] = val & 255; } function writeVarint32(val, buf2, pos) { while (val > 127) { buf2[pos++] = val & 127 | 128; val >>>= 7; } buf2[pos] = val; } function VarintOp(len, val) { this.len = len; this.next = void 0; this.val = val; } VarintOp.prototype = Object.create(Op.prototype); VarintOp.prototype.fn = writeVarint32; Writer.prototype.uint32 = function write_uint32(value) { this.len += (this.tail = this.tail.next = new VarintOp( (value = value >>> 0) < 128 ? 1 : value < 16384 ? 2 : value < 2097152 ? 3 : value < 268435456 ? 4 : 5, value )).len; return this; }; Writer.prototype.int32 = function write_int32(value) { return value < 0 ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) : this.uint32(value); }; Writer.prototype.sint32 = function write_sint32(value) { return this.uint32((value << 1 ^ value >> 31) >>> 0); }; function writeVarint64(val, buf2, pos) { while (val.hi) { buf2[pos++] = val.lo & 127 | 128; val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; val.hi >>>= 7; } while (val.lo > 127) { buf2[pos++] = val.lo & 127 | 128; val.lo = val.lo >>> 7; } buf2[pos++] = val.lo; } Writer.prototype.uint64 = function write_uint64(value) { var bits = LongBits.from(value); return this._push(writeVarint64, bits.length(), bits); }; Writer.prototype.int64 = Writer.prototype.uint64; Writer.prototype.sint64 = function write_sint64(value) { var bits = LongBits.from(value).zzEncode(); return this._push(writeVarint64, bits.length(), bits); }; Writer.prototype.bool = function write_bool(value) { return this._push(writeByte, 1, value ? 1 : 0); }; function writeFixed32(val, buf2, pos) { buf2[pos] = val & 255; buf2[pos + 1] = val >>> 8 & 255; buf2[pos + 2] = val >>> 16 & 255; buf2[pos + 3] = val >>> 24; } Writer.prototype.fixed32 = function write_fixed32(value) { return this._push(writeFixed32, 4, value >>> 0); }; Writer.prototype.sfixed32 = Writer.prototype.fixed32; Writer.prototype.fixed64 = function write_fixed64(value) { var bits = LongBits.from(value); return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); }; Writer.prototype.sfixed64 = Writer.prototype.fixed64; Writer.prototype.float = function write_float(value) { return this._push(util2.float.writeFloatLE, 4, value); }; Writer.prototype.double = function write_double(value) { return this._push(util2.float.writeDoubleLE, 8, value); }; var writeBytes = util2.Array.prototype.set ? function writeBytes_set(val, buf2, pos) { buf2.set(val, pos); } : function writeBytes_for(val, buf2, pos) { for (var i = 0; i < val.length; ++i) buf2[pos + i] = val[i]; }; Writer.prototype.bytes = function write_bytes(value) { var len = value.length >>> 0; if (!len) return this._push(writeByte, 1, 0); if (util2.isString(value)) { var buf2 = Writer.alloc(len = base642.length(value)); base642.decode(value, buf2, 0); value = buf2; } return this.uint32(len)._push(writeBytes, len, value); }; Writer.prototype.string = function write_string(value) { var len = utf8.length(value); return len ? this.uint32(len)._push(utf8.write, len, value) : this._push(writeByte, 1, 0); }; Writer.prototype.fork = function fork() { this.states = new State(this); this.head = this.tail = new Op(noop, 0, 0); this.len = 0; return this; }; Writer.prototype.reset = function reset() { if (this.states) { this.head = this.states.head; this.tail = this.states.tail; this.len = this.states.len; this.states = this.states.next; } else { this.head = this.tail = new Op(noop, 0, 0); this.len = 0; } return this; }; Writer.prototype.ldelim = function ldelim() { var head = this.head, tail = this.tail, len = this.len; this.reset().uint32(len); if (len) { this.tail.next = head.next; this.tail = tail; this.len += len; } return this; }; Writer.prototype.finish = function finish() { var head = this.head.next, buf2 = this.constructor.alloc(this.len), pos = 0; while (head) { head.fn(head.val, buf2, pos); pos += head.len; head = head.next; } return buf2; }; Writer._configure = function(BufferWriter_) { BufferWriter = BufferWriter_; Writer.create = create5(); BufferWriter._configure(); }; } }); // node_modules/protobufjs/src/writer_buffer.js var require_writer_buffer = __commonJS({ "node_modules/protobufjs/src/writer_buffer.js"(exports2, module2) { "use strict"; module2.exports = BufferWriter; var Writer = require_writer(); (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; var util2 = require_minimal(); function BufferWriter() { Writer.call(this); } BufferWriter._configure = function() { BufferWriter.alloc = util2._Buffer_allocUnsafe; BufferWriter.writeBytesBuffer = util2.Buffer && util2.Buffer.prototype instanceof Uint8Array && util2.Buffer.prototype.set.name === "set" ? function writeBytesBuffer_set(val, buf2, pos) { buf2.set(val, pos); } : function writeBytesBuffer_copy(val, buf2, pos) { if (val.copy) val.copy(buf2, pos, 0, val.length); else for (var i = 0; i < val.length; ) buf2[pos++] = val[i++]; }; }; BufferWriter.prototype.bytes = function write_bytes_buffer(value) { if (util2.isString(value)) value = util2._Buffer_from(value, "base64"); var len = value.length >>> 0; this.uint32(len); if (len) this._push(BufferWriter.writeBytesBuffer, len, value); return this; }; function writeStringBuffer(val, buf2, pos) { if (val.length < 40) util2.utf8.write(val, buf2, pos); else if (buf2.utf8Write) buf2.utf8Write(val, pos); else buf2.write(val, pos); } BufferWriter.prototype.string = function write_string_buffer(value) { var len = util2.Buffer.byteLength(value); this.uint32(len); if (len) this._push(writeStringBuffer, len, value); return this; }; BufferWriter._configure(); } }); // node_modules/murmurhash3js-revisited/lib/murmurHash3js.js var require_murmurHash3js = __commonJS({ "node_modules/murmurhash3js-revisited/lib/murmurHash3js.js"(exports2, module2) { (function(root, undefined2) { "use strict"; var library = { "version": "3.0.0", "x86": {}, "x64": {}, "inputValidation": true }; function _validBytes(bytes2) { if (!Array.isArray(bytes2) && !ArrayBuffer.isView(bytes2)) { return false; } for (var i = 0; i < bytes2.length; i++) { if (!Number.isInteger(bytes2[i]) || bytes2[i] < 0 || bytes2[i] > 255) { return false; } } return true; } function _x86Multiply(m, n) { return (m & 65535) * n + (((m >>> 16) * n & 65535) << 16); } function _x86Rotl(m, n) { return m << n | m >>> 32 - n; } function _x86Fmix(h) { h ^= h >>> 16; h = _x86Multiply(h, 2246822507); h ^= h >>> 13; h = _x86Multiply(h, 3266489909); h ^= h >>> 16; return h; } function _x64Add(m, n) { m = [m[0] >>> 16, m[0] & 65535, m[1] >>> 16, m[1] & 65535]; n = [n[0] >>> 16, n[0] & 65535, n[1] >>> 16, n[1] & 65535]; var o = [0, 0, 0, 0]; o[3] += m[3] + n[3]; o[2] += o[3] >>> 16; o[3] &= 65535; o[2] += m[2] + n[2]; o[1] += o[2] >>> 16; o[2] &= 65535; o[1] += m[1] + n[1]; o[0] += o[1] >>> 16; o[1] &= 65535; o[0] += m[0] + n[0]; o[0] &= 65535; return [o[0] << 16 | o[1], o[2] << 16 | o[3]]; } function _x64Multiply(m, n) { m = [m[0] >>> 16, m[0] & 65535, m[1] >>> 16, m[1] & 65535]; n = [n[0] >>> 16, n[0] & 65535, n[1] >>> 16, n[1] & 65535]; var o = [0, 0, 0, 0]; o[3] += m[3] * n[3]; o[2] += o[3] >>> 16; o[3] &= 65535; o[2] += m[2] * n[3]; o[1] += o[2] >>> 16; o[2] &= 65535; o[2] += m[3] * n[2]; o[1] += o[2] >>> 16; o[2] &= 65535; o[1] += m[1] * n[3]; o[0] += o[1] >>> 16; o[1] &= 65535; o[1] += m[2] * n[2]; o[0] += o[1] >>> 16; o[1] &= 65535; o[1] += m[3] * n[1]; o[0] += o[1] >>> 16; o[1] &= 65535; o[0] += m[0] * n[3] + m[1] * n[2] + m[2] * n[1] + m[3] * n[0]; o[0] &= 65535; return [o[0] << 16 | o[1], o[2] << 16 | o[3]]; } function _x64Rotl(m, n) { n %= 64; if (n === 32) { return [m[1], m[0]]; } else if (n < 32) { return [m[0] << n | m[1] >>> 32 - n, m[1] << n | m[0] >>> 32 - n]; } else { n -= 32; return [m[1] << n | m[0] >>> 32 - n, m[0] << n | m[1] >>> 32 - n]; } } function _x64LeftShift(m, n) { n %= 64; if (n === 0) { return m; } else if (n < 32) { return [m[0] << n | m[1] >>> 32 - n, m[1] << n]; } else { return [m[1] << n - 32, 0]; } } function _x64Xor(m, n) { return [m[0] ^ n[0], m[1] ^ n[1]]; } function _x64Fmix(h) { h = _x64Xor(h, [0, h[0] >>> 1]); h = _x64Multiply(h, [4283543511, 3981806797]); h = _x64Xor(h, [0, h[0] >>> 1]); h = _x64Multiply(h, [3301882366, 444984403]); h = _x64Xor(h, [0, h[0] >>> 1]); return h; } library.x86.hash32 = function(bytes2, seed) { if (library.inputValidation && !_validBytes(bytes2)) { return undefined2; } seed = seed || 0; var remainder = bytes2.length % 4; var blocks = bytes2.length - remainder; var h1 = seed; var k1 = 0; var c1 = 3432918353; var c2 = 461845907; for (var i = 0; i < blocks; i = i + 4) { k1 = bytes2[i] | bytes2[i + 1] << 8 | bytes2[i + 2] << 16 | bytes2[i + 3] << 24; k1 = _x86Multiply(k1, c1); k1 = _x86Rotl(k1, 15); k1 = _x86Multiply(k1, c2); h1 ^= k1; h1 = _x86Rotl(h1, 13); h1 = _x86Multiply(h1, 5) + 3864292196; } k1 = 0; switch (remainder) { case 3: k1 ^= bytes2[i + 2] << 16; case 2: k1 ^= bytes2[i + 1] << 8; case 1: k1 ^= bytes2[i]; k1 = _x86Multiply(k1, c1); k1 = _x86Rotl(k1, 15); k1 = _x86Multiply(k1, c2); h1 ^= k1; } h1 ^= bytes2.length; h1 = _x86Fmix(h1); return h1 >>> 0; }; library.x86.hash128 = function(bytes2, seed) { if (library.inputValidation && !_validBytes(bytes2)) { return undefined2; } seed = seed || 0; var remainder = bytes2.length % 16; var blocks = bytes2.length - remainder; var h1 = seed; var h2 = seed; var h3 = seed; var h4 = seed; var k1 = 0; var k2 = 0; var k3 = 0; var k4 = 0; var c1 = 597399067; var c2 = 2869860233; var c3 = 951274213; var c4 = 2716044179; for (var i = 0; i < blocks; i = i + 16) { k1 = bytes2[i] | bytes2[i + 1] << 8 | bytes2[i + 2] << 16 | bytes2[i + 3] << 24; k2 = bytes2[i + 4] | bytes2[i + 5] << 8 | bytes2[i + 6] << 16 | bytes2[i + 7] << 24; k3 = bytes2[i + 8] | bytes2[i + 9] << 8 | bytes2[i + 10] << 16 | bytes2[i + 11] << 24; k4 = bytes2[i + 12] | bytes2[i + 13] << 8 | bytes2[i + 14] << 16 | bytes2[i + 15] << 24; k1 = _x86Multiply(k1, c1); k1 = _x86Rotl(k1, 15); k1 = _x86Multiply(k1, c2); h1 ^= k1; h1 = _x86Rotl(h1, 19); h1 += h2; h1 = _x86Multiply(h1, 5) + 1444728091; k2 = _x86Multiply(k2, c2); k2 = _x86Rotl(k2, 16); k2 = _x86Multiply(k2, c3); h2 ^= k2; h2 = _x86Rotl(h2, 17); h2 += h3; h2 = _x86Multiply(h2, 5) + 197830471; k3 = _x86Multiply(k3, c3); k3 = _x86Rotl(k3, 17); k3 = _x86Multiply(k3, c4); h3 ^= k3; h3 = _x86Rotl(h3, 15); h3 += h4; h3 = _x86Multiply(h3, 5) + 2530024501; k4 = _x86Multiply(k4, c4); k4 = _x86Rotl(k4, 18); k4 = _x86Multiply(k4, c1); h4 ^= k4; h4 = _x86Rotl(h4, 13); h4 += h1; h4 = _x86Multiply(h4, 5) + 850148119; } k1 = 0; k2 = 0; k3 = 0; k4 = 0; switch (remainder) { case 15: k4 ^= bytes2[i + 14] << 16; case 14: k4 ^= bytes2[i + 13] << 8; case 13: k4 ^= bytes2[i + 12]; k4 = _x86Multiply(k4, c4); k4 = _x86Rotl(k4, 18); k4 = _x86Multiply(k4, c1); h4 ^= k4; case 12: k3 ^= bytes2[i + 11] << 24; case 11: k3 ^= bytes2[i + 10] << 16; case 10: k3 ^= bytes2[i + 9] << 8; case 9: k3 ^= bytes2[i + 8]; k3 = _x86Multiply(k3, c3); k3 = _x86Rotl(k3, 17); k3 = _x86Multiply(k3, c4); h3 ^= k3; case 8: k2 ^= bytes2[i + 7] << 24; case 7: k2 ^= bytes2[i + 6] << 16; case 6: k2 ^= bytes2[i + 5] << 8; case 5: k2 ^= bytes2[i + 4]; k2 = _x86Multiply(k2, c2); k2 = _x86Rotl(k2, 16); k2 = _x86Multiply(k2, c3); h2 ^= k2; case 4: k1 ^= bytes2[i + 3] << 24; case 3: k1 ^= bytes2[i + 2] << 16; case 2: k1 ^= bytes2[i + 1] << 8; case 1: k1 ^= bytes2[i]; k1 = _x86Multiply(k1, c1); k1 = _x86Rotl(k1, 15); k1 = _x86Multiply(k1, c2); h1 ^= k1; } h1 ^= bytes2.length; h2 ^= bytes2.length; h3 ^= bytes2.length; h4 ^= bytes2.length; h1 += h2; h1 += h3; h1 += h4; h2 += h1; h3 += h1; h4 += h1; h1 = _x86Fmix(h1); h2 = _x86Fmix(h2); h3 = _x86Fmix(h3); h4 = _x86Fmix(h4); h1 += h2; h1 += h3; h1 += h4; h2 += h1; h3 += h1; h4 += h1; return ("00000000" + (h1 >>> 0).toString(16)).slice(-8) + ("00000000" + (h2 >>> 0).toString(16)).slice(-8) + ("00000000" + (h3 >>> 0).toString(16)).slice(-8) + ("00000000" + (h4 >>> 0).toString(16)).slice(-8); }; library.x64.hash128 = function(bytes2, seed) { if (library.inputValidation && !_validBytes(bytes2)) { return undefined2; } seed = seed || 0; var remainder = bytes2.length % 16; var blocks = bytes2.length - remainder; var h1 = [0, seed]; var h2 = [0, seed]; var k1 = [0, 0]; var k2 = [0, 0]; var c1 = [2277735313, 289559509]; var c2 = [1291169091, 658871167]; for (var i = 0; i < blocks; i = i + 16) { k1 = [bytes2[i + 4] | bytes2[i + 5] << 8 | bytes2[i + 6] << 16 | bytes2[i + 7] << 24, bytes2[i] | bytes2[i + 1] << 8 | bytes2[i + 2] << 16 | bytes2[i + 3] << 24]; k2 = [bytes2[i + 12] | bytes2[i + 13] << 8 | bytes2[i + 14] << 16 | bytes2[i + 15] << 24, bytes2[i + 8] | bytes2[i + 9] << 8 | bytes2[i + 10] << 16 | bytes2[i + 11] << 24]; k1 = _x64Multiply(k1, c1); k1 = _x64Rotl(k1, 31); k1 = _x64Multiply(k1, c2); h1 = _x64Xor(h1, k1); h1 = _x64Rotl(h1, 27); h1 = _x64Add(h1, h2); h1 = _x64Add(_x64Multiply(h1, [0, 5]), [0, 1390208809]); k2 = _x64Multiply(k2, c2); k2 = _x64Rotl(k2, 33); k2 = _x64Multiply(k2, c1); h2 = _x64Xor(h2, k2); h2 = _x64Rotl(h2, 31); h2 = _x64Add(h2, h1); h2 = _x64Add(_x64Multiply(h2, [0, 5]), [0, 944331445]); } k1 = [0, 0]; k2 = [0, 0]; switch (remainder) { case 15: k2 = _x64Xor(k2, _x64LeftShift([0, bytes2[i + 14]], 48)); case 14: k2 = _x64Xor(k2, _x64LeftShift([0, bytes2[i + 13]], 40)); case 13: k2 = _x64Xor(k2, _x64LeftShift([0, bytes2[i + 12]], 32)); case 12: k2 = _x64Xor(k2, _x64LeftShift([0, bytes2[i + 11]], 24)); case 11: k2 = _x64Xor(k2, _x64LeftShift([0, bytes2[i + 10]], 16)); case 10: k2 = _x64Xor(k2, _x64LeftShift([0, bytes2[i + 9]], 8)); case 9: k2 = _x64Xor(k2, [0, bytes2[i + 8]]); k2 = _x64Multiply(k2, c2); k2 = _x64Rotl(k2, 33); k2 = _x64Multiply(k2, c1); h2 = _x64Xor(h2, k2); case 8: k1 = _x64Xor(k1, _x64LeftShift([0, bytes2[i + 7]], 56)); case 7: k1 = _x64Xor(k1, _x64LeftShift([0, bytes2[i + 6]], 48)); case 6: k1 = _x64Xor(k1, _x64LeftShift([0, bytes2[i + 5]], 40)); case 5: k1 = _x64Xor(k1, _x64LeftShift([0, bytes2[i + 4]], 32)); case 4: k1 = _x64Xor(k1, _x64LeftShift([0, bytes2[i + 3]], 24)); case 3: k1 = _x64Xor(k1, _x64LeftShift([0, bytes2[i + 2]], 16)); case 2: k1 = _x64Xor(k1, _x64LeftShift([0, bytes2[i + 1]], 8)); case 1: k1 = _x64Xor(k1, [0, bytes2[i]]); k1 = _x64Multiply(k1, c1); k1 = _x64Rotl(k1, 31); k1 = _x64Multiply(k1, c2); h1 = _x64Xor(h1, k1); } h1 = _x64Xor(h1, [0, bytes2.length]); h2 = _x64Xor(h2, [0, bytes2.length]); h1 = _x64Add(h1, h2); h2 = _x64Add(h2, h1); h1 = _x64Fmix(h1); h2 = _x64Fmix(h2); h1 = _x64Add(h1, h2); h2 = _x64Add(h2, h1); return ("00000000" + (h1[0] >>> 0).toString(16)).slice(-8) + ("00000000" + (h1[1] >>> 0).toString(16)).slice(-8) + ("00000000" + (h2[0] >>> 0).toString(16)).slice(-8) + ("00000000" + (h2[1] >>> 0).toString(16)).slice(-8); }; if (typeof exports2 !== "undefined") { if (typeof module2 !== "undefined" && module2.exports) { exports2 = module2.exports = library; } exports2.murmurHash3 = library; } else if (typeof define === "function" && define.amd) { define([], function() { return library; }); } else { library._murmurHash3 = root.murmurHash3; library.noConflict = function() { root.murmurHash3 = library._murmurHash3; library._murmurHash3 = undefined2; library.noConflict = undefined2; return library; }; root.murmurHash3 = library; } })(exports2); } }); // node_modules/murmurhash3js-revisited/index.js var require_murmurhash3js_revisited = __commonJS({ "node_modules/murmurhash3js-revisited/index.js"(exports2, module2) { module2.exports = require_murmurHash3js(); } }); // node_modules/sparse-array/index.js var require_sparse_array = __commonJS({ "node_modules/sparse-array/index.js"(exports2, module2) { "use strict"; var BITS_PER_BYTE = 7; module2.exports = class SparseArray { constructor() { this._bitArrays = []; this._data = []; this._length = 0; this._changedLength = false; this._changedData = false; } set(index, value) { let pos = this._internalPositionFor(index, false); if (value === void 0) { if (pos !== -1) { this._unsetInternalPos(pos); this._unsetBit(index); this._changedLength = true; this._changedData = true; } } else { let needsSort = false; if (pos === -1) { pos = this._data.length; this._setBit(index); this._changedData = true; } else { needsSort = true; } this._setInternalPos(pos, index, value, needsSort); this._changedLength = true; } } unset(index) { this.set(index, void 0); } get(index) { this._sortData(); const pos = this._internalPositionFor(index, true); if (pos === -1) { return void 0; } return this._data[pos][1]; } push(value) { this.set(this.length, value); return this.length; } get length() { this._sortData(); if (this._changedLength) { const last2 = this._data[this._data.length - 1]; this._length = last2 ? last2[0] + 1 : 0; this._changedLength = false; } return this._length; } forEach(iterator) { let i = 0; while (i < this.length) { iterator(this.get(i), i, this); i++; } } map(iterator) { let i = 0; let mapped = new Array(this.length); while (i < this.length) { mapped[i] = iterator(this.get(i), i, this); i++; } return mapped; } reduce(reducer, initialValue) { let i = 0; let acc = initialValue; while (i < this.length) { const value = this.get(i); acc = reducer(acc, value, i); i++; } return acc; } find(finder) { let i = 0, found, last2; while (i < this.length && !found) { last2 = this.get(i); found = finder(last2); i++; } return found ? last2 : void 0; } _internalPositionFor(index, noCreate) { const bytePos = this._bytePosFor(index, noCreate); if (bytePos >= this._bitArrays.length) { return -1; } const byte = this._bitArrays[bytePos]; const bitPos = index - bytePos * BITS_PER_BYTE; const exists3 = (byte & 1 << bitPos) > 0; if (!exists3) { return -1; } const previousPopCount = this._bitArrays.slice(0, bytePos).reduce(popCountReduce, 0); const mask = ~(4294967295 << bitPos + 1); const bytePopCount = popCount(byte & mask); const arrayPos = previousPopCount + bytePopCount - 1; return arrayPos; } _bytePosFor(index, noCreate) { const bytePos = Math.floor(index / BITS_PER_BYTE); const targetLength = bytePos + 1; while (!noCreate && this._bitArrays.length < targetLength) { this._bitArrays.push(0); } return bytePos; } _setBit(index) { const bytePos = this._bytePosFor(index, false); this._bitArrays[bytePos] |= 1 << index - bytePos * BITS_PER_BYTE; } _unsetBit(index) { const bytePos = this._bytePosFor(index, false); this._bitArrays[bytePos] &= ~(1 << index - bytePos * BITS_PER_BYTE); } _setInternalPos(pos, index, value, needsSort) { const data = this._data; const elem = [index, value]; if (needsSort) { this._sortData(); data[pos] = elem; } else { if (data.length) { if (data[data.length - 1][0] >= index) { data.push(elem); } else if (data[0][0] <= index) { data.unshift(elem); } else { const randomIndex = Math.round(data.length / 2); this._data = data.slice(0, randomIndex).concat(elem).concat(data.slice(randomIndex)); } } else { this._data.push(elem); } this._changedData = true; this._changedLength = true; } } _unsetInternalPos(pos) { this._data.splice(pos, 1); } _sortData() { if (this._changedData) { this._data.sort(sortInternal); } this._changedData = false; } bitField() { const bytes2 = []; let pendingBitsForResultingByte = 8; let pendingBitsForNewByte = 0; let resultingByte = 0; let newByte; const pending = this._bitArrays.slice(); while (pending.length || pendingBitsForNewByte) { if (pendingBitsForNewByte === 0) { newByte = pending.shift(); pendingBitsForNewByte = 7; } const usingBits = Math.min(pendingBitsForNewByte, pendingBitsForResultingByte); const mask = ~(255 << usingBits); const masked = newByte & mask; resultingByte |= masked << 8 - pendingBitsForResultingByte; newByte = newByte >>> usingBits; pendingBitsForNewByte -= usingBits; pendingBitsForResultingByte -= usingBits; if (!pendingBitsForResultingByte || !pendingBitsForNewByte && !pending.length) { bytes2.push(resultingByte); resultingByte = 0; pendingBitsForResultingByte = 8; } } for (var i = bytes2.length - 1; i > 0; i--) { const value = bytes2[i]; if (value === 0) { bytes2.pop(); } else { break; } } return bytes2; } compactArray() { this._sortData(); return this._data.map(valueOnly); } }; function popCountReduce(count, byte) { return count + popCount(byte); } function popCount(_v) { let v = _v; v = v - (v >> 1 & 1431655765); v = (v & 858993459) + (v >> 2 & 858993459); return (v + (v >> 4) & 252645135) * 16843009 >> 24; } function sortInternal(a, b) { return a[0] - b[0]; } function valueOnly(elem) { return elem[1]; } } }); // node_modules/eventemitter3/index.js var require_eventemitter3 = __commonJS({ "node_modules/eventemitter3/index.js"(exports2, module2) { "use strict"; var has = Object.prototype.hasOwnProperty; var prefix = "~"; function Events2() { } if (Object.create) { Events2.prototype = /* @__PURE__ */ Object.create(null); if (!new Events2().__proto__) prefix = false; } function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } function addListener(emitter, event, fn, context, once) { if (typeof fn !== "function") { throw new TypeError("The listener must be a function"); } var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; } function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events2(); else delete emitter._events[evt]; } function EventEmitter3() { this._events = new Events2(); this._eventsCount = 0; } EventEmitter3.prototype.eventNames = function eventNames() { var names = [], events, name5; if (this._eventsCount === 0) return names; for (name5 in events = this._events) { if (has.call(events, name5)) names.push(prefix ? name5.slice(1) : name5); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)); } return names; }; EventEmitter3.prototype.listeners = function listeners(event) { var evt = prefix ? prefix + event : event, handlers = this._events[evt]; if (!handlers) return []; if (handlers.fn) return [handlers.fn]; for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { ee[i] = handlers[i].fn; } return ee; }; EventEmitter3.prototype.listenerCount = function listenerCount(event) { var evt = prefix ? prefix + event : event, listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; EventEmitter3.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt], len = arguments.length, args, i; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, void 0, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i = 1, args = new Array(len - 1); i < len; i++) { args[i - 1] = arguments[i]; } listeners.fn.apply(listeners.context, args); } else { var length5 = listeners.length, j; for (i = 0; i < length5; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, void 0, true); switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; default: if (!args) for (j = 1, args = new Array(len - 1); j < len; j++) { args[j - 1] = arguments[j]; } listeners[i].fn.apply(listeners[i].context, args); } } } return true; }; EventEmitter3.prototype.on = function on(event, fn, context) { return addListener(this, event, fn, context, false); }; EventEmitter3.prototype.once = function once(event, fn, context) { return addListener(this, event, fn, context, true); }; EventEmitter3.prototype.removeListener = function removeListener(event, fn, context, once) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) { clearEvent(this, evt); } } else { for (var i = 0, events = [], length5 = listeners.length; i < length5; i++) { if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) { events.push(listeners[i]); } } if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt); } return this; }; EventEmitter3.prototype.removeAllListeners = function removeAllListeners(event) { var evt; if (event) { evt = prefix ? prefix + event : event; if (this._events[evt]) clearEvent(this, evt); } else { this._events = new Events2(); this._eventsCount = 0; } return this; }; EventEmitter3.prototype.off = EventEmitter3.prototype.removeListener; EventEmitter3.prototype.addListener = EventEmitter3.prototype.on; EventEmitter3.prefixed = prefix; EventEmitter3.EventEmitter = EventEmitter3; if ("undefined" !== typeof module2) { module2.exports = EventEmitter3; } } }); // dist/esm/src/index.js var src_exports3 = {}; __export(src_exports3, { AllowAllTenantGate: () => AllowAllTenantGate, Cid: () => Cid, DataStoreLevel: () => DataStoreLevel, DataStream: () => DataStream, DateSort: () => DateSort, Dwn: () => Dwn, DwnConstant: () => DwnConstant, DwnError: () => DwnError, DwnErrorCode: () => DwnErrorCode, DwnInterfaceName: () => DwnInterfaceName, DwnMethodName: () => DwnMethodName, Encoder: () => Encoder2, Encryption: () => Encryption, EncryptionAlgorithm: () => EncryptionAlgorithm, EventEmitterStream: () => EventEmitterStream, EventLogLevel: () => EventLogLevel, EventsGet: () => EventsGet2, EventsQuery: () => EventsQuery2, EventsSubscribe: () => EventsSubscribe2, HdKey: () => HdKey, Jws: () => Jws, KeyDerivationScheme: () => KeyDerivationScheme, Message: () => Message, MessageStoreLevel: () => MessageStoreLevel, MessagesGet: () => MessagesGet2, PermissionsProtocol: () => PermissionsProtocol, PrivateKeySigner: () => PrivateKeySigner, Protocols: () => Protocols, ProtocolsConfigure: () => ProtocolsConfigure2, ProtocolsQuery: () => ProtocolsQuery2, Records: () => Records, RecordsDelete: () => RecordsDelete2, RecordsQuery: () => RecordsQuery2, RecordsRead: () => RecordsRead2, RecordsSubscribe: () => RecordsSubscribe2, RecordsWrite: () => RecordsWrite2, Secp256k1: () => Secp256k1, Secp256r1: () => Secp256r1, SortDirection: () => SortDirection, TestDataGenerator: () => TestDataGenerator, Time: () => Time, authenticate: () => authenticate, executeUnlessAborted: () => executeUnlessAborted }); module.exports = __toCommonJS(src_exports3); // dist/esm/src/utils/jws.js var import_isPlainObject = __toESM(require("lodash/isPlainObject.js"), 1); // node_modules/multiformats/src/bases/base64.js var base64_exports = {}; __export(base64_exports, { base64: () => base64, base64pad: () => base64pad, base64url: () => base64url, base64urlpad: () => base64urlpad }); // node_modules/multiformats/vendor/base-x.js function base(ALPHABET, name5) { 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 encode16(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 length5 = 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 < length5) && 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"); } length5 = i2; pbegin++; } var it2 = size - length5; while (it2 !== size && b58[it2] === 0) { it2++; } var str3 = LEADER.repeat(zeroes); for (; it2 < size; ++it2) { str3 += ALPHABET.charAt(b58[it2]); } return str3; } 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 length5 = 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 < length5) && 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"); } length5 = i2; psz++; } if (source[psz] === " ") { return; } var it4 = size - length5; 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 decode23(string2) { var buffer2 = decodeUnsafe(string2); if (buffer2) { return buffer2; } throw new Error(`Non-${name5} character`); } return { encode: encode16, decodeUnsafe, decode: decode23 }; } var src = base; var _brrp__multiformats_scope_baseX = src; var base_x_default = _brrp__multiformats_scope_baseX; // node_modules/multiformats/src/bytes.js var empty = new Uint8Array(0); var 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; }; var 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"); }; var fromString = (str3) => new TextEncoder().encode(str3); var toString = (b) => new TextDecoder().decode(b); // node_modules/multiformats/src/bases/base.js var Encoder = class { /** * @param {Base} name * @param {Prefix} prefix * @param {(bytes:Uint8Array) => string} baseEncode */ constructor(name5, prefix, baseEncode) { this.name = name5; this.prefix = prefix; this.baseEncode = baseEncode; } /** * @param {Uint8Array} bytes * @returns {API.Multibase} */ encode(bytes2) { if (bytes2 instanceof Uint8Array) { return `${this.prefix}${this.baseEncode(bytes2)}`; } else { throw Error("Unknown type, must be binary type"); } } }; var Decoder = class { /** * @param {Base} name * @param {Prefix} prefix * @param {(text:string) => Uint8Array} baseDecode */ constructor(name5, prefix, baseDecode) { this.name = name5; this.prefix = prefix; if (prefix.codePointAt(0) === void 0) { throw new Error("Invalid prefix character"); } this.prefixCodePoint = /** @type {number} */ prefix.codePointAt(0); this.baseDecode = baseDecode; } /** * @param {string} text */ 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"); } } /** * @template {string} OtherPrefix * @param {API.UnibaseDecoder|ComposedDecoder} decoder * @returns {ComposedDecoder} */ or(decoder) { return or(this, decoder); } }; var ComposedDecoder = class { /** * @param {Decoders} decoders */ constructor(decoders) { this.decoders = decoders; } /** * @template {string} OtherPrefix * @param {API.UnibaseDecoder|ComposedDecoder} decoder * @returns {ComposedDecoder} */ or(decoder) { return or(this, decoder); } /** * @param {string} input * @returns {Uint8Array} */ decode(input) { const prefix = ( /** @type {Prefix} */ input[0] ); const decoder = this.decoders[prefix]; if (decoder) { return decoder.decode(input); } else { throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); } } }; var or = (left, right) => new ComposedDecoder( /** @type {Decoders} */ { ...left.decoders || { [ /** @type API.UnibaseDecoder */ left.prefix ]: left }, ...right.decoders || { [ /** @type API.UnibaseDecoder */ right.prefix ]: right } } ); var Codec = class { /** * @param {Base} name * @param {Prefix} prefix * @param {(bytes:Uint8Array) => string} baseEncode * @param {(text:string) => Uint8Array} baseDecode */ constructor(name5, prefix, baseEncode, baseDecode) { this.name = name5; this.prefix = prefix; this.baseEncode = baseEncode; this.baseDecode = baseDecode; this.encoder = new Encoder(name5, prefix, baseEncode); this.decoder = new Decoder(name5, prefix, baseDecode); } /** * @param {Uint8Array} input */ encode(input) { return this.encoder.encode(input); } /** * @param {string} input */ decode(input) { return this.decoder.decode(input); } }; var from = ({ name: name5, prefix, encode: encode16, decode: decode23 }) => new Codec(name5, prefix, encode16, decode23); var baseX = ({ prefix, name: name5, alphabet: alphabet2 }) => { const { encode: encode16, decode: decode23 } = base_x_default(alphabet2, name5); return from({ prefix, name: name5, encode: encode16, /** * @param {string} text */ decode: (text) => coerce(decode23(text)) }); }; var decode = (string2, alphabet2, bitsPerChar, name5) => { const codes = {}; for (let i = 0; i < alphabet2.length; ++i) { codes[alphabet2[i]] = i; } let end = string2.length; while (string2[end - 1] === "=") { --end; } const out = new Uint8Array(end * bitsPerChar / 8 | 0); let bits = 0; let buffer2 = 0; let written = 0; for (let i = 0; i < end; ++i) { const value = codes[string2[i]]; if (value === void 0) { throw new SyntaxError(`Non-${name5} character`); } buffer2 = buffer2 << bitsPerChar | value; bits += bitsPerChar; if (bits >= 8) { bits -= 8; out[written++] = 255 & buffer2 >> bits; } } if (bits >= bitsPerChar || 255 & buffer2 << 8 - bits) { throw new SyntaxError("Unexpected end of data"); } return out; }; var encode = (data, alphabet2, bitsPerChar) => { const pad = alphabet2[alphabet2.length - 1] === "="; const mask = (1 << bitsPerChar) - 1; let out = ""; let bits = 0; let buffer2 = 0; for (let i = 0; i < data.length; ++i) { buffer2 = buffer2 << 8 | data[i]; bits += 8; while (bits > bitsPerChar) { bits -= bitsPerChar; out += alphabet2[mask & buffer2 >> bits]; } } if (bits) { out += alphabet2[mask & buffer2 << bitsPerChar - bits]; } if (pad) { while (out.length * bitsPerChar & 7) { out += "="; } } return out; }; var rfc4648 = ({ name: name5, prefix, bitsPerChar, alphabet: alphabet2 }) => { return from({ prefix, name: name5, encode(input) { return encode(input, alphabet2, bitsPerChar); }, decode(input) { return decode(input, alphabet2, bitsPerChar, name5); } }); }; // node_modules/multiformats/src/bases/base64.js 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 }); // dist/esm/src/utils/encoder.js var textEncoder = new TextEncoder(); var textDecoder = new TextDecoder(); var Encoder2 = class { static base64UrlToBytes(base64urlString) { const content = base64url.baseDecode(base64urlString); return content; } static base64UrlToObject(base64urlString) { const payloadBytes = base64url.baseDecode(base64urlString); const payloadObject = Encoder2.bytesToObject(payloadBytes); return payloadObject; } static bytesToBase64Url(bytes2) { const base64UrlString = base64url.baseEncode(bytes2); return base64UrlString; } static bytesToString(content) { const bytes2 = textDecoder.decode(content); return bytes2; } static bytesToObject(content) { const contentString = Encoder2.bytesToString(content); const contentObject = JSON.parse(contentString); return contentObject; } static objectToBytes(obj) { const objectString = JSON.stringify(obj); const objectBytes = textEncoder.encode(objectString); return objectBytes; } static stringToBase64Url(content) { const bytes2 = textEncoder.encode(content); const base64UrlString = base64url.baseEncode(bytes2); return base64UrlString; } static stringToBytes(content) { const bytes2 = textEncoder.encode(content); return bytes2; } }; // node_modules/@noble/ed25519/index.js var P = 2n ** 255n - 19n; var N = 2n ** 252n + 27742317777372353535851937790883648493n; var Gx = 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an; var Gy = 0x6666666666666666666666666666666666666666666666666666666666666658n; var CURVE = { a: -1n, d: 37095705934669439343138083508754565189542113879843219016388785533085940283555n, p: P, n: N, h: 8, Gx, Gy // field prime, curve (group) order, cofactor }; var err = (m = "") => { throw new Error(m); }; var str = (s) => typeof s === "string"; var au8 = (a, l) => ( // is Uint8Array (of specific length) !(a instanceof Uint8Array) || typeof l === "number" && l > 0 && a.length !== l ? err("Uint8Array expected") : a ); var u8n = (data) => new Uint8Array(data); var toU8 = (a, len) => au8(str(a) ? h2b(a) : u8n(a), len); var mod2 = (a, b = P) => { let r = a % b; return r >= 0n ? r : b + r; }; var isPoint = (p) => p instanceof Point ? p : err("Point expected"); var Gpows = void 0; var Point = class { constructor(ex, ey, ez, et) { this.ex = ex; this.ey = ey; this.ez = ez; this.et = et; } static fromAffine(p) { return new Point(p.x, p.y, 1n, mod2(p.x * p.y)); } static fromHex(hex, strict = true) { const { d } = CURVE; hex = toU8(hex, 32); const normed = hex.slice(); normed[31] = hex[31] & ~128; const y = b2n_LE(normed); if (y === 0n) { } else { if (strict && !(0n < y && y < P)) err("bad y coord 1"); if (!strict && !(0n < y && y < 2n ** 256n)) err("bad y coord 2"); } const y2 = mod2(y * y); const u = mod2(y2 - 1n); const v = mod2(d * y2 + 1n); let { isValid, value: x } = uvRatio(u, v); if (!isValid) err("bad y coordinate 3"); const isXOdd = (x & 1n) === 1n; const isHeadOdd = (hex[31] & 128) !== 0; if (isHeadOdd !== isXOdd) x = mod2(-x); return new Point(x, y, 1n, mod2(x * y)); } get x() { return this.toAffine().x; } // .x, .y will call expensive toAffine. get y() { return this.toAffine().y; } // Should be used with care. equals(other) { const { ex: X1, ey: Y1, ez: Z1 } = this; const { ex: X2, ey: Y2, ez: Z2 } = isPoint(other); const X1Z2 = mod2(X1 * Z2), X2Z1 = mod2(X2 * Z1); const Y1Z2 = mod2(Y1 * Z2), Y2Z1 = mod2(Y2 * Z1); return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; } is0() { return this.equals(I); } negate() { return new Point(mod2(-this.ex), this.ey, this.ez, mod2(-this.et)); } double() { const { ex: X1, ey: Y1, ez: Z1 } = this; const { a } = CURVE; const A = mod2(X1 * X1); const B = mod2(Y1 * Y1); const C = mod2(2n * mod2(Z1 * Z1)); const D = mod2(a * A); const x1y1 = X1 + Y1; const E = mod2(mod2(x1y1 * x1y1) - A - B); const G3 = D + B; const F = G3 - C; const H = D - B; const X3 = mod2(E * F); const Y3 = mod2(G3 * H); const T3 = mod2(E * H); const Z3 = mod2(F * G3); return new Point(X3, Y3, Z3, T3); } add(other) { const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; const { ex: X2, ey: Y2, ez: Z2, et: T2 } = isPoint(other); const { a, d } = CURVE; const A = mod2(X1 * X2); const B = mod2(Y1 * Y2); const C = mod2(T1 * d * T2); const D = mod2(Z1 * Z2); const E = mod2((X1 + Y1) * (X2 + Y2) - A - B); const F = mod2(D - C); const G3 = mod2(D + C); const H = mod2(B - a * A); const X3 = mod2(E * F); const Y3 = mod2(G3 * H); const T3 = mod2(E * H); const Z3 = mod2(F * G3); return new Point(X3, Y3, Z3, T3); } mul(n, safe = true) { if (n === 0n) return safe === true ? err("cannot multiply by 0") : I; if (!(typeof n === "bigint" && 0n < n && n < N)) err("invalid scalar, must be < L"); if (!safe && this.is0() || n === 1n) return this; if (this.equals(G)) return wNAF(n).p; let p = I, f = G; for (let d = this; n > 0n; d = d.double(), n >>= 1n) { if (n & 1n) p = p.add(d); else if (safe) f = f.add(d); } return p; } multiply(scalar) { return this.mul(scalar); } // Aliases for compatibilty clearCofactor() { return this.mul(BigInt(CURVE.h), false); } // multiply by cofactor isSmallOrder() { return this.clearCofactor().is0(); } // check if P is small order isTorsionFree() { let p = this.mul(N / 2n, false).double(); if (N % 2n) p = p.add(this); return p.is0(); } toAffine() { const { ex: x, ey: y, ez: z } = this; if (this.is0()) return { x: 0n, y: 0n }; const iz = invert(z); if (mod2(z * iz) !== 1n) err("invalid inverse"); return { x: mod2(x * iz), y: mod2(y * iz) }; } toRawBytes() { const { x, y } = this.toAffine(); const b = n2b_32LE(y); b[31] |= x & 1n ? 128 : 0; return b; } toHex() { return b2h(this.toRawBytes()); } // encode to hex string }; Point.BASE = new Point(Gx, Gy, 1n, mod2(Gx * Gy)); Point.ZERO = new Point(0n, 1n, 1n, 0n); var { BASE: G, ZERO: I } = Point; var padh = (num, pad) => num.toString(16).padStart(pad, "0"); var b2h = (b) => Array.from(b).map((e) => padh(e, 2)).join(""); var h2b = (hex) => { const l = hex.length; if (!str(hex) || l % 2) err("hex invalid 1"); const arr = u8n(l / 2); for (let i = 0; i < arr.length; i++) { const j = i * 2; const h = hex.slice(j, j + 2); const b = Number.parseInt(h, 16); if (Number.isNaN(b) || b < 0) err("hex invalid 2"); arr[i] = b; } return arr; }; var n2b_32LE = (num) => h2b(padh(num, 32 * 2)).reverse(); var b2n_LE = (b) => BigInt("0x" + b2h(u8n(au8(b)).reverse())); var concatB = (...arrs) => { const r = u8n(arrs.reduce((sum, a) => sum + au8(a).length, 0)); let pad = 0; arrs.forEach((a) => { r.set(a, pad); pad += a.length; }); return r; }; var invert = (num, md = P) => { if (num === 0n || md <= 0n) err("no inverse n=" + num + " mod=" + md); let a = mod2(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n; while (a !== 0n) { const q = b / a, r = b % a; const m = x - u * q, n = y - v * q; b = a, a = r, x = u, y = v, u = m, v = n; } return b === 1n ? mod2(x, md) : err("no inverse"); }; var pow2 = (x, power) => { let r = x; while (power-- > 0n) { r *= r; r %= P; } return r; }; var pow_2_252_3 = (x) => { const x2 = x * x % P; const b2 = x2 * x % P; const b4 = pow2(b2, 2n) * b2 % P; const b5 = pow2(b4, 1n) * x % P; const b10 = pow2(b5, 5n) * b5 % P; const b20 = pow2(b10, 10n) * b10 % P; const b40 = pow2(b20, 20n) * b20 % P; const b80 = pow2(b40, 40n) * b40 % P; const b160 = pow2(b80, 80n) * b80 % P; const b240 = pow2(b160, 80n) * b80 % P; const b250 = pow2(b240, 10n) * b10 % P; const pow_p_5_8 = pow2(b250, 2n) * x % P; return { pow_p_5_8, b2 }; }; var RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n; var uvRatio = (u, v) => { const v3 = mod2(v * v * v); const v7 = mod2(v3 * v3 * v); const pow3 = pow_2_252_3(u * v7).pow_p_5_8; let x = mod2(u * v3 * pow3); const vx2 = mod2(v * x * x); const root1 = x; const root2 = mod2(x * RM1); const useRoot1 = vx2 === u; const useRoot2 = vx2 === mod2(-u); const noRoot = vx2 === mod2(-u * RM1); if (useRoot1) x = root1; if (useRoot2 || noRoot) x = root2; if ((mod2(x) & 1n) === 1n) x = mod2(-x); return { isValid: useRoot1 || useRoot2, value: x }; }; var modL_LE = (hash2) => mod2(b2n_LE(hash2), N); var _shaS; var sha512a = (...m) => etc.sha512Async(...m); var sha512s = (...m) => ( // Sync SHA512, not set by default typeof _shaS === "function" ? _shaS(...m) : err("etc.sha512Sync not set") ); var hash2extK = (hashed) => { const head = hashed.slice(0, 32); head[0] &= 248; head[31] &= 127; head[31] |= 64; const prefix = hashed.slice(32, 64); const scalar = modL_LE(head); const point = G.mul(scalar); const pointBytes = point.toRawBytes(); return { head, prefix, scalar, point, pointBytes }; }; var getExtendedPublicKeyAsync = (priv) => sha512a(toU8(priv, 32)).then(hash2extK); var getExtendedPublicKey = (priv) => hash2extK(sha512s(toU8(priv, 32))); var getPublicKeyAsync = (priv) => getExtendedPublicKeyAsync(priv).then((p) => p.pointBytes); function hashFinish(asynchronous, res) { if (asynchronous) return sha512a(res.hashable).then(res.finish); return res.finish(sha512s(res.hashable)); } var _sign = (e, rBytes, msg) => { const { pointBytes: P3, scalar: s } = e; const r = modL_LE(rBytes); const R = G.mul(r).toRawBytes(); const hashable = concatB(R, P3, msg); const finish = (hashed) => { const S = mod2(r + modL_LE(hashed) * s, N); return au8(concatB(R, n2b_32LE(S)), 64); }; return { hashable, finish }; }; var signAsync = async (msg, privKey) => { const m = toU8(msg); const e = await getExtendedPublicKeyAsync(privKey); const rBytes = await sha512a(e.prefix, m); return hashFinish(true, _sign(e, rBytes, m)); }; var _verify = (sig, msg, pub) => { msg = toU8(msg); sig = toU8(sig, 64); const A = Point.fromHex(pub, false); const R = Point.fromHex(sig.slice(0, 32), false); const s = b2n_LE(sig.slice(32, 64)); const SB = G.mul(s, false); const hashable = concatB(R.toRawBytes(), A.toRawBytes(), msg); const finish = (hashed) => { const k = modL_LE(hashed); const RkA = R.add(A.mul(k, false)); return RkA.add(SB.negate()).clearCofactor().is0(); }; return { hashable, finish }; }; var verifyAsync = async (s, m, p) => hashFinish(true, _verify(s, m, p)); var cr = () => ( // We support: 1) browsers 2) node.js 19+ typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0 ); var etc = { bytesToHex: b2h, hexToBytes: h2b, concatBytes: concatB, mod: mod2, invert, randomBytes: (len) => { const crypto5 = cr(); if (!crypto5) err("crypto.getRandomValues must be defined"); return crypto5.getRandomValues(u8n(len)); }, sha512Async: async (...messages) => { const crypto5 = cr(); if (!crypto5) err("crypto.subtle or etc.sha512Async must be defined"); const m = concatB(...messages); return u8n(await crypto5.subtle.digest("SHA-512", m.buffer)); }, sha512Sync: void 0 // Actual logic below }; Object.defineProperties(etc, { sha512Sync: { configurable: false, get() { return _shaS; }, set(f) { if (!_shaS) _shaS = f; } } }); var utils = { getExtendedPublicKeyAsync, getExtendedPublicKey, randomPrivateKey: () => etc.randomBytes(32), precompute(w = 8, p = G) { p.multiply(3n); return p; } // no-op }; var W = 8; var precompute = () => { const points = []; const windows = 256 / W + 1; let p = G, b = p; for (let w = 0; w < windows; w++) { b = p; points.push(b); for (let i = 1; i < 2 ** (W - 1); i++) { b = b.add(p); points.push(b); } p = b.double(); } return points; }; var wNAF = (n) => { const comp = Gpows || (Gpows = precompute()); const neg = (cnd, p2) => { let n2 = p2.negate(); return cnd ? n2 : p2; }; let p = I, f = G; const windows = 1 + 256 / W; const wsize = 2 ** (W - 1); const mask = BigInt(2 ** W - 1); const maxNum = 2 ** W; const shiftBy = BigInt(W); for (let w = 0; w < windows; w++) { const off = w * wsize; let wbits = Number(n & mask); n >>= shiftBy; if (wbits > wsize) { wbits -= maxNum; n += 1n; } const off1 = off, off2 = off + Math.abs(wbits) - 1; const cnd1 = w % 2 !== 0, cnd2 = wbits < 0; if (wbits === 0) { f = f.add(neg(cnd1, comp[off1])); } else { p = p.add(neg(cnd2, comp[off2])); } } return { p, f }; }; // dist/esm/src/core/dwn-error.js var DwnError = class extends Error { constructor(code5, message2) { super(`${code5}: ${message2}`); this.code = code5; this.name = "DwnError"; } }; var DwnErrorCode; (function(DwnErrorCode2) { DwnErrorCode2["AuthenticateJwsMissing"] = "AuthenticateJwsMissing"; DwnErrorCode2["AuthenticateDescriptorCidMismatch"] = "AuthenticateDescriptorCidMismatch"; DwnErrorCode2["AuthenticationMoreThanOneSignatureNotSupported"] = "AuthenticationMoreThanOneSignatureNotSupported"; DwnErrorCode2["AuthorizationAuthorNotOwner"] = "AuthorizationAuthorNotOwner"; DwnErrorCode2["AuthorizationNotGrantedToAuthor"] = "AuthorizationNotGrantedToAuthor"; DwnErrorCode2["ComputeCidCodecNotSupported"] = "ComputeCidCodecNotSupported"; DwnErrorCode2["ComputeCidMultihashNotSupported"] = "ComputeCidMultihashNotSupported"; DwnErrorCode2["DidMethodNotSupported"] = "DidMethodNotSupported"; DwnErrorCode2["DidNotString"] = "DidNotString"; DwnErrorCode2["DidNotValid"] = "DidNotValid"; DwnErrorCode2["DidResolutionFailed"] = "DidResolutionFailed"; DwnErrorCode2["Ed25519InvalidJwk"] = "Ed25519InvalidJwk"; DwnErrorCode2["EventEmitterStreamNotOpenError"] = "EventEmitterStreamNotOpenError"; DwnErrorCode2["EventsSubscribeEventStreamUnimplemented"] = "EventsSubscribeEventStreamUnimplemented"; DwnErrorCode2["GeneralJwsVerifierGetPublicKeyNotFound"] = "GeneralJwsVerifierGetPublicKeyNotFound"; DwnErrorCode2["GeneralJwsVerifierInvalidSignature"] = "GeneralJwsVerifierInvalidSignature"; DwnErrorCode2["GrantAuthorizationGrantExpired"] = "GrantAuthorizationGrantExpired"; DwnErrorCode2["GrantAuthorizationGrantMissing"] = "GrantAuthorizationGrantMissing"; DwnErrorCode2["GrantAuthorizationGrantRevoked"] = "GrantAuthorizationGrantRevoked"; DwnErrorCode2["GrantAuthorizationInterfaceMismatch"] = "GrantAuthorizationInterfaceMismatch"; DwnErrorCode2["GrantAuthorizationMethodMismatch"] = "GrantAuthorizationMethodMismatch"; DwnErrorCode2["GrantAuthorizationNotGrantedForTenant"] = "GrantAuthorizationNotGrantedForTenant"; DwnErrorCode2["GrantAuthorizationNotGrantedToAuthor"] = "GrantAuthorizationNotGrantedToAuthor"; DwnErrorCode2["GrantAuthorizationGrantNotYetActive"] = "GrantAuthorizationGrantNotYetActive"; DwnErrorCode2["HdKeyDerivationPathInvalid"] = "HdKeyDerivationPathInvalid"; DwnErrorCode2["JwsVerifySignatureUnsupportedCrv"] = "JwsVerifySignatureUnsupportedCrv"; DwnErrorCode2["IndexInvalidCursorValueType"] = "IndexInvalidCursorValueType"; DwnErrorCode2["IndexInvalidCursorSortProperty"] = "IndexInvalidCursorSortProperty"; DwnErrorCode2["IndexInvalidSortPropertyInMemory"] = "IndexInvalidSortPropertyInMemory"; DwnErrorCode2["IndexMissingIndexableProperty"] = "IndexMissingIndexableProperty"; DwnErrorCode2["JwsDecodePlainObjectPayloadInvalid"] = "JwsDecodePlainObjectPayloadInvalid"; DwnErrorCode2["MessageGetInvalidCid"] = "MessageGetInvalidCid"; DwnErrorCode2["ParseCidCodecNotSupported"] = "ParseCidCodecNotSupported"; DwnErrorCode2["ParseCidMultihashNotSupported"] = "ParseCidMultihashNotSupported"; DwnErrorCode2["PermissionsProtocolValidateSchemaUnexpectedRecord"] = "PermissionsProtocolValidateSchemaUnexpectedRecord"; DwnErrorCode2["PermissionsProtocolValidateScopeContextIdProhibitedProperties"] = "PermissionsProtocolValidateScopeContextIdProhibitedProperties"; DwnErrorCode2["PermissionsProtocolValidateScopeSchemaProhibitedProperties"] = "PermissionsProtocolValidateScopeSchemaProhibitedProperties"; DwnErrorCode2["PrivateKeySignerUnableToDeduceAlgorithm"] = "PrivateKeySignerUnableToDeduceAlgorithm"; DwnErrorCode2["PrivateKeySignerUnableToDeduceKeyId"] = "PrivateKeySignerUnableToDeduceKeyId"; DwnErrorCode2["PrivateKeySignerUnsupportedCurve"] = "PrivateKeySignerUnsupportedCurve"; DwnErrorCode2["ProtocolAuthorizationActionNotAllowed"] = "ProtocolAuthorizationActionNotAllowed"; DwnErrorCode2["ProtocolAuthorizationActionRulesNotFound"] = "ProtocolAuthorizationActionRulesNotFound"; DwnErrorCode2["ProtocolAuthorizationIncorrectDataFormat"] = "ProtocolAuthorizationIncorrectDataFormat"; DwnErrorCode2["ProtocolAuthorizationIncorrectContextId"] = "ProtocolAuthorizationIncorrectContextId"; DwnErrorCode2["ProtocolAuthorizationIncorrectProtocolPath"] = "ProtocolAuthorizationIncorrectProtocolPath"; DwnErrorCode2["ProtocolAuthorizationDuplicateRoleRecipient"] = "ProtocolAuthorizationDuplicateRoleRecipient"; DwnErrorCode2["ProtocolAuthorizationInvalidSchema"] = "ProtocolAuthorizationInvalidSchema"; DwnErrorCode2["ProtocolAuthorizationInvalidType"] = "ProtocolAuthorizationInvalidType"; DwnErrorCode2["ProtocolAuthorizationMatchingRoleRecordNotFound"] = "ProtocolAuthorizationMatchingRoleRecordNotFound"; DwnErrorCode2["ProtocolAuthorizationMaxSizeInvalid"] = "ProtocolAuthorizationMaxSizeInvalid"; DwnErrorCode2["ProtocolAuthorizationMinSizeInvalid"] = "ProtocolAuthorizationMinSizeInvalid"; DwnErrorCode2["ProtocolAuthorizationMissingContextId"] = "ProtocolAuthorizationMissingContextId"; DwnErrorCode2["ProtocolAuthorizationMissingRuleSet"] = "ProtocolAuthorizationMissingRuleSet"; DwnErrorCode2["ProtocolAuthorizationParentlessIncorrectProtocolPath"] = "ProtocolAuthorizationParentlessIncorrectProtocolPath"; DwnErrorCode2["ProtocolAuthorizationNotARole"] = "ProtocolAuthorizationNotARole"; DwnErrorCode2["ProtocolAuthorizationParentNotFoundConstructingRecordChain"] = "ProtocolAuthorizationParentNotFoundConstructingRecordChain"; DwnErrorCode2["ProtocolAuthorizationProtocolNotFound"] = "ProtocolAuthorizationProtocolNotFound"; DwnErrorCode2["ProtocolAuthorizationQueryWithoutRole"] = "ProtocolAuthorizationQueryWithoutRole"; DwnErrorCode2["ProtocolAuthorizationRoleMissingRecipient"] = "ProtocolAuthorizationRoleMissingRecipient"; DwnErrorCode2["ProtocolAuthorizationTagsInvalidSchema"] = "ProtocolAuthorizationTagsInvalidSchema"; DwnErrorCode2["ProtocolsConfigureDuplicateActorInRuleSet"] = "ProtocolsConfigureDuplicateActorInRuleSet"; DwnErrorCode2["ProtocolsConfigureDuplicateRoleInRuleSet"] = "ProtocolsConfigureDuplicateRoleInRuleSet"; DwnErrorCode2["ProtocolsConfigureInvalidSize"] = "ProtocolsConfigureInvalidSize"; DwnErrorCode2["ProtocolsConfigureInvalidActionMissingOf"] = "ProtocolsConfigureInvalidActionMissingOf"; DwnErrorCode2["ProtocolsConfigureInvalidActionOfNotAllowed"] = "ProtocolsConfigureInvalidActionOfNotAllowed"; DwnErrorCode2["ProtocolsConfigureInvalidActionDeleteWithoutCreate"] = "ProtocolsConfigureInvalidActionDeleteWithoutCreate"; DwnErrorCode2["ProtocolsConfigureInvalidActionUpdateWithoutCreate"] = "ProtocolsConfigureInvalidActionUpdateWithoutCreate"; DwnErrorCode2["ProtocolsConfigureInvalidRecipientOfAction"] = "ProtocolsConfigureInvalidRecipientOfAction"; DwnErrorCode2["ProtocolsConfigureInvalidRuleSetRecordType"] = "ProtocolsConfigureInvalidRuleSetRecordType"; DwnErrorCode2["ProtocolsConfigureInvalidTagSchema"] = "ProtocolsConfigureInvalidTagSchema"; DwnErrorCode2["ProtocolsConfigureQueryNotAllowed"] = "ProtocolsConfigureQueryNotAllowed"; DwnErrorCode2["ProtocolsConfigureRecordNestingDepthExceeded"] = "ProtocolsConfigureRecordNestingDepthExceeded"; DwnErrorCode2["ProtocolsConfigureRoleDoesNotExistAtGivenPath"] = "ProtocolsConfigureRoleDoesNotExistAtGivenPath"; DwnErrorCode2["ProtocolsConfigureUnauthorized"] = "ProtocolsConfigureUnauthorized"; DwnErrorCode2["ProtocolsQueryUnauthorized"] = "ProtocolsQueryUnauthorized"; DwnErrorCode2["RecordsAuthorDelegatedGrantAndIdExistenceMismatch"] = "RecordsAuthorDelegatedGrantAndIdExistenceMismatch"; DwnErrorCode2["RecordsAuthorDelegatedGrantCidMismatch"] = "RecordsAuthorDelegatedGrantCidMismatch"; DwnErrorCode2["RecordsAuthorDelegatedGrantGrantedToAndOwnerSignatureMismatch"] = "RecordsAuthorDelegatedGrantGrantedToAndOwnerSignatureMismatch"; DwnErrorCode2["RecordsAuthorDelegatedGrantNotADelegatedGrant"] = "RecordsAuthorDelegatedGrantNotADelegatedGrant"; DwnErrorCode2["RecordsDecryptNoMatchingKeyEncryptedFound"] = "RecordsDecryptNoMatchingKeyEncryptedFound"; DwnErrorCode2["RecordsDeleteAuthorizationFailed"] = "RecordsDeleteAuthorizationFailed"; DwnErrorCode2["RecordsQueryCreateFilterPublishedSortInvalid"] = "RecordsQueryCreateFilterPublishedSortInvalid"; DwnErrorCode2["RecordsQueryParseFilterPublishedSortInvalid"] = "RecordsQueryParseFilterPublishedSortInvalid"; DwnErrorCode2["RecordsGrantAuthorizationConditionPublicationProhibited"] = "RecordsGrantAuthorizationConditionPublicationProhibited"; DwnErrorCode2["RecordsGrantAuthorizationConditionPublicationRequired"] = "RecordsGrantAuthorizationConditionPublicationRequired"; DwnErrorCode2["RecordsGrantAuthorizationDeleteProtocolScopeMismatch"] = "RecordsGrantAuthorizationDeleteProtocolScopeMismatch"; DwnErrorCode2["RecordsGrantAuthorizationQueryOrSubscribeProtocolScopeMismatch"] = "RecordsGrantAuthorizationQueryOrSubscribeProtocolScopeMismatch"; DwnErrorCode2["RecordsGrantAuthorizationScopeContextIdMismatch"] = "RecordsGrantAuthorizationScopeContextIdMismatch"; DwnErrorCode2["RecordsGrantAuthorizationScopeMissingProtocol"] = "RecordsGrantAuthorizationScopeMissingProtocol"; DwnErrorCode2["RecordsGrantAuthorizationScopeNotRecords"] = "RecordsGrantAuthorizationScopeNotRecords"; DwnErrorCode2["RecordsGrantAuthorizationScopeProtocolMismatch"] = "RecordsGrantAuthorizationScopeProtocolMismatch"; DwnErrorCode2["RecordsGrantAuthorizationScopeProtocolPathMismatch"] = "RecordsGrantAuthorizationScopeProtocolPathMismatch"; DwnErrorCode2["RecordsGrantAuthorizationScopeSchema"] = "RecordsGrantAuthorizationScopeSchema"; DwnErrorCode2["RecordsDerivePrivateKeyUnSupportedCurve"] = "RecordsDerivePrivateKeyUnSupportedCurve"; DwnErrorCode2["RecordsInvalidAncestorKeyDerivationSegment"] = "RecordsInvalidAncestorKeyDerivationSegment"; DwnErrorCode2["RecordsOwnerDelegatedGrantAndIdExistenceMismatch"] = "RecordsOwnerDelegatedGrantAndIdExistenceMismatch"; DwnErrorCode2["RecordsOwnerDelegatedGrantCidMismatch"] = "RecordsOwnerDelegatedGrantCidMismatch"; DwnErrorCode2["RecordsOwnerDelegatedGrantGrantedToAndOwnerSignatureMismatch"] = "RecordsOwnerDelegatedGrantGrantedToAndOwnerSignatureMismatch"; DwnErrorCode2["RecordsOwnerDelegatedGrantNotADelegatedGrant"] = "RecordsOwnerDelegatedGrantNotADelegatedGrant"; DwnErrorCode2["RecordsProtocolContextDerivationSchemeMissingContextId"] = "RecordsProtocolContextDerivationSchemeMissingContextId"; DwnErrorCode2["RecordsProtocolPathDerivationSchemeMissingProtocol"] = "RecordsProtocolPathDerivationSchemeMissingProtocol"; DwnErrorCode2["RecordsQueryFilterMissingRequiredProperties"] = "RecordsQueryFilterMissingRequiredProperties"; DwnErrorCode2["RecordsReadReturnedMultiple"] = "RecordsReadReturnedMultiple"; DwnErrorCode2["RecordsReadAuthorizationFailed"] = "RecordsReadAuthorizationFailed"; DwnErrorCode2["RecordsSubscribeEventStreamUnimplemented"] = "RecordsSubscribeEventStreamUnimplemented"; DwnErrorCode2["RecordsSubscribeFilterMissingRequiredProperties"] = "RecordsSubscribeFilterMissingRequiredProperties"; DwnErrorCode2["RecordsSchemasDerivationSchemeMissingSchema"] = "RecordsSchemasDerivationSchemeMissingSchema"; DwnErrorCode2["RecordsWriteAttestationIntegrityMoreThanOneSignature"] = "RecordsWriteAttestationIntegrityMoreThanOneSignature"; DwnErrorCode2["RecordsWriteAttestationIntegrityDescriptorCidMismatch"] = "RecordsWriteAttestationIntegrityDescriptorCidMismatch"; DwnErrorCode2["RecordsWriteAttestationIntegrityInvalidPayloadProperty"] = "RecordsWriteAttestationIntegrityInvalidPayloadProperty"; DwnErrorCode2["RecordsWriteAuthorizationFailed"] = "RecordsWriteAuthorizationFailed"; DwnErrorCode2["RecordsWriteCreateMissingSigner"] = "RecordsWriteCreateMissingSigner"; DwnErrorCode2["RecordsWriteCreateDataAndDataCidMutuallyExclusive"] = "RecordsWriteCreateDataAndDataCidMutuallyExclusive"; DwnErrorCode2["RecordsWriteCreateDataCidAndDataSizeMutuallyInclusive"] = "RecordsWriteCreateDataCidAndDataSizeMutuallyInclusive"; DwnErrorCode2["RecordsWriteCreateProtocolAndProtocolPathMutuallyInclusive"] = "RecordsWriteCreateProtocolAndProtocolPathMutuallyInclusive"; DwnErrorCode2["RecordsWriteDataCidMismatch"] = "RecordsWriteDataCidMismatch"; DwnErrorCode2["RecordsWriteDataSizeMismatch"] = "RecordsWriteDataSizeMismatch"; DwnErrorCode2["RecordsWriteGetEntryIdUndefinedAuthor"] = "RecordsWriteGetEntryIdUndefinedAuthor"; DwnErrorCode2["RecordsWriteGetInitialWriteNotFound"] = "RecordsWriteGetInitialWriteNotFound"; DwnErrorCode2["RecordsWriteImmutablePropertyChanged"] = "RecordsWriteImmutablePropertyChanged"; DwnErrorCode2["RecordsWriteMissingSigner"] = "RecordsWriteMissingSigner"; DwnErrorCode2["RecordsWriteMissingDataInPrevious"] = "RecordsWriteMissingDataInPrevious"; DwnErrorCode2["RecordsWriteMissingEncodedDataInPrevious"] = "RecordsWriteMissingEncodedDataInPrevious"; DwnErrorCode2["RecordsWriteMissingDataStream"] = "RecordsWriteMissingDataStream"; DwnErrorCode2["RecordsWriteMissingProtocol"] = "RecordsWriteMissingProtocol"; DwnErrorCode2["RecordsWriteMissingSchema"] = "RecordsWriteMissingSchema"; DwnErrorCode2["RecordsWriteOwnerAndTenantMismatch"] = "RecordsWriteOwnerAndTenantMismatch"; DwnErrorCode2["RecordsWriteSignAsOwnerDelegateUnknownAuthor"] = "RecordsWriteSignAsOwnerDelegateUnknownAuthor"; DwnErrorCode2["RecordsWriteSignAsOwnerUnknownAuthor"] = "RecordsWriteSignAsOwnerUnknownAuthor"; DwnErrorCode2["RecordsWriteValidateIntegrityAttestationMismatch"] = "RecordsWriteValidateIntegrityAttestationMismatch"; DwnErrorCode2["RecordsWriteValidateIntegrityContextIdMismatch"] = "RecordsWriteValidateIntegrityContextIdMismatch"; DwnErrorCode2["RecordsWriteValidateIntegrityContextIdNotInSignerSignaturePayload"] = "RecordsWriteValidateIntegrityContextIdNotInSignerSignaturePayload"; DwnErrorCode2["RecordsWriteValidateIntegrityDateCreatedMismatch"] = "RecordsWriteValidateIntegrityDateCreatedMismatch"; DwnErrorCode2["RecordsWriteValidateIntegrityEncryptionCidMismatch"] = "RecordsWriteValidateIntegrityEncryptionCidMismatch"; DwnErrorCode2["RecordsWriteValidateIntegrityRecordIdUnauthorized"] = "RecordsWriteValidateIntegrityRecordIdUnauthorized"; DwnErrorCode2["SchemaValidatorAdditionalPropertyNotAllowed"] = "SchemaValidatorAdditionalPropertyNotAllowed"; DwnErrorCode2["SchemaValidatorFailure"] = "SchemaValidatorFailure"; DwnErrorCode2["SchemaValidatorSchemaNotFound"] = "SchemaValidatorSchemaNotFound"; DwnErrorCode2["SchemaValidatorUnevaluatedPropertyNotAllowed"] = "SchemaValidatorUnevaluatedPropertyNotAllowed"; DwnErrorCode2["Secp256k1KeyNotValid"] = "Secp256k1KeyNotValid"; DwnErrorCode2["Secp256r1KeyNotValid"] = "Secp256r1KeyNotValid"; DwnErrorCode2["TimestampInvalid"] = "TimestampInvalid"; DwnErrorCode2["UrlProtocolNotNormalized"] = "UrlProtocolNotNormalized"; DwnErrorCode2["UrlProtocolNotNormalizable"] = "UrlProtocolNotNormalizable"; DwnErrorCode2["UrlSchemaNotNormalized"] = "UrlSchemaNotNormalized"; DwnErrorCode2["UrlSchemaNotNormalizable"] = "UrlSchemaNotNormalizable"; })(DwnErrorCode || (DwnErrorCode = {})); // dist/esm/src/jose/algorithms/signing/ed25519.js var __awaiter = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; function validateKey(jwk) { if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519") { throw new DwnError(DwnErrorCode.Ed25519InvalidJwk, "invalid jwk. kty MUST be OKP. crv MUST be Ed25519"); } } function publicKeyToJwk(publicKeyBytes) { const x = Encoder2.bytesToBase64Url(publicKeyBytes); const publicJwk = { alg: "EdDSA", kty: "OKP", crv: "Ed25519", x }; return publicJwk; } var ed25519 = { sign: (content, privateJwk) => __awaiter(void 0, void 0, void 0, function* () { validateKey(privateJwk); const privateKeyBytes = Encoder2.base64UrlToBytes(privateJwk.d); return signAsync(content, privateKeyBytes); }), verify: (content, signature, publicJwk) => __awaiter(void 0, void 0, void 0, function* () { validateKey(publicJwk); const publicKeyBytes = Encoder2.base64UrlToBytes(publicJwk.x); return verifyAsync(signature, content, publicKeyBytes); }), generateKeyPair: () => __awaiter(void 0, void 0, void 0, function* () { const privateKeyBytes = utils.randomPrivateKey(); const publicKeyBytes = yield getPublicKeyAsync(privateKeyBytes); const d = Encoder2.bytesToBase64Url(privateKeyBytes); const publicJwk = publicKeyToJwk(publicKeyBytes); const privateJwk = Object.assign(Object.assign({}, publicJwk), { d }); return { publicJwk, privateJwk }; }), publicKeyToJwk: (publicKeyBytes) => __awaiter(void 0, void 0, void 0, function* () { return publicKeyToJwk(publicKeyBytes); }) }; // node_modules/@noble/secp256k1/index.js var B256 = 2n ** 256n; var P2 = B256 - 0x1000003d1n; var N2 = B256 - 0x14551231950b75fc4402da1732fc9bebfn; var Gx2 = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n; var Gy2 = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n; var CURVE2 = { p: P2, n: N2, a: 0n, b: 7n, Gx: Gx2, Gy: Gy2 }; var fLen = 32; var crv = (x) => mod3(mod3(x * x) * x + CURVE2.b); var err2 = (m = "") => { throw new Error(m); }; var big = (n) => typeof n === "bigint"; var str2 = (s) => typeof s === "string"; var fe = (n) => big(n) && 0n < n && n < P2; var ge = (n) => big(n) && 0n < n && n < N2; var au82 = (a, l) => ( // is Uint8Array (of specific length) !(a instanceof Uint8Array) || typeof l === "number" && l > 0 && a.length !== l ? err2("Uint8Array expected") : a ); var u8n2 = (data) => new Uint8Array(data); var toU82 = (a, len) => au82(str2(a) ? h2b2(a) : u8n2(a), len); var mod3 = (a, b = P2) => { let r = a % b; return r >= 0n ? r : b + r; }; var isPoint2 = (p) => p instanceof Point2 ? p : err2("Point expected"); var Gpows2 = void 0; var Point2 = class { constructor(px, py, pz) { this.px = px; this.py = py; this.pz = pz; } //3d=less inversions static fromAffine(p) { return new Point2(p.x, p.y, 1n); } static fromHex(hex) { hex = toU82(hex); let p = void 0; const head = hex[0], tail = hex.subarray(1); const x = slcNum(tail, 0, fLen), len = hex.length; if (len === 33 && [2, 3].includes(head)) { if (!fe(x)) err2("Point hex invalid: x not FE"); let y = sqrt(crv(x)); const isYOdd = (y & 1n) === 1n; const headOdd = (head & 1) === 1; if (headOdd !== isYOdd) y = mod3(-y); p = new Point2(x, y, 1n); } if (len === 65 && head === 4) p = new Point2(x, slcNum(tail, fLen, 2 * fLen), 1n); return p ? p.ok() : err2("Point is not on curve"); } static fromPrivateKey(k) { return G2.mul(toPriv(k)); } // Create point from a private key. get x() { return this.aff().x; } // .x, .y will call expensive toAffine: get y() { return this.aff().y; } // should be used with care. equals(other) { const { px: X1, py: Y1, pz: Z1 } = this; const { px: X2, py: Y2, pz: Z2 } = isPoint2(other); const X1Z2 = mod3(X1 * Z2), X2Z1 = mod3(X2 * Z1); const Y1Z2 = mod3(Y1 * Z2), Y2Z1 = mod3(Y2 * Z1); return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; } negate() { return new Point2(this.px, mod3(-this.py), this.pz); } // Flip point over y coord double() { return this.add(this); } // Point doubling: P+P, complete formula. add(other) { const { px: X1, py: Y1, pz: Z1 } = this; const { px: X2, py: Y2, pz: Z2 } = isPoint2(other); const { a, b } = CURVE2; let X3 = 0n, Y3 = 0n, Z3 = 0n; const b3 = mod3(b * 3n); let t0 = mod3(X1 * X2), t1 = mod3(Y1 * Y2), t2 = mod3(Z1 * Z2), t3 = mod3(X1 + Y1); let t4 = mod3(X2 + Y2); t3 = mod3(t3 * t4); t4 = mod3(t0 + t1); t3 = mod3(t3 - t4); t4 = mod3(X1 + Z1); let t5 = mod3(X2 + Z2); t4 = mod3(t4 * t5); t5 = mod3(t0 + t2); t4 = mod3(t4 - t5); t5 = mod3(Y1 + Z1); X3 = mod3(Y2 + Z2); t5 = mod3(t5 * X3); X3 = mod3(t1 + t2); t5 = mod3(t5 - X3); Z3 = mod3(a * t4); X3 = mod3(b3 * t2); Z3 = mod3(X3 + Z3); X3 = mod3(t1 - Z3); Z3 = mod3(t1 + Z3); Y3 = mod3(X3 * Z3); t1 = mod3(t0 + t0); t1 = mod3(t1 + t0); t2 = mod3(a * t2); t4 = mod3(b3 * t4); t1 = mod3(t1 + t2); t2 = mod3(t0 - t2); t2 = mod3(a * t2); t4 = mod3(t4 + t2); t0 = mod3(t1 * t4); Y3 = mod3(Y3 + t0); t0 = mod3(t5 * t4); X3 = mod3(t3 * X3); X3 = mod3(X3 - t0); t0 = mod3(t3 * t1); Z3 = mod3(t5 * Z3); Z3 = mod3(Z3 + t0); return new Point2(X3, Y3, Z3); } mul(n, safe = true) { if (!safe && n === 0n) return I2; if (!ge(n)) err2("invalid scalar"); if (this.equals(G2)) return wNAF2(n).p; let p = I2, f = G2; for (let d = this; n > 0n; d = d.double(), n >>= 1n) { if (n & 1n) p = p.add(d); else if (safe) f = f.add(d); } return p; } mulAddQUns(R, u1, u2) { return this.mul(u1, false).add(R.mul(u2, false)).ok(); } // to private keys. Doesn't use Shamir trick toAffine() { const { px: x, py: y, pz: z } = this; if (this.equals(I2)) return { x: 0n, y: 0n }; if (z === 1n) return { x, y }; const iz = inv(z); if (mod3(z * iz) !== 1n) err2("invalid inverse"); return { x: mod3(x * iz), y: mod3(y * iz) }; } assertValidity() { const { x, y } = this.aff(); if (!fe(x) || !fe(y)) err2("Point invalid: x or y"); return mod3(y * y) === crv(x) ? ( // y² = x³ + ax + b, must be equal this ) : err2("Point invalid: not on curve"); } multiply(n) { return this.mul(n); } // Aliases to compress code aff() { return this.toAffine(); } ok() { return this.assertValidity(); } toHex(isCompressed = true) { const { x, y } = this.aff(); const head = isCompressed ? (y & 1n) === 0n ? "02" : "03" : "04"; return head + n2h(x) + (isCompressed ? "" : n2h(y)); } toRawBytes(isCompressed = true) { return h2b2(this.toHex(isCompressed)); } }; Point2.BASE = new Point2(Gx2, Gy2, 1n); Point2.ZERO = new Point2(0n, 1n, 0n); var { BASE: G2, ZERO: I2 } = Point2; var padh2 = (n, pad) => n.toString(16).padStart(pad, "0"); var b2h2 = (b) => Array.from(b).map((e) => padh2(e, 2)).join(""); var h2b2 = (hex) => { const l = hex.length; if (!str2(hex) || l % 2) err2("hex invalid 1"); const arr = u8n2(l / 2); for (let i = 0; i < arr.length; i++) { const j = i * 2; const h = hex.slice(j, j + 2); const b = Number.parseInt(h, 16); if (Number.isNaN(b) || b < 0) err2("hex invalid 2"); arr[i] = b; } return arr; }; var b2n = (b) => BigInt("0x" + (b2h2(b) || "0")); var slcNum = (b, from7, to) => b2n(b.slice(from7, to)); var n2b = (num) => { return big(num) && num >= 0n && num < B256 ? h2b2(padh2(num, 2 * fLen)) : err2("bigint expected"); }; var n2h = (num) => b2h2(n2b(num)); var concatB2 = (...arrs) => { const r = u8n2(arrs.reduce((sum, a) => sum + au82(a).length, 0)); let pad = 0; arrs.forEach((a) => { r.set(a, pad); pad += a.length; }); return r; }; var inv = (num, md = P2) => { if (num === 0n || md <= 0n) err2("no inverse n=" + num + " mod=" + md); let a = mod3(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n; while (a !== 0n) { const q = b / a, r = b % a; const m = x - u * q, n = y - v * q; b = a, a = r, x = u, y = v, u = m, v = n; } return b === 1n ? mod3(x, md) : err2("no inverse"); }; var sqrt = (n) => { let r = 1n; for (let num = n, e = (P2 + 1n) / 4n; e > 0n; e >>= 1n) { if (e & 1n) r = r * num % P2; num = num * num % P2; } return mod3(r * r) === n ? r : err2("sqrt invalid"); }; var toPriv = (p) => { if (!big(p)) p = b2n(toU82(p, fLen)); return ge(p) ? p : err2("private key out of range"); }; var moreThanHalfN = (n) => n > N2 >> 1n; function getPublicKey(privKey, isCompressed = true) { return Point2.fromPrivateKey(privKey).toRawBytes(isCompressed); } var Signature = class { constructor(r, s, recovery) { this.r = r; this.s = s; this.recovery = recovery; this.assertValidity(); } // constructed outside. static fromCompact(hex) { hex = toU82(hex, 64); return new Signature(slcNum(hex, 0, fLen), slcNum(hex, fLen, 2 * fLen)); } assertValidity() { return ge(this.r) && ge(this.s) ? this : err2(); } // 0 < r or s < CURVE.n addRecoveryBit(rec) { return new Signature(this.r, this.s, rec); } hasHighS() { return moreThanHalfN(this.s); } recoverPublicKey(msgh) { const { r, s, recovery: rec } = this; if (![0, 1, 2, 3].includes(rec)) err2("recovery id invalid"); const h = bits2int_modN(toU82(msgh, 32)); const radj = rec === 2 || rec === 3 ? r + N2 : r; if (radj >= P2) err2("q.x invalid"); const head = (rec & 1) === 0 ? "02" : "03"; const R = Point2.fromHex(head + n2h(radj)); const ir = inv(radj, N2); const u1 = mod3(-h * ir, N2); const u2 = mod3(s * ir, N2); return G2.mulAddQUns(R, u1, u2); } toCompactRawBytes() { return h2b2(this.toCompactHex()); } // Uint8Array 64b compact repr toCompactHex() { return n2h(this.r) + n2h(this.s); } // hex 64b compact repr }; var bits2int = (bytes2) => { const delta = bytes2.length * 8 - 256; const num = b2n(bytes2); return delta > 0 ? num >> BigInt(delta) : num; }; var bits2int_modN = (bytes2) => { return mod3(bits2int(bytes2), N2); }; var i2o = (num) => n2b(num); var cr2 = () => ( // We support: 1) browsers 2) node.js 19+ 3) deno, other envs with crypto typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0 ); var _hmacSync; var optS = { lowS: true }; var optV = { lowS: true }; function prepSig(msgh, priv, opts = optS) { if (["der", "recovered", "canonical"].some((k) => k in opts)) err2("sign() legacy options not supported"); let { lowS } = opts; if (lowS == null) lowS = true; const h1i = bits2int_modN(toU82(msgh)); const h1o = i2o(h1i); const d = toPriv(priv); const seed = [i2o(d), h1o]; let ent = opts.extraEntropy; if (ent) { if (ent === true) ent = etc2.randomBytes(fLen); const e = toU82(ent); if (e.length !== fLen) err2(); seed.push(e); } const m = h1i; const k2sig = (kBytes) => { const k = bits2int(kBytes); if (!ge(k)) return; const ik = inv(k, N2); const q = G2.mul(k).aff(); const r = mod3(q.x, N2); if (r === 0n) return; const s = mod3(ik * mod3(m + mod3(d * r, N2), N2), N2); if (s === 0n) return; let normS = s; let rec = (q.x === r ? 0 : 2) | Number(q.y & 1n); if (lowS && moreThanHalfN(s)) { normS = mod3(-s, N2); rec ^= 1; } return new Signature(r, normS, rec); }; return { seed: concatB2(...seed), k2sig }; } function hmacDrbg(asynchronous) { let v = u8n2(fLen); let k = u8n2(fLen); let i = 0; const reset = () => { v.fill(1); k.fill(0); i = 0; }; const _e = "drbg: tried 1000 values"; if (asynchronous) { const h = (...b) => etc2.hmacSha256Async(k, v, ...b); const reseed = async (seed = u8n2()) => { k = await h(u8n2([0]), seed); v = await h(); if (seed.length === 0) return; k = await h(u8n2([1]), seed); v = await h(); }; const gen = async () => { if (i++ >= 1e3) err2(_e); v = await h(); return v; }; return async (seed, pred) => { reset(); await reseed(seed); let res = void 0; while (!(res = pred(await gen()))) await reseed(); reset(); return res; }; } else { const h = (...b) => { const f = _hmacSync; if (!f) err2("etc.hmacSha256Sync not set"); return f(k, v, ...b); }; const reseed = (seed = u8n2()) => { k = h(u8n2([0]), seed); v = h(); if (seed.length === 0) return; k = h(u8n2([1]), seed); v = h(); }; const gen = () => { if (i++ >= 1e3) err2(_e); v = h(); return v; }; return (seed, pred) => { reset(); reseed(seed); let res = void 0; while (!(res = pred(gen()))) reseed(); reset(); return res; }; } } async function signAsync2(msgh, priv, opts = optS) { const { seed, k2sig } = prepSig(msgh, priv, opts); return hmacDrbg(true)(seed, k2sig); } function verify(sig, msgh, pub, opts = optV) { let { lowS } = opts; if (lowS == null) lowS = true; if ("strict" in opts) err2("verify() legacy options not supported"); let sig_, h, P3; const rs = sig && typeof sig === "object" && "r" in sig; if (!rs && toU82(sig).length !== 2 * fLen) err2("signature must be 64 bytes"); try { sig_ = rs ? new Signature(sig.r, sig.s).assertValidity() : Signature.fromCompact(sig); h = bits2int_modN(toU82(msgh, fLen)); P3 = pub instanceof Point2 ? pub.ok() : Point2.fromHex(pub); } catch (e) { return false; } if (!sig_) return false; const { r, s } = sig_; if (lowS && moreThanHalfN(s)) return false; let R; try { const is2 = inv(s, N2); const u1 = mod3(h * is2, N2); const u2 = mod3(r * is2, N2); R = G2.mulAddQUns(P3, u1, u2).aff(); } catch (error) { return false; } if (!R) return false; const v = mod3(R.x, N2); return v === r; } function hashToPrivateKey(hash2) { hash2 = toU82(hash2); const minLen = fLen + 8; if (hash2.length < minLen || hash2.length > 1024) err2("expected proper params"); const num = mod3(b2n(hash2), N2 - 1n) + 1n; return n2b(num); } var etc2 = { hexToBytes: h2b2, bytesToHex: b2h2, concatBytes: concatB2, bytesToNumberBE: b2n, numberToBytesBE: n2b, mod: mod3, invert: inv, hmacSha256Async: async (key, ...msgs) => { const crypto5 = cr2(); if (!crypto5) return err2("etc.hmacSha256Async not set"); const s = crypto5.subtle; const k = await s.importKey("raw", key, { name: "HMAC", hash: { name: "SHA-256" } }, false, ["sign"]); return u8n2(await s.sign("HMAC", k, concatB2(...msgs))); }, hmacSha256Sync: _hmacSync, hashToPrivateKey, randomBytes: (len) => { const crypto5 = cr2(); if (!crypto5) err2("crypto.getRandomValues must be defined"); return crypto5.getRandomValues(u8n2(len)); } }; var utils2 = { normPrivateKeyToScalar: toPriv, isValidPrivateKey: (key) => { try { return !!toPriv(key); } catch (e) { return false; } }, randomPrivateKey: () => hashToPrivateKey(etc2.randomBytes(fLen + 8)), precompute(w = 8, p = G2) { p.multiply(3n); return p; } // no-op }; Object.defineProperties(etc2, { hmacSha256Sync: { configurable: false, get() { return _hmacSync; }, set(f) { if (!_hmacSync) _hmacSync = f; } } }); var W2 = 8; var precompute2 = () => { const points = []; const windows = 256 / W2 + 1; let p = G2, b = p; for (let w = 0; w < windows; w++) { b = p; points.push(b); for (let i = 1; i < 2 ** (W2 - 1); i++) { b = b.add(p); points.push(b); } p = b.double(); } return points; }; var wNAF2 = (n) => { const comp = Gpows2 || (Gpows2 = precompute2()); const neg = (cnd, p2) => { let n2 = p2.negate(); return cnd ? n2 : p2; }; let p = I2, f = G2; const windows = 1 + 256 / W2; const wsize = 2 ** (W2 - 1); const mask = BigInt(2 ** W2 - 1); const maxNum = 2 ** W2; const shiftBy = BigInt(W2); for (let w = 0; w < windows; w++) { const off = w * wsize; let wbits = Number(n & mask); n >>= shiftBy; if (wbits > wsize) { wbits -= maxNum; n += 1n; } const off1 = off, off2 = off + Math.abs(wbits) - 1; const cnd1 = w % 2 !== 0, cnd2 = wbits < 0; if (wbits === 0) { f = f.add(neg(cnd1, comp[off1])); } else { p = p.add(neg(cnd2, comp[off2])); } } return { p, f }; }; // node_modules/multiformats/src/hashes/sha2.js var sha2_exports = {}; __export(sha2_exports, { sha256: () => sha256, sha512: () => sha512 }); var import_crypto = __toESM(require("crypto"), 1); // node_modules/multiformats/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(buf2, offset) { var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf2.length; do { if (counter >= l) { read.bytes = 0; throw new RangeError("Could not decode varint"); } b = buf2[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 N22 = 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 < N22 ? 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/multiformats/src/varint.js var decode3 = (data, offset = 0) => { const code5 = varint_default.decode(data, offset); return [code5, varint_default.decode.bytes]; }; var encodeTo = (int, target, offset = 0) => { varint_default.encode(int, target, offset); return target; }; var encodingLength = (int) => { return varint_default.encodingLength(int); }; // node_modules/multiformats/src/hashes/digest.js var create = (code5, digest2) => { const size = digest2.byteLength; const sizeOffset = encodingLength(code5); const digestOffset = sizeOffset + encodingLength(size); const bytes2 = new Uint8Array(digestOffset + size); encodeTo(code5, bytes2, 0); encodeTo(size, bytes2, sizeOffset); bytes2.set(digest2, digestOffset); return new Digest(code5, size, digest2, bytes2); }; var decode4 = (multihash) => { const bytes2 = coerce(multihash); const [code5, sizeOffset] = decode3(bytes2); const [size, digestOffset] = decode3(bytes2.subarray(sizeOffset)); const digest2 = bytes2.subarray(sizeOffset + digestOffset); if (digest2.byteLength !== size) { throw new Error("Incorrect length"); } return new Digest(code5, size, digest2, bytes2); }; var equals2 = (a, b) => { if (a === b) { return true; } else { const data = ( /** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */ b ); return a.code === data.code && a.size === data.size && data.bytes instanceof Uint8Array && equals(a.bytes, data.bytes); } }; var Digest = class { /** * Creates a multihash digest. * * @param {Code} code * @param {Size} size * @param {Uint8Array} digest * @param {Uint8Array} bytes */ constructor(code5, size, digest2, bytes2) { this.code = code5; this.size = size; this.digest = digest2; this.bytes = bytes2; } }; // node_modules/multiformats/src/hashes/hasher.js var from2 = ({ name: name5, code: code5, encode: encode16 }) => new Hasher(name5, code5, encode16); var Hasher = class { /** * * @param {Name} name * @param {Code} code * @param {(input: Uint8Array) => Await} encode */ constructor(name5, code5, encode16) { this.name = name5; this.code = code5; this.encode = encode16; } /** * @param {Uint8Array} input * @returns {Await>} */ digest(input) { if (input instanceof Uint8Array) { const result = this.encode(input); return result instanceof Uint8Array ? create(this.code, result) : result.then((digest2) => create(this.code, digest2)); } else { throw Error("Unknown type, must be binary type"); } } }; // node_modules/multiformats/src/hashes/sha2.js var sha256 = from2({ name: "sha2-256", code: 18, encode: (input) => coerce(import_crypto.default.createHash("sha256").update(input).digest()) }); var sha512 = from2({ name: "sha2-512", code: 19, encode: (input) => coerce(import_crypto.default.createHash("sha512").update(input).digest()) }); // dist/esm/src/utils/secp256k1.js var __awaiter2 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __rest = function(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var Secp256k1 = class { /** * Validates the given JWK is a SECP256K1 key. * @throws {Error} if fails validation. */ static validateKey(jwk) { if (jwk.kty !== "EC" || jwk.crv !== "secp256k1") { throw new DwnError(DwnErrorCode.Secp256k1KeyNotValid, "Invalid SECP256K1 JWK: `kty` MUST be `EC`. `crv` MUST be `secp256k1`"); } } /** * Converts a public key in bytes into a JWK. */ static publicKeyToJwk(publicKeyBytes) { return __awaiter2(this, void 0, void 0, function* () { let uncompressedPublicKeyBytes; if (publicKeyBytes.byteLength === 33) { const curvePoints = Point2.fromHex(publicKeyBytes); uncompressedPublicKeyBytes = curvePoints.toRawBytes(false); } else { uncompressedPublicKeyBytes = publicKeyBytes; } const x = Encoder2.bytesToBase64Url(uncompressedPublicKeyBytes.subarray(1, 33)); const y = Encoder2.bytesToBase64Url(uncompressedPublicKeyBytes.subarray(33, 65)); const publicJwk = { alg: "ES256K", kty: "EC", crv: "secp256k1", x, y }; return publicJwk; }); } /** * Converts a private key in bytes into a JWK. */ static privateKeyToJwk(privateKeyBytes) { return __awaiter2(this, void 0, void 0, function* () { const publicKeyBytes = yield Secp256k1.getPublicKey(privateKeyBytes); const jwk = yield Secp256k1.publicKeyToJwk(publicKeyBytes); jwk.d = Encoder2.bytesToBase64Url(privateKeyBytes); return jwk; }); } /** * Creates a compressed key in raw bytes from the given SECP256K1 JWK. */ static publicJwkToBytes(publicJwk) { const x = Encoder2.base64UrlToBytes(publicJwk.x); const y = Encoder2.base64UrlToBytes(publicJwk.y); return Point2.fromAffine({ x: etc2.bytesToNumberBE(x), y: etc2.bytesToNumberBE(y) }).toRawBytes(true); } /** * Creates a private key in raw bytes from the given SECP256K1 JWK. */ static privateJwkToBytes(privateJwk) { const privateKey = Encoder2.base64UrlToBytes(privateJwk.d); return privateKey; } /** * Signs the provided content using the provided JWK. */ static sign(content, privateJwk) { return __awaiter2(this, void 0, void 0, function* () { Secp256k1.validateKey(privateJwk); const hashedContent = yield sha256.encode(content); const privateKeyBytes = Secp256k1.privateJwkToBytes(privateJwk); return (yield signAsync2(hashedContent, privateKeyBytes)).toCompactRawBytes(); }); } /** * Verifies a signature against the provided payload hash and public key. * @returns a boolean indicating whether the signature is valid. */ static verify(content, signature, publicJwk) { return __awaiter2(this, void 0, void 0, function* () { Secp256k1.validateKey(publicJwk); const publicKeyBytes = Secp256k1.publicJwkToBytes(publicJwk); const hashedContent = yield sha256.encode(content); return verify(signature, hashedContent, publicKeyBytes); }); } /** * Generates a random key pair in JWK format. */ static generateKeyPair() { return __awaiter2(this, void 0, void 0, function* () { const privateKeyBytes = utils2.randomPrivateKey(); const publicKeyBytes = getPublicKey(privateKeyBytes, false); const d = Encoder2.bytesToBase64Url(privateKeyBytes); const publicJwk = yield Secp256k1.publicKeyToJwk(publicKeyBytes); const privateJwk = Object.assign(Object.assign({}, publicJwk), { d }); return { publicJwk, privateJwk }; }); } /** * Generates key pair in raw bytes, where the `publicKey` is compressed. */ static generateKeyPairRaw() { return __awaiter2(this, void 0, void 0, function* () { const privateKey = utils2.randomPrivateKey(); const publicKey = getPublicKey(privateKey, true); return { publicKey, privateKey }; }); } /** * Gets the compressed public key of the given private key. */ static getPublicKey(privateKey) { return __awaiter2(this, void 0, void 0, function* () { const publicKey = getPublicKey(privateKey, true); return publicKey; }); } /** * Gets the public JWK of the given private JWK. */ static getPublicJwk(privateKeyJwk) { return __awaiter2(this, void 0, void 0, function* () { const { d: _d } = privateKeyJwk, publicKey = __rest(privateKeyJwk, ["d"]); return publicKey; }); } }; // node_modules/@noble/hashes/esm/_assert.js function number(n) { if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`); } function isBytes(a) { return a instanceof Uint8Array || a != null && typeof a === "object" && a.constructor.name === "Uint8Array"; } function bytes(b, ...lengths) { if (!isBytes(b)) throw new Error("Expected Uint8Array"); if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); } function hash(hash2) { if (typeof hash2 !== "function" || typeof hash2.create !== "function") throw new Error("Hash should be wrapped by utils.wrapConstructor"); number(hash2.outputLen); number(hash2.blockLen); } function exists(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 output(out, instance) { bytes(out); const min = instance.outputLen; if (out.length < min) { throw new Error(`digestInto() expects output buffer of length at least ${min}`); } } // node_modules/@noble/hashes/esm/cryptoNode.js var nc = __toESM(require("node:crypto"), 1); var crypto3 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : void 0; // node_modules/@noble/hashes/esm/utils.js function isBytes2(a) { return a instanceof Uint8Array || a != null && typeof a === "object" && a.constructor.name === "Uint8Array"; } var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); var rotr = (word, shift) => word << 32 - shift | word >>> shift; var isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68; if (!isLE) throw new Error("Non little-endian hardware is not supported"); function utf8ToBytes(str3) { if (typeof str3 !== "string") throw new Error(`utf8ToBytes expected string, got ${typeof str3}`); return new Uint8Array(new TextEncoder().encode(str3)); } function toBytes(data) { if (typeof data === "string") data = utf8ToBytes(data); if (!isBytes2(data)) throw new Error(`expected Uint8Array, got ${typeof data}`); return data; } function concatBytes(...arrays) { let sum = 0; for (let i = 0; i < arrays.length; i++) { const a = arrays[i]; if (!isBytes2(a)) throw new Error("Uint8Array expected"); 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 { // Safe version that clones internal state clone() { return this._cloneInto(); } }; var toStr = {}.toString; function wrapConstructor(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 (crypto3 && typeof crypto3.getRandomValues === "function") { return crypto3.getRandomValues(new Uint8Array(bytesLength)); } throw new Error("crypto.getRandomValues must be defined"); } // node_modules/@noble/hashes/esm/hmac.js var HMAC = class extends Hash { constructor(hash2, _key) { super(); this.finished = false; this.destroyed = false; hash(hash2); const key = toBytes(_key); this.iHash = hash2.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 ? hash2.create().update(key).digest() : key); for (let i = 0; i < pad.length; i++) pad[i] ^= 54; this.iHash.update(pad); this.oHash = hash2.create(); for (let i = 0; i < pad.length; i++) pad[i] ^= 54 ^ 92; this.oHash.update(pad); pad.fill(0); } update(buf2) { exists(this); this.iHash.update(buf2); return this; } digestInto(out) { exists(this); bytes(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; } destroy() { this.destroyed = true; this.oHash.destroy(); this.iHash.destroy(); } }; var hmac = (hash2, key, message2) => new HMAC(hash2, key).update(message2).digest(); hmac.create = (hash2, key) => new HMAC(hash2, key); // node_modules/@noble/curves/esm/abstract/utils.js var utils_exports = {}; __export(utils_exports, { bitGet: () => bitGet, bitLen: () => bitLen, bitMask: () => bitMask, bitSet: () => bitSet, bytesToHex: () => bytesToHex, bytesToNumberBE: () => bytesToNumberBE, bytesToNumberLE: () => bytesToNumberLE, concatBytes: () => concatBytes2, createHmacDrbg: () => createHmacDrbg, ensureBytes: () => ensureBytes, equalBytes: () => equalBytes, hexToBytes: () => hexToBytes, hexToNumber: () => hexToNumber, isBytes: () => isBytes3, numberToBytesBE: () => numberToBytesBE, numberToBytesLE: () => numberToBytesLE, numberToHexUnpadded: () => numberToHexUnpadded, numberToVarBytesBE: () => numberToVarBytesBE, utf8ToBytes: () => utf8ToBytes2, validateObject: () => validateObject }); var _0n = BigInt(0); var _1n = BigInt(1); var _2n = BigInt(2); function isBytes3(a) { return a instanceof Uint8Array || a != null && typeof a === "object" && a.constructor.name === "Uint8Array"; } var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); function bytesToHex(bytes2) { if (!isBytes3(bytes2)) throw new Error("Uint8Array expected"); let hex = ""; for (let i = 0; i < bytes2.length; i++) { hex += hexes[bytes2[i]]; } return hex; } 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 BigInt(hex === "" ? "0" : `0x${hex}`); } var asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 }; function asciiToBase16(char) { if (char >= asciis._0 && char <= asciis._9) return char - asciis._0; if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10); if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10); return; } function hexToBytes(hex) { if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex); const hl = hex.length; const al = hl / 2; if (hl % 2) throw new Error("padded 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 bytesToNumberBE(bytes2) { return hexToNumber(bytesToHex(bytes2)); } function bytesToNumberLE(bytes2) { if (!isBytes3(bytes2)) throw new Error("Uint8Array expected"); return hexToNumber(bytesToHex(Uint8Array.from(bytes2).reverse())); } function numberToBytesBE(n, len) { return hexToBytes(n.toString(16).padStart(len * 2, "0")); } function numberToBytesLE(n, len) { return numberToBytesBE(n, len).reverse(); } function numberToVarBytesBE(n) { return hexToBytes(numberToHexUnpadded(n)); } function ensureBytes(title, hex, expectedLength) { let res; if (typeof hex === "string") { try { res = hexToBytes(hex); } catch (e) { throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); } } else if (isBytes3(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} expected ${expectedLength} bytes, got ${len}`); return res; } function concatBytes2(...arrays) { let sum = 0; for (let i = 0; i < arrays.length; i++) { const a = arrays[i]; if (!isBytes3(a)) throw new Error("Uint8Array expected"); sum += a.length; } let res = new Uint8Array(sum); let pad = 0; for (let i = 0; i < arrays.length; i++) { const a = arrays[i]; res.set(a, pad); pad += a.length; } return res; } function equalBytes(a, b) { if (a.length !== b.length) return false; let diff = 0; for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i]; return diff === 0; } function utf8ToBytes2(str3) { if (typeof str3 !== "string") throw new Error(`utf8ToBytes expected string, got ${typeof str3}`); return new Uint8Array(new TextEncoder().encode(str3)); } function bitLen(n) { let len; for (len = 0; n > _0n; n >>= _1n, len += 1) ; return len; } function bitGet(n, pos) { return n >> BigInt(pos) & _1n; } var bitSet = (n, pos, value) => { return n | (value ? _1n : _0n) << BigInt(pos); }; var bitMask = (n) => (_2n << BigInt(n - 1)) - _1n; var u8n3 = (data) => new Uint8Array(data); var u8fr = (arr) => Uint8Array.from(arr); 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"); let v = u8n3(hashLen); let k = u8n3(hashLen); let i = 0; const reset = () => { v.fill(1); k.fill(0); i = 0; }; const h = (...b) => hmacFn(k, v, ...b); const reseed = (seed = u8n3()) => { k = h(u8fr([0]), seed); v = h(); if (seed.length === 0) return; k = h(u8fr([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 concatBytes2(...out); }; const genUntil = (seed, pred) => { reset(); reseed(seed); let res = void 0; while (!(res = pred(gen()))) reseed(); reset(); return res; }; return genUntil; } var validatorFns = { bigint: (val) => typeof val === "bigint", function: (val) => typeof val === "function", boolean: (val) => typeof val === "boolean", string: (val) => typeof val === "string", stringOrUint8Array: (val) => typeof val === "string" || isBytes3(val), isSafeInteger: (val) => Number.isSafeInteger(val), array: (val) => Array.isArray(val), field: (val, object) => object.Fp.isValid(val), hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) }; function validateObject(object, validators, optValidators = {}) { const checkField = (fieldName, type, isOptional) => { const checkVal = validatorFns[type]; if (typeof checkVal !== "function") throw new Error(`Invalid validator "${type}", expected function`); const val = object[fieldName]; if (isOptional && val === void 0) return; if (!checkVal(val, object)) { throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); } }; for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type, false); for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type, true); return object; } // node_modules/@noble/curves/esm/abstract/modular.js var _0n2 = BigInt(0); var _1n2 = BigInt(1); var _2n2 = BigInt(2); var _3n = BigInt(3); var _4n = BigInt(4); var _5n = BigInt(5); var _8n = BigInt(8); var _9n = BigInt(9); var _16n = BigInt(16); function mod4(a, b) { const result = a % b; return result >= _0n2 ? result : b + result; } function pow(num, power, modulo) { if (modulo <= _0n2 || power < _0n2) throw new Error("Expected power/modulo > 0"); if (modulo === _1n2) return _0n2; let res = _1n2; while (power > _0n2) { if (power & _1n2) res = res * num % modulo; num = num * num % modulo; power >>= _1n2; } return res; } function invert2(number2, modulo) { if (number2 === _0n2 || modulo <= _0n2) { throw new Error(`invert: expected positive integers, got n=${number2} mod=${modulo}`); } let a = mod4(number2, 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 mod4(x, modulo); } function tonelliShanks(P3) { const legendreC = (P3 - _1n2) / _2n2; let Q, S, Z; for (Q = P3 - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++) ; for (Z = _2n2; Z < P3 && pow(Z, legendreC, P3) !== P3 - _1n2; Z++) ; if (S === 1) { const p1div4 = (P3 + _1n2) / _4n; return function tonelliFast(Fp2, n) { const root = Fp2.pow(n, p1div4); if (!Fp2.eql(Fp2.sqr(root), n)) throw new Error("Cannot find square root"); return root; }; } const Q1div2 = (Q + _1n2) / _2n2; return function tonelliSlow(Fp2, n) { if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE)) throw new Error("Cannot find square root"); let r = S; let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z), Q); let x = Fp2.pow(n, Q1div2); let b = Fp2.pow(n, Q); while (!Fp2.eql(b, Fp2.ONE)) { if (Fp2.eql(b, Fp2.ZERO)) return Fp2.ZERO; let m = 1; for (let t2 = Fp2.sqr(b); m < r; m++) { if (Fp2.eql(t2, Fp2.ONE)) break; t2 = Fp2.sqr(t2); } const ge2 = Fp2.pow(g, _1n2 << BigInt(r - m - 1)); g = Fp2.sqr(ge2); x = Fp2.mul(x, ge2); b = Fp2.mul(b, g); r = m; } return x; }; } function FpSqrt(P3) { if (P3 % _4n === _3n) { const p1div4 = (P3 + _1n2) / _4n; return function sqrt3mod4(Fp2, n) { const root = Fp2.pow(n, p1div4); if (!Fp2.eql(Fp2.sqr(root), n)) throw new Error("Cannot find square root"); return root; }; } if (P3 % _8n === _5n) { const c1 = (P3 - _5n) / _8n; return function sqrt5mod8(Fp2, n) { const n2 = Fp2.mul(n, _2n2); const v = Fp2.pow(n2, c1); const nv = Fp2.mul(n, v); const i = Fp2.mul(Fp2.mul(nv, _2n2), v); const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE)); if (!Fp2.eql(Fp2.sqr(root), n)) throw new Error("Cannot find square root"); return root; }; } if (P3 % _16n === _9n) { } return tonelliShanks(P3); } 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: "isSafeInteger", BITS: "isSafeInteger" }; const opts = FIELD_FIELDS.reduce((map2, val) => { map2[val] = "function"; return map2; }, initial); return validateObject(field, opts); } function FpPow(f, num, power) { if (power < _0n2) throw new Error("Expected power > 0"); if (power === _0n2) return f.ONE; if (power === _1n2) return num; let p = f.ONE; let d = num; while (power > _0n2) { if (power & _1n2) p = f.mul(p, d); d = f.sqr(d); power >>= _1n2; } return p; } function FpInvertBatch(f, nums) { const tmp = new Array(nums.length); const lastMultiplied = nums.reduce((acc, num, i) => { if (f.is0(num)) return acc; tmp[i] = acc; return f.mul(acc, num); }, f.ONE); const inverted = f.inv(lastMultiplied); nums.reduceRight((acc, num, i) => { if (f.is0(num)) return acc; tmp[i] = f.mul(acc, tmp[i]); return f.mul(acc, num); }, inverted); return tmp; } function nLength(n, nBitLength) { const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; const nByteLength = Math.ceil(_nBitLength / 8); return { nBitLength: _nBitLength, nByteLength }; } function Field(ORDER, bitLen2, isLE2 = false, redef = {}) { if (ORDER <= _0n2) throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); if (BYTES > 2048) throw new Error("Field lengths over 2048 bytes are not supported"); const sqrtP = FpSqrt(ORDER); const f = Object.freeze({ ORDER, BITS, BYTES, MASK: bitMask(BITS), ZERO: _0n2, ONE: _1n2, create: (num) => mod4(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, isOdd: (num) => (num & _1n2) === _1n2, neg: (num) => mod4(-num, ORDER), eql: (lhs, rhs) => lhs === rhs, sqr: (num) => mod4(num * num, ORDER), add: (lhs, rhs) => mod4(lhs + rhs, ORDER), sub: (lhs, rhs) => mod4(lhs - rhs, ORDER), mul: (lhs, rhs) => mod4(lhs * rhs, ORDER), pow: (num, power) => FpPow(f, num, power), div: (lhs, rhs) => mod4(lhs * invert2(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) => invert2(num, ORDER), sqrt: redef.sqrt || ((n) => sqrtP(f, n)), invertBatch: (lst) => FpInvertBatch(f, lst), // TODO: do we really need constant cmov? // We don't have const-time bigints anyway, so probably will be not very useful cmov: (a, b, c) => c ? b : a, toBytes: (num) => isLE2 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES), fromBytes: (bytes2) => { if (bytes2.length !== BYTES) throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes2.length}`); return isLE2 ? bytesToNumberLE(bytes2) : bytesToNumberBE(bytes2); } }); 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 length5 = getFieldBytesLength(fieldOrder); return length5 + Math.ceil(length5 / 2); } function mapHashToField(key, fieldOrder, isLE2 = 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 = isLE2 ? bytesToNumberBE(key) : bytesToNumberLE(key); const reduced = mod4(num, fieldOrder - _1n2) + _1n2; return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); } // node_modules/@noble/curves/esm/abstract/curve.js var _0n3 = BigInt(0); var _1n3 = BigInt(1); function wNAF3(c, bits) { const constTimeNegate = (condition, item) => { const neg = item.negate(); return condition ? neg : item; }; const opts = (W3) => { const windows = Math.ceil(bits / W3) + 1; const windowSize = 2 ** (W3 - 1); return { windows, windowSize }; }; return { constTimeNegate, // non-const time multiplication ladder unsafeLadder(elm, n) { let p = c.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. * @returns precomputed point tables flattened to a single array */ precomputeWindow(elm, W3) { const { windows, windowSize } = opts(W3); const points = []; let p = elm; let base6 = p; for (let window2 = 0; window2 < windows; window2++) { base6 = p; points.push(base6); for (let i = 1; i < windowSize; i++) { base6 = base6.add(p); points.push(base6); } p = base6.double(); } return points; }, /** * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. * @param W window size * @param precomputes precomputed tables * @param n scalar (we don't check here, but should be less than curve order) * @returns real and fake (for const-time) points */ wNAF(W3, precomputes, n) { const { windows, windowSize } = opts(W3); let p = c.ZERO; let f = c.BASE; const mask = BigInt(2 ** W3 - 1); const maxNumber = 2 ** W3; const shiftBy = BigInt(W3); for (let window2 = 0; window2 < windows; window2++) { const offset = window2 * windowSize; let wbits = Number(n & mask); n >>= shiftBy; if (wbits > windowSize) { wbits -= maxNumber; n += _1n3; } const offset1 = offset; const offset2 = offset + Math.abs(wbits) - 1; const cond1 = window2 % 2 !== 0; const cond2 = wbits < 0; if (wbits === 0) { f = f.add(constTimeNegate(cond1, precomputes[offset1])); } else { p = p.add(constTimeNegate(cond2, precomputes[offset2])); } } return { p, f }; }, wNAFCached(P3, precomputesMap, n, transform) { const W3 = P3._WINDOW_SIZE || 1; let comp = precomputesMap.get(P3); if (!comp) { comp = this.precomputeWindow(P3, W3); if (W3 !== 1) { precomputesMap.set(P3, transform(comp)); } } return this.wNAF(W3, comp, n); } }; } function validateBasic(curve) { validateField(curve.Fp); validateObject(curve, { n: "bigint", h: "bigint", Gx: "field", Gy: "field" }, { nBitLength: "isSafeInteger", nByteLength: "isSafeInteger" }); return Object.freeze({ ...nLength(curve.n, curve.nBitLength), ...curve, ...{ p: curve.Fp.ORDER } }); } // node_modules/@noble/curves/esm/abstract/weierstrass.js function validatePointOpts(curve) { const opts = validateBasic(curve); validateObject(opts, { a: "field", b: "field" }, { allowedPrivateKeyLengths: "array", wrapPrivateKey: "boolean", isTorsionFree: "function", clearCofactor: "function", allowInfinityPoint: "boolean", fromBytes: "function", toBytes: "function" }); const { endo, Fp: Fp2, a } = opts; if (endo) { if (!Fp2.eql(a, Fp2.ZERO)) { throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0"); } if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { throw new Error("Expected endomorphism with beta: bigint and splitScalar: function"); } } return Object.freeze({ ...opts }); } var { bytesToNumberBE: b2n2, hexToBytes: h2b3 } = utils_exports; var DER = { // asn.1 DER encoding utils Err: class DERErr extends Error { constructor(m = "") { super(m); } }, _parseInt(data) { const { Err: E } = DER; if (data.length < 2 || data[0] !== 2) throw new E("Invalid signature integer tag"); const len = data[1]; const res = data.subarray(2, len + 2); if (!len || res.length !== len) throw new E("Invalid signature integer: wrong length"); if (res[0] & 128) throw new E("Invalid signature integer: negative"); if (res[0] === 0 && !(res[1] & 128)) throw new E("Invalid signature integer: unnecessary leading zero"); return { d: b2n2(res), l: data.subarray(len + 2) }; }, toSig(hex) { const { Err: E } = DER; const data = typeof hex === "string" ? h2b3(hex) : hex; if (!isBytes3(data)) throw new Error("ui8a expected"); let l = data.length; if (l < 2 || data[0] != 48) throw new E("Invalid signature tag"); if (data[1] !== l - 2) throw new E("Invalid signature: incorrect length"); const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); if (rBytesLeft.length) throw new E("Invalid signature: left bytes after parsing"); return { r, s }; }, hexFromSig(sig) { const slice2 = (s2) => Number.parseInt(s2[0], 16) & 8 ? "00" + s2 : s2; const h = (num) => { const hex = num.toString(16); return hex.length & 1 ? `0${hex}` : hex; }; const s = slice2(h(sig.s)); const r = slice2(h(sig.r)); const shl = s.length / 2; const rhl = r.length / 2; const sl = h(shl); const rl = h(rhl); return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; } }; var _0n4 = BigInt(0); var _1n4 = BigInt(1); var _2n3 = BigInt(2); var _3n2 = BigInt(3); var _4n2 = BigInt(4); function weierstrassPoints(opts) { const CURVE3 = validatePointOpts(opts); const { Fp: Fp2 } = CURVE3; const toBytes2 = CURVE3.toBytes || ((_c, point, _isCompressed) => { const a = point.toAffine(); return concatBytes2(Uint8Array.from([4]), Fp2.toBytes(a.x), Fp2.toBytes(a.y)); }); const fromBytes = CURVE3.fromBytes || ((bytes2) => { const tail = bytes2.subarray(1); const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); return { x, y }; }); function weierstrassEquation(x) { const { a, b } = CURVE3; const x2 = Fp2.sqr(x); const x3 = Fp2.mul(x2, x); return Fp2.add(Fp2.add(x3, Fp2.mul(x, a)), b); } if (!Fp2.eql(Fp2.sqr(CURVE3.Gy), weierstrassEquation(CURVE3.Gx))) throw new Error("bad generator point: equation left != right"); function isWithinCurveOrder(num) { return typeof num === "bigint" && _0n4 < num && num < CURVE3.n; } function assertGE(num) { if (!isWithinCurveOrder(num)) throw new Error("Expected valid bigint: 0 < bigint < curve.n"); } function normPrivateKeyToScalar(key) { const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE3; if (lengths && typeof key !== "bigint") { if (isBytes3(key)) key = bytesToHex(key); if (typeof key !== "string" || !lengths.includes(key.length)) throw new Error("Invalid key"); key = key.padStart(nByteLength * 2, "0"); } let num; try { num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); } catch (error) { throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); } if (wrapPrivateKey) num = mod4(num, n); assertGE(num); return num; } const pointPrecomputes = /* @__PURE__ */ new Map(); function assertPrjPoint(other) { if (!(other instanceof Point3)) throw new Error("ProjectivePoint expected"); } class Point3 { constructor(px, py, pz) { this.px = px; this.py = py; this.pz = pz; if (px == null || !Fp2.isValid(px)) throw new Error("x required"); if (py == null || !Fp2.isValid(py)) throw new Error("y required"); if (pz == null || !Fp2.isValid(pz)) throw new Error("z required"); } // Does not validate if the point is on-curve. // Use fromHex instead, or call assertValidity() later. static fromAffine(p) { const { x, y } = p || {}; if (!p || !Fp2.isValid(x) || !Fp2.isValid(y)) throw new Error("invalid affine point"); if (p instanceof Point3) throw new Error("projective point not allowed"); const is0 = (i) => Fp2.eql(i, Fp2.ZERO); if (is0(x) && is0(y)) return Point3.ZERO; return new Point3(x, y, Fp2.ONE); } get x() { return this.toAffine().x; } get y() { return this.toAffine().y; } /** * Takes a bunch of Projective Points but executes only one * inversion on all of them. Inversion is very slow operation, * so this improves performance massively. * Optimization: converts a list of projective points to a list of identical points with Z=1. */ static normalizeZ(points) { const toInv = Fp2.invertBatch(points.map((p) => p.pz)); return points.map((p, i) => p.toAffine(toInv[i])).map(Point3.fromAffine); } /** * Converts hash string or Uint8Array to Point. * @param hex short/long ECDSA hex */ static fromHex(hex) { const P3 = Point3.fromAffine(fromBytes(ensureBytes("pointHex", hex))); P3.assertValidity(); return P3; } // Multiplies generator point by privateKey. static fromPrivateKey(privateKey) { return Point3.BASE.multiply(normPrivateKeyToScalar(privateKey)); } // "Private method", don't use it directly _setWindowSize(windowSize) { this._WINDOW_SIZE = windowSize; pointPrecomputes.delete(this); } // A point on curve is valid if it conforms to equation. assertValidity() { if (this.is0()) { if (CURVE3.allowInfinityPoint && !Fp2.is0(this.py)) return; throw new Error("bad point: ZERO"); } const { x, y } = this.toAffine(); if (!Fp2.isValid(x) || !Fp2.isValid(y)) throw new Error("bad point: x or y not FE"); const left = Fp2.sqr(y); const right = weierstrassEquation(x); if (!Fp2.eql(left, right)) throw new Error("bad point: equation left != right"); if (!this.isTorsionFree()) throw new Error("bad point: not in prime-order subgroup"); } hasEvenY() { const { y } = this.toAffine(); if (Fp2.isOdd) return !Fp2.isOdd(y); throw new Error("Field doesn't support isOdd"); } /** * Compare one point to another. */ equals(other) { assertPrjPoint(other); const { px: X1, py: Y1, pz: Z1 } = this; const { px: X2, py: Y2, pz: Z2 } = other; const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1)); const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1)); return U1 && U2; } /** * Flips point to one corresponding to (x, -y) in Affine coordinates. */ negate() { return new Point3(this.px, Fp2.neg(this.py), this.pz); } // 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 } = CURVE3; const b3 = Fp2.mul(b, _3n2); const { px: X1, py: Y1, pz: Z1 } = this; let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; let t0 = Fp2.mul(X1, X1); let t1 = Fp2.mul(Y1, Y1); let t2 = Fp2.mul(Z1, Z1); let t3 = Fp2.mul(X1, Y1); t3 = Fp2.add(t3, t3); Z3 = Fp2.mul(X1, Z1); Z3 = Fp2.add(Z3, Z3); X3 = Fp2.mul(a, Z3); Y3 = Fp2.mul(b3, t2); Y3 = Fp2.add(X3, Y3); X3 = Fp2.sub(t1, Y3); Y3 = Fp2.add(t1, Y3); Y3 = Fp2.mul(X3, Y3); X3 = Fp2.mul(t3, X3); Z3 = Fp2.mul(b3, Z3); t2 = Fp2.mul(a, t2); t3 = Fp2.sub(t0, t2); t3 = Fp2.mul(a, t3); t3 = Fp2.add(t3, Z3); Z3 = Fp2.add(t0, t0); t0 = Fp2.add(Z3, t0); t0 = Fp2.add(t0, t2); t0 = Fp2.mul(t0, t3); Y3 = Fp2.add(Y3, t0); t2 = Fp2.mul(Y1, Z1); t2 = Fp2.add(t2, t2); t0 = Fp2.mul(t2, t3); X3 = Fp2.sub(X3, t0); Z3 = Fp2.mul(t2, t1); Z3 = Fp2.add(Z3, Z3); Z3 = Fp2.add(Z3, Z3); return new Point3(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) { assertPrjPoint(other); const { px: X1, py: Y1, pz: Z1 } = this; const { px: X2, py: Y2, pz: Z2 } = other; let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; const a = CURVE3.a; const b3 = Fp2.mul(CURVE3.b, _3n2); let t0 = Fp2.mul(X1, X2); let t1 = Fp2.mul(Y1, Y2); let t2 = Fp2.mul(Z1, Z2); let t3 = Fp2.add(X1, Y1); let t4 = Fp2.add(X2, Y2); t3 = Fp2.mul(t3, t4); t4 = Fp2.add(t0, t1); t3 = Fp2.sub(t3, t4); t4 = Fp2.add(X1, Z1); let t5 = Fp2.add(X2, Z2); t4 = Fp2.mul(t4, t5); t5 = Fp2.add(t0, t2); t4 = Fp2.sub(t4, t5); t5 = Fp2.add(Y1, Z1); X3 = Fp2.add(Y2, Z2); t5 = Fp2.mul(t5, X3); X3 = Fp2.add(t1, t2); t5 = Fp2.sub(t5, X3); Z3 = Fp2.mul(a, t4); X3 = Fp2.mul(b3, t2); Z3 = Fp2.add(X3, Z3); X3 = Fp2.sub(t1, Z3); Z3 = Fp2.add(t1, Z3); Y3 = Fp2.mul(X3, Z3); t1 = Fp2.add(t0, t0); t1 = Fp2.add(t1, t0); t2 = Fp2.mul(a, t2); t4 = Fp2.mul(b3, t4); t1 = Fp2.add(t1, t2); t2 = Fp2.sub(t0, t2); t2 = Fp2.mul(a, t2); t4 = Fp2.add(t4, t2); t0 = Fp2.mul(t1, t4); Y3 = Fp2.add(Y3, t0); t0 = Fp2.mul(t5, t4); X3 = Fp2.mul(t3, X3); X3 = Fp2.sub(X3, t0); t0 = Fp2.mul(t3, t1); Z3 = Fp2.mul(t5, Z3); Z3 = Fp2.add(Z3, t0); return new Point3(X3, Y3, Z3); } subtract(other) { return this.add(other.negate()); } is0() { return this.equals(Point3.ZERO); } wNAF(n) { return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { const toInv = Fp2.invertBatch(comp.map((p) => p.pz)); return comp.map((p, i) => p.toAffine(toInv[i])).map(Point3.fromAffine); }); } /** * 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 private key e.g. sig verification, which works over *public* keys. */ multiplyUnsafe(n) { const I3 = Point3.ZERO; if (n === _0n4) return I3; assertGE(n); if (n === _1n4) return this; const { endo } = CURVE3; if (!endo) return wnaf.unsafeLadder(this, n); let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); let k1p = I3; let k2p = I3; let d = this; while (k1 > _0n4 || k2 > _0n4) { if (k1 & _1n4) k1p = k1p.add(d); if (k2 & _1n4) k2p = k2p.add(d); d = d.double(); k1 >>= _1n4; k2 >>= _1n4; } if (k1neg) k1p = k1p.negate(); if (k2neg) k2p = k2p.negate(); k2p = new Point3(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); return k1p.add(k2p); } /** * 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) { assertGE(scalar); let n = scalar; let point, fake; const { endo } = CURVE3; if (endo) { const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); let { p: k1p, f: f1p } = this.wNAF(k1); let { p: k2p, f: f2p } = this.wNAF(k2); k1p = wnaf.constTimeNegate(k1neg, k1p); k2p = wnaf.constTimeNegate(k2neg, k2p); k2p = new Point3(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); point = k1p.add(k2p); fake = f1p.add(f2p); } else { const { p, f } = this.wNAF(n); point = p; fake = f; } return Point3.normalizeZ([point, fake])[0]; } /** * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. * Not using Strauss-Shamir trick: precomputation tables are faster. * The trick could be useful if both P and Q are not G (not in our case). * @returns non-zero affine point */ multiplyAndAddUnsafe(Q, a, b) { const G3 = Point3.BASE; const mul = (P3, a2) => a2 === _0n4 || a2 === _1n4 || !P3.equals(G3) ? P3.multiplyUnsafe(a2) : P3.multiply(a2); const sum = mul(this, a).add(mul(Q, b)); return sum.is0() ? void 0 : sum; } // Converts Projective point to affine (x, y) coordinates. // Can accept precomputed Z^-1 - for example, from invertBatch. // (x, y, z) ∋ (x=x/z, y=y/z) toAffine(iz) { const { px: x, py: y, pz: z } = this; const is0 = this.is0(); if (iz == null) iz = is0 ? Fp2.ONE : Fp2.inv(z); const ax = Fp2.mul(x, iz); const ay = Fp2.mul(y, iz); const zz = Fp2.mul(z, iz); if (is0) return { x: Fp2.ZERO, y: Fp2.ZERO }; if (!Fp2.eql(zz, Fp2.ONE)) throw new Error("invZ was invalid"); return { x: ax, y: ay }; } isTorsionFree() { const { h: cofactor, isTorsionFree } = CURVE3; if (cofactor === _1n4) return true; if (isTorsionFree) return isTorsionFree(Point3, this); throw new Error("isTorsionFree() has not been declared for the elliptic curve"); } clearCofactor() { const { h: cofactor, clearCofactor } = CURVE3; if (cofactor === _1n4) return this; if (clearCofactor) return clearCofactor(Point3, this); return this.multiplyUnsafe(CURVE3.h); } toRawBytes(isCompressed = true) { this.assertValidity(); return toBytes2(Point3, this, isCompressed); } toHex(isCompressed = true) { return bytesToHex(this.toRawBytes(isCompressed)); } } Point3.BASE = new Point3(CURVE3.Gx, CURVE3.Gy, Fp2.ONE); Point3.ZERO = new Point3(Fp2.ZERO, Fp2.ONE, Fp2.ZERO); const _bits = CURVE3.nBitLength; const wnaf = wNAF3(Point3, CURVE3.endo ? Math.ceil(_bits / 2) : _bits); return { CURVE: CURVE3, ProjectivePoint: Point3, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder }; } function validateOpts(curve) { const opts = validateBasic(curve); validateObject(opts, { hash: "hash", hmac: "function", randomBytes: "function" }, { bits2int: "function", bits2int_modN: "function", lowS: "boolean" }); return Object.freeze({ lowS: true, ...opts }); } function weierstrass(curveDef) { const CURVE3 = validateOpts(curveDef); const { Fp: Fp2, n: CURVE_ORDER } = CURVE3; const compressedLen = Fp2.BYTES + 1; const uncompressedLen = 2 * Fp2.BYTES + 1; function isValidFieldElement(num) { return _0n4 < num && num < Fp2.ORDER; } function modN(a) { return mod4(a, CURVE_ORDER); } function invN(a) { return invert2(a, CURVE_ORDER); } const { ProjectivePoint: Point3, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ ...CURVE3, toBytes(_c, point, isCompressed) { const a = point.toAffine(); const x = Fp2.toBytes(a.x); const cat = concatBytes2; if (isCompressed) { return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x); } else { return cat(Uint8Array.from([4]), x, Fp2.toBytes(a.y)); } }, fromBytes(bytes2) { const len = bytes2.length; const head = bytes2[0]; const tail = bytes2.subarray(1); if (len === compressedLen && (head === 2 || head === 3)) { const x = bytesToNumberBE(tail); if (!isValidFieldElement(x)) throw new Error("Point is not on curve"); const y2 = weierstrassEquation(x); let y = Fp2.sqrt(y2); const isYOdd = (y & _1n4) === _1n4; const isHeadOdd = (head & 1) === 1; if (isHeadOdd !== isYOdd) y = Fp2.neg(y); return { x, y }; } else if (len === uncompressedLen && head === 4) { const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); return { x, y }; } else { throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); } } }); const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE3.nByteLength)); function isBiggerThanHalfOrder(number2) { const HALF = CURVE_ORDER >> _1n4; return number2 > HALF; } function normalizeS(s) { return isBiggerThanHalfOrder(s) ? modN(-s) : s; } const slcNum2 = (b, from7, to) => bytesToNumberBE(b.slice(from7, to)); class Signature2 { constructor(r, s, recovery) { this.r = r; this.s = s; this.recovery = recovery; this.assertValidity(); } // pair (bytes of r, bytes of s) static fromCompact(hex) { const l = CURVE3.nByteLength; hex = ensureBytes("compactSignature", hex, l * 2); return new Signature2(slcNum2(hex, 0, l), slcNum2(hex, l, 2 * l)); } // DER encoded ECDSA signature // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script static fromDER(hex) { const { r, s } = DER.toSig(ensureBytes("DER", hex)); return new Signature2(r, s); } assertValidity() { if (!isWithinCurveOrder(this.r)) throw new Error("r must be 0 < r < CURVE.n"); if (!isWithinCurveOrder(this.s)) throw new Error("s must be 0 < s < CURVE.n"); } addRecoveryBit(recovery) { return new Signature2(this.r, this.s, recovery); } recoverPublicKey(msgHash) { const { r, s, recovery: rec } = this; const h = bits2int_modN2(ensureBytes("msgHash", msgHash)); if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error("recovery id invalid"); const radj = rec === 2 || rec === 3 ? r + CURVE3.n : r; if (radj >= Fp2.ORDER) throw new Error("recovery id 2 or 3 invalid"); const prefix = (rec & 1) === 0 ? "02" : "03"; const R = Point3.fromHex(prefix + numToNByteStr(radj)); const ir = invN(radj); const u1 = modN(-h * ir); const u2 = modN(s * ir); const Q = Point3.BASE.multiplyAndAddUnsafe(R, u1, u2); if (!Q) throw new Error("point at infinify"); Q.assertValidity(); return Q; } // Signatures should be low-s, to prevent malleability. hasHighS() { return isBiggerThanHalfOrder(this.s); } normalizeS() { return this.hasHighS() ? new Signature2(this.r, modN(-this.s), this.recovery) : this; } // DER-encoded toDERRawBytes() { return hexToBytes(this.toDERHex()); } toDERHex() { return DER.hexFromSig({ r: this.r, s: this.s }); } // padded bytes of r, then padded bytes of s toCompactRawBytes() { return hexToBytes(this.toCompactHex()); } toCompactHex() { return numToNByteStr(this.r) + numToNByteStr(this.s); } } const utils3 = { isValidPrivateKey(privateKey) { try { normPrivateKeyToScalar(privateKey); return true; } catch (error) { return false; } }, normPrivateKeyToScalar, /** * Produces cryptographically secure private key from random of size * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. */ randomPrivateKey: () => { const length5 = getMinHashLength(CURVE3.n); return mapHashToField(CURVE3.randomBytes(length5), CURVE3.n); }, /** * Creates precompute table for an arbitrary EC point. Makes point "cached". * Allows to massively speed-up `point.multiply(scalar)`. * @returns cached point * @example * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); * fast.multiply(privKey); // much faster ECDH now */ precompute(windowSize = 8, point = Point3.BASE) { point._setWindowSize(windowSize); point.multiply(BigInt(3)); return point; } }; function getPublicKey2(privateKey, isCompressed = true) { return Point3.fromPrivateKey(privateKey).toRawBytes(isCompressed); } function isProbPub(item) { const arr = isBytes3(item); const str3 = typeof item === "string"; const len = (arr || str3) && item.length; if (arr) return len === compressedLen || len === uncompressedLen; if (str3) return len === 2 * compressedLen || len === 2 * uncompressedLen; if (item instanceof Point3) return true; return false; } function getSharedSecret(privateA, publicB, isCompressed = true) { if (isProbPub(privateA)) throw new Error("first arg must be private key"); if (!isProbPub(publicB)) throw new Error("second arg must be public key"); const b = Point3.fromHex(publicB); return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); } const bits2int2 = CURVE3.bits2int || function(bytes2) { const num = bytesToNumberBE(bytes2); const delta = bytes2.length * 8 - CURVE3.nBitLength; return delta > 0 ? num >> BigInt(delta) : num; }; const bits2int_modN2 = CURVE3.bits2int_modN || function(bytes2) { return modN(bits2int2(bytes2)); }; const ORDER_MASK = bitMask(CURVE3.nBitLength); function int2octets(num) { if (typeof num !== "bigint") throw new Error("bigint expected"); if (!(_0n4 <= num && num < ORDER_MASK)) throw new Error(`bigint expected < 2^${CURVE3.nBitLength}`); return numberToBytesBE(num, CURVE3.nByteLength); } function prepSig2(msgHash, privateKey, opts = defaultSigOpts) { if (["recovered", "canonical"].some((k) => k in opts)) throw new Error("sign() legacy options not supported"); const { hash: hash2, randomBytes: randomBytes2 } = CURVE3; let { lowS, prehash, extraEntropy: ent } = opts; if (lowS == null) lowS = true; msgHash = ensureBytes("msgHash", msgHash); if (prehash) msgHash = ensureBytes("prehashed msgHash", hash2(msgHash)); const h1int = bits2int_modN2(msgHash); const d = normPrivateKeyToScalar(privateKey); const seedArgs = [int2octets(d), int2octets(h1int)]; if (ent != null) { const e = ent === true ? randomBytes2(Fp2.BYTES) : ent; seedArgs.push(ensureBytes("extraEntropy", e)); } const seed = concatBytes2(...seedArgs); const m = h1int; function k2sig(kBytes) { const k = bits2int2(kBytes); if (!isWithinCurveOrder(k)) return; const ik = invN(k); const q = Point3.BASE.multiply(k).toAffine(); const r = modN(q.x); if (r === _0n4) return; const s = modN(ik * modN(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 = normalizeS(s); recovery ^= 1; } return new Signature2(r, normS, recovery); } return { seed, k2sig }; } const defaultSigOpts = { lowS: CURVE3.lowS, prehash: false }; const defaultVerOpts = { lowS: CURVE3.lowS, prehash: false }; function sign(msgHash, privKey, opts = defaultSigOpts) { const { seed, k2sig } = prepSig2(msgHash, privKey, opts); const C = CURVE3; const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); return drbg(seed, k2sig); } Point3.BASE._setWindowSize(8); function verify2(signature, msgHash, publicKey, opts = defaultVerOpts) { const sg = signature; msgHash = ensureBytes("msgHash", msgHash); publicKey = ensureBytes("publicKey", publicKey); if ("strict" in opts) throw new Error("options.strict was renamed to lowS"); const { lowS, prehash } = opts; let _sig = void 0; let P3; try { if (typeof sg === "string" || isBytes3(sg)) { try { _sig = Signature2.fromDER(sg); } catch (derError) { if (!(derError instanceof DER.Err)) throw derError; _sig = Signature2.fromCompact(sg); } } else if (typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint") { const { r: r2, s: s2 } = sg; _sig = new Signature2(r2, s2); } else { throw new Error("PARSE"); } P3 = Point3.fromHex(publicKey); } catch (error) { if (error.message === "PARSE") throw new Error(`signature must be Signature instance, Uint8Array or hex string`); return false; } if (lowS && _sig.hasHighS()) return false; if (prehash) msgHash = CURVE3.hash(msgHash); const { r, s } = _sig; const h = bits2int_modN2(msgHash); const is2 = invN(s); const u1 = modN(h * is2); const u2 = modN(r * is2); const R = Point3.BASE.multiplyAndAddUnsafe(P3, u1, u2)?.toAffine(); if (!R) return false; const v = modN(R.x); return v === r; } return { CURVE: CURVE3, getPublicKey: getPublicKey2, getSharedSecret, sign, verify: verify2, ProjectivePoint: Point3, Signature: Signature2, utils: utils3 }; } // node_modules/@noble/curves/esm/_shortw_utils.js function getHash(hash2) { return { hash: hash2, hmac: (key, ...msgs) => hmac(hash2, key, concatBytes(...msgs)), randomBytes }; } function createCurve(curveDef, defHash) { const create5 = (hash2) => weierstrass({ ...curveDef, ...getHash(hash2) }); return Object.freeze({ ...create5(defHash), create: create5 }); } // node_modules/@noble/hashes/esm/_sha2.js function setBigUint64(view, byteOffset, value, isLE2) { if (typeof view.setBigUint64 === "function") return view.setBigUint64(byteOffset, value, isLE2); const _32n = BigInt(32); const _u32_max = BigInt(4294967295); const wh = Number(value >> _32n & _u32_max); const wl = Number(value & _u32_max); const h = isLE2 ? 4 : 0; const l = isLE2 ? 0 : 4; view.setUint32(byteOffset + h, wh, isLE2); view.setUint32(byteOffset + l, wl, isLE2); } var SHA2 = class extends Hash { constructor(blockLen, outputLen, padOffset, isLE2) { super(); this.blockLen = blockLen; this.outputLen = outputLen; this.padOffset = padOffset; this.isLE = isLE2; this.finished = false; this.length = 0; this.pos = 0; this.destroyed = false; this.buffer = new Uint8Array(blockLen); this.view = createView(this.buffer); } update(data) { exists(this); const { view, buffer: buffer2, blockLen } = this; data = toBytes(data); const len = data.length; for (let pos = 0; pos < len; ) { const take = Math.min(blockLen - this.pos, len - pos); if (take === blockLen) { const dataView2 = createView(data); for (; blockLen <= len - pos; pos += blockLen) this.process(dataView2, pos); continue; } buffer2.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) { exists(this); output(out, this); this.finished = true; const { buffer: buffer2, view, blockLen, isLE: isLE2 } = this; let { pos } = this; buffer2[pos++] = 128; this.buffer.subarray(pos).fill(0); if (this.padOffset > blockLen - pos) { this.process(view, 0); pos = 0; } for (let i = pos; i < blockLen; i++) buffer2[i] = 0; setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2); 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], isLE2); } digest() { const { buffer: buffer2, outputLen } = this; this.digestInto(buffer2); const res = buffer2.slice(0, outputLen); this.destroy(); return res; } _cloneInto(to) { to || (to = new this.constructor()); to.set(...this.get()); const { blockLen, buffer: buffer2, length: length5, finished, destroyed, pos } = this; to.length = length5; to.pos = pos; to.finished = finished; to.destroyed = destroyed; if (length5 % blockLen) to.buffer.set(buffer2); return to; } }; // node_modules/@noble/hashes/esm/sha256.js var Chi = (a, b, c) => a & b ^ ~a & c; var Maj = (a, b, c) => a & b ^ a & c ^ b & c; var SHA256_K = /* @__PURE__ */ new Uint32Array([ 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 IV = /* @__PURE__ */ new Uint32Array([ 1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225 ]); var SHA256_W = /* @__PURE__ */ new Uint32Array(64); var SHA256 = class extends SHA2 { constructor() { super(64, 32, 8, false); this.A = IV[0] | 0; this.B = IV[1] | 0; this.C = IV[2] | 0; this.D = IV[3] | 0; this.E = IV[4] | 0; this.F = IV[5] | 0; this.G = IV[6] | 0; this.H = IV[7] | 0; } get() { const { A, B, C, D, E, F, G: G3, H } = this; return [A, B, C, D, E, F, G3, H]; } // prettier-ignore set(A, B, C, D, E, F, G3, 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 = G3 | 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 W22 = SHA256_W[i - 2]; const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; const s1 = rotr(W22, 17) ^ rotr(W22, 19) ^ W22 >>> 10; SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; } let { A, B, C, D, E, F, G: G3, 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, G3) + 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 = G3; G3 = 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; G3 = G3 + this.G | 0; H = H + this.H | 0; this.set(A, B, C, D, E, F, G3, H); } roundClean() { SHA256_W.fill(0); } destroy() { this.set(0, 0, 0, 0, 0, 0, 0, 0); this.buffer.fill(0); } }; var sha2562 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); // node_modules/@noble/curves/esm/p256.js var Fp = Field(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")); var CURVE_A = Fp.create(BigInt("-3")); var CURVE_B = BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"); var p256 = createCurve({ a: CURVE_A, // Equation params: a, b b: CURVE_B, Fp, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n // Curve order, total count of valid points in the field n: BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"), // Base (generator) point (x, y) Gx: BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"), Gy: BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"), h: BigInt(1), lowS: false }, sha2562); var secp256r1 = p256; // node_modules/uint8arrays/dist/src/util/as-uint8array.js function asUint8Array(buf2) { if (globalThis.Buffer != null) { return new Uint8Array(buf2.buffer, buf2.byteOffset, buf2.byteLength); } return buf2; } // node_modules/uint8arrays/dist/src/alloc.js function alloc(size = 0) { if (globalThis.Buffer?.alloc != null) { return asUint8Array(globalThis.Buffer.alloc(size)); } return new Uint8Array(size); } function allocUnsafe(size = 0) { if (globalThis.Buffer?.allocUnsafe != null) { return asUint8Array(globalThis.Buffer.allocUnsafe(size)); } return new Uint8Array(size); } // node_modules/uint8arrays/dist/src/concat.js function concat(arrays, length5) { if (length5 == null) { length5 = arrays.reduce((acc, curr) => acc + curr.length, 0); } const output2 = allocUnsafe(length5); let offset = 0; for (const arr of arrays) { output2.set(arr, offset); offset += arr.length; } return asUint8Array(output2); } // 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/multiformats/src/bases/identity.js var identity_exports = {}; __export(identity_exports, { identity: () => identity }); var identity = from({ prefix: "\0", name: "identity", encode: (buf2) => toString(buf2), decode: (str3) => fromString(str3) }); // node_modules/multiformats/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/multiformats/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/multiformats/src/bases/base10.js var base10_exports = {}; __export(base10_exports, { base10: () => base10 }); var base10 = baseX({ prefix: "9", name: "base10", alphabet: "0123456789" }); // node_modules/multiformats/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/multiformats/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 }); 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/multiformats/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/multiformats/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/multiformats/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 = ( /** @type {string[]} */ alphabet.reduce( (p, c, i) => { p[i] = c; return p; }, /** @type {string[]} */ [] ) ); var alphabetCharsToBytes = ( /** @type {number[]} */ alphabet.reduce( (p, c, i) => { p[ /** @type {number} */ c.codePointAt(0) ] = i; return p; }, /** @type {number[]} */ [] ) ); function encode3(data) { return data.reduce((p, c) => { p += alphabetBytesToChars[c]; return p; }, ""); } function decode5(str3) { const byts = []; for (const char of str3) { const byt = alphabetCharsToBytes[ /** @type {number} */ char.codePointAt(0) ]; if (byt === void 0) { 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/multiformats/src/hashes/identity.js var identity_exports2 = {}; __export(identity_exports2, { identity: () => identity2 }); var code = 0; var name = "identity"; var encode4 = coerce; var digest = (input) => create(code, encode4(input)); var identity2 = { code, name, encode: encode4, digest }; // node_modules/multiformats/src/codecs/raw.js var raw_exports = {}; __export(raw_exports, { code: () => code2, decode: () => decode6, encode: () => encode5, name: () => name2 }); var name2 = "raw"; var code2 = 85; var encode5 = (node) => coerce(node); var decode6 = (data) => coerce(data); // node_modules/multiformats/src/codecs/json.js var textEncoder2 = new TextEncoder(); var textDecoder2 = new TextDecoder(); // node_modules/multiformats/src/cid.js var format = (link, base6) => { const { bytes: bytes2, version } = link; switch (version) { case 0: return toStringV0( bytes2, baseCache(link), /** @type {API.MultibaseEncoder<"z">} */ base6 || base58btc.encoder ); default: return toStringV1( bytes2, baseCache(link), /** @type {API.MultibaseEncoder} */ base6 || base32.encoder ); } }; var cache = /* @__PURE__ */ new WeakMap(); var baseCache = (cid) => { const baseCache5 = cache.get(cid); if (baseCache5 == null) { const baseCache6 = /* @__PURE__ */ new Map(); cache.set(cid, baseCache6); return baseCache6; } return baseCache5; }; var CID = class { /** * @param {Version} version - Version of the CID * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv * @param {API.MultihashDigest} multihash - (Multi)hash of the of the content. * @param {Uint8Array} bytes * */ constructor(version, code5, multihash, bytes2) { this.code = code5; this.version = version; this.multihash = multihash; this.bytes = bytes2; this["/"] = bytes2; } /** * 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; } /** * @returns {CID} */ toV0() { switch (this.version) { case 0: { return ( /** @type {CID} */ this ); } case 1: { const { code: code5, multihash } = this; if (code5 !== 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 ( /** @type {CID} */ CID.createV0( /** @type {API.MultihashDigest} */ multihash ) ); } default: { throw Error( `Can not convert CID version ${this.version} to version 0. This is a bug please report` ); } } } /** * @returns {CID} */ toV1() { switch (this.version) { case 0: { const { code: code5, digest: digest2 } = this.multihash; const multihash = create(code5, digest2); return ( /** @type {CID} */ CID.createV1(this.code, multihash) ); } case 1: { return ( /** @type {CID} */ this ); } default: { throw Error( `Can not convert CID version ${this.version} to version 1. This is a bug please report` ); } } } /** * @param {unknown} other * @returns {other is CID} */ equals(other) { return CID.equals(this, other); } /** * @template {unknown} Data * @template {number} Format * @template {number} Alg * @template {API.Version} Version * @param {API.Link} self * @param {unknown} other * @returns {other is CID} */ static equals(self2, other) { const unknown = ( /** @type {{code?:unknown, version?:unknown, multihash?:unknown}} */ other ); return unknown && self2.code === unknown.code && self2.version === unknown.version && equals2(self2.multihash, unknown.multihash); } /** * @param {API.MultibaseEncoder} [base] * @returns {string} */ toString(base6) { return format(this, base6); } toJSON() { return { "/": format(this) }; } link() { return this; } get [Symbol.toStringTag]() { return "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. * * @template {unknown} Data * @template {number} Format * @template {number} Alg * @template {API.Version} Version * @template {unknown} U * @param {API.Link|U} input * @returns {CID|null} */ static asCID(input) { if (input == null) { return null; } const value = ( /** @type {any} */ input ); if (value instanceof CID) { return value; } else if (value["/"] != null && value["/"] === value.bytes || value.asCID === value) { const { version, code: code5, multihash, bytes: bytes2 } = value; return new CID( version, code5, /** @type {API.MultihashDigest} */ multihash, bytes2 || encodeCID(version, code5, multihash.bytes) ); } else if (value[cidSymbol] === true) { const { version, multihash, code: code5 } = value; const digest2 = ( /** @type {API.MultihashDigest} */ decode4(multihash) ); return CID.create(version, code5, digest2); } else { return null; } } /** * * @template {unknown} Data * @template {number} Format * @template {number} Alg * @template {API.Version} Version * @param {Version} version - Version of the CID * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv * @param {API.MultihashDigest} digest - (Multi)hash of the of the content. * @returns {CID} */ static create(version, code5, digest2) { if (typeof code5 !== "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 (code5 !== DAG_PB_CODE) { throw new Error( `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding` ); } else { return new CID(version, code5, digest2, digest2.bytes); } } case 1: { const bytes2 = encodeCID(version, code5, digest2.bytes); return new CID(version, code5, digest2, bytes2); } default: { throw new Error("Invalid version"); } } } /** * Simplified version of `create` for CIDv0. * * @template {unknown} [T=unknown] * @param {API.MultihashDigest} digest - Multihash. * @returns {CID} */ static createV0(digest2) { return CID.create(0, DAG_PB_CODE, digest2); } /** * Simplified version of `create` for CIDv1. * * @template {unknown} Data * @template {number} Code * @template {number} Alg * @param {Code} code - Content encoding format code. * @param {API.MultihashDigest} digest - Miltihash of the content. * @returns {CID} */ static createV1(code5, digest2) { return CID.create(1, code5, 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. * * @template {unknown} Data * @template {number} Code * @template {number} Alg * @template {API.Version} Ver * @param {API.ByteView>} bytes * @returns {CID} */ static decode(bytes2) { const [cid, remainder] = CID.decodeFirst(bytes2); if (remainder.length) { 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. * * @template {unknown} T * @template {number} C * @template {number} A * @template {API.Version} V * @param {API.ByteView>} bytes * @returns {[CID, Uint8Array]} */ static decodeFirst(bytes2) { const specs = CID.inspectBytes(bytes2); const prefixSize = specs.size - specs.multihashSize; const multihashBytes = coerce( bytes2.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( /** @type {API.MultihashDigest} */ digest2 ) : CID.createV1(specs.codec, digest2); return [ /** @type {CID} */ cid, bytes2.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. * * @template {unknown} T * @template {number} C * @template {number} A * @template {API.Version} V * @param {API.ByteView>} initialBytes * @returns {{ version:V, codec:C, multihashCode:A, digestSize:number, multihashSize:number, size:number }} */ static inspectBytes(initialBytes) { let offset = 0; const next = () => { const [i, length5] = decode3(initialBytes.subarray(offset)); offset += length5; return i; }; let version = ( /** @type {V} */ next() ); let codec = ( /** @type {C} */ DAG_PB_CODE ); if ( /** @type {number} */ version === 18 ) { version = /** @type {V} */ 0; offset = 0; } else { codec = /** @type {C} */ next(); } if (version !== 0 && version !== 1) { throw new RangeError(`Invalid CID version ${version}`); } const prefixSize = offset; const multihashCode = ( /** @type {A} */ 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). * * @template {string} Prefix * @template {unknown} Data * @template {number} Code * @template {number} Alg * @template {API.Version} Ver * @param {API.ToString, Prefix>} source * @param {API.MultibaseDecoder} [base] * @returns {CID} */ static parse(source, base6) { const [prefix, bytes2] = parseCIDtoBytes(source, base6); const cid = CID.decode(bytes2); 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; } }; var parseCIDtoBytes = (source, base6) => { switch (source[0]) { case "Q": { const decoder = base6 || base58btc; return [ /** @type {Prefix} */ base58btc.prefix, decoder.decode(`${base58btc.prefix}${source}`) ]; } case base58btc.prefix: { const decoder = base6 || base58btc; return [ /** @type {Prefix} */ base58btc.prefix, decoder.decode(source) ]; } case base32.prefix: { const decoder = base6 || base32; return [ /** @type {Prefix} */ base32.prefix, decoder.decode(source) ]; } default: { if (base6 == null) { throw Error( "To parse non base32 or base58btc encoded CID multibase decoder must be provided" ); } return [ /** @type {Prefix} */ source[0], base6.decode(source) ]; } } }; var toStringV0 = (bytes2, cache5, base6) => { const { prefix } = base6; if (prefix !== base58btc.prefix) { throw Error(`Cannot string encode V0 in ${base6.name} encoding`); } const cid = cache5.get(prefix); if (cid == null) { const cid2 = base6.encode(bytes2).slice(1); cache5.set(prefix, cid2); return cid2; } else { return cid; } }; var toStringV1 = (bytes2, cache5, base6) => { const { prefix } = base6; const cid = cache5.get(prefix); if (cid == null) { const cid2 = base6.encode(bytes2); cache5.set(prefix, cid2); return cid2; } else { return cid; } }; var DAG_PB_CODE = 112; var SHA_256_CODE = 18; var encodeCID = (version, code5, multihash) => { const codeOffset = encodingLength(version); const hashOffset = codeOffset + encodingLength(code5); const bytes2 = new Uint8Array(hashOffset + multihash.byteLength); encodeTo(version, bytes2, 0); encodeTo(code5, bytes2, codeOffset); bytes2.set(multihash, hashOffset); return bytes2; }; var cidSymbol = Symbol.for("@ipld/js-cid/CID"); // node_modules/multiformats/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/uint8arrays/dist/src/util/bases.js function createCodec(name5, prefix, encode16, decode23) { return { name: name5, prefix, encoder: { name: name5, prefix, encode: encode16 }, decoder: { decode: decode23 } }; } var string = createCodec("utf8", "u", (buf2) => { const decoder = new TextDecoder("utf8"); return "u" + decoder.decode(buf2); }, (str3) => { const encoder = new TextEncoder(); return encoder.encode(str3.substring(1)); }); var ascii = createCodec("ascii", "a", (buf2) => { let string2 = "a"; for (let i = 0; i < buf2.length; i++) { string2 += String.fromCharCode(buf2[i]); } return string2; }, (str3) => { str3 = str3.substring(1); const buf2 = allocUnsafe(str3.length); for (let i = 0; i < str3.length; i++) { buf2[i] = str3.charCodeAt(i); } return buf2; }); var BASES = { utf8: string, "utf-8": string, hex: bases.base16, latin1: ascii, ascii, binary: ascii, ...bases }; var bases_default = BASES; // node_modules/uint8arrays/dist/src/from-string.js function fromString2(string2, encoding = "utf8") { const base6 = bases_default[encoding]; if (base6 == null) { throw new Error(`Unsupported encoding "${encoding}"`); } if ((encoding === "utf8" || encoding === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null) { return asUint8Array(globalThis.Buffer.from(string2, "utf-8")); } return base6.decoder.decode(`${base6.prefix}${string2}`); } // node_modules/uint8arrays/dist/src/to-string.js function toString2(array, encoding = "utf8") { const base6 = bases_default[encoding]; if (base6 == null) { throw new Error(`Unsupported encoding "${encoding}"`); } if ((encoding === "utf8" || encoding === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null) { return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString("utf8"); } return base6.encoder.encode(array).substring(1); } // dist/esm/src/utils/secp256r1.js var __awaiter3 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var u8a = { toString: toString2, fromString: fromString2 }; var Secp256r1 = class { /** * Validates the given JWK is a SECP256R1 key. * @throws {Error} if fails validation. */ static validateKey(jwk) { if (jwk.kty !== "EC" || jwk.crv !== "P-256") { throw new DwnError(DwnErrorCode.Secp256r1KeyNotValid, "Invalid SECP256R1 JWK: `kty` MUST be `EC`. `crv` MUST be `P-256`"); } } /** * Converts a public key in bytes into a JWK. */ static publicKeyToJwk(publicKeyBytes) { return __awaiter3(this, void 0, void 0, function* () { let uncompressedPublicKeyBytes; if (publicKeyBytes.byteLength === 33) { const curvePoints = p256.ProjectivePoint.fromHex(publicKeyBytes); uncompressedPublicKeyBytes = curvePoints.toRawBytes(false); } else { uncompressedPublicKeyBytes = publicKeyBytes; } const x = Encoder2.bytesToBase64Url(uncompressedPublicKeyBytes.subarray(1, 33)); const y = Encoder2.bytesToBase64Url(uncompressedPublicKeyBytes.subarray(33, 65)); const publicJwk = { alg: "ES256", kty: "EC", crv: "P-256", x, y }; return publicJwk; }); } /** * Creates a private key in raw bytes from the given SECP256R1 JWK. */ static privateJwkToBytes(privateJwk) { const privateKey = Encoder2.base64UrlToBytes(privateJwk.d); return privateKey; } /** * Signs the provided content using the provided JWK. * Signature that is outputted is JWS format, not DER. */ static sign(content, privateJwk) { return __awaiter3(this, void 0, void 0, function* () { Secp256r1.validateKey(privateJwk); const hashedContent = yield sha256.encode(content); const privateKeyBytes = Secp256r1.privateJwkToBytes(privateJwk); return Promise.resolve(p256.sign(hashedContent, privateKeyBytes).toCompactRawBytes()); }); } /** * Verifies a signature against the provided payload hash and public key. * @param signature - the signature to verify. Can be in either DER or compact format. If using Oracle Cloud KMS, keys will be DER formatted. * @returns a boolean indicating whether the signature is valid. */ static verify(content, signature, publicJwk) { return __awaiter3(this, void 0, void 0, function* () { Secp256r1.validateKey(publicJwk); let sig; if (signature.length === 64) { sig = p256.Signature.fromCompact(signature); } else { sig = p256.Signature.fromDER(signature); } const hashedContent = yield sha256.encode(content); const keyBytes = p256.ProjectivePoint.fromAffine({ x: Secp256r1.bytesToBigInt(Encoder2.base64UrlToBytes(publicJwk.x)), y: Secp256r1.bytesToBigInt(Encoder2.base64UrlToBytes(publicJwk.y)) }).toRawBytes(false); return p256.verify(sig, hashedContent, keyBytes); }); } /** * Generates a random key pair in JWK format. */ static generateKeyPair() { return __awaiter3(this, void 0, void 0, function* () { const privateKeyBytes = p256.utils.randomPrivateKey(); const publicKeyBytes = secp256r1.getPublicKey(privateKeyBytes, false); const d = Encoder2.bytesToBase64Url(privateKeyBytes); const publicJwk = yield Secp256r1.publicKeyToJwk(publicKeyBytes); const privateJwk = Object.assign(Object.assign({}, publicJwk), { d }); return { publicJwk, privateJwk }; }); } static bytesToBigInt(b) { return BigInt(`0x` + u8a.toString(b, "base16")); } }; // dist/esm/src/jose/algorithms/signing/signature-algorithms.js var signatureAlgorithms = { "Ed25519": ed25519, "secp256k1": { sign: Secp256k1.sign, verify: Secp256k1.verify, generateKeyPair: Secp256k1.generateKeyPair, publicKeyToJwk: Secp256k1.publicKeyToJwk }, "P-256": { sign: Secp256r1.sign, verify: Secp256r1.verify, generateKeyPair: Secp256r1.generateKeyPair, publicKeyToJwk: Secp256r1.publicKeyToJwk } }; // dist/esm/src/utils/private-key-signer.js var __awaiter4 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var PrivateKeySigner = class { constructor(options) { var _a, _b; if (options.keyId === void 0 && options.privateJwk.kid === void 0) { throw new DwnError(DwnErrorCode.PrivateKeySignerUnableToDeduceKeyId, `Unable to deduce the key ID`); } if (options.algorithm === void 0 && options.privateJwk.alg === void 0) { throw new DwnError(DwnErrorCode.PrivateKeySignerUnableToDeduceAlgorithm, `Unable to deduce the signature algorithm`); } this.keyId = (_a = options.keyId) !== null && _a !== void 0 ? _a : options.privateJwk.kid; this.algorithm = (_b = options.algorithm) !== null && _b !== void 0 ? _b : options.privateJwk.alg; this.privateJwk = options.privateJwk; this.signatureAlgorithm = signatureAlgorithms[options.privateJwk.crv]; if (!this.signatureAlgorithm) { throw new DwnError(DwnErrorCode.PrivateKeySignerUnsupportedCurve, `Unsupported crv ${options.privateJwk.crv}, crv must be one of ${Object.keys(signatureAlgorithms)}`); } } /** * Signs the given content and returns the signature as bytes. */ sign(content) { return __awaiter4(this, void 0, void 0, function* () { const signatureBytes = yield this.signatureAlgorithm.sign(content, this.privateJwk); return signatureBytes; }); } }; // dist/esm/src/utils/jws.js var __awaiter5 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var Jws = class { /** * Gets the `kid` from a general JWS signature entry. */ static getKid(signatureEntry) { const { kid } = Encoder2.base64UrlToObject(signatureEntry.protected); return kid; } /** * Gets the signer DID from a general JWS signature entry. */ static getSignerDid(signatureEntry) { const kid = Jws.getKid(signatureEntry); const did = Jws.extractDid(kid); return did; } /** * Verifies the signature against the given payload. * @returns `true` if signature is valid; `false` otherwise */ static verifySignature(base64UrlPayload, signatureEntry, jwkPublic) { return __awaiter5(this, void 0, void 0, function* () { const signatureAlgorithm = signatureAlgorithms[jwkPublic.crv]; if (!signatureAlgorithm) { throw new DwnError(DwnErrorCode.JwsVerifySignatureUnsupportedCrv, `unsupported crv. crv must be one of ${Object.keys(signatureAlgorithms)}`); } const payload = Encoder2.stringToBytes(`${signatureEntry.protected}.${base64UrlPayload}`); const signatureBytes = Encoder2.base64UrlToBytes(signatureEntry.signature); return yield signatureAlgorithm.verify(payload, signatureBytes, jwkPublic); }); } /** * Decodes the payload of the given JWS object as a plain object. */ static decodePlainObjectPayload(jws) { let payloadJson; try { payloadJson = Encoder2.base64UrlToObject(jws.payload); } catch (_a) { throw new DwnError(DwnErrorCode.JwsDecodePlainObjectPayloadInvalid, "payload is not a JSON object"); } if (!(0, import_isPlainObject.default)(payloadJson)) { throw new DwnError(DwnErrorCode.JwsDecodePlainObjectPayloadInvalid, "signed payload must be a plain object"); } return payloadJson; } /** * Extracts the DID from the given `kid` string. */ static extractDid(kid) { const [did] = kid.split("#"); return did; } /** * Creates a Signer[] from the given Personas. */ static createSigners(keyMaterials) { const signers = keyMaterials.map((keyMaterial) => Jws.createSigner(keyMaterial)); return signers; } /** * Creates a Signer from the given Persona. */ static createSigner(keyMaterial) { const privateJwk = keyMaterial.keyPair.privateJwk; const keyId = keyMaterial.keyId; const signer = new PrivateKeySigner({ privateJwk, keyId }); return signer; } }; // dist/esm/src/utils/memory-cache.js var import_lru_cache = require("lru-cache"); var __awaiter6 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var MemoryCache = class { /** * @param timeToLiveInSeconds time-to-live for every key-value pair set in the cache */ constructor(timeToLiveInSeconds) { this.timeToLiveInSeconds = timeToLiveInSeconds; this.cache = new import_lru_cache.LRUCache({ max: 1e5, ttl: timeToLiveInSeconds * 1e3 }); } set(key, value) { return __awaiter6(this, void 0, void 0, function* () { try { this.cache.set(key, value); } catch (_a) { } }); } get(key) { return __awaiter6(this, void 0, void 0, function* () { return this.cache.get(key); }); } }; // dist/esm/generated/precompiled-validators.js var precompiled_validators_exports = {}; __export(precompiled_validators_exports, { Authorization: () => Authorization, AuthorizationDelegatedGrant: () => AuthorizationDelegatedGrant, AuthorizationOwner: () => AuthorizationOwner, Definitions: () => Definitions, EventsFilter: () => EventsFilter, EventsGet: () => EventsGet, EventsQuery: () => EventsQuery, EventsSubscribe: () => EventsSubscribe, GeneralJwk: () => GeneralJwk, GeneralJws: () => GeneralJws, GenericSignaturePayload: () => GenericSignaturePayload, JwkVerificationMethod: () => JwkVerificationMethod, MessagesGet: () => MessagesGet, NumberRangeFilter: () => NumberRangeFilter, PaginationCursor: () => PaginationCursor, PermissionGrantData: () => PermissionGrantData, PermissionRequestData: () => PermissionRequestData, PermissionRevocationData: () => PermissionRevocationData, PermissionsDefinitions: () => PermissionsDefinitions, PermissionsScopes: () => PermissionsScopes, ProtocolDefinition: () => ProtocolDefinition, ProtocolRuleSet: () => ProtocolRuleSet, ProtocolsConfigure: () => ProtocolsConfigure, ProtocolsQuery: () => ProtocolsQuery, PublicJwk: () => PublicJwk, RecordsDelete: () => RecordsDelete, RecordsFilter: () => RecordsFilter, RecordsQuery: () => RecordsQuery, RecordsRead: () => RecordsRead, RecordsSubscribe: () => RecordsSubscribe, RecordsWrite: () => RecordsWrite, RecordsWriteDataEncoded: () => RecordsWriteDataEncoded, RecordsWriteSignaturePayload: () => RecordsWriteSignaturePayload, RecordsWriteUnidentified: () => RecordsWriteUnidentified, StringRangeFilter: () => StringRangeFilter }); var Authorization = validate20; var pattern4 = new RegExp("^[A-Za-z0-9_-]+$", "u"); function validate21(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate21.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "payload" || key0 === "signatures")) { validate21.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.payload !== void 0) { let data0 = data.payload; const _errs2 = errors; const _errs3 = errors; if (errors === _errs3) { if (typeof data0 === "string") { if (!pattern4.test(data0)) { validate21.errors = [{ instancePath: instancePath + "/payload", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url/pattern", keyword: "pattern", params: { pattern: "^[A-Za-z0-9_-]+$" }, message: 'must match pattern "^[A-Za-z0-9_-]+$"' }]; return false; } } else { validate21.errors = [{ instancePath: instancePath + "/payload", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.signatures !== void 0) { let data1 = data.signatures; const _errs5 = errors; if (errors === _errs5) { if (Array.isArray(data1)) { if (data1.length < 1) { validate21.errors = [{ instancePath: instancePath + "/signatures", schemaPath: "#/properties/signatures/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; return false; } else { var valid2 = true; const len0 = data1.length; for (let i0 = 0; i0 < len0; i0++) { let data2 = data1[i0]; const _errs7 = errors; if (errors === _errs7) { if (data2 && typeof data2 == "object" && !Array.isArray(data2)) { if (data2.protected !== void 0) { let data3 = data2.protected; const _errs9 = errors; const _errs10 = errors; if (errors === _errs10) { if (typeof data3 === "string") { if (!pattern4.test(data3)) { validate21.errors = [{ instancePath: instancePath + "/signatures/" + i0 + "/protected", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url/pattern", keyword: "pattern", params: { pattern: "^[A-Za-z0-9_-]+$" }, message: 'must match pattern "^[A-Za-z0-9_-]+$"' }]; return false; } } else { validate21.errors = [{ instancePath: instancePath + "/signatures/" + i0 + "/protected", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid3 = _errs9 === errors; } else { var valid3 = true; } if (valid3) { if (data2.signature !== void 0) { let data4 = data2.signature; const _errs12 = errors; const _errs13 = errors; if (errors === _errs13) { if (typeof data4 === "string") { if (!pattern4.test(data4)) { validate21.errors = [{ instancePath: instancePath + "/signatures/" + i0 + "/signature", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url/pattern", keyword: "pattern", params: { pattern: "^[A-Za-z0-9_-]+$" }, message: 'must match pattern "^[A-Za-z0-9_-]+$"' }]; return false; } } else { validate21.errors = [{ instancePath: instancePath + "/signatures/" + i0 + "/signature", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid3 = _errs12 === errors; } else { var valid3 = true; } } } else { validate21.errors = [{ instancePath: instancePath + "/signatures/" + i0, schemaPath: "#/properties/signatures/items/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid2 = _errs7 === errors; if (!valid2) { break; } } } } else { validate21.errors = [{ instancePath: instancePath + "/signatures", schemaPath: "#/properties/signatures/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; return false; } } var valid0 = _errs5 === errors; } else { var valid0 = true; } } } } else { validate21.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate21.errors = vErrors; return errors === 0; } validate21.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; function validate20(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate20.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "signature")) { validate20.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.signature !== void 0) { if (!validate21(data.signature, { instancePath: instancePath + "/signature", parentData: data, parentDataProperty: "signature", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate21.errors : vErrors.concat(validate21.errors); errors = vErrors.length; } } } } else { validate20.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate20.errors = vErrors; return errors === 0; } validate20.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var AuthorizationDelegatedGrant = validate24; var schema39 = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://identity.foundation/dwn/json-schemas/records-write-unidentified.json", "type": "object", "required": ["descriptor"], "properties": { "recordId": { "type": "string" }, "contextId": { "type": "string", "pattern": "^[a-zA-Z0-9]+(/[a-zA-Z0-9]+)*$" }, "attestation": { "$ref": "https://identity.foundation/dwn/json-schemas/general-jws.json" }, "authorization": { "$ref": "https://identity.foundation/dwn/json-schemas/authorization-owner.json" }, "encryption": { "type": "object", "properties": { "algorithm": { "type": "string", "enum": ["A256CTR"] }, "initializationVector": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url" }, "keyEncryption": { "type": "array", "minItems": 1, "items": { "type": "object", "properties": { "rootKeyId": { "type": "string" }, "derivationScheme": { "type": "string", "enum": ["dataFormats", "protocolContext", "protocolPath", "schemas"] }, "derivedPublicKey": { "$ref": "https://identity.foundation/dwn/json-schemas/public-jwk.json" }, "algorithm": { "type": "string", "enum": ["ECIES-ES256K"] }, "encryptedKey": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url" }, "initializationVector": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url" }, "ephemeralPublicKey": { "$ref": "https://identity.foundation/dwn/json-schemas/public-jwk.json" }, "messageAuthenticationCode": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url" } }, "additionalProperties": false, "required": ["rootKeyId", "derivationScheme", "algorithm", "encryptedKey", "initializationVector", "ephemeralPublicKey", "messageAuthenticationCode"] } } }, "additionalProperties": false, "required": ["algorithm", "initializationVector", "keyEncryption"] }, "descriptor": { "type": "object", "properties": { "interface": { "enum": ["Records"], "type": "string" }, "method": { "enum": ["Write"], "type": "string" }, "recipient": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did" }, "protocol": { "type": "string" }, "protocolPath": { "type": "string", "pattern": "^[a-zA-Z]+(/[a-zA-Z]+)*$" }, "schema": { "type": "string" }, "tags": { "type": "object", "minProperties": 1, "maxProperties": 10, "additionalProperties": { "oneOf": [{ "type": "string" }, { "type": "number" }, { "type": "boolean" }, { "type": "array", "minItems": 1, "maxItems": 10, "items": { "type": "string" } }, { "type": "array", "minItems": 1, "maxItems": 10, "items": { "type": "number" } }] } }, "parentId": { "type": "string" }, "dataCid": { "type": "string" }, "dataSize": { "type": "number" }, "dateCreated": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" }, "messageTimestamp": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" }, "published": { "type": "boolean" }, "datePublished": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" }, "dataFormat": { "type": "string" } }, "additionalProperties": false, "required": ["interface", "method", "dataCid", "dataSize", "dateCreated", "messageTimestamp", "dataFormat"], "dependencies": { "parentId": ["protocol"] }, "allOf": [{ "$comment": "rule defining `published` and `datePublished` relationship", "anyOf": [{ "properties": { "published": { "type": "boolean", "enum": [true] } }, "required": ["published", "datePublished"] }, { "properties": { "published": { "type": "boolean", "enum": [false] } }, "not": { "required": ["datePublished"] } }, { "allOf": [{ "not": { "required": ["published"] } }, { "not": { "required": ["datePublished"] } }] }] }] } }, "$comment": "rule defining `protocol` and `contextId` relationship", "anyOf": [{ "properties": { "descriptor": { "type": "object", "required": ["protocol", "protocolPath"] } }, "required": ["contextId"] }, { "allOf": [{ "not": { "required": ["contextId"] } }, { "properties": { "descriptor": { "type": "object", "not": { "required": ["protocol"] } } } }, { "properties": { "descriptor": { "type": "object", "not": { "required": ["protocolPath"] } } } }] }] }; var pattern7 = new RegExp("^[a-zA-Z0-9]+(/[a-zA-Z0-9]+)*$", "u"); var pattern12 = new RegExp("^did:([a-z0-9]+):((?:(?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))*:)*((?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))+))((;[a-zA-Z0-9_.:%-]+=[a-zA-Z0-9_.:%-]*)*)(/[^#?]*)?([?][^#]*)?(#.*)?$", "u"); var pattern13 = new RegExp("^[a-zA-Z]+(/[a-zA-Z]+)*$", "u"); var pattern14 = new RegExp("^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$", "u"); var wrapper0 = { validate: validate26 }; function validate29(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate29.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "signature" || key0 === "authorDelegatedGrant" || key0 === "ownerSignature" || key0 === "ownerDelegatedGrant")) { validate29.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { let missing0; if (data.ownerSignature !== void 0 && (data.signature === void 0 && (missing0 = "signature"))) { validate29.errors = [{ instancePath, schemaPath: "#/dependencies", keyword: "dependencies", params: { property: "ownerSignature", missingProperty: missing0, depsCount: 1, deps: "signature" }, message: "must have property signature when property ownerSignature is present" }]; return false; } else { if (data.signature !== void 0) { const _errs2 = errors; if (!validate21(data.signature, { instancePath: instancePath + "/signature", parentData: data, parentDataProperty: "signature", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate21.errors : vErrors.concat(validate21.errors); errors = vErrors.length; } var valid1 = _errs2 === errors; } else { var valid1 = true; } if (valid1) { if (data.authorDelegatedGrant !== void 0) { const _errs3 = errors; if (!wrapper0.validate(data.authorDelegatedGrant, { instancePath: instancePath + "/authorDelegatedGrant", parentData: data, parentDataProperty: "authorDelegatedGrant", rootData, dynamicAnchors })) { vErrors = vErrors === null ? wrapper0.validate.errors : vErrors.concat(wrapper0.validate.errors); errors = vErrors.length; } var valid1 = _errs3 === errors; } else { var valid1 = true; } if (valid1) { if (data.ownerSignature !== void 0) { const _errs4 = errors; if (!validate21(data.ownerSignature, { instancePath: instancePath + "/ownerSignature", parentData: data, parentDataProperty: "ownerSignature", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate21.errors : vErrors.concat(validate21.errors); errors = vErrors.length; } var valid1 = _errs4 === errors; } else { var valid1 = true; } if (valid1) { if (data.ownerDelegatedGrant !== void 0) { const _errs5 = errors; if (!wrapper0.validate(data.ownerDelegatedGrant, { instancePath: instancePath + "/ownerDelegatedGrant", parentData: data, parentDataProperty: "ownerDelegatedGrant", rootData, dynamicAnchors })) { vErrors = vErrors === null ? wrapper0.validate.errors : vErrors.concat(wrapper0.validate.errors); errors = vErrors.length; } var valid1 = _errs5 === errors; } else { var valid1 = true; } } } } } } } else { validate29.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate29.errors = vErrors; return errors === 0; } validate29.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var schema43 = { "$id": "https://identity.foundation/dwn/json-schemas/general-jwk.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "required": ["kty"], "properties": { "alg": { "type": "string" }, "kid": { "type": "string" }, "kty": { "enum": ["EC", "RSA", "oct", "OKP"] }, "crv": { "type": "string" }, "use": { "type": "string" }, "key_ops": { "type": "string" }, "x5u": { "type": "string" }, "x5c": { "type": "string" }, "x5t": { "type": "string" }, "x5t#S256": { "type": "string" } }, "oneOf": [{ "properties": { "kty": { "const": "EC" }, "crv": { "type": "string" }, "x": { "type": "string" }, "y": { "type": "string" }, "d": { "type": "string" } }, "required": ["crv", "x"] }, { "properties": { "kty": { "const": "OKP" }, "crv": { "type": "string" }, "x": { "type": "string" }, "d": { "type": "string" } }, "required": ["crv", "x"] }, { "properties": { "kty": { "const": "RSA" }, "n": { "type": "string" }, "e": { "type": "string" }, "d": { "type": "string" }, "p": { "type": "string" }, "q": { "type": "string" }, "dp": { "type": "string" }, "dq": { "type": "string" }, "qi": { "type": "string" }, "oth": { "type": "object" } }, "required": ["n", "e"] }, { "properties": { "kty": { "const": "oct" }, "k": { "type": "string" } }, "required": ["k"] }] }; function validate33(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate33.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } const _errs0 = errors; const _errs2 = errors; let valid1 = false; let passing0 = null; const _errs3 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.crv === void 0 && (missing0 = "crv") || data.x === void 0 && (missing0 = "x")) { const err0 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/0/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }; if (vErrors === null) { vErrors = [err0]; } else { vErrors.push(err0); } errors++; } else { if (data.kty !== void 0) { const _errs4 = errors; if ("EC" !== data.kty) { const err1 = { instancePath: instancePath + "/kty", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/0/properties/kty/const", keyword: "const", params: { allowedValue: "EC" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err1]; } else { vErrors.push(err1); } errors++; } var valid2 = _errs4 === errors; } else { var valid2 = true; } if (valid2) { if (data.crv !== void 0) { const _errs5 = errors; if (typeof data.crv !== "string") { const err22 = { instancePath: instancePath + "/crv", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/0/properties/crv/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err22]; } else { vErrors.push(err22); } errors++; } var valid2 = _errs5 === errors; } else { var valid2 = true; } if (valid2) { if (data.x !== void 0) { const _errs7 = errors; if (typeof data.x !== "string") { const err3 = { instancePath: instancePath + "/x", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/0/properties/x/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err3]; } else { vErrors.push(err3); } errors++; } var valid2 = _errs7 === errors; } else { var valid2 = true; } if (valid2) { if (data.y !== void 0) { const _errs9 = errors; if (typeof data.y !== "string") { const err4 = { instancePath: instancePath + "/y", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/0/properties/y/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err4]; } else { vErrors.push(err4); } errors++; } var valid2 = _errs9 === errors; } else { var valid2 = true; } if (valid2) { if (data.d !== void 0) { const _errs11 = errors; if (typeof data.d !== "string") { const err5 = { instancePath: instancePath + "/d", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/0/properties/d/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err5]; } else { vErrors.push(err5); } errors++; } var valid2 = _errs11 === errors; } else { var valid2 = true; } } } } } } } var _valid0 = _errs3 === errors; if (_valid0) { valid1 = true; passing0 = 0; var props0 = {}; props0.kty = true; props0.crv = true; props0.x = true; props0.y = true; props0.d = true; } const _errs13 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing1; if (data.crv === void 0 && (missing1 = "crv") || data.x === void 0 && (missing1 = "x")) { const err6 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/1/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }; if (vErrors === null) { vErrors = [err6]; } else { vErrors.push(err6); } errors++; } else { if (data.kty !== void 0) { const _errs14 = errors; if ("OKP" !== data.kty) { const err7 = { instancePath: instancePath + "/kty", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/1/properties/kty/const", keyword: "const", params: { allowedValue: "OKP" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err7]; } else { vErrors.push(err7); } errors++; } var valid3 = _errs14 === errors; } else { var valid3 = true; } if (valid3) { if (data.crv !== void 0) { const _errs15 = errors; if (typeof data.crv !== "string") { const err8 = { instancePath: instancePath + "/crv", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/1/properties/crv/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err8]; } else { vErrors.push(err8); } errors++; } var valid3 = _errs15 === errors; } else { var valid3 = true; } if (valid3) { if (data.x !== void 0) { const _errs17 = errors; if (typeof data.x !== "string") { const err9 = { instancePath: instancePath + "/x", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/1/properties/x/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err9]; } else { vErrors.push(err9); } errors++; } var valid3 = _errs17 === errors; } else { var valid3 = true; } if (valid3) { if (data.d !== void 0) { const _errs19 = errors; if (typeof data.d !== "string") { const err10 = { instancePath: instancePath + "/d", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/1/properties/d/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err10]; } else { vErrors.push(err10); } errors++; } var valid3 = _errs19 === errors; } else { var valid3 = true; } } } } } } var _valid0 = _errs13 === errors; if (_valid0 && valid1) { valid1 = false; passing0 = [passing0, 1]; } else { if (_valid0) { valid1 = true; passing0 = 1; if (props0 !== true) { props0 = props0 || {}; props0.kty = true; props0.crv = true; props0.x = true; props0.d = true; } } const _errs21 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing2; if (data.n === void 0 && (missing2 = "n") || data.e === void 0 && (missing2 = "e")) { const err11 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/2/required", keyword: "required", params: { missingProperty: missing2 }, message: "must have required property '" + missing2 + "'" }; if (vErrors === null) { vErrors = [err11]; } else { vErrors.push(err11); } errors++; } else { if (data.kty !== void 0) { const _errs22 = errors; if ("RSA" !== data.kty) { const err12 = { instancePath: instancePath + "/kty", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/2/properties/kty/const", keyword: "const", params: { allowedValue: "RSA" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err12]; } else { vErrors.push(err12); } errors++; } var valid4 = _errs22 === errors; } else { var valid4 = true; } if (valid4) { if (data.n !== void 0) { const _errs23 = errors; if (typeof data.n !== "string") { const err13 = { instancePath: instancePath + "/n", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/2/properties/n/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err13]; } else { vErrors.push(err13); } errors++; } var valid4 = _errs23 === errors; } else { var valid4 = true; } if (valid4) { if (data.e !== void 0) { const _errs25 = errors; if (typeof data.e !== "string") { const err14 = { instancePath: instancePath + "/e", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/2/properties/e/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err14]; } else { vErrors.push(err14); } errors++; } var valid4 = _errs25 === errors; } else { var valid4 = true; } if (valid4) { if (data.d !== void 0) { const _errs27 = errors; if (typeof data.d !== "string") { const err15 = { instancePath: instancePath + "/d", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/2/properties/d/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err15]; } else { vErrors.push(err15); } errors++; } var valid4 = _errs27 === errors; } else { var valid4 = true; } if (valid4) { if (data.p !== void 0) { const _errs29 = errors; if (typeof data.p !== "string") { const err16 = { instancePath: instancePath + "/p", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/2/properties/p/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err16]; } else { vErrors.push(err16); } errors++; } var valid4 = _errs29 === errors; } else { var valid4 = true; } if (valid4) { if (data.q !== void 0) { const _errs31 = errors; if (typeof data.q !== "string") { const err17 = { instancePath: instancePath + "/q", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/2/properties/q/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err17]; } else { vErrors.push(err17); } errors++; } var valid4 = _errs31 === errors; } else { var valid4 = true; } if (valid4) { if (data.dp !== void 0) { const _errs33 = errors; if (typeof data.dp !== "string") { const err18 = { instancePath: instancePath + "/dp", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/2/properties/dp/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err18]; } else { vErrors.push(err18); } errors++; } var valid4 = _errs33 === errors; } else { var valid4 = true; } if (valid4) { if (data.dq !== void 0) { const _errs35 = errors; if (typeof data.dq !== "string") { const err19 = { instancePath: instancePath + "/dq", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/2/properties/dq/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err19]; } else { vErrors.push(err19); } errors++; } var valid4 = _errs35 === errors; } else { var valid4 = true; } if (valid4) { if (data.qi !== void 0) { const _errs37 = errors; if (typeof data.qi !== "string") { const err20 = { instancePath: instancePath + "/qi", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/2/properties/qi/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err20]; } else { vErrors.push(err20); } errors++; } var valid4 = _errs37 === errors; } else { var valid4 = true; } if (valid4) { if (data.oth !== void 0) { let data18 = data.oth; const _errs39 = errors; if (!(data18 && typeof data18 == "object" && !Array.isArray(data18))) { const err21 = { instancePath: instancePath + "/oth", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/2/properties/oth/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err21]; } else { vErrors.push(err21); } errors++; } var valid4 = _errs39 === errors; } else { var valid4 = true; } } } } } } } } } } } } var _valid0 = _errs21 === errors; if (_valid0 && valid1) { valid1 = false; passing0 = [passing0, 2]; } else { if (_valid0) { valid1 = true; passing0 = 2; if (props0 !== true) { props0 = props0 || {}; props0.kty = true; props0.n = true; props0.e = true; props0.d = true; props0.p = true; props0.q = true; props0.dp = true; props0.dq = true; props0.qi = true; props0.oth = true; } } const _errs41 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing3; if (data.k === void 0 && (missing3 = "k")) { const err22 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/3/required", keyword: "required", params: { missingProperty: missing3 }, message: "must have required property '" + missing3 + "'" }; if (vErrors === null) { vErrors = [err22]; } else { vErrors.push(err22); } errors++; } else { if (data.kty !== void 0) { const _errs42 = errors; if ("oct" !== data.kty) { const err23 = { instancePath: instancePath + "/kty", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/3/properties/kty/const", keyword: "const", params: { allowedValue: "oct" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err23]; } else { vErrors.push(err23); } errors++; } var valid5 = _errs42 === errors; } else { var valid5 = true; } if (valid5) { if (data.k !== void 0) { const _errs43 = errors; if (typeof data.k !== "string") { const err24 = { instancePath: instancePath + "/k", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf/3/properties/k/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err24]; } else { vErrors.push(err24); } errors++; } var valid5 = _errs43 === errors; } else { var valid5 = true; } } } } var _valid0 = _errs41 === errors; if (_valid0 && valid1) { valid1 = false; passing0 = [passing0, 3]; } else { if (_valid0) { valid1 = true; passing0 = 3; if (props0 !== true) { props0 = props0 || {}; props0.kty = true; props0.k = true; } } } } } if (!valid1) { const err25 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/oneOf", keyword: "oneOf", params: { passingSchemas: passing0 }, message: "must match exactly one schema in oneOf" }; if (vErrors === null) { vErrors = [err25]; } else { vErrors.push(err25); } errors++; validate33.errors = vErrors; return false; } else { errors = _errs2; if (vErrors !== null) { if (_errs2) { vErrors.length = _errs2; } else { vErrors = null; } } } if (errors === _errs0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing4; if (data.kty === void 0 && (missing4 = "kty")) { validate33.errors = [{ instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/required", keyword: "required", params: { missingProperty: missing4 }, message: "must have required property '" + missing4 + "'" }]; return false; } else { if (props0 !== true) { props0 = props0 || {}; props0.alg = true; props0.kid = true; props0.kty = true; props0.crv = true; props0.use = true; props0.key_ops = true; props0.x5u = true; props0.x5c = true; props0.x5t = true; props0["x5t#S256"] = true; } if (data.alg !== void 0) { const _errs45 = errors; if (typeof data.alg !== "string") { validate33.errors = [{ instancePath: instancePath + "/alg", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/properties/alg/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid6 = _errs45 === errors; } else { var valid6 = true; } if (valid6) { if (data.kid !== void 0) { const _errs47 = errors; if (typeof data.kid !== "string") { validate33.errors = [{ instancePath: instancePath + "/kid", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/properties/kid/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid6 = _errs47 === errors; } else { var valid6 = true; } if (valid6) { if (data.kty !== void 0) { let data23 = data.kty; const _errs49 = errors; if (!(data23 === "EC" || data23 === "RSA" || data23 === "oct" || data23 === "OKP")) { validate33.errors = [{ instancePath: instancePath + "/kty", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/properties/kty/enum", keyword: "enum", params: { allowedValues: schema43.properties.kty.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid6 = _errs49 === errors; } else { var valid6 = true; } if (valid6) { if (data.crv !== void 0) { const _errs50 = errors; if (typeof data.crv !== "string") { validate33.errors = [{ instancePath: instancePath + "/crv", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/properties/crv/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid6 = _errs50 === errors; } else { var valid6 = true; } if (valid6) { if (data.use !== void 0) { const _errs52 = errors; if (typeof data.use !== "string") { validate33.errors = [{ instancePath: instancePath + "/use", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/properties/use/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid6 = _errs52 === errors; } else { var valid6 = true; } if (valid6) { if (data.key_ops !== void 0) { const _errs54 = errors; if (typeof data.key_ops !== "string") { validate33.errors = [{ instancePath: instancePath + "/key_ops", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/properties/key_ops/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid6 = _errs54 === errors; } else { var valid6 = true; } if (valid6) { if (data.x5u !== void 0) { const _errs56 = errors; if (typeof data.x5u !== "string") { validate33.errors = [{ instancePath: instancePath + "/x5u", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/properties/x5u/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid6 = _errs56 === errors; } else { var valid6 = true; } if (valid6) { if (data.x5c !== void 0) { const _errs58 = errors; if (typeof data.x5c !== "string") { validate33.errors = [{ instancePath: instancePath + "/x5c", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/properties/x5c/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid6 = _errs58 === errors; } else { var valid6 = true; } if (valid6) { if (data.x5t !== void 0) { const _errs60 = errors; if (typeof data.x5t !== "string") { validate33.errors = [{ instancePath: instancePath + "/x5t", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/properties/x5t/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid6 = _errs60 === errors; } else { var valid6 = true; } if (valid6) { if (data["x5t#S256"] !== void 0) { const _errs62 = errors; if (typeof data["x5t#S256"] !== "string") { validate33.errors = [{ instancePath: instancePath + "/x5t#S256", schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/properties/x5t%23S256/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid6 = _errs62 === errors; } else { var valid6 = true; } } } } } } } } } } } } else { validate33.errors = [{ instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/general-jwk.json/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs0 === errors; if (valid0) { const _errs64 = errors; const _errs65 = errors; const _errs66 = errors; let valid8 = false; const _errs67 = errors; const _errs69 = errors; let valid9 = false; const _errs70 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing5; if (data.d === void 0 && (missing5 = "d")) { const err26 = {}; if (vErrors === null) { vErrors = [err26]; } else { vErrors.push(err26); } errors++; } } var _valid2 = _errs70 === errors; valid9 = valid9 || _valid2; if (!valid9) { const err27 = {}; if (vErrors === null) { vErrors = [err27]; } else { vErrors.push(err27); } errors++; } else { errors = _errs69; if (vErrors !== null) { if (_errs69) { vErrors.length = _errs69; } else { vErrors = null; } } } if (errors === _errs67) { if (data && typeof data == "object" && !Array.isArray(data)) { if (data.kty !== void 0) { if ("EC" !== data.kty) { const err28 = {}; if (vErrors === null) { vErrors = [err28]; } else { vErrors.push(err28); } errors++; } } } else { const err29 = {}; if (vErrors === null) { vErrors = [err29]; } else { vErrors.push(err29); } errors++; } } var _valid1 = _errs67 === errors; valid8 = valid8 || _valid1; if (_valid1) { var props1 = {}; props1.kty = true; } const _errs72 = errors; const _errs74 = errors; let valid11 = false; const _errs75 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing6; if (data.d === void 0 && (missing6 = "d")) { const err30 = {}; if (vErrors === null) { vErrors = [err30]; } else { vErrors.push(err30); } errors++; } } var _valid3 = _errs75 === errors; valid11 = valid11 || _valid3; if (!valid11) { const err31 = {}; if (vErrors === null) { vErrors = [err31]; } else { vErrors.push(err31); } errors++; } else { errors = _errs74; if (vErrors !== null) { if (_errs74) { vErrors.length = _errs74; } else { vErrors = null; } } } if (errors === _errs72) { if (data && typeof data == "object" && !Array.isArray(data)) { if (data.kty !== void 0) { if ("OKP" !== data.kty) { const err32 = {}; if (vErrors === null) { vErrors = [err32]; } else { vErrors.push(err32); } errors++; } } } else { const err33 = {}; if (vErrors === null) { vErrors = [err33]; } else { vErrors.push(err33); } errors++; } } var _valid1 = _errs72 === errors; valid8 = valid8 || _valid1; if (_valid1) { if (props1 !== true) { props1 = props1 || {}; props1.kty = true; } } const _errs77 = errors; const _errs79 = errors; let valid13 = false; const _errs80 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing7; if (data.d === void 0 && (missing7 = "d")) { const err34 = {}; if (vErrors === null) { vErrors = [err34]; } else { vErrors.push(err34); } errors++; } } var _valid4 = _errs80 === errors; valid13 = valid13 || _valid4; const _errs81 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing8; if (data.p === void 0 && (missing8 = "p")) { const err35 = {}; if (vErrors === null) { vErrors = [err35]; } else { vErrors.push(err35); } errors++; } } var _valid4 = _errs81 === errors; valid13 = valid13 || _valid4; const _errs82 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing9; if (data.q === void 0 && (missing9 = "q")) { const err36 = {}; if (vErrors === null) { vErrors = [err36]; } else { vErrors.push(err36); } errors++; } } var _valid4 = _errs82 === errors; valid13 = valid13 || _valid4; const _errs83 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing10; if (data.dp === void 0 && (missing10 = "dp")) { const err37 = {}; if (vErrors === null) { vErrors = [err37]; } else { vErrors.push(err37); } errors++; } } var _valid4 = _errs83 === errors; valid13 = valid13 || _valid4; const _errs84 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing11; if (data.dq === void 0 && (missing11 = "dq")) { const err38 = {}; if (vErrors === null) { vErrors = [err38]; } else { vErrors.push(err38); } errors++; } } var _valid4 = _errs84 === errors; valid13 = valid13 || _valid4; const _errs85 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing12; if (data.qi === void 0 && (missing12 = "qi")) { const err39 = {}; if (vErrors === null) { vErrors = [err39]; } else { vErrors.push(err39); } errors++; } } var _valid4 = _errs85 === errors; valid13 = valid13 || _valid4; const _errs86 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing13; if (data.oth === void 0 && (missing13 = "oth")) { const err40 = {}; if (vErrors === null) { vErrors = [err40]; } else { vErrors.push(err40); } errors++; } } var _valid4 = _errs86 === errors; valid13 = valid13 || _valid4; if (!valid13) { const err41 = {}; if (vErrors === null) { vErrors = [err41]; } else { vErrors.push(err41); } errors++; } else { errors = _errs79; if (vErrors !== null) { if (_errs79) { vErrors.length = _errs79; } else { vErrors = null; } } } if (errors === _errs77) { if (data && typeof data == "object" && !Array.isArray(data)) { if (data.kty !== void 0) { const _errs87 = errors; if ("RSA" !== data.kty) { const err42 = {}; if (vErrors === null) { vErrors = [err42]; } else { vErrors.push(err42); } errors++; } var valid14 = _errs87 === errors; } else { var valid14 = true; } if (valid14) { if (data.oth !== void 0) { let data34 = data.oth; const _errs88 = errors; if (!(data34 && typeof data34 == "object" && !Array.isArray(data34))) { const err43 = {}; if (vErrors === null) { vErrors = [err43]; } else { vErrors.push(err43); } errors++; } var valid14 = _errs88 === errors; } else { var valid14 = true; } } } else { const err44 = {}; if (vErrors === null) { vErrors = [err44]; } else { vErrors.push(err44); } errors++; } } var _valid1 = _errs77 === errors; valid8 = valid8 || _valid1; if (_valid1) { if (props1 !== true) { props1 = props1 || {}; props1.kty = true; props1.d = true; props1.p = true; props1.q = true; props1.dp = true; props1.dq = true; props1.qi = true; props1.oth = true; } } if (!valid8) { const err45 = {}; if (vErrors === null) { vErrors = [err45]; } else { vErrors.push(err45); } errors++; } else { errors = _errs66; if (vErrors !== null) { if (_errs66) { vErrors.length = _errs66; } else { vErrors = null; } } } var valid7 = _errs65 === errors; if (valid7) { validate33.errors = [{ instancePath, schemaPath: "#/not", keyword: "not", params: {}, message: "must NOT be valid" }]; return false; } else { errors = _errs64; if (vErrors !== null) { if (_errs64) { vErrors.length = _errs64; } else { vErrors = null; } } } } validate33.errors = vErrors; evaluated0.props = props0; return errors === 0; } validate33.evaluated = { "dynamicProps": true, "dynamicItems": false }; var func1 = Object.prototype.hasOwnProperty; function validate27(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate27.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } const _errs2 = errors; let valid0 = false; const _errs3 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.contextId === void 0 && (missing0 = "contextId")) { const err0 = { instancePath, schemaPath: "#/anyOf/0/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }; if (vErrors === null) { vErrors = [err0]; } else { vErrors.push(err0); } errors++; } else { if (data.descriptor !== void 0) { let data0 = data.descriptor; const _errs4 = errors; if (errors === _errs4) { if (data0 && typeof data0 == "object" && !Array.isArray(data0)) { let missing1; if (data0.protocol === void 0 && (missing1 = "protocol") || data0.protocolPath === void 0 && (missing1 = "protocolPath")) { const err1 = { instancePath: instancePath + "/descriptor", schemaPath: "#/anyOf/0/properties/descriptor/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }; if (vErrors === null) { vErrors = [err1]; } else { vErrors.push(err1); } errors++; } } else { const err22 = { instancePath: instancePath + "/descriptor", schemaPath: "#/anyOf/0/properties/descriptor/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err22]; } else { vErrors.push(err22); } errors++; } } } } } var _valid0 = _errs3 === errors; valid0 = valid0 || _valid0; if (_valid0) { var props0 = {}; props0.descriptor = true; } const _errs6 = errors; const _errs7 = errors; const _errs8 = errors; const _errs9 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing2; if (data.contextId === void 0 && (missing2 = "contextId")) { const err3 = {}; if (vErrors === null) { vErrors = [err3]; } else { vErrors.push(err3); } errors++; } } var valid3 = _errs9 === errors; if (valid3) { const err4 = { instancePath, schemaPath: "#/anyOf/1/allOf/0/not", keyword: "not", params: {}, message: "must NOT be valid" }; if (vErrors === null) { vErrors = [err4]; } else { vErrors.push(err4); } errors++; } else { errors = _errs8; if (vErrors !== null) { if (_errs8) { vErrors.length = _errs8; } else { vErrors = null; } } } var valid2 = _errs7 === errors; if (valid2) { const _errs10 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { if (data.descriptor !== void 0) { let data1 = data.descriptor; if (!(data1 && typeof data1 == "object" && !Array.isArray(data1))) { const err5 = { instancePath: instancePath + "/descriptor", schemaPath: "#/anyOf/1/allOf/1/properties/descriptor/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err5]; } else { vErrors.push(err5); } errors++; } const _errs13 = errors; const _errs14 = errors; if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { let missing3; if (data1.protocol === void 0 && (missing3 = "protocol")) { const err6 = {}; if (vErrors === null) { vErrors = [err6]; } else { vErrors.push(err6); } errors++; } } var valid5 = _errs14 === errors; if (valid5) { const err7 = { instancePath: instancePath + "/descriptor", schemaPath: "#/anyOf/1/allOf/1/properties/descriptor/not", keyword: "not", params: {}, message: "must NOT be valid" }; if (vErrors === null) { vErrors = [err7]; } else { vErrors.push(err7); } errors++; } else { errors = _errs13; if (vErrors !== null) { if (_errs13) { vErrors.length = _errs13; } else { vErrors = null; } } } } } var valid2 = _errs10 === errors; if (valid2) { const _errs15 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { if (data.descriptor !== void 0) { let data2 = data.descriptor; if (!(data2 && typeof data2 == "object" && !Array.isArray(data2))) { const err8 = { instancePath: instancePath + "/descriptor", schemaPath: "#/anyOf/1/allOf/2/properties/descriptor/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err8]; } else { vErrors.push(err8); } errors++; } const _errs18 = errors; const _errs19 = errors; if (data2 && typeof data2 == "object" && !Array.isArray(data2)) { let missing4; if (data2.protocolPath === void 0 && (missing4 = "protocolPath")) { const err9 = {}; if (vErrors === null) { vErrors = [err9]; } else { vErrors.push(err9); } errors++; } } var valid7 = _errs19 === errors; if (valid7) { const err10 = { instancePath: instancePath + "/descriptor", schemaPath: "#/anyOf/1/allOf/2/properties/descriptor/not", keyword: "not", params: {}, message: "must NOT be valid" }; if (vErrors === null) { vErrors = [err10]; } else { vErrors.push(err10); } errors++; } else { errors = _errs18; if (vErrors !== null) { if (_errs18) { vErrors.length = _errs18; } else { vErrors = null; } } } } } var valid2 = _errs15 === errors; } } var _valid0 = _errs6 === errors; valid0 = valid0 || _valid0; if (_valid0) { if (props0 !== true) { props0 = props0 || {}; props0.descriptor = true; } } if (!valid0) { const err11 = { instancePath, schemaPath: "#/anyOf", keyword: "anyOf", params: {}, message: "must match a schema in anyOf" }; if (vErrors === null) { vErrors = [err11]; } else { vErrors.push(err11); } errors++; validate27.errors = vErrors; return false; } else { errors = _errs2; if (vErrors !== null) { if (_errs2) { vErrors.length = _errs2; } else { vErrors = null; } } } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing5; if (data.descriptor === void 0 && (missing5 = "descriptor")) { validate27.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing5 }, message: "must have required property '" + missing5 + "'" }]; return false; } else { if (props0 !== true) { props0 = props0 || {}; props0.recordId = true; props0.contextId = true; props0.attestation = true; props0.authorization = true; props0.encryption = true; props0.descriptor = true; } if (data.recordId !== void 0) { const _errs20 = errors; if (typeof data.recordId !== "string") { validate27.errors = [{ instancePath: instancePath + "/recordId", schemaPath: "#/properties/recordId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid8 = _errs20 === errors; } else { var valid8 = true; } if (valid8) { if (data.contextId !== void 0) { let data4 = data.contextId; const _errs22 = errors; if (errors === _errs22) { if (typeof data4 === "string") { if (!pattern7.test(data4)) { validate27.errors = [{ instancePath: instancePath + "/contextId", schemaPath: "#/properties/contextId/pattern", keyword: "pattern", params: { pattern: "^[a-zA-Z0-9]+(/[a-zA-Z0-9]+)*$" }, message: 'must match pattern "^[a-zA-Z0-9]+(/[a-zA-Z0-9]+)*$"' }]; return false; } } else { validate27.errors = [{ instancePath: instancePath + "/contextId", schemaPath: "#/properties/contextId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid8 = _errs22 === errors; } else { var valid8 = true; } if (valid8) { if (data.attestation !== void 0) { const _errs24 = errors; if (!validate21(data.attestation, { instancePath: instancePath + "/attestation", parentData: data, parentDataProperty: "attestation", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate21.errors : vErrors.concat(validate21.errors); errors = vErrors.length; } var valid8 = _errs24 === errors; } else { var valid8 = true; } if (valid8) { if (data.authorization !== void 0) { const _errs25 = errors; if (!validate29(data.authorization, { instancePath: instancePath + "/authorization", parentData: data, parentDataProperty: "authorization", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate29.errors : vErrors.concat(validate29.errors); errors = vErrors.length; } var valid8 = _errs25 === errors; } else { var valid8 = true; } if (valid8) { if (data.encryption !== void 0) { let data7 = data.encryption; const _errs26 = errors; if (errors === _errs26) { if (data7 && typeof data7 == "object" && !Array.isArray(data7)) { let missing6; if (data7.algorithm === void 0 && (missing6 = "algorithm") || data7.initializationVector === void 0 && (missing6 = "initializationVector") || data7.keyEncryption === void 0 && (missing6 = "keyEncryption")) { validate27.errors = [{ instancePath: instancePath + "/encryption", schemaPath: "#/properties/encryption/required", keyword: "required", params: { missingProperty: missing6 }, message: "must have required property '" + missing6 + "'" }]; return false; } else { const _errs28 = errors; for (const key0 in data7) { if (!(key0 === "algorithm" || key0 === "initializationVector" || key0 === "keyEncryption")) { validate27.errors = [{ instancePath: instancePath + "/encryption", schemaPath: "#/properties/encryption/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs28 === errors) { if (data7.algorithm !== void 0) { let data8 = data7.algorithm; const _errs29 = errors; if (typeof data8 !== "string") { validate27.errors = [{ instancePath: instancePath + "/encryption/algorithm", schemaPath: "#/properties/encryption/properties/algorithm/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data8 === "A256CTR")) { validate27.errors = [{ instancePath: instancePath + "/encryption/algorithm", schemaPath: "#/properties/encryption/properties/algorithm/enum", keyword: "enum", params: { allowedValues: schema39.properties.encryption.properties.algorithm.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid9 = _errs29 === errors; } else { var valid9 = true; } if (valid9) { if (data7.initializationVector !== void 0) { let data9 = data7.initializationVector; const _errs31 = errors; const _errs32 = errors; if (errors === _errs32) { if (typeof data9 === "string") { if (!pattern4.test(data9)) { validate27.errors = [{ instancePath: instancePath + "/encryption/initializationVector", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url/pattern", keyword: "pattern", params: { pattern: "^[A-Za-z0-9_-]+$" }, message: 'must match pattern "^[A-Za-z0-9_-]+$"' }]; return false; } } else { validate27.errors = [{ instancePath: instancePath + "/encryption/initializationVector", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid9 = _errs31 === errors; } else { var valid9 = true; } if (valid9) { if (data7.keyEncryption !== void 0) { let data10 = data7.keyEncryption; const _errs34 = errors; if (errors === _errs34) { if (Array.isArray(data10)) { if (data10.length < 1) { validate27.errors = [{ instancePath: instancePath + "/encryption/keyEncryption", schemaPath: "#/properties/encryption/properties/keyEncryption/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; return false; } else { var valid11 = true; const len0 = data10.length; for (let i0 = 0; i0 < len0; i0++) { let data11 = data10[i0]; const _errs36 = errors; if (errors === _errs36) { if (data11 && typeof data11 == "object" && !Array.isArray(data11)) { let missing7; if (data11.rootKeyId === void 0 && (missing7 = "rootKeyId") || data11.derivationScheme === void 0 && (missing7 = "derivationScheme") || data11.algorithm === void 0 && (missing7 = "algorithm") || data11.encryptedKey === void 0 && (missing7 = "encryptedKey") || data11.initializationVector === void 0 && (missing7 = "initializationVector") || data11.ephemeralPublicKey === void 0 && (missing7 = "ephemeralPublicKey") || data11.messageAuthenticationCode === void 0 && (missing7 = "messageAuthenticationCode")) { validate27.errors = [{ instancePath: instancePath + "/encryption/keyEncryption/" + i0, schemaPath: "#/properties/encryption/properties/keyEncryption/items/required", keyword: "required", params: { missingProperty: missing7 }, message: "must have required property '" + missing7 + "'" }]; return false; } else { const _errs38 = errors; for (const key1 in data11) { if (!(key1 === "rootKeyId" || key1 === "derivationScheme" || key1 === "derivedPublicKey" || key1 === "algorithm" || key1 === "encryptedKey" || key1 === "initializationVector" || key1 === "ephemeralPublicKey" || key1 === "messageAuthenticationCode")) { validate27.errors = [{ instancePath: instancePath + "/encryption/keyEncryption/" + i0, schemaPath: "#/properties/encryption/properties/keyEncryption/items/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs38 === errors) { if (data11.rootKeyId !== void 0) { const _errs39 = errors; if (typeof data11.rootKeyId !== "string") { validate27.errors = [{ instancePath: instancePath + "/encryption/keyEncryption/" + i0 + "/rootKeyId", schemaPath: "#/properties/encryption/properties/keyEncryption/items/properties/rootKeyId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid12 = _errs39 === errors; } else { var valid12 = true; } if (valid12) { if (data11.derivationScheme !== void 0) { let data13 = data11.derivationScheme; const _errs41 = errors; if (typeof data13 !== "string") { validate27.errors = [{ instancePath: instancePath + "/encryption/keyEncryption/" + i0 + "/derivationScheme", schemaPath: "#/properties/encryption/properties/keyEncryption/items/properties/derivationScheme/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data13 === "dataFormats" || data13 === "protocolContext" || data13 === "protocolPath" || data13 === "schemas")) { validate27.errors = [{ instancePath: instancePath + "/encryption/keyEncryption/" + i0 + "/derivationScheme", schemaPath: "#/properties/encryption/properties/keyEncryption/items/properties/derivationScheme/enum", keyword: "enum", params: { allowedValues: schema39.properties.encryption.properties.keyEncryption.items.properties.derivationScheme.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid12 = _errs41 === errors; } else { var valid12 = true; } if (valid12) { if (data11.derivedPublicKey !== void 0) { const _errs43 = errors; if (!validate33(data11.derivedPublicKey, { instancePath: instancePath + "/encryption/keyEncryption/" + i0 + "/derivedPublicKey", parentData: data11, parentDataProperty: "derivedPublicKey", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate33.errors : vErrors.concat(validate33.errors); errors = vErrors.length; } var valid12 = _errs43 === errors; } else { var valid12 = true; } if (valid12) { if (data11.algorithm !== void 0) { let data15 = data11.algorithm; const _errs44 = errors; if (typeof data15 !== "string") { validate27.errors = [{ instancePath: instancePath + "/encryption/keyEncryption/" + i0 + "/algorithm", schemaPath: "#/properties/encryption/properties/keyEncryption/items/properties/algorithm/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data15 === "ECIES-ES256K")) { validate27.errors = [{ instancePath: instancePath + "/encryption/keyEncryption/" + i0 + "/algorithm", schemaPath: "#/properties/encryption/properties/keyEncryption/items/properties/algorithm/enum", keyword: "enum", params: { allowedValues: schema39.properties.encryption.properties.keyEncryption.items.properties.algorithm.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid12 = _errs44 === errors; } else { var valid12 = true; } if (valid12) { if (data11.encryptedKey !== void 0) { let data16 = data11.encryptedKey; const _errs46 = errors; const _errs47 = errors; if (errors === _errs47) { if (typeof data16 === "string") { if (!pattern4.test(data16)) { validate27.errors = [{ instancePath: instancePath + "/encryption/keyEncryption/" + i0 + "/encryptedKey", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url/pattern", keyword: "pattern", params: { pattern: "^[A-Za-z0-9_-]+$" }, message: 'must match pattern "^[A-Za-z0-9_-]+$"' }]; return false; } } else { validate27.errors = [{ instancePath: instancePath + "/encryption/keyEncryption/" + i0 + "/encryptedKey", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid12 = _errs46 === errors; } else { var valid12 = true; } if (valid12) { if (data11.initializationVector !== void 0) { let data17 = data11.initializationVector; const _errs49 = errors; const _errs50 = errors; if (errors === _errs50) { if (typeof data17 === "string") { if (!pattern4.test(data17)) { validate27.errors = [{ instancePath: instancePath + "/encryption/keyEncryption/" + i0 + "/initializationVector", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url/pattern", keyword: "pattern", params: { pattern: "^[A-Za-z0-9_-]+$" }, message: 'must match pattern "^[A-Za-z0-9_-]+$"' }]; return false; } } else { validate27.errors = [{ instancePath: instancePath + "/encryption/keyEncryption/" + i0 + "/initializationVector", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid12 = _errs49 === errors; } else { var valid12 = true; } if (valid12) { if (data11.ephemeralPublicKey !== void 0) { const _errs52 = errors; if (!validate33(data11.ephemeralPublicKey, { instancePath: instancePath + "/encryption/keyEncryption/" + i0 + "/ephemeralPublicKey", parentData: data11, parentDataProperty: "ephemeralPublicKey", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate33.errors : vErrors.concat(validate33.errors); errors = vErrors.length; } var valid12 = _errs52 === errors; } else { var valid12 = true; } if (valid12) { if (data11.messageAuthenticationCode !== void 0) { let data19 = data11.messageAuthenticationCode; const _errs53 = errors; const _errs54 = errors; if (errors === _errs54) { if (typeof data19 === "string") { if (!pattern4.test(data19)) { validate27.errors = [{ instancePath: instancePath + "/encryption/keyEncryption/" + i0 + "/messageAuthenticationCode", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url/pattern", keyword: "pattern", params: { pattern: "^[A-Za-z0-9_-]+$" }, message: 'must match pattern "^[A-Za-z0-9_-]+$"' }]; return false; } } else { validate27.errors = [{ instancePath: instancePath + "/encryption/keyEncryption/" + i0 + "/messageAuthenticationCode", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/base64url/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid12 = _errs53 === errors; } else { var valid12 = true; } } } } } } } } } } } else { validate27.errors = [{ instancePath: instancePath + "/encryption/keyEncryption/" + i0, schemaPath: "#/properties/encryption/properties/keyEncryption/items/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid11 = _errs36 === errors; if (!valid11) { break; } } } } else { validate27.errors = [{ instancePath: instancePath + "/encryption/keyEncryption", schemaPath: "#/properties/encryption/properties/keyEncryption/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; return false; } } var valid9 = _errs34 === errors; } else { var valid9 = true; } } } } } } else { validate27.errors = [{ instancePath: instancePath + "/encryption", schemaPath: "#/properties/encryption/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid8 = _errs26 === errors; } else { var valid8 = true; } if (valid8) { if (data.descriptor !== void 0) { let data20 = data.descriptor; const _errs56 = errors; const _errs60 = errors; let valid17 = false; const _errs61 = errors; if (data20 && typeof data20 == "object" && !Array.isArray(data20)) { let missing8; if (data20.published === void 0 && (missing8 = "published") || data20.datePublished === void 0 && (missing8 = "datePublished")) { const err12 = { instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/allOf/0/anyOf/0/required", keyword: "required", params: { missingProperty: missing8 }, message: "must have required property '" + missing8 + "'" }; if (vErrors === null) { vErrors = [err12]; } else { vErrors.push(err12); } errors++; } else { if (data20.published !== void 0) { let data21 = data20.published; if (typeof data21 !== "boolean") { const err13 = { instancePath: instancePath + "/descriptor/published", schemaPath: "#/properties/descriptor/allOf/0/anyOf/0/properties/published/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }; if (vErrors === null) { vErrors = [err13]; } else { vErrors.push(err13); } errors++; } if (!(data21 === true)) { const err14 = { instancePath: instancePath + "/descriptor/published", schemaPath: "#/properties/descriptor/allOf/0/anyOf/0/properties/published/enum", keyword: "enum", params: { allowedValues: schema39.properties.descriptor.allOf[0].anyOf[0].properties.published.enum }, message: "must be equal to one of the allowed values" }; if (vErrors === null) { vErrors = [err14]; } else { vErrors.push(err14); } errors++; } } } } var _valid1 = _errs61 === errors; valid17 = valid17 || _valid1; if (_valid1) { var props3 = {}; props3.published = true; } const _errs64 = errors; const _errs65 = errors; const _errs66 = errors; if (data20 && typeof data20 == "object" && !Array.isArray(data20)) { let missing9; if (data20.datePublished === void 0 && (missing9 = "datePublished")) { const err15 = {}; if (vErrors === null) { vErrors = [err15]; } else { vErrors.push(err15); } errors++; } } var valid19 = _errs66 === errors; if (valid19) { const err16 = { instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/allOf/0/anyOf/1/not", keyword: "not", params: {}, message: "must NOT be valid" }; if (vErrors === null) { vErrors = [err16]; } else { vErrors.push(err16); } errors++; } else { errors = _errs65; if (vErrors !== null) { if (_errs65) { vErrors.length = _errs65; } else { vErrors = null; } } } if (errors === _errs64) { if (data20 && typeof data20 == "object" && !Array.isArray(data20)) { if (data20.published !== void 0) { let data22 = data20.published; if (typeof data22 !== "boolean") { const err17 = { instancePath: instancePath + "/descriptor/published", schemaPath: "#/properties/descriptor/allOf/0/anyOf/1/properties/published/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }; if (vErrors === null) { vErrors = [err17]; } else { vErrors.push(err17); } errors++; } if (!(data22 === false)) { const err18 = { instancePath: instancePath + "/descriptor/published", schemaPath: "#/properties/descriptor/allOf/0/anyOf/1/properties/published/enum", keyword: "enum", params: { allowedValues: schema39.properties.descriptor.allOf[0].anyOf[1].properties.published.enum }, message: "must be equal to one of the allowed values" }; if (vErrors === null) { vErrors = [err18]; } else { vErrors.push(err18); } errors++; } } } } var _valid1 = _errs64 === errors; valid17 = valid17 || _valid1; if (_valid1) { if (props3 !== true) { props3 = props3 || {}; props3.published = true; } } const _errs69 = errors; const _errs70 = errors; const _errs71 = errors; const _errs72 = errors; if (data20 && typeof data20 == "object" && !Array.isArray(data20)) { let missing10; if (data20.published === void 0 && (missing10 = "published")) { const err19 = {}; if (vErrors === null) { vErrors = [err19]; } else { vErrors.push(err19); } errors++; } } var valid22 = _errs72 === errors; if (valid22) { const err20 = { instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/allOf/0/anyOf/2/allOf/0/not", keyword: "not", params: {}, message: "must NOT be valid" }; if (vErrors === null) { vErrors = [err20]; } else { vErrors.push(err20); } errors++; } else { errors = _errs71; if (vErrors !== null) { if (_errs71) { vErrors.length = _errs71; } else { vErrors = null; } } } var valid21 = _errs70 === errors; if (valid21) { const _errs73 = errors; const _errs74 = errors; const _errs75 = errors; if (data20 && typeof data20 == "object" && !Array.isArray(data20)) { let missing11; if (data20.datePublished === void 0 && (missing11 = "datePublished")) { const err21 = {}; if (vErrors === null) { vErrors = [err21]; } else { vErrors.push(err21); } errors++; } } var valid23 = _errs75 === errors; if (valid23) { const err22 = { instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/allOf/0/anyOf/2/allOf/1/not", keyword: "not", params: {}, message: "must NOT be valid" }; if (vErrors === null) { vErrors = [err22]; } else { vErrors.push(err22); } errors++; } else { errors = _errs74; if (vErrors !== null) { if (_errs74) { vErrors.length = _errs74; } else { vErrors = null; } } } var valid21 = _errs73 === errors; } var _valid1 = _errs69 === errors; valid17 = valid17 || _valid1; if (!valid17) { const err23 = { instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/allOf/0/anyOf", keyword: "anyOf", params: {}, message: "must match a schema in anyOf" }; if (vErrors === null) { vErrors = [err23]; } else { vErrors.push(err23); } errors++; validate27.errors = vErrors; return false; } else { errors = _errs60; if (vErrors !== null) { if (_errs60) { vErrors.length = _errs60; } else { vErrors = null; } } } if (errors === _errs56) { if (data20 && typeof data20 == "object" && !Array.isArray(data20)) { let missing12; if (data20.interface === void 0 && (missing12 = "interface") || data20.method === void 0 && (missing12 = "method") || data20.dataCid === void 0 && (missing12 = "dataCid") || data20.dataSize === void 0 && (missing12 = "dataSize") || data20.dateCreated === void 0 && (missing12 = "dateCreated") || data20.messageTimestamp === void 0 && (missing12 = "messageTimestamp") || data20.dataFormat === void 0 && (missing12 = "dataFormat")) { validate27.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/required", keyword: "required", params: { missingProperty: missing12 }, message: "must have required property '" + missing12 + "'" }]; return false; } else { const _errs76 = errors; for (const key2 in data20) { if (!func1.call(schema39.properties.descriptor.properties, key2)) { validate27.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs76 === errors) { let missing13; if (data20.parentId !== void 0 && (data20.protocol === void 0 && (missing13 = "protocol"))) { validate27.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/dependencies", keyword: "dependencies", params: { property: "parentId", missingProperty: missing13, depsCount: 1, deps: "protocol" }, message: "must have property protocol when property parentId is present" }]; return false; } else { if (data20.interface !== void 0) { let data23 = data20.interface; const _errs77 = errors; if (typeof data23 !== "string") { validate27.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data23 === "Records")) { validate27.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/enum", keyword: "enum", params: { allowedValues: schema39.properties.descriptor.properties.interface.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid25 = _errs77 === errors; } else { var valid25 = true; } if (valid25) { if (data20.method !== void 0) { let data24 = data20.method; const _errs79 = errors; if (typeof data24 !== "string") { validate27.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data24 === "Write")) { validate27.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/enum", keyword: "enum", params: { allowedValues: schema39.properties.descriptor.properties.method.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid25 = _errs79 === errors; } else { var valid25 = true; } if (valid25) { if (data20.recipient !== void 0) { let data25 = data20.recipient; const _errs81 = errors; const _errs82 = errors; if (errors === _errs82) { if (typeof data25 === "string") { if (!pattern12.test(data25)) { validate27.errors = [{ instancePath: instancePath + "/descriptor/recipient", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did/pattern", keyword: "pattern", params: { pattern: "^did:([a-z0-9]+):((?:(?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))*:)*((?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))+))((;[a-zA-Z0-9_.:%-]+=[a-zA-Z0-9_.:%-]*)*)(/[^#?]*)?([?][^#]*)?(#.*)?$" }, message: 'must match pattern "^did:([a-z0-9]+):((?:(?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))*:)*((?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))+))((;[a-zA-Z0-9_.:%-]+=[a-zA-Z0-9_.:%-]*)*)(/[^#?]*)?([?][^#]*)?(#.*)?$"' }]; return false; } } else { validate27.errors = [{ instancePath: instancePath + "/descriptor/recipient", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid25 = _errs81 === errors; } else { var valid25 = true; } if (valid25) { if (data20.protocol !== void 0) { const _errs84 = errors; if (typeof data20.protocol !== "string") { validate27.errors = [{ instancePath: instancePath + "/descriptor/protocol", schemaPath: "#/properties/descriptor/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid25 = _errs84 === errors; } else { var valid25 = true; } if (valid25) { if (data20.protocolPath !== void 0) { let data27 = data20.protocolPath; const _errs86 = errors; if (errors === _errs86) { if (typeof data27 === "string") { if (!pattern13.test(data27)) { validate27.errors = [{ instancePath: instancePath + "/descriptor/protocolPath", schemaPath: "#/properties/descriptor/properties/protocolPath/pattern", keyword: "pattern", params: { pattern: "^[a-zA-Z]+(/[a-zA-Z]+)*$" }, message: 'must match pattern "^[a-zA-Z]+(/[a-zA-Z]+)*$"' }]; return false; } } else { validate27.errors = [{ instancePath: instancePath + "/descriptor/protocolPath", schemaPath: "#/properties/descriptor/properties/protocolPath/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid25 = _errs86 === errors; } else { var valid25 = true; } if (valid25) { if (data20.schema !== void 0) { const _errs88 = errors; if (typeof data20.schema !== "string") { validate27.errors = [{ instancePath: instancePath + "/descriptor/schema", schemaPath: "#/properties/descriptor/properties/schema/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid25 = _errs88 === errors; } else { var valid25 = true; } if (valid25) { if (data20.tags !== void 0) { let data29 = data20.tags; const _errs90 = errors; if (errors === _errs90) { if (data29 && typeof data29 == "object" && !Array.isArray(data29)) { if (Object.keys(data29).length > 10) { validate27.errors = [{ instancePath: instancePath + "/descriptor/tags", schemaPath: "#/properties/descriptor/properties/tags/maxProperties", keyword: "maxProperties", params: { limit: 10 }, message: "must NOT have more than 10 properties" }]; return false; } else { if (Object.keys(data29).length < 1) { validate27.errors = [{ instancePath: instancePath + "/descriptor/tags", schemaPath: "#/properties/descriptor/properties/tags/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { for (const key3 in data29) { let data30 = data29[key3]; const _errs93 = errors; const _errs94 = errors; let valid28 = false; let passing0 = null; const _errs95 = errors; if (typeof data30 !== "string") { const err24 = { instancePath: instancePath + "/descriptor/tags/" + key3.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/descriptor/properties/tags/additionalProperties/oneOf/0/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err24]; } else { vErrors.push(err24); } errors++; } var _valid2 = _errs95 === errors; if (_valid2) { valid28 = true; passing0 = 0; } const _errs97 = errors; if (!(typeof data30 == "number" && isFinite(data30))) { const err25 = { instancePath: instancePath + "/descriptor/tags/" + key3.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/descriptor/properties/tags/additionalProperties/oneOf/1/type", keyword: "type", params: { type: "number" }, message: "must be number" }; if (vErrors === null) { vErrors = [err25]; } else { vErrors.push(err25); } errors++; } var _valid2 = _errs97 === errors; if (_valid2 && valid28) { valid28 = false; passing0 = [passing0, 1]; } else { if (_valid2) { valid28 = true; passing0 = 1; } const _errs99 = errors; if (typeof data30 !== "boolean") { const err26 = { instancePath: instancePath + "/descriptor/tags/" + key3.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/descriptor/properties/tags/additionalProperties/oneOf/2/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }; if (vErrors === null) { vErrors = [err26]; } else { vErrors.push(err26); } errors++; } var _valid2 = _errs99 === errors; if (_valid2 && valid28) { valid28 = false; passing0 = [passing0, 2]; } else { if (_valid2) { valid28 = true; passing0 = 2; } const _errs101 = errors; if (errors === _errs101) { if (Array.isArray(data30)) { if (data30.length > 10) { const err27 = { instancePath: instancePath + "/descriptor/tags/" + key3.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/descriptor/properties/tags/additionalProperties/oneOf/3/maxItems", keyword: "maxItems", params: { limit: 10 }, message: "must NOT have more than 10 items" }; if (vErrors === null) { vErrors = [err27]; } else { vErrors.push(err27); } errors++; } else { if (data30.length < 1) { const err28 = { instancePath: instancePath + "/descriptor/tags/" + key3.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/descriptor/properties/tags/additionalProperties/oneOf/3/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }; if (vErrors === null) { vErrors = [err28]; } else { vErrors.push(err28); } errors++; } else { var valid29 = true; const len1 = data30.length; for (let i1 = 0; i1 < len1; i1++) { const _errs103 = errors; if (typeof data30[i1] !== "string") { const err29 = { instancePath: instancePath + "/descriptor/tags/" + key3.replace(/~/g, "~0").replace(/\//g, "~1") + "/" + i1, schemaPath: "#/properties/descriptor/properties/tags/additionalProperties/oneOf/3/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err29]; } else { vErrors.push(err29); } errors++; } var valid29 = _errs103 === errors; if (!valid29) { break; } } } } } else { const err30 = { instancePath: instancePath + "/descriptor/tags/" + key3.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/descriptor/properties/tags/additionalProperties/oneOf/3/type", keyword: "type", params: { type: "array" }, message: "must be array" }; if (vErrors === null) { vErrors = [err30]; } else { vErrors.push(err30); } errors++; } } var _valid2 = _errs101 === errors; if (_valid2 && valid28) { valid28 = false; passing0 = [passing0, 3]; } else { if (_valid2) { valid28 = true; passing0 = 3; var items0 = true; } const _errs105 = errors; if (errors === _errs105) { if (Array.isArray(data30)) { if (data30.length > 10) { const err31 = { instancePath: instancePath + "/descriptor/tags/" + key3.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/descriptor/properties/tags/additionalProperties/oneOf/4/maxItems", keyword: "maxItems", params: { limit: 10 }, message: "must NOT have more than 10 items" }; if (vErrors === null) { vErrors = [err31]; } else { vErrors.push(err31); } errors++; } else { if (data30.length < 1) { const err32 = { instancePath: instancePath + "/descriptor/tags/" + key3.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/descriptor/properties/tags/additionalProperties/oneOf/4/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }; if (vErrors === null) { vErrors = [err32]; } else { vErrors.push(err32); } errors++; } else { var valid30 = true; const len2 = data30.length; for (let i2 = 0; i2 < len2; i2++) { let data32 = data30[i2]; const _errs107 = errors; if (!(typeof data32 == "number" && isFinite(data32))) { const err33 = { instancePath: instancePath + "/descriptor/tags/" + key3.replace(/~/g, "~0").replace(/\//g, "~1") + "/" + i2, schemaPath: "#/properties/descriptor/properties/tags/additionalProperties/oneOf/4/items/type", keyword: "type", params: { type: "number" }, message: "must be number" }; if (vErrors === null) { vErrors = [err33]; } else { vErrors.push(err33); } errors++; } var valid30 = _errs107 === errors; if (!valid30) { break; } } } } } else { const err34 = { instancePath: instancePath + "/descriptor/tags/" + key3.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/descriptor/properties/tags/additionalProperties/oneOf/4/type", keyword: "type", params: { type: "array" }, message: "must be array" }; if (vErrors === null) { vErrors = [err34]; } else { vErrors.push(err34); } errors++; } } var _valid2 = _errs105 === errors; if (_valid2 && valid28) { valid28 = false; passing0 = [passing0, 4]; } else { if (_valid2) { valid28 = true; passing0 = 4; if (items0 !== true) { items0 = true; } } } } } } if (!valid28) { const err35 = { instancePath: instancePath + "/descriptor/tags/" + key3.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/descriptor/properties/tags/additionalProperties/oneOf", keyword: "oneOf", params: { passingSchemas: passing0 }, message: "must match exactly one schema in oneOf" }; if (vErrors === null) { vErrors = [err35]; } else { vErrors.push(err35); } errors++; validate27.errors = vErrors; return false; } else { errors = _errs94; if (vErrors !== null) { if (_errs94) { vErrors.length = _errs94; } else { vErrors = null; } } } var valid27 = _errs93 === errors; if (!valid27) { break; } } } } } else { validate27.errors = [{ instancePath: instancePath + "/descriptor/tags", schemaPath: "#/properties/descriptor/properties/tags/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid25 = _errs90 === errors; } else { var valid25 = true; } if (valid25) { if (data20.parentId !== void 0) { const _errs109 = errors; if (typeof data20.parentId !== "string") { validate27.errors = [{ instancePath: instancePath + "/descriptor/parentId", schemaPath: "#/properties/descriptor/properties/parentId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid25 = _errs109 === errors; } else { var valid25 = true; } if (valid25) { if (data20.dataCid !== void 0) { const _errs111 = errors; if (typeof data20.dataCid !== "string") { validate27.errors = [{ instancePath: instancePath + "/descriptor/dataCid", schemaPath: "#/properties/descriptor/properties/dataCid/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid25 = _errs111 === errors; } else { var valid25 = true; } if (valid25) { if (data20.dataSize !== void 0) { let data35 = data20.dataSize; const _errs113 = errors; if (!(typeof data35 == "number" && isFinite(data35))) { validate27.errors = [{ instancePath: instancePath + "/descriptor/dataSize", schemaPath: "#/properties/descriptor/properties/dataSize/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } var valid25 = _errs113 === errors; } else { var valid25 = true; } if (valid25) { if (data20.dateCreated !== void 0) { let data36 = data20.dateCreated; const _errs115 = errors; const _errs116 = errors; if (errors === _errs116) { if (typeof data36 === "string") { if (!pattern14.test(data36)) { validate27.errors = [{ instancePath: instancePath + "/descriptor/dateCreated", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate27.errors = [{ instancePath: instancePath + "/descriptor/dateCreated", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid25 = _errs115 === errors; } else { var valid25 = true; } if (valid25) { if (data20.messageTimestamp !== void 0) { let data37 = data20.messageTimestamp; const _errs118 = errors; const _errs119 = errors; if (errors === _errs119) { if (typeof data37 === "string") { if (!pattern14.test(data37)) { validate27.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate27.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid25 = _errs118 === errors; } else { var valid25 = true; } if (valid25) { if (data20.published !== void 0) { const _errs121 = errors; if (typeof data20.published !== "boolean") { validate27.errors = [{ instancePath: instancePath + "/descriptor/published", schemaPath: "#/properties/descriptor/properties/published/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } var valid25 = _errs121 === errors; } else { var valid25 = true; } if (valid25) { if (data20.datePublished !== void 0) { let data39 = data20.datePublished; const _errs123 = errors; const _errs124 = errors; if (errors === _errs124) { if (typeof data39 === "string") { if (!pattern14.test(data39)) { validate27.errors = [{ instancePath: instancePath + "/descriptor/datePublished", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate27.errors = [{ instancePath: instancePath + "/descriptor/datePublished", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid25 = _errs123 === errors; } else { var valid25 = true; } if (valid25) { if (data20.dataFormat !== void 0) { const _errs126 = errors; if (typeof data20.dataFormat !== "string") { validate27.errors = [{ instancePath: instancePath + "/descriptor/dataFormat", schemaPath: "#/properties/descriptor/properties/dataFormat/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid25 = _errs126 === errors; } else { var valid25 = true; } } } } } } } } } } } } } } } } } } } else { validate27.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid8 = _errs56 === errors; } else { var valid8 = true; } } } } } } } } else { validate27.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate27.errors = vErrors; evaluated0.props = props0; return errors === 0; } validate27.evaluated = { "dynamicProps": true, "dynamicItems": false }; function validate26(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate26.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (!validate27(data, { instancePath, parentData, parentDataProperty, rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate27.errors : vErrors.concat(validate27.errors); errors = vErrors.length; } else { var props0 = validate27.evaluated.props; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.recordId === void 0 && (missing0 = "recordId") || data.authorization === void 0 && (missing0 = "authorization") || data.encodedData === void 0 && (missing0 = "encodedData")) { validate26.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { if (props0 !== true) { props0 = props0 || {}; props0.encodedData = true; } if (data.encodedData !== void 0) { const _errs1 = errors; if (typeof data.encodedData !== "string") { validate26.errors = [{ instancePath: instancePath + "/encodedData", schemaPath: "#/properties/encodedData/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs1 === errors; } else { var valid0 = true; } if (valid0) { if (props0 !== true) { for (const key0 in data) { if (!props0 || !props0[key0]) { validate26.errors = [{ instancePath, schemaPath: "#/unevaluatedProperties", keyword: "unevaluatedProperties", params: { unevaluatedProperty: key0 }, message: "must NOT have unevaluated properties" }]; return false; break; } } } } } } else { validate26.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate26.errors = vErrors; return errors === 0; } validate26.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; function validate24(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate24.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "signature" || key0 === "authorDelegatedGrant")) { validate24.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.signature !== void 0) { const _errs2 = errors; if (!validate21(data.signature, { instancePath: instancePath + "/signature", parentData: data, parentDataProperty: "signature", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate21.errors : vErrors.concat(validate21.errors); errors = vErrors.length; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.authorDelegatedGrant !== void 0) { const _errs3 = errors; if (!validate26(data.authorDelegatedGrant, { instancePath: instancePath + "/authorDelegatedGrant", parentData: data, parentDataProperty: "authorDelegatedGrant", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate26.errors : vErrors.concat(validate26.errors); errors = vErrors.length; } var valid0 = _errs3 === errors; } else { var valid0 = true; } } } } else { validate24.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate24.errors = vErrors; return errors === 0; } validate24.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var AuthorizationOwner = validate29; var RecordsDelete = validate38; var schema51 = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://identity.foundation/dwn/json-schemas/records-delete.json", "type": "object", "additionalProperties": false, "required": ["authorization", "descriptor"], "properties": { "authorization": { "$ref": "https://identity.foundation/dwn/json-schemas/authorization-delegated-grant.json" }, "descriptor": { "type": "object", "additionalProperties": false, "required": ["interface", "method", "messageTimestamp", "recordId", "prune"], "properties": { "interface": { "enum": ["Records"], "type": "string" }, "method": { "enum": ["Delete"], "type": "string" }, "messageTimestamp": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" }, "recordId": { "type": "string" }, "prune": { "type": "boolean" } } } } }; function validate38(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate38.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.authorization === void 0 && (missing0 = "authorization") || data.descriptor === void 0 && (missing0 = "descriptor")) { validate38.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "authorization" || key0 === "descriptor")) { validate38.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.authorization !== void 0) { const _errs2 = errors; if (!validate24(data.authorization, { instancePath: instancePath + "/authorization", parentData: data, parentDataProperty: "authorization", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate24.errors : vErrors.concat(validate24.errors); errors = vErrors.length; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.descriptor !== void 0) { let data1 = data.descriptor; const _errs3 = errors; if (errors === _errs3) { if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { let missing1; if (data1.interface === void 0 && (missing1 = "interface") || data1.method === void 0 && (missing1 = "method") || data1.messageTimestamp === void 0 && (missing1 = "messageTimestamp") || data1.recordId === void 0 && (missing1 = "recordId") || data1.prune === void 0 && (missing1 = "prune")) { validate38.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }]; return false; } else { const _errs5 = errors; for (const key1 in data1) { if (!(key1 === "interface" || key1 === "method" || key1 === "messageTimestamp" || key1 === "recordId" || key1 === "prune")) { validate38.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs5 === errors) { if (data1.interface !== void 0) { let data2 = data1.interface; const _errs6 = errors; if (typeof data2 !== "string") { validate38.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data2 === "Records")) { validate38.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/enum", keyword: "enum", params: { allowedValues: schema51.properties.descriptor.properties.interface.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs6 === errors; } else { var valid1 = true; } if (valid1) { if (data1.method !== void 0) { let data3 = data1.method; const _errs8 = errors; if (typeof data3 !== "string") { validate38.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data3 === "Delete")) { validate38.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/enum", keyword: "enum", params: { allowedValues: schema51.properties.descriptor.properties.method.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs8 === errors; } else { var valid1 = true; } if (valid1) { if (data1.messageTimestamp !== void 0) { let data4 = data1.messageTimestamp; const _errs10 = errors; const _errs11 = errors; if (errors === _errs11) { if (typeof data4 === "string") { if (!pattern14.test(data4)) { validate38.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate38.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid1 = _errs10 === errors; } else { var valid1 = true; } if (valid1) { if (data1.recordId !== void 0) { const _errs13 = errors; if (typeof data1.recordId !== "string") { validate38.errors = [{ instancePath: instancePath + "/descriptor/recordId", schemaPath: "#/properties/descriptor/properties/recordId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid1 = _errs13 === errors; } else { var valid1 = true; } if (valid1) { if (data1.prune !== void 0) { const _errs15 = errors; if (typeof data1.prune !== "boolean") { validate38.errors = [{ instancePath: instancePath + "/descriptor/prune", schemaPath: "#/properties/descriptor/properties/prune/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } var valid1 = _errs15 === errors; } else { var valid1 = true; } } } } } } } } else { validate38.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs3 === errors; } else { var valid0 = true; } } } } } else { validate38.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate38.errors = vErrors; return errors === 0; } validate38.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var RecordsQuery = validate40; var schema53 = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://identity.foundation/dwn/json-schemas/records-query.json", "type": "object", "additionalProperties": false, "required": ["descriptor"], "properties": { "authorization": { "$ref": "https://identity.foundation/dwn/json-schemas/authorization-delegated-grant.json" }, "descriptor": { "type": "object", "additionalProperties": false, "required": ["interface", "method", "messageTimestamp", "filter"], "properties": { "interface": { "enum": ["Records"], "type": "string" }, "method": { "enum": ["Query"], "type": "string" }, "messageTimestamp": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" }, "filter": { "$ref": "https://identity.foundation/dwn/json-schemas/records-filter.json" }, "pagination": { "type": "object", "additionalProperties": false, "properties": { "limit": { "type": "number", "minimum": 1 }, "cursor": { "$ref": "https://identity.foundation/dwn/json-schemas/pagination-cursor.json" } } }, "dateSort": { "enum": ["createdAscending", "createdDescending", "publishedAscending", "publishedDescending"], "type": "string" } } } } }; var schema68 = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://identity.foundation/dwn/json-schemas/pagination-cursor.json", "type": "object", "minProperties": 1, "additionalProperties": false, "required": ["messageCid", "value"], "properties": { "messageCid": { "type": "string" }, "value": { "type": ["string", "number"] } } }; var schema55 = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://identity.foundation/dwn/json-schemas/records-filter.json", "type": "object", "minProperties": 1, "additionalProperties": false, "properties": { "protocol": { "type": "string" }, "protocolPath": { "type": "string" }, "author": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did" }, "attester": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did" }, "recipient": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did" }, "contextId": { "type": "string" }, "schema": { "type": "string" }, "tags": { "type": "object", "minProperties": 1, "additionalProperties": { "oneOf": [{ "type": "string" }, { "type": "number" }, { "type": "boolean" }, { "type": "object", "minProperties": 1, "additionalProperties": false, "properties": { "startsWith": { "type": "string" } } }, { "$ref": "https://identity.foundation/dwn/json-schemas/string-range-filter.json" }, { "$ref": "https://identity.foundation/dwn/json-schemas/number-range-filter.json" }] } }, "recordId": { "type": "string" }, "parentId": { "type": "string" }, "published": { "type": "boolean" }, "dataFormat": { "type": "string" }, "dataSize": { "$ref": "https://identity.foundation/dwn/json-schemas/number-range-filter.json" }, "dataCid": { "type": "string" }, "dateCreated": { "type": "object", "minProperties": 1, "additionalProperties": false, "properties": { "from": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" }, "to": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" } } }, "datePublished": { "type": "object", "minProperties": 1, "additionalProperties": false, "properties": { "from": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" }, "to": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" } } }, "dateUpdated": { "type": "object", "minProperties": 1, "additionalProperties": false, "properties": { "from": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" }, "to": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" } } } }, "dependencies": { "datePublished": { "oneOf": [{ "properties": { "published": { "enum": [true] } }, "required": ["published"] }, { "not": { "required": ["published"] } }] } } }; function validate42(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate42.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { if (Object.keys(data).length < 1) { validate42.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!func1.call(schema55.properties, key0)) { validate42.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.datePublished !== void 0) { const _errs2 = errors; const _errs3 = errors; let valid1 = false; let passing0 = null; const _errs4 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.published === void 0 && (missing0 = "published")) { const err0 = { instancePath, schemaPath: "#/dependencies/datePublished/oneOf/0/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }; if (vErrors === null) { vErrors = [err0]; } else { vErrors.push(err0); } errors++; } else { if (data.published !== void 0) { if (!(data.published === true)) { const err1 = { instancePath: instancePath + "/published", schemaPath: "#/dependencies/datePublished/oneOf/0/properties/published/enum", keyword: "enum", params: { allowedValues: schema55.dependencies.datePublished.oneOf[0].properties.published.enum }, message: "must be equal to one of the allowed values" }; if (vErrors === null) { vErrors = [err1]; } else { vErrors.push(err1); } errors++; } } } } var _valid0 = _errs4 === errors; if (_valid0) { valid1 = true; passing0 = 0; var props0 = {}; props0.published = true; } const _errs6 = errors; const _errs7 = errors; const _errs8 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing1; if (data.published === void 0 && (missing1 = "published")) { const err22 = {}; if (vErrors === null) { vErrors = [err22]; } else { vErrors.push(err22); } errors++; } } var valid3 = _errs8 === errors; if (valid3) { const err3 = { instancePath, schemaPath: "#/dependencies/datePublished/oneOf/1/not", keyword: "not", params: {}, message: "must NOT be valid" }; if (vErrors === null) { vErrors = [err3]; } else { vErrors.push(err3); } errors++; } else { errors = _errs7; if (vErrors !== null) { if (_errs7) { vErrors.length = _errs7; } else { vErrors = null; } } } var _valid0 = _errs6 === errors; if (_valid0 && valid1) { valid1 = false; passing0 = [passing0, 1]; } else { if (_valid0) { valid1 = true; passing0 = 1; } } if (!valid1) { const err4 = { instancePath, schemaPath: "#/dependencies/datePublished/oneOf", keyword: "oneOf", params: { passingSchemas: passing0 }, message: "must match exactly one schema in oneOf" }; if (vErrors === null) { vErrors = [err4]; } else { vErrors.push(err4); } errors++; validate42.errors = vErrors; return false; } else { errors = _errs3; if (vErrors !== null) { if (_errs3) { vErrors.length = _errs3; } else { vErrors = null; } } } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.protocol !== void 0) { const _errs9 = errors; if (typeof data.protocol !== "string") { validate42.errors = [{ instancePath: instancePath + "/protocol", schemaPath: "#/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid4 = _errs9 === errors; } else { var valid4 = true; } if (valid4) { if (data.protocolPath !== void 0) { const _errs11 = errors; if (typeof data.protocolPath !== "string") { validate42.errors = [{ instancePath: instancePath + "/protocolPath", schemaPath: "#/properties/protocolPath/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid4 = _errs11 === errors; } else { var valid4 = true; } if (valid4) { if (data.author !== void 0) { let data3 = data.author; const _errs13 = errors; const _errs14 = errors; if (errors === _errs14) { if (typeof data3 === "string") { if (!pattern12.test(data3)) { validate42.errors = [{ instancePath: instancePath + "/author", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did/pattern", keyword: "pattern", params: { pattern: "^did:([a-z0-9]+):((?:(?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))*:)*((?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))+))((;[a-zA-Z0-9_.:%-]+=[a-zA-Z0-9_.:%-]*)*)(/[^#?]*)?([?][^#]*)?(#.*)?$" }, message: 'must match pattern "^did:([a-z0-9]+):((?:(?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))*:)*((?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))+))((;[a-zA-Z0-9_.:%-]+=[a-zA-Z0-9_.:%-]*)*)(/[^#?]*)?([?][^#]*)?(#.*)?$"' }]; return false; } } else { validate42.errors = [{ instancePath: instancePath + "/author", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid4 = _errs13 === errors; } else { var valid4 = true; } if (valid4) { if (data.attester !== void 0) { let data4 = data.attester; const _errs16 = errors; const _errs17 = errors; if (errors === _errs17) { if (typeof data4 === "string") { if (!pattern12.test(data4)) { validate42.errors = [{ instancePath: instancePath + "/attester", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did/pattern", keyword: "pattern", params: { pattern: "^did:([a-z0-9]+):((?:(?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))*:)*((?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))+))((;[a-zA-Z0-9_.:%-]+=[a-zA-Z0-9_.:%-]*)*)(/[^#?]*)?([?][^#]*)?(#.*)?$" }, message: 'must match pattern "^did:([a-z0-9]+):((?:(?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))*:)*((?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))+))((;[a-zA-Z0-9_.:%-]+=[a-zA-Z0-9_.:%-]*)*)(/[^#?]*)?([?][^#]*)?(#.*)?$"' }]; return false; } } else { validate42.errors = [{ instancePath: instancePath + "/attester", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid4 = _errs16 === errors; } else { var valid4 = true; } if (valid4) { if (data.recipient !== void 0) { let data5 = data.recipient; const _errs19 = errors; const _errs20 = errors; if (errors === _errs20) { if (typeof data5 === "string") { if (!pattern12.test(data5)) { validate42.errors = [{ instancePath: instancePath + "/recipient", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did/pattern", keyword: "pattern", params: { pattern: "^did:([a-z0-9]+):((?:(?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))*:)*((?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))+))((;[a-zA-Z0-9_.:%-]+=[a-zA-Z0-9_.:%-]*)*)(/[^#?]*)?([?][^#]*)?(#.*)?$" }, message: 'must match pattern "^did:([a-z0-9]+):((?:(?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))*:)*((?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))+))((;[a-zA-Z0-9_.:%-]+=[a-zA-Z0-9_.:%-]*)*)(/[^#?]*)?([?][^#]*)?(#.*)?$"' }]; return false; } } else { validate42.errors = [{ instancePath: instancePath + "/recipient", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid4 = _errs19 === errors; } else { var valid4 = true; } if (valid4) { if (data.contextId !== void 0) { const _errs22 = errors; if (typeof data.contextId !== "string") { validate42.errors = [{ instancePath: instancePath + "/contextId", schemaPath: "#/properties/contextId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid4 = _errs22 === errors; } else { var valid4 = true; } if (valid4) { if (data.schema !== void 0) { const _errs24 = errors; if (typeof data.schema !== "string") { validate42.errors = [{ instancePath: instancePath + "/schema", schemaPath: "#/properties/schema/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid4 = _errs24 === errors; } else { var valid4 = true; } if (valid4) { if (data.tags !== void 0) { let data8 = data.tags; const _errs26 = errors; if (errors === _errs26) { if (data8 && typeof data8 == "object" && !Array.isArray(data8)) { if (Object.keys(data8).length < 1) { validate42.errors = [{ instancePath: instancePath + "/tags", schemaPath: "#/properties/tags/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { for (const key1 in data8) { let data9 = data8[key1]; const _errs29 = errors; const _errs30 = errors; let valid9 = false; let passing1 = null; const _errs31 = errors; if (typeof data9 !== "string") { const err5 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/tags/additionalProperties/oneOf/0/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err5]; } else { vErrors.push(err5); } errors++; } var _valid1 = _errs31 === errors; if (_valid1) { valid9 = true; passing1 = 0; } const _errs33 = errors; if (!(typeof data9 == "number" && isFinite(data9))) { const err6 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/tags/additionalProperties/oneOf/1/type", keyword: "type", params: { type: "number" }, message: "must be number" }; if (vErrors === null) { vErrors = [err6]; } else { vErrors.push(err6); } errors++; } var _valid1 = _errs33 === errors; if (_valid1 && valid9) { valid9 = false; passing1 = [passing1, 1]; } else { if (_valid1) { valid9 = true; passing1 = 1; } const _errs35 = errors; if (typeof data9 !== "boolean") { const err7 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/tags/additionalProperties/oneOf/2/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }; if (vErrors === null) { vErrors = [err7]; } else { vErrors.push(err7); } errors++; } var _valid1 = _errs35 === errors; if (_valid1 && valid9) { valid9 = false; passing1 = [passing1, 2]; } else { if (_valid1) { valid9 = true; passing1 = 2; } const _errs37 = errors; if (errors === _errs37) { if (data9 && typeof data9 == "object" && !Array.isArray(data9)) { if (Object.keys(data9).length < 1) { const err8 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/tags/additionalProperties/oneOf/3/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }; if (vErrors === null) { vErrors = [err8]; } else { vErrors.push(err8); } errors++; } else { const _errs39 = errors; for (const key2 in data9) { if (!(key2 === "startsWith")) { const err9 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/tags/additionalProperties/oneOf/3/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }; if (vErrors === null) { vErrors = [err9]; } else { vErrors.push(err9); } errors++; break; } } if (_errs39 === errors) { if (data9.startsWith !== void 0) { if (typeof data9.startsWith !== "string") { const err10 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1") + "/startsWith", schemaPath: "#/properties/tags/additionalProperties/oneOf/3/properties/startsWith/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err10]; } else { vErrors.push(err10); } errors++; } } } } } else { const err11 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/tags/additionalProperties/oneOf/3/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err11]; } else { vErrors.push(err11); } errors++; } } var _valid1 = _errs37 === errors; if (_valid1 && valid9) { valid9 = false; passing1 = [passing1, 3]; } else { if (_valid1) { valid9 = true; passing1 = 3; var props1 = true; } const _errs42 = errors; const _errs43 = errors; if (errors === _errs43) { if (data9 && typeof data9 == "object" && !Array.isArray(data9)) { if (Object.keys(data9).length < 1) { const err12 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "https://identity.foundation/dwn/json-schemas/string-range-filter.json/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }; if (vErrors === null) { vErrors = [err12]; } else { vErrors.push(err12); } errors++; } else { const _errs45 = errors; for (const key3 in data9) { if (!(key3 === "gt" || key3 === "gte" || key3 === "lt" || key3 === "lte")) { const err13 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "https://identity.foundation/dwn/json-schemas/string-range-filter.json/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key3 }, message: "must NOT have additional properties" }; if (vErrors === null) { vErrors = [err13]; } else { vErrors.push(err13); } errors++; break; } } if (_errs45 === errors) { if (data9.gt !== void 0) { const _errs46 = errors; const _errs47 = errors; const _errs48 = errors; if (data9 && typeof data9 == "object" && !Array.isArray(data9)) { let missing2; if (data9.gte === void 0 && (missing2 = "gte")) { const err14 = {}; if (vErrors === null) { vErrors = [err14]; } else { vErrors.push(err14); } errors++; } } var valid13 = _errs48 === errors; if (valid13) { const err15 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "https://identity.foundation/dwn/json-schemas/string-range-filter.json/dependencies/gt/not", keyword: "not", params: {}, message: "must NOT be valid" }; if (vErrors === null) { vErrors = [err15]; } else { vErrors.push(err15); } errors++; } else { errors = _errs47; if (vErrors !== null) { if (_errs47) { vErrors.length = _errs47; } else { vErrors = null; } } } var valid12 = _errs46 === errors; } else { var valid12 = true; } if (valid12) { if (data9.gte !== void 0) { const _errs49 = errors; const _errs50 = errors; const _errs51 = errors; if (data9 && typeof data9 == "object" && !Array.isArray(data9)) { let missing3; if (data9.gt === void 0 && (missing3 = "gt")) { const err16 = {}; if (vErrors === null) { vErrors = [err16]; } else { vErrors.push(err16); } errors++; } } var valid14 = _errs51 === errors; if (valid14) { const err17 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "https://identity.foundation/dwn/json-schemas/string-range-filter.json/dependencies/gte/not", keyword: "not", params: {}, message: "must NOT be valid" }; if (vErrors === null) { vErrors = [err17]; } else { vErrors.push(err17); } errors++; } else { errors = _errs50; if (vErrors !== null) { if (_errs50) { vErrors.length = _errs50; } else { vErrors = null; } } } var valid12 = _errs49 === errors; } else { var valid12 = true; } if (valid12) { if (data9.lt !== void 0) { const _errs52 = errors; const _errs53 = errors; const _errs54 = errors; if (data9 && typeof data9 == "object" && !Array.isArray(data9)) { let missing4; if (data9.lte === void 0 && (missing4 = "lte")) { const err18 = {}; if (vErrors === null) { vErrors = [err18]; } else { vErrors.push(err18); } errors++; } } var valid15 = _errs54 === errors; if (valid15) { const err19 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "https://identity.foundation/dwn/json-schemas/string-range-filter.json/dependencies/lt/not", keyword: "not", params: {}, message: "must NOT be valid" }; if (vErrors === null) { vErrors = [err19]; } else { vErrors.push(err19); } errors++; } else { errors = _errs53; if (vErrors !== null) { if (_errs53) { vErrors.length = _errs53; } else { vErrors = null; } } } var valid12 = _errs52 === errors; } else { var valid12 = true; } if (valid12) { if (data9.lte !== void 0) { const _errs55 = errors; const _errs56 = errors; const _errs57 = errors; if (data9 && typeof data9 == "object" && !Array.isArray(data9)) { let missing5; if (data9.lt === void 0 && (missing5 = "lt")) { const err20 = {}; if (vErrors === null) { vErrors = [err20]; } else { vErrors.push(err20); } errors++; } } var valid16 = _errs57 === errors; if (valid16) { const err21 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "https://identity.foundation/dwn/json-schemas/string-range-filter.json/dependencies/lte/not", keyword: "not", params: {}, message: "must NOT be valid" }; if (vErrors === null) { vErrors = [err21]; } else { vErrors.push(err21); } errors++; } else { errors = _errs56; if (vErrors !== null) { if (_errs56) { vErrors.length = _errs56; } else { vErrors = null; } } } var valid12 = _errs55 === errors; } else { var valid12 = true; } if (valid12) { if (data9.gt !== void 0) { const _errs58 = errors; if (typeof data9.gt !== "string") { const err22 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1") + "/gt", schemaPath: "https://identity.foundation/dwn/json-schemas/string-range-filter.json/properties/gt/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err22]; } else { vErrors.push(err22); } errors++; } var valid17 = _errs58 === errors; } else { var valid17 = true; } if (valid17) { if (data9.gte !== void 0) { const _errs60 = errors; if (typeof data9.gte !== "string") { const err23 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1") + "/gte", schemaPath: "https://identity.foundation/dwn/json-schemas/string-range-filter.json/properties/gte/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err23]; } else { vErrors.push(err23); } errors++; } var valid17 = _errs60 === errors; } else { var valid17 = true; } if (valid17) { if (data9.lt !== void 0) { const _errs62 = errors; if (typeof data9.lt !== "string") { const err24 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1") + "/lt", schemaPath: "https://identity.foundation/dwn/json-schemas/string-range-filter.json/properties/lt/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err24]; } else { vErrors.push(err24); } errors++; } var valid17 = _errs62 === errors; } else { var valid17 = true; } if (valid17) { if (data9.lte !== void 0) { const _errs64 = errors; if (typeof data9.lte !== "string") { const err25 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1") + "/lte", schemaPath: "https://identity.foundation/dwn/json-schemas/string-range-filter.json/properties/lte/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err25]; } else { vErrors.push(err25); } errors++; } var valid17 = _errs64 === errors; } else { var valid17 = true; } } } } } } } } } } } else { const err26 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "https://identity.foundation/dwn/json-schemas/string-range-filter.json/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err26]; } else { vErrors.push(err26); } errors++; } } var _valid1 = _errs42 === errors; if (_valid1 && valid9) { valid9 = false; passing1 = [passing1, 4]; } else { if (_valid1) { valid9 = true; passing1 = 4; if (props1 !== true) { props1 = true; } } const _errs66 = errors; const _errs67 = errors; if (errors === _errs67) { if (data9 && typeof data9 == "object" && !Array.isArray(data9)) { if (Object.keys(data9).length < 1) { const err27 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }; if (vErrors === null) { vErrors = [err27]; } else { vErrors.push(err27); } errors++; } else { const _errs69 = errors; for (const key4 in data9) { if (!(key4 === "gt" || key4 === "gte" || key4 === "lt" || key4 === "lte")) { const err28 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key4 }, message: "must NOT have additional properties" }; if (vErrors === null) { vErrors = [err28]; } else { vErrors.push(err28); } errors++; break; } } if (_errs69 === errors) { if (data9.gt !== void 0) { const _errs70 = errors; const _errs71 = errors; const _errs72 = errors; if (data9 && typeof data9 == "object" && !Array.isArray(data9)) { let missing6; if (data9.gte === void 0 && (missing6 = "gte")) { const err29 = {}; if (vErrors === null) { vErrors = [err29]; } else { vErrors.push(err29); } errors++; } } var valid20 = _errs72 === errors; if (valid20) { const err30 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/dependencies/gt/not", keyword: "not", params: {}, message: "must NOT be valid" }; if (vErrors === null) { vErrors = [err30]; } else { vErrors.push(err30); } errors++; } else { errors = _errs71; if (vErrors !== null) { if (_errs71) { vErrors.length = _errs71; } else { vErrors = null; } } } var valid19 = _errs70 === errors; } else { var valid19 = true; } if (valid19) { if (data9.gte !== void 0) { const _errs73 = errors; const _errs74 = errors; const _errs75 = errors; if (data9 && typeof data9 == "object" && !Array.isArray(data9)) { let missing7; if (data9.gt === void 0 && (missing7 = "gt")) { const err31 = {}; if (vErrors === null) { vErrors = [err31]; } else { vErrors.push(err31); } errors++; } } var valid21 = _errs75 === errors; if (valid21) { const err32 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/dependencies/gte/not", keyword: "not", params: {}, message: "must NOT be valid" }; if (vErrors === null) { vErrors = [err32]; } else { vErrors.push(err32); } errors++; } else { errors = _errs74; if (vErrors !== null) { if (_errs74) { vErrors.length = _errs74; } else { vErrors = null; } } } var valid19 = _errs73 === errors; } else { var valid19 = true; } if (valid19) { if (data9.lt !== void 0) { const _errs76 = errors; const _errs77 = errors; const _errs78 = errors; if (data9 && typeof data9 == "object" && !Array.isArray(data9)) { let missing8; if (data9.lte === void 0 && (missing8 = "lte")) { const err33 = {}; if (vErrors === null) { vErrors = [err33]; } else { vErrors.push(err33); } errors++; } } var valid22 = _errs78 === errors; if (valid22) { const err34 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/dependencies/lt/not", keyword: "not", params: {}, message: "must NOT be valid" }; if (vErrors === null) { vErrors = [err34]; } else { vErrors.push(err34); } errors++; } else { errors = _errs77; if (vErrors !== null) { if (_errs77) { vErrors.length = _errs77; } else { vErrors = null; } } } var valid19 = _errs76 === errors; } else { var valid19 = true; } if (valid19) { if (data9.lte !== void 0) { const _errs79 = errors; const _errs80 = errors; const _errs81 = errors; if (data9 && typeof data9 == "object" && !Array.isArray(data9)) { let missing9; if (data9.lt === void 0 && (missing9 = "lt")) { const err35 = {}; if (vErrors === null) { vErrors = [err35]; } else { vErrors.push(err35); } errors++; } } var valid23 = _errs81 === errors; if (valid23) { const err36 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/dependencies/lte/not", keyword: "not", params: {}, message: "must NOT be valid" }; if (vErrors === null) { vErrors = [err36]; } else { vErrors.push(err36); } errors++; } else { errors = _errs80; if (vErrors !== null) { if (_errs80) { vErrors.length = _errs80; } else { vErrors = null; } } } var valid19 = _errs79 === errors; } else { var valid19 = true; } if (valid19) { if (data9.gt !== void 0) { let data15 = data9.gt; const _errs82 = errors; if (!(typeof data15 == "number" && isFinite(data15))) { const err37 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1") + "/gt", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/properties/gt/type", keyword: "type", params: { type: "number" }, message: "must be number" }; if (vErrors === null) { vErrors = [err37]; } else { vErrors.push(err37); } errors++; } var valid24 = _errs82 === errors; } else { var valid24 = true; } if (valid24) { if (data9.gte !== void 0) { let data16 = data9.gte; const _errs84 = errors; if (!(typeof data16 == "number" && isFinite(data16))) { const err38 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1") + "/gte", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/properties/gte/type", keyword: "type", params: { type: "number" }, message: "must be number" }; if (vErrors === null) { vErrors = [err38]; } else { vErrors.push(err38); } errors++; } var valid24 = _errs84 === errors; } else { var valid24 = true; } if (valid24) { if (data9.lt !== void 0) { let data17 = data9.lt; const _errs86 = errors; if (!(typeof data17 == "number" && isFinite(data17))) { const err39 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1") + "/lt", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/properties/lt/type", keyword: "type", params: { type: "number" }, message: "must be number" }; if (vErrors === null) { vErrors = [err39]; } else { vErrors.push(err39); } errors++; } var valid24 = _errs86 === errors; } else { var valid24 = true; } if (valid24) { if (data9.lte !== void 0) { let data18 = data9.lte; const _errs88 = errors; if (!(typeof data18 == "number" && isFinite(data18))) { const err40 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1") + "/lte", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/properties/lte/type", keyword: "type", params: { type: "number" }, message: "must be number" }; if (vErrors === null) { vErrors = [err40]; } else { vErrors.push(err40); } errors++; } var valid24 = _errs88 === errors; } else { var valid24 = true; } } } } } } } } } } } else { const err41 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err41]; } else { vErrors.push(err41); } errors++; } } var _valid1 = _errs66 === errors; if (_valid1 && valid9) { valid9 = false; passing1 = [passing1, 5]; } else { if (_valid1) { valid9 = true; passing1 = 5; if (props1 !== true) { props1 = true; } } } } } } } if (!valid9) { const err42 = { instancePath: instancePath + "/tags/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/tags/additionalProperties/oneOf", keyword: "oneOf", params: { passingSchemas: passing1 }, message: "must match exactly one schema in oneOf" }; if (vErrors === null) { vErrors = [err42]; } else { vErrors.push(err42); } errors++; validate42.errors = vErrors; return false; } else { errors = _errs30; if (vErrors !== null) { if (_errs30) { vErrors.length = _errs30; } else { vErrors = null; } } } var valid8 = _errs29 === errors; if (!valid8) { break; } } } } else { validate42.errors = [{ instancePath: instancePath + "/tags", schemaPath: "#/properties/tags/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid4 = _errs26 === errors; } else { var valid4 = true; } if (valid4) { if (data.recordId !== void 0) { const _errs90 = errors; if (typeof data.recordId !== "string") { validate42.errors = [{ instancePath: instancePath + "/recordId", schemaPath: "#/properties/recordId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid4 = _errs90 === errors; } else { var valid4 = true; } if (valid4) { if (data.parentId !== void 0) { const _errs92 = errors; if (typeof data.parentId !== "string") { validate42.errors = [{ instancePath: instancePath + "/parentId", schemaPath: "#/properties/parentId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid4 = _errs92 === errors; } else { var valid4 = true; } if (valid4) { if (data.published !== void 0) { const _errs94 = errors; if (typeof data.published !== "boolean") { validate42.errors = [{ instancePath: instancePath + "/published", schemaPath: "#/properties/published/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } var valid4 = _errs94 === errors; } else { var valid4 = true; } if (valid4) { if (data.dataFormat !== void 0) { const _errs96 = errors; if (typeof data.dataFormat !== "string") { validate42.errors = [{ instancePath: instancePath + "/dataFormat", schemaPath: "#/properties/dataFormat/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid4 = _errs96 === errors; } else { var valid4 = true; } if (valid4) { if (data.dataSize !== void 0) { let data23 = data.dataSize; const _errs98 = errors; const _errs99 = errors; if (errors === _errs99) { if (data23 && typeof data23 == "object" && !Array.isArray(data23)) { if (Object.keys(data23).length < 1) { validate42.errors = [{ instancePath: instancePath + "/dataSize", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { const _errs101 = errors; for (const key5 in data23) { if (!(key5 === "gt" || key5 === "gte" || key5 === "lt" || key5 === "lte")) { validate42.errors = [{ instancePath: instancePath + "/dataSize", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key5 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs101 === errors) { if (data23.gt !== void 0) { const _errs102 = errors; const _errs103 = errors; const _errs104 = errors; if (data23 && typeof data23 == "object" && !Array.isArray(data23)) { let missing10; if (data23.gte === void 0 && (missing10 = "gte")) { const err43 = {}; if (vErrors === null) { vErrors = [err43]; } else { vErrors.push(err43); } errors++; } } var valid27 = _errs104 === errors; if (valid27) { validate42.errors = [{ instancePath: instancePath + "/dataSize", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/dependencies/gt/not", keyword: "not", params: {}, message: "must NOT be valid" }]; return false; } else { errors = _errs103; if (vErrors !== null) { if (_errs103) { vErrors.length = _errs103; } else { vErrors = null; } } } var valid26 = _errs102 === errors; } else { var valid26 = true; } if (valid26) { if (data23.gte !== void 0) { const _errs105 = errors; const _errs106 = errors; const _errs107 = errors; if (data23 && typeof data23 == "object" && !Array.isArray(data23)) { let missing11; if (data23.gt === void 0 && (missing11 = "gt")) { const err44 = {}; if (vErrors === null) { vErrors = [err44]; } else { vErrors.push(err44); } errors++; } } var valid28 = _errs107 === errors; if (valid28) { validate42.errors = [{ instancePath: instancePath + "/dataSize", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/dependencies/gte/not", keyword: "not", params: {}, message: "must NOT be valid" }]; return false; } else { errors = _errs106; if (vErrors !== null) { if (_errs106) { vErrors.length = _errs106; } else { vErrors = null; } } } var valid26 = _errs105 === errors; } else { var valid26 = true; } if (valid26) { if (data23.lt !== void 0) { const _errs108 = errors; const _errs109 = errors; const _errs110 = errors; if (data23 && typeof data23 == "object" && !Array.isArray(data23)) { let missing12; if (data23.lte === void 0 && (missing12 = "lte")) { const err45 = {}; if (vErrors === null) { vErrors = [err45]; } else { vErrors.push(err45); } errors++; } } var valid29 = _errs110 === errors; if (valid29) { validate42.errors = [{ instancePath: instancePath + "/dataSize", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/dependencies/lt/not", keyword: "not", params: {}, message: "must NOT be valid" }]; return false; } else { errors = _errs109; if (vErrors !== null) { if (_errs109) { vErrors.length = _errs109; } else { vErrors = null; } } } var valid26 = _errs108 === errors; } else { var valid26 = true; } if (valid26) { if (data23.lte !== void 0) { const _errs111 = errors; const _errs112 = errors; const _errs113 = errors; if (data23 && typeof data23 == "object" && !Array.isArray(data23)) { let missing13; if (data23.lt === void 0 && (missing13 = "lt")) { const err46 = {}; if (vErrors === null) { vErrors = [err46]; } else { vErrors.push(err46); } errors++; } } var valid30 = _errs113 === errors; if (valid30) { validate42.errors = [{ instancePath: instancePath + "/dataSize", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/dependencies/lte/not", keyword: "not", params: {}, message: "must NOT be valid" }]; return false; } else { errors = _errs112; if (vErrors !== null) { if (_errs112) { vErrors.length = _errs112; } else { vErrors = null; } } } var valid26 = _errs111 === errors; } else { var valid26 = true; } if (valid26) { if (data23.gt !== void 0) { let data24 = data23.gt; const _errs114 = errors; if (!(typeof data24 == "number" && isFinite(data24))) { validate42.errors = [{ instancePath: instancePath + "/dataSize/gt", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/properties/gt/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } var valid31 = _errs114 === errors; } else { var valid31 = true; } if (valid31) { if (data23.gte !== void 0) { let data25 = data23.gte; const _errs116 = errors; if (!(typeof data25 == "number" && isFinite(data25))) { validate42.errors = [{ instancePath: instancePath + "/dataSize/gte", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/properties/gte/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } var valid31 = _errs116 === errors; } else { var valid31 = true; } if (valid31) { if (data23.lt !== void 0) { let data26 = data23.lt; const _errs118 = errors; if (!(typeof data26 == "number" && isFinite(data26))) { validate42.errors = [{ instancePath: instancePath + "/dataSize/lt", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/properties/lt/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } var valid31 = _errs118 === errors; } else { var valid31 = true; } if (valid31) { if (data23.lte !== void 0) { let data27 = data23.lte; const _errs120 = errors; if (!(typeof data27 == "number" && isFinite(data27))) { validate42.errors = [{ instancePath: instancePath + "/dataSize/lte", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/properties/lte/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } var valid31 = _errs120 === errors; } else { var valid31 = true; } } } } } } } } } } } else { validate42.errors = [{ instancePath: instancePath + "/dataSize", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid4 = _errs98 === errors; } else { var valid4 = true; } if (valid4) { if (data.dataCid !== void 0) { const _errs122 = errors; if (typeof data.dataCid !== "string") { validate42.errors = [{ instancePath: instancePath + "/dataCid", schemaPath: "#/properties/dataCid/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid4 = _errs122 === errors; } else { var valid4 = true; } if (valid4) { if (data.dateCreated !== void 0) { let data29 = data.dateCreated; const _errs124 = errors; if (errors === _errs124) { if (data29 && typeof data29 == "object" && !Array.isArray(data29)) { if (Object.keys(data29).length < 1) { validate42.errors = [{ instancePath: instancePath + "/dateCreated", schemaPath: "#/properties/dateCreated/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { const _errs126 = errors; for (const key6 in data29) { if (!(key6 === "from" || key6 === "to")) { validate42.errors = [{ instancePath: instancePath + "/dateCreated", schemaPath: "#/properties/dateCreated/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key6 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs126 === errors) { if (data29.from !== void 0) { let data30 = data29.from; const _errs127 = errors; const _errs128 = errors; if (errors === _errs128) { if (typeof data30 === "string") { if (!pattern14.test(data30)) { validate42.errors = [{ instancePath: instancePath + "/dateCreated/from", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate42.errors = [{ instancePath: instancePath + "/dateCreated/from", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid32 = _errs127 === errors; } else { var valid32 = true; } if (valid32) { if (data29.to !== void 0) { let data31 = data29.to; const _errs130 = errors; const _errs131 = errors; if (errors === _errs131) { if (typeof data31 === "string") { if (!pattern14.test(data31)) { validate42.errors = [{ instancePath: instancePath + "/dateCreated/to", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate42.errors = [{ instancePath: instancePath + "/dateCreated/to", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid32 = _errs130 === errors; } else { var valid32 = true; } } } } } else { validate42.errors = [{ instancePath: instancePath + "/dateCreated", schemaPath: "#/properties/dateCreated/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid4 = _errs124 === errors; } else { var valid4 = true; } if (valid4) { if (data.datePublished !== void 0) { let data32 = data.datePublished; const _errs133 = errors; if (errors === _errs133) { if (data32 && typeof data32 == "object" && !Array.isArray(data32)) { if (Object.keys(data32).length < 1) { validate42.errors = [{ instancePath: instancePath + "/datePublished", schemaPath: "#/properties/datePublished/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { const _errs135 = errors; for (const key7 in data32) { if (!(key7 === "from" || key7 === "to")) { validate42.errors = [{ instancePath: instancePath + "/datePublished", schemaPath: "#/properties/datePublished/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key7 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs135 === errors) { if (data32.from !== void 0) { let data33 = data32.from; const _errs136 = errors; const _errs137 = errors; if (errors === _errs137) { if (typeof data33 === "string") { if (!pattern14.test(data33)) { validate42.errors = [{ instancePath: instancePath + "/datePublished/from", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate42.errors = [{ instancePath: instancePath + "/datePublished/from", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid35 = _errs136 === errors; } else { var valid35 = true; } if (valid35) { if (data32.to !== void 0) { let data34 = data32.to; const _errs139 = errors; const _errs140 = errors; if (errors === _errs140) { if (typeof data34 === "string") { if (!pattern14.test(data34)) { validate42.errors = [{ instancePath: instancePath + "/datePublished/to", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate42.errors = [{ instancePath: instancePath + "/datePublished/to", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid35 = _errs139 === errors; } else { var valid35 = true; } } } } } else { validate42.errors = [{ instancePath: instancePath + "/datePublished", schemaPath: "#/properties/datePublished/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid4 = _errs133 === errors; } else { var valid4 = true; } if (valid4) { if (data.dateUpdated !== void 0) { let data35 = data.dateUpdated; const _errs142 = errors; if (errors === _errs142) { if (data35 && typeof data35 == "object" && !Array.isArray(data35)) { if (Object.keys(data35).length < 1) { validate42.errors = [{ instancePath: instancePath + "/dateUpdated", schemaPath: "#/properties/dateUpdated/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { const _errs144 = errors; for (const key8 in data35) { if (!(key8 === "from" || key8 === "to")) { validate42.errors = [{ instancePath: instancePath + "/dateUpdated", schemaPath: "#/properties/dateUpdated/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key8 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs144 === errors) { if (data35.from !== void 0) { let data36 = data35.from; const _errs145 = errors; const _errs146 = errors; if (errors === _errs146) { if (typeof data36 === "string") { if (!pattern14.test(data36)) { validate42.errors = [{ instancePath: instancePath + "/dateUpdated/from", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate42.errors = [{ instancePath: instancePath + "/dateUpdated/from", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid38 = _errs145 === errors; } else { var valid38 = true; } if (valid38) { if (data35.to !== void 0) { let data37 = data35.to; const _errs148 = errors; const _errs149 = errors; if (errors === _errs149) { if (typeof data37 === "string") { if (!pattern14.test(data37)) { validate42.errors = [{ instancePath: instancePath + "/dateUpdated/to", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate42.errors = [{ instancePath: instancePath + "/dateUpdated/to", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid38 = _errs148 === errors; } else { var valid38 = true; } } } } } else { validate42.errors = [{ instancePath: instancePath + "/dateUpdated", schemaPath: "#/properties/dateUpdated/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid4 = _errs142 === errors; } else { var valid4 = true; } } } } } } } } } } } } } } } } } } } } } else { validate42.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate42.errors = vErrors; return errors === 0; } validate42.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; function validate40(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate40.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.descriptor === void 0 && (missing0 = "descriptor")) { validate40.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "authorization" || key0 === "descriptor")) { validate40.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.authorization !== void 0) { const _errs2 = errors; if (!validate24(data.authorization, { instancePath: instancePath + "/authorization", parentData: data, parentDataProperty: "authorization", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate24.errors : vErrors.concat(validate24.errors); errors = vErrors.length; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.descriptor !== void 0) { let data1 = data.descriptor; const _errs3 = errors; if (errors === _errs3) { if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { let missing1; if (data1.interface === void 0 && (missing1 = "interface") || data1.method === void 0 && (missing1 = "method") || data1.messageTimestamp === void 0 && (missing1 = "messageTimestamp") || data1.filter === void 0 && (missing1 = "filter")) { validate40.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }]; return false; } else { const _errs5 = errors; for (const key1 in data1) { if (!(key1 === "interface" || key1 === "method" || key1 === "messageTimestamp" || key1 === "filter" || key1 === "pagination" || key1 === "dateSort")) { validate40.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs5 === errors) { if (data1.interface !== void 0) { let data2 = data1.interface; const _errs6 = errors; if (typeof data2 !== "string") { validate40.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data2 === "Records")) { validate40.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/enum", keyword: "enum", params: { allowedValues: schema53.properties.descriptor.properties.interface.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs6 === errors; } else { var valid1 = true; } if (valid1) { if (data1.method !== void 0) { let data3 = data1.method; const _errs8 = errors; if (typeof data3 !== "string") { validate40.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data3 === "Query")) { validate40.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/enum", keyword: "enum", params: { allowedValues: schema53.properties.descriptor.properties.method.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs8 === errors; } else { var valid1 = true; } if (valid1) { if (data1.messageTimestamp !== void 0) { let data4 = data1.messageTimestamp; const _errs10 = errors; const _errs11 = errors; if (errors === _errs11) { if (typeof data4 === "string") { if (!pattern14.test(data4)) { validate40.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate40.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid1 = _errs10 === errors; } else { var valid1 = true; } if (valid1) { if (data1.filter !== void 0) { const _errs13 = errors; if (!validate42(data1.filter, { instancePath: instancePath + "/descriptor/filter", parentData: data1, parentDataProperty: "filter", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate42.errors : vErrors.concat(validate42.errors); errors = vErrors.length; } var valid1 = _errs13 === errors; } else { var valid1 = true; } if (valid1) { if (data1.pagination !== void 0) { let data6 = data1.pagination; const _errs14 = errors; if (errors === _errs14) { if (data6 && typeof data6 == "object" && !Array.isArray(data6)) { const _errs16 = errors; for (const key2 in data6) { if (!(key2 === "limit" || key2 === "cursor")) { validate40.errors = [{ instancePath: instancePath + "/descriptor/pagination", schemaPath: "#/properties/descriptor/properties/pagination/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs16 === errors) { if (data6.limit !== void 0) { let data7 = data6.limit; const _errs17 = errors; if (errors === _errs17) { if (typeof data7 == "number" && isFinite(data7)) { if (data7 < 1 || isNaN(data7)) { validate40.errors = [{ instancePath: instancePath + "/descriptor/pagination/limit", schemaPath: "#/properties/descriptor/properties/pagination/properties/limit/minimum", keyword: "minimum", params: { comparison: ">=", limit: 1 }, message: "must be >= 1" }]; return false; } } else { validate40.errors = [{ instancePath: instancePath + "/descriptor/pagination/limit", schemaPath: "#/properties/descriptor/properties/pagination/properties/limit/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } } var valid3 = _errs17 === errors; } else { var valid3 = true; } if (valid3) { if (data6.cursor !== void 0) { let data8 = data6.cursor; const _errs19 = errors; const _errs20 = errors; if (errors === _errs20) { if (data8 && typeof data8 == "object" && !Array.isArray(data8)) { if (Object.keys(data8).length < 1) { validate40.errors = [{ instancePath: instancePath + "/descriptor/pagination/cursor", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { let missing2; if (data8.messageCid === void 0 && (missing2 = "messageCid") || data8.value === void 0 && (missing2 = "value")) { validate40.errors = [{ instancePath: instancePath + "/descriptor/pagination/cursor", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/required", keyword: "required", params: { missingProperty: missing2 }, message: "must have required property '" + missing2 + "'" }]; return false; } else { const _errs22 = errors; for (const key3 in data8) { if (!(key3 === "messageCid" || key3 === "value")) { validate40.errors = [{ instancePath: instancePath + "/descriptor/pagination/cursor", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key3 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs22 === errors) { if (data8.messageCid !== void 0) { const _errs23 = errors; if (typeof data8.messageCid !== "string") { validate40.errors = [{ instancePath: instancePath + "/descriptor/pagination/cursor/messageCid", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/properties/messageCid/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid5 = _errs23 === errors; } else { var valid5 = true; } if (valid5) { if (data8.value !== void 0) { let data10 = data8.value; const _errs25 = errors; if (typeof data10 !== "string" && !(typeof data10 == "number" && isFinite(data10))) { validate40.errors = [{ instancePath: instancePath + "/descriptor/pagination/cursor/value", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/properties/value/type", keyword: "type", params: { type: schema68.properties.value.type }, message: "must be string,number" }]; return false; } var valid5 = _errs25 === errors; } else { var valid5 = true; } } } } } } else { validate40.errors = [{ instancePath: instancePath + "/descriptor/pagination/cursor", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid3 = _errs19 === errors; } else { var valid3 = true; } } } } else { validate40.errors = [{ instancePath: instancePath + "/descriptor/pagination", schemaPath: "#/properties/descriptor/properties/pagination/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid1 = _errs14 === errors; } else { var valid1 = true; } if (valid1) { if (data1.dateSort !== void 0) { let data11 = data1.dateSort; const _errs27 = errors; if (typeof data11 !== "string") { validate40.errors = [{ instancePath: instancePath + "/descriptor/dateSort", schemaPath: "#/properties/descriptor/properties/dateSort/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data11 === "createdAscending" || data11 === "createdDescending" || data11 === "publishedAscending" || data11 === "publishedDescending")) { validate40.errors = [{ instancePath: instancePath + "/descriptor/dateSort", schemaPath: "#/properties/descriptor/properties/dateSort/enum", keyword: "enum", params: { allowedValues: schema53.properties.descriptor.properties.dateSort.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs27 === errors; } else { var valid1 = true; } } } } } } } } } else { validate40.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs3 === errors; } else { var valid0 = true; } } } } } else { validate40.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate40.errors = vErrors; return errors === 0; } validate40.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var RecordsSubscribe = validate44; var schema69 = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://identity.foundation/dwn/json-schemas/records-subscribe.json", "type": "object", "additionalProperties": false, "required": ["descriptor"], "properties": { "authorization": { "$ref": "https://identity.foundation/dwn/json-schemas/authorization-delegated-grant.json" }, "descriptor": { "type": "object", "additionalProperties": false, "required": ["interface", "method", "messageTimestamp", "filter"], "properties": { "interface": { "enum": ["Records"], "type": "string" }, "method": { "enum": ["Subscribe"], "type": "string" }, "messageTimestamp": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" }, "filter": { "$ref": "https://identity.foundation/dwn/json-schemas/records-filter.json" } } } } }; function validate44(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate44.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.descriptor === void 0 && (missing0 = "descriptor")) { validate44.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "authorization" || key0 === "descriptor")) { validate44.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.authorization !== void 0) { const _errs2 = errors; if (!validate24(data.authorization, { instancePath: instancePath + "/authorization", parentData: data, parentDataProperty: "authorization", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate24.errors : vErrors.concat(validate24.errors); errors = vErrors.length; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.descriptor !== void 0) { let data1 = data.descriptor; const _errs3 = errors; if (errors === _errs3) { if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { let missing1; if (data1.interface === void 0 && (missing1 = "interface") || data1.method === void 0 && (missing1 = "method") || data1.messageTimestamp === void 0 && (missing1 = "messageTimestamp") || data1.filter === void 0 && (missing1 = "filter")) { validate44.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }]; return false; } else { const _errs5 = errors; for (const key1 in data1) { if (!(key1 === "interface" || key1 === "method" || key1 === "messageTimestamp" || key1 === "filter")) { validate44.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs5 === errors) { if (data1.interface !== void 0) { let data2 = data1.interface; const _errs6 = errors; if (typeof data2 !== "string") { validate44.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data2 === "Records")) { validate44.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/enum", keyword: "enum", params: { allowedValues: schema69.properties.descriptor.properties.interface.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs6 === errors; } else { var valid1 = true; } if (valid1) { if (data1.method !== void 0) { let data3 = data1.method; const _errs8 = errors; if (typeof data3 !== "string") { validate44.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data3 === "Subscribe")) { validate44.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/enum", keyword: "enum", params: { allowedValues: schema69.properties.descriptor.properties.method.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs8 === errors; } else { var valid1 = true; } if (valid1) { if (data1.messageTimestamp !== void 0) { let data4 = data1.messageTimestamp; const _errs10 = errors; const _errs11 = errors; if (errors === _errs11) { if (typeof data4 === "string") { if (!pattern14.test(data4)) { validate44.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate44.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid1 = _errs10 === errors; } else { var valid1 = true; } if (valid1) { if (data1.filter !== void 0) { const _errs13 = errors; if (!validate42(data1.filter, { instancePath: instancePath + "/descriptor/filter", parentData: data1, parentDataProperty: "filter", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate42.errors : vErrors.concat(validate42.errors); errors = vErrors.length; } var valid1 = _errs13 === errors; } else { var valid1 = true; } } } } } } } else { validate44.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs3 === errors; } else { var valid0 = true; } } } } } else { validate44.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate44.errors = vErrors; return errors === 0; } validate44.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var RecordsWrite = validate47; function validate47(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate47.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (!validate27(data, { instancePath, parentData, parentDataProperty, rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate27.errors : vErrors.concat(validate27.errors); errors = vErrors.length; } else { var props0 = validate27.evaluated.props; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.recordId === void 0 && (missing0 = "recordId") || data.authorization === void 0 && (missing0 = "authorization")) { validate47.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { if (props0 !== true) { for (const key0 in data) { if (!props0 || !props0[key0]) { validate47.errors = [{ instancePath, schemaPath: "#/unevaluatedProperties", keyword: "unevaluatedProperties", params: { unevaluatedProperty: key0 }, message: "must NOT have unevaluated properties" }]; return false; break; } } } } } else { validate47.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate47.errors = vErrors; return errors === 0; } validate47.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var RecordsWriteDataEncoded = validate26; var RecordsWriteUnidentified = validate27; var EventsFilter = validate49; var schema72 = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://identity.foundation/dwn/json-schemas/events-filter.json", "type": "object", "additionalProperties": false, "minProperties": 1, "properties": { "interface": { "enum": ["Permissions", "Protocols", "Records"], "type": "string" }, "method": { "enum": ["Configure", "Delete", "Grant", "Revoke", "Write"], "type": "string" }, "protocol": { "type": "string" }, "protocolPath": { "type": "string" }, "recipient": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did" }, "contextId": { "type": "string" }, "schema": { "type": "string" }, "recordId": { "type": "string" }, "parentId": { "type": "string" }, "dataFormat": { "type": "string" }, "dataSize": { "$ref": "https://identity.foundation/dwn/json-schemas/number-range-filter.json" }, "dateCreated": { "type": "object", "minProperties": 1, "additionalProperties": false, "properties": { "from": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" }, "to": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" } } }, "datePublished": { "type": "object", "minProperties": 1, "additionalProperties": false, "properties": { "from": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" }, "to": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" } } }, "dateUpdated": { "type": "object", "minProperties": 1, "additionalProperties": false, "properties": { "from": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" }, "to": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" } } } }, "dependencies": { "datePublished": { "oneOf": [{ "properties": { "published": { "enum": [true] } }, "required": ["published"] }, { "not": { "required": ["published"] } }] } } }; function validate49(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate49.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { if (Object.keys(data).length < 1) { validate49.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!func1.call(schema72.properties, key0)) { validate49.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.datePublished !== void 0) { const _errs2 = errors; const _errs3 = errors; let valid1 = false; let passing0 = null; const _errs4 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.published === void 0 && (missing0 = "published")) { const err0 = { instancePath, schemaPath: "#/dependencies/datePublished/oneOf/0/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }; if (vErrors === null) { vErrors = [err0]; } else { vErrors.push(err0); } errors++; } else { if (data.published !== void 0) { if (!(data.published === true)) { const err1 = { instancePath: instancePath + "/published", schemaPath: "#/dependencies/datePublished/oneOf/0/properties/published/enum", keyword: "enum", params: { allowedValues: schema72.dependencies.datePublished.oneOf[0].properties.published.enum }, message: "must be equal to one of the allowed values" }; if (vErrors === null) { vErrors = [err1]; } else { vErrors.push(err1); } errors++; } } } } var _valid0 = _errs4 === errors; if (_valid0) { valid1 = true; passing0 = 0; var props0 = {}; props0.published = true; } const _errs6 = errors; const _errs7 = errors; const _errs8 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing1; if (data.published === void 0 && (missing1 = "published")) { const err22 = {}; if (vErrors === null) { vErrors = [err22]; } else { vErrors.push(err22); } errors++; } } var valid3 = _errs8 === errors; if (valid3) { const err3 = { instancePath, schemaPath: "#/dependencies/datePublished/oneOf/1/not", keyword: "not", params: {}, message: "must NOT be valid" }; if (vErrors === null) { vErrors = [err3]; } else { vErrors.push(err3); } errors++; } else { errors = _errs7; if (vErrors !== null) { if (_errs7) { vErrors.length = _errs7; } else { vErrors = null; } } } var _valid0 = _errs6 === errors; if (_valid0 && valid1) { valid1 = false; passing0 = [passing0, 1]; } else { if (_valid0) { valid1 = true; passing0 = 1; } } if (!valid1) { const err4 = { instancePath, schemaPath: "#/dependencies/datePublished/oneOf", keyword: "oneOf", params: { passingSchemas: passing0 }, message: "must match exactly one schema in oneOf" }; if (vErrors === null) { vErrors = [err4]; } else { vErrors.push(err4); } errors++; validate49.errors = vErrors; return false; } else { errors = _errs3; if (vErrors !== null) { if (_errs3) { vErrors.length = _errs3; } else { vErrors = null; } } } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.interface !== void 0) { let data1 = data.interface; const _errs9 = errors; if (typeof data1 !== "string") { validate49.errors = [{ instancePath: instancePath + "/interface", schemaPath: "#/properties/interface/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data1 === "Permissions" || data1 === "Protocols" || data1 === "Records")) { validate49.errors = [{ instancePath: instancePath + "/interface", schemaPath: "#/properties/interface/enum", keyword: "enum", params: { allowedValues: schema72.properties.interface.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid4 = _errs9 === errors; } else { var valid4 = true; } if (valid4) { if (data.method !== void 0) { let data2 = data.method; const _errs11 = errors; if (typeof data2 !== "string") { validate49.errors = [{ instancePath: instancePath + "/method", schemaPath: "#/properties/method/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data2 === "Configure" || data2 === "Delete" || data2 === "Grant" || data2 === "Revoke" || data2 === "Write")) { validate49.errors = [{ instancePath: instancePath + "/method", schemaPath: "#/properties/method/enum", keyword: "enum", params: { allowedValues: schema72.properties.method.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid4 = _errs11 === errors; } else { var valid4 = true; } if (valid4) { if (data.protocol !== void 0) { const _errs13 = errors; if (typeof data.protocol !== "string") { validate49.errors = [{ instancePath: instancePath + "/protocol", schemaPath: "#/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid4 = _errs13 === errors; } else { var valid4 = true; } if (valid4) { if (data.protocolPath !== void 0) { const _errs15 = errors; if (typeof data.protocolPath !== "string") { validate49.errors = [{ instancePath: instancePath + "/protocolPath", schemaPath: "#/properties/protocolPath/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid4 = _errs15 === errors; } else { var valid4 = true; } if (valid4) { if (data.recipient !== void 0) { let data5 = data.recipient; const _errs17 = errors; const _errs18 = errors; if (errors === _errs18) { if (typeof data5 === "string") { if (!pattern12.test(data5)) { validate49.errors = [{ instancePath: instancePath + "/recipient", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did/pattern", keyword: "pattern", params: { pattern: "^did:([a-z0-9]+):((?:(?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))*:)*((?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))+))((;[a-zA-Z0-9_.:%-]+=[a-zA-Z0-9_.:%-]*)*)(/[^#?]*)?([?][^#]*)?(#.*)?$" }, message: 'must match pattern "^did:([a-z0-9]+):((?:(?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))*:)*((?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))+))((;[a-zA-Z0-9_.:%-]+=[a-zA-Z0-9_.:%-]*)*)(/[^#?]*)?([?][^#]*)?(#.*)?$"' }]; return false; } } else { validate49.errors = [{ instancePath: instancePath + "/recipient", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid4 = _errs17 === errors; } else { var valid4 = true; } if (valid4) { if (data.contextId !== void 0) { const _errs20 = errors; if (typeof data.contextId !== "string") { validate49.errors = [{ instancePath: instancePath + "/contextId", schemaPath: "#/properties/contextId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid4 = _errs20 === errors; } else { var valid4 = true; } if (valid4) { if (data.schema !== void 0) { const _errs22 = errors; if (typeof data.schema !== "string") { validate49.errors = [{ instancePath: instancePath + "/schema", schemaPath: "#/properties/schema/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid4 = _errs22 === errors; } else { var valid4 = true; } if (valid4) { if (data.recordId !== void 0) { const _errs24 = errors; if (typeof data.recordId !== "string") { validate49.errors = [{ instancePath: instancePath + "/recordId", schemaPath: "#/properties/recordId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid4 = _errs24 === errors; } else { var valid4 = true; } if (valid4) { if (data.parentId !== void 0) { const _errs26 = errors; if (typeof data.parentId !== "string") { validate49.errors = [{ instancePath: instancePath + "/parentId", schemaPath: "#/properties/parentId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid4 = _errs26 === errors; } else { var valid4 = true; } if (valid4) { if (data.dataFormat !== void 0) { const _errs28 = errors; if (typeof data.dataFormat !== "string") { validate49.errors = [{ instancePath: instancePath + "/dataFormat", schemaPath: "#/properties/dataFormat/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid4 = _errs28 === errors; } else { var valid4 = true; } if (valid4) { if (data.dataSize !== void 0) { let data11 = data.dataSize; const _errs30 = errors; const _errs31 = errors; if (errors === _errs31) { if (data11 && typeof data11 == "object" && !Array.isArray(data11)) { if (Object.keys(data11).length < 1) { validate49.errors = [{ instancePath: instancePath + "/dataSize", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { const _errs33 = errors; for (const key1 in data11) { if (!(key1 === "gt" || key1 === "gte" || key1 === "lt" || key1 === "lte")) { validate49.errors = [{ instancePath: instancePath + "/dataSize", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs33 === errors) { if (data11.gt !== void 0) { const _errs34 = errors; const _errs35 = errors; const _errs36 = errors; if (data11 && typeof data11 == "object" && !Array.isArray(data11)) { let missing2; if (data11.gte === void 0 && (missing2 = "gte")) { const err5 = {}; if (vErrors === null) { vErrors = [err5]; } else { vErrors.push(err5); } errors++; } } var valid8 = _errs36 === errors; if (valid8) { validate49.errors = [{ instancePath: instancePath + "/dataSize", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/dependencies/gt/not", keyword: "not", params: {}, message: "must NOT be valid" }]; return false; } else { errors = _errs35; if (vErrors !== null) { if (_errs35) { vErrors.length = _errs35; } else { vErrors = null; } } } var valid7 = _errs34 === errors; } else { var valid7 = true; } if (valid7) { if (data11.gte !== void 0) { const _errs37 = errors; const _errs38 = errors; const _errs39 = errors; if (data11 && typeof data11 == "object" && !Array.isArray(data11)) { let missing3; if (data11.gt === void 0 && (missing3 = "gt")) { const err6 = {}; if (vErrors === null) { vErrors = [err6]; } else { vErrors.push(err6); } errors++; } } var valid9 = _errs39 === errors; if (valid9) { validate49.errors = [{ instancePath: instancePath + "/dataSize", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/dependencies/gte/not", keyword: "not", params: {}, message: "must NOT be valid" }]; return false; } else { errors = _errs38; if (vErrors !== null) { if (_errs38) { vErrors.length = _errs38; } else { vErrors = null; } } } var valid7 = _errs37 === errors; } else { var valid7 = true; } if (valid7) { if (data11.lt !== void 0) { const _errs40 = errors; const _errs41 = errors; const _errs42 = errors; if (data11 && typeof data11 == "object" && !Array.isArray(data11)) { let missing4; if (data11.lte === void 0 && (missing4 = "lte")) { const err7 = {}; if (vErrors === null) { vErrors = [err7]; } else { vErrors.push(err7); } errors++; } } var valid10 = _errs42 === errors; if (valid10) { validate49.errors = [{ instancePath: instancePath + "/dataSize", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/dependencies/lt/not", keyword: "not", params: {}, message: "must NOT be valid" }]; return false; } else { errors = _errs41; if (vErrors !== null) { if (_errs41) { vErrors.length = _errs41; } else { vErrors = null; } } } var valid7 = _errs40 === errors; } else { var valid7 = true; } if (valid7) { if (data11.lte !== void 0) { const _errs43 = errors; const _errs44 = errors; const _errs45 = errors; if (data11 && typeof data11 == "object" && !Array.isArray(data11)) { let missing5; if (data11.lt === void 0 && (missing5 = "lt")) { const err8 = {}; if (vErrors === null) { vErrors = [err8]; } else { vErrors.push(err8); } errors++; } } var valid11 = _errs45 === errors; if (valid11) { validate49.errors = [{ instancePath: instancePath + "/dataSize", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/dependencies/lte/not", keyword: "not", params: {}, message: "must NOT be valid" }]; return false; } else { errors = _errs44; if (vErrors !== null) { if (_errs44) { vErrors.length = _errs44; } else { vErrors = null; } } } var valid7 = _errs43 === errors; } else { var valid7 = true; } if (valid7) { if (data11.gt !== void 0) { let data12 = data11.gt; const _errs46 = errors; if (!(typeof data12 == "number" && isFinite(data12))) { validate49.errors = [{ instancePath: instancePath + "/dataSize/gt", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/properties/gt/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } var valid12 = _errs46 === errors; } else { var valid12 = true; } if (valid12) { if (data11.gte !== void 0) { let data13 = data11.gte; const _errs48 = errors; if (!(typeof data13 == "number" && isFinite(data13))) { validate49.errors = [{ instancePath: instancePath + "/dataSize/gte", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/properties/gte/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } var valid12 = _errs48 === errors; } else { var valid12 = true; } if (valid12) { if (data11.lt !== void 0) { let data14 = data11.lt; const _errs50 = errors; if (!(typeof data14 == "number" && isFinite(data14))) { validate49.errors = [{ instancePath: instancePath + "/dataSize/lt", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/properties/lt/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } var valid12 = _errs50 === errors; } else { var valid12 = true; } if (valid12) { if (data11.lte !== void 0) { let data15 = data11.lte; const _errs52 = errors; if (!(typeof data15 == "number" && isFinite(data15))) { validate49.errors = [{ instancePath: instancePath + "/dataSize/lte", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/properties/lte/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } var valid12 = _errs52 === errors; } else { var valid12 = true; } } } } } } } } } } } else { validate49.errors = [{ instancePath: instancePath + "/dataSize", schemaPath: "https://identity.foundation/dwn/json-schemas/number-range-filter.json/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid4 = _errs30 === errors; } else { var valid4 = true; } if (valid4) { if (data.dateCreated !== void 0) { let data16 = data.dateCreated; const _errs54 = errors; if (errors === _errs54) { if (data16 && typeof data16 == "object" && !Array.isArray(data16)) { if (Object.keys(data16).length < 1) { validate49.errors = [{ instancePath: instancePath + "/dateCreated", schemaPath: "#/properties/dateCreated/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { const _errs56 = errors; for (const key2 in data16) { if (!(key2 === "from" || key2 === "to")) { validate49.errors = [{ instancePath: instancePath + "/dateCreated", schemaPath: "#/properties/dateCreated/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs56 === errors) { if (data16.from !== void 0) { let data17 = data16.from; const _errs57 = errors; const _errs58 = errors; if (errors === _errs58) { if (typeof data17 === "string") { if (!pattern14.test(data17)) { validate49.errors = [{ instancePath: instancePath + "/dateCreated/from", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate49.errors = [{ instancePath: instancePath + "/dateCreated/from", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid13 = _errs57 === errors; } else { var valid13 = true; } if (valid13) { if (data16.to !== void 0) { let data18 = data16.to; const _errs60 = errors; const _errs61 = errors; if (errors === _errs61) { if (typeof data18 === "string") { if (!pattern14.test(data18)) { validate49.errors = [{ instancePath: instancePath + "/dateCreated/to", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate49.errors = [{ instancePath: instancePath + "/dateCreated/to", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid13 = _errs60 === errors; } else { var valid13 = true; } } } } } else { validate49.errors = [{ instancePath: instancePath + "/dateCreated", schemaPath: "#/properties/dateCreated/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid4 = _errs54 === errors; } else { var valid4 = true; } if (valid4) { if (data.datePublished !== void 0) { let data19 = data.datePublished; const _errs63 = errors; if (errors === _errs63) { if (data19 && typeof data19 == "object" && !Array.isArray(data19)) { if (Object.keys(data19).length < 1) { validate49.errors = [{ instancePath: instancePath + "/datePublished", schemaPath: "#/properties/datePublished/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { const _errs65 = errors; for (const key3 in data19) { if (!(key3 === "from" || key3 === "to")) { validate49.errors = [{ instancePath: instancePath + "/datePublished", schemaPath: "#/properties/datePublished/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key3 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs65 === errors) { if (data19.from !== void 0) { let data20 = data19.from; const _errs66 = errors; const _errs67 = errors; if (errors === _errs67) { if (typeof data20 === "string") { if (!pattern14.test(data20)) { validate49.errors = [{ instancePath: instancePath + "/datePublished/from", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate49.errors = [{ instancePath: instancePath + "/datePublished/from", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid16 = _errs66 === errors; } else { var valid16 = true; } if (valid16) { if (data19.to !== void 0) { let data21 = data19.to; const _errs69 = errors; const _errs70 = errors; if (errors === _errs70) { if (typeof data21 === "string") { if (!pattern14.test(data21)) { validate49.errors = [{ instancePath: instancePath + "/datePublished/to", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate49.errors = [{ instancePath: instancePath + "/datePublished/to", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid16 = _errs69 === errors; } else { var valid16 = true; } } } } } else { validate49.errors = [{ instancePath: instancePath + "/datePublished", schemaPath: "#/properties/datePublished/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid4 = _errs63 === errors; } else { var valid4 = true; } if (valid4) { if (data.dateUpdated !== void 0) { let data22 = data.dateUpdated; const _errs72 = errors; if (errors === _errs72) { if (data22 && typeof data22 == "object" && !Array.isArray(data22)) { if (Object.keys(data22).length < 1) { validate49.errors = [{ instancePath: instancePath + "/dateUpdated", schemaPath: "#/properties/dateUpdated/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { const _errs74 = errors; for (const key4 in data22) { if (!(key4 === "from" || key4 === "to")) { validate49.errors = [{ instancePath: instancePath + "/dateUpdated", schemaPath: "#/properties/dateUpdated/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key4 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs74 === errors) { if (data22.from !== void 0) { let data23 = data22.from; const _errs75 = errors; const _errs76 = errors; if (errors === _errs76) { if (typeof data23 === "string") { if (!pattern14.test(data23)) { validate49.errors = [{ instancePath: instancePath + "/dateUpdated/from", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate49.errors = [{ instancePath: instancePath + "/dateUpdated/from", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid19 = _errs75 === errors; } else { var valid19 = true; } if (valid19) { if (data22.to !== void 0) { let data24 = data22.to; const _errs78 = errors; const _errs79 = errors; if (errors === _errs79) { if (typeof data24 === "string") { if (!pattern14.test(data24)) { validate49.errors = [{ instancePath: instancePath + "/dateUpdated/to", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate49.errors = [{ instancePath: instancePath + "/dateUpdated/to", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid19 = _errs78 === errors; } else { var valid19 = true; } } } } } else { validate49.errors = [{ instancePath: instancePath + "/dateUpdated", schemaPath: "#/properties/dateUpdated/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid4 = _errs72 === errors; } else { var valid4 = true; } } } } } } } } } } } } } } } } } } else { validate49.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate49.errors = vErrors; return errors === 0; } validate49.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var EventsGet = validate50; var schema81 = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://identity.foundation/dwn/json-schemas/events-get.json", "type": "object", "additionalProperties": false, "required": ["authorization", "descriptor"], "properties": { "authorization": { "$ref": "https://identity.foundation/dwn/json-schemas/authorization.json" }, "descriptor": { "type": "object", "additionalProperties": false, "required": ["interface", "method", "messageTimestamp"], "properties": { "interface": { "enum": ["Events"], "type": "string" }, "method": { "enum": ["Get"], "type": "string" }, "messageTimestamp": { "type": "string" }, "cursor": { "$ref": "https://identity.foundation/dwn/json-schemas/pagination-cursor.json" } } } } }; function validate50(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate50.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.authorization === void 0 && (missing0 = "authorization") || data.descriptor === void 0 && (missing0 = "descriptor")) { validate50.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "authorization" || key0 === "descriptor")) { validate50.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.authorization !== void 0) { const _errs2 = errors; if (!validate20(data.authorization, { instancePath: instancePath + "/authorization", parentData: data, parentDataProperty: "authorization", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate20.errors : vErrors.concat(validate20.errors); errors = vErrors.length; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.descriptor !== void 0) { let data1 = data.descriptor; const _errs3 = errors; if (errors === _errs3) { if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { let missing1; if (data1.interface === void 0 && (missing1 = "interface") || data1.method === void 0 && (missing1 = "method") || data1.messageTimestamp === void 0 && (missing1 = "messageTimestamp")) { validate50.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }]; return false; } else { const _errs5 = errors; for (const key1 in data1) { if (!(key1 === "interface" || key1 === "method" || key1 === "messageTimestamp" || key1 === "cursor")) { validate50.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs5 === errors) { if (data1.interface !== void 0) { let data2 = data1.interface; const _errs6 = errors; if (typeof data2 !== "string") { validate50.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data2 === "Events")) { validate50.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/enum", keyword: "enum", params: { allowedValues: schema81.properties.descriptor.properties.interface.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs6 === errors; } else { var valid1 = true; } if (valid1) { if (data1.method !== void 0) { let data3 = data1.method; const _errs8 = errors; if (typeof data3 !== "string") { validate50.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data3 === "Get")) { validate50.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/enum", keyword: "enum", params: { allowedValues: schema81.properties.descriptor.properties.method.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs8 === errors; } else { var valid1 = true; } if (valid1) { if (data1.messageTimestamp !== void 0) { const _errs10 = errors; if (typeof data1.messageTimestamp !== "string") { validate50.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "#/properties/descriptor/properties/messageTimestamp/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid1 = _errs10 === errors; } else { var valid1 = true; } if (valid1) { if (data1.cursor !== void 0) { let data5 = data1.cursor; const _errs12 = errors; const _errs13 = errors; if (errors === _errs13) { if (data5 && typeof data5 == "object" && !Array.isArray(data5)) { if (Object.keys(data5).length < 1) { validate50.errors = [{ instancePath: instancePath + "/descriptor/cursor", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { let missing2; if (data5.messageCid === void 0 && (missing2 = "messageCid") || data5.value === void 0 && (missing2 = "value")) { validate50.errors = [{ instancePath: instancePath + "/descriptor/cursor", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/required", keyword: "required", params: { missingProperty: missing2 }, message: "must have required property '" + missing2 + "'" }]; return false; } else { const _errs15 = errors; for (const key2 in data5) { if (!(key2 === "messageCid" || key2 === "value")) { validate50.errors = [{ instancePath: instancePath + "/descriptor/cursor", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs15 === errors) { if (data5.messageCid !== void 0) { const _errs16 = errors; if (typeof data5.messageCid !== "string") { validate50.errors = [{ instancePath: instancePath + "/descriptor/cursor/messageCid", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/properties/messageCid/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid3 = _errs16 === errors; } else { var valid3 = true; } if (valid3) { if (data5.value !== void 0) { let data7 = data5.value; const _errs18 = errors; if (typeof data7 !== "string" && !(typeof data7 == "number" && isFinite(data7))) { validate50.errors = [{ instancePath: instancePath + "/descriptor/cursor/value", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/properties/value/type", keyword: "type", params: { type: schema68.properties.value.type }, message: "must be string,number" }]; return false; } var valid3 = _errs18 === errors; } else { var valid3 = true; } } } } } } else { validate50.errors = [{ instancePath: instancePath + "/descriptor/cursor", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid1 = _errs12 === errors; } else { var valid1 = true; } } } } } } } else { validate50.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs3 === errors; } else { var valid0 = true; } } } } } else { validate50.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate50.errors = vErrors; return errors === 0; } validate50.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var EventsQuery = validate52; var schema83 = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://identity.foundation/dwn/json-schemas/events-query.json", "type": "object", "additionalProperties": false, "required": ["authorization", "descriptor"], "properties": { "authorization": { "$ref": "https://identity.foundation/dwn/json-schemas/authorization.json" }, "descriptor": { "type": "object", "additionalProperties": false, "required": ["interface", "method", "messageTimestamp", "filters"], "properties": { "interface": { "enum": ["Events"], "type": "string" }, "method": { "enum": ["Query"], "type": "string" }, "messageTimestamp": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" }, "filters": { "type": "array", "minItems": 1, "items": { "$ref": "https://identity.foundation/dwn/json-schemas/events-filter.json" } }, "cursor": { "$ref": "https://identity.foundation/dwn/json-schemas/pagination-cursor.json" } } } } }; function validate52(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate52.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.authorization === void 0 && (missing0 = "authorization") || data.descriptor === void 0 && (missing0 = "descriptor")) { validate52.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "authorization" || key0 === "descriptor")) { validate52.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.authorization !== void 0) { const _errs2 = errors; if (!validate20(data.authorization, { instancePath: instancePath + "/authorization", parentData: data, parentDataProperty: "authorization", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate20.errors : vErrors.concat(validate20.errors); errors = vErrors.length; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.descriptor !== void 0) { let data1 = data.descriptor; const _errs3 = errors; if (errors === _errs3) { if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { let missing1; if (data1.interface === void 0 && (missing1 = "interface") || data1.method === void 0 && (missing1 = "method") || data1.messageTimestamp === void 0 && (missing1 = "messageTimestamp") || data1.filters === void 0 && (missing1 = "filters")) { validate52.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }]; return false; } else { const _errs5 = errors; for (const key1 in data1) { if (!(key1 === "interface" || key1 === "method" || key1 === "messageTimestamp" || key1 === "filters" || key1 === "cursor")) { validate52.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs5 === errors) { if (data1.interface !== void 0) { let data2 = data1.interface; const _errs6 = errors; if (typeof data2 !== "string") { validate52.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data2 === "Events")) { validate52.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/enum", keyword: "enum", params: { allowedValues: schema83.properties.descriptor.properties.interface.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs6 === errors; } else { var valid1 = true; } if (valid1) { if (data1.method !== void 0) { let data3 = data1.method; const _errs8 = errors; if (typeof data3 !== "string") { validate52.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data3 === "Query")) { validate52.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/enum", keyword: "enum", params: { allowedValues: schema83.properties.descriptor.properties.method.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs8 === errors; } else { var valid1 = true; } if (valid1) { if (data1.messageTimestamp !== void 0) { let data4 = data1.messageTimestamp; const _errs10 = errors; const _errs11 = errors; if (errors === _errs11) { if (typeof data4 === "string") { if (!pattern14.test(data4)) { validate52.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate52.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid1 = _errs10 === errors; } else { var valid1 = true; } if (valid1) { if (data1.filters !== void 0) { let data5 = data1.filters; const _errs13 = errors; if (errors === _errs13) { if (Array.isArray(data5)) { if (data5.length < 1) { validate52.errors = [{ instancePath: instancePath + "/descriptor/filters", schemaPath: "#/properties/descriptor/properties/filters/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; return false; } else { var valid3 = true; const len0 = data5.length; for (let i0 = 0; i0 < len0; i0++) { const _errs15 = errors; if (!validate49(data5[i0], { instancePath: instancePath + "/descriptor/filters/" + i0, parentData: data5, parentDataProperty: i0, rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate49.errors : vErrors.concat(validate49.errors); errors = vErrors.length; } var valid3 = _errs15 === errors; if (!valid3) { break; } } } } else { validate52.errors = [{ instancePath: instancePath + "/descriptor/filters", schemaPath: "#/properties/descriptor/properties/filters/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; return false; } } var valid1 = _errs13 === errors; } else { var valid1 = true; } if (valid1) { if (data1.cursor !== void 0) { let data7 = data1.cursor; const _errs16 = errors; const _errs17 = errors; if (errors === _errs17) { if (data7 && typeof data7 == "object" && !Array.isArray(data7)) { if (Object.keys(data7).length < 1) { validate52.errors = [{ instancePath: instancePath + "/descriptor/cursor", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { let missing2; if (data7.messageCid === void 0 && (missing2 = "messageCid") || data7.value === void 0 && (missing2 = "value")) { validate52.errors = [{ instancePath: instancePath + "/descriptor/cursor", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/required", keyword: "required", params: { missingProperty: missing2 }, message: "must have required property '" + missing2 + "'" }]; return false; } else { const _errs19 = errors; for (const key2 in data7) { if (!(key2 === "messageCid" || key2 === "value")) { validate52.errors = [{ instancePath: instancePath + "/descriptor/cursor", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs19 === errors) { if (data7.messageCid !== void 0) { const _errs20 = errors; if (typeof data7.messageCid !== "string") { validate52.errors = [{ instancePath: instancePath + "/descriptor/cursor/messageCid", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/properties/messageCid/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid5 = _errs20 === errors; } else { var valid5 = true; } if (valid5) { if (data7.value !== void 0) { let data9 = data7.value; const _errs22 = errors; if (typeof data9 !== "string" && !(typeof data9 == "number" && isFinite(data9))) { validate52.errors = [{ instancePath: instancePath + "/descriptor/cursor/value", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/properties/value/type", keyword: "type", params: { type: schema68.properties.value.type }, message: "must be string,number" }]; return false; } var valid5 = _errs22 === errors; } else { var valid5 = true; } } } } } } else { validate52.errors = [{ instancePath: instancePath + "/descriptor/cursor", schemaPath: "https://identity.foundation/dwn/json-schemas/pagination-cursor.json/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid1 = _errs16 === errors; } else { var valid1 = true; } } } } } } } } else { validate52.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs3 === errors; } else { var valid0 = true; } } } } } else { validate52.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate52.errors = vErrors; return errors === 0; } validate52.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var EventsSubscribe = validate55; var schema86 = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://identity.foundation/dwn/json-schemas/events-subscribe.json", "type": "object", "additionalProperties": false, "required": ["descriptor", "authorization"], "properties": { "authorization": { "$ref": "https://identity.foundation/dwn/json-schemas/authorization.json" }, "descriptor": { "type": "object", "additionalProperties": false, "required": ["interface", "method", "messageTimestamp", "filters"], "properties": { "interface": { "enum": ["Events"], "type": "string" }, "method": { "enum": ["Subscribe"], "type": "string" }, "messageTimestamp": { "type": "string" }, "filters": { "type": "array", "items": { "$ref": "https://identity.foundation/dwn/json-schemas/events-filter.json" } } } } } }; function validate55(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate55.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.descriptor === void 0 && (missing0 = "descriptor") || data.authorization === void 0 && (missing0 = "authorization")) { validate55.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "authorization" || key0 === "descriptor")) { validate55.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.authorization !== void 0) { const _errs2 = errors; if (!validate20(data.authorization, { instancePath: instancePath + "/authorization", parentData: data, parentDataProperty: "authorization", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate20.errors : vErrors.concat(validate20.errors); errors = vErrors.length; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.descriptor !== void 0) { let data1 = data.descriptor; const _errs3 = errors; if (errors === _errs3) { if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { let missing1; if (data1.interface === void 0 && (missing1 = "interface") || data1.method === void 0 && (missing1 = "method") || data1.messageTimestamp === void 0 && (missing1 = "messageTimestamp") || data1.filters === void 0 && (missing1 = "filters")) { validate55.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }]; return false; } else { const _errs5 = errors; for (const key1 in data1) { if (!(key1 === "interface" || key1 === "method" || key1 === "messageTimestamp" || key1 === "filters")) { validate55.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs5 === errors) { if (data1.interface !== void 0) { let data2 = data1.interface; const _errs6 = errors; if (typeof data2 !== "string") { validate55.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data2 === "Events")) { validate55.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/enum", keyword: "enum", params: { allowedValues: schema86.properties.descriptor.properties.interface.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs6 === errors; } else { var valid1 = true; } if (valid1) { if (data1.method !== void 0) { let data3 = data1.method; const _errs8 = errors; if (typeof data3 !== "string") { validate55.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data3 === "Subscribe")) { validate55.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/enum", keyword: "enum", params: { allowedValues: schema86.properties.descriptor.properties.method.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs8 === errors; } else { var valid1 = true; } if (valid1) { if (data1.messageTimestamp !== void 0) { const _errs10 = errors; if (typeof data1.messageTimestamp !== "string") { validate55.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "#/properties/descriptor/properties/messageTimestamp/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid1 = _errs10 === errors; } else { var valid1 = true; } if (valid1) { if (data1.filters !== void 0) { let data5 = data1.filters; const _errs12 = errors; if (errors === _errs12) { if (Array.isArray(data5)) { var valid2 = true; const len0 = data5.length; for (let i0 = 0; i0 < len0; i0++) { const _errs14 = errors; if (!validate49(data5[i0], { instancePath: instancePath + "/descriptor/filters/" + i0, parentData: data5, parentDataProperty: i0, rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate49.errors : vErrors.concat(validate49.errors); errors = vErrors.length; } var valid2 = _errs14 === errors; if (!valid2) { break; } } } else { validate55.errors = [{ instancePath: instancePath + "/descriptor/filters", schemaPath: "#/properties/descriptor/properties/filters/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; return false; } } var valid1 = _errs12 === errors; } else { var valid1 = true; } } } } } } } else { validate55.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs3 === errors; } else { var valid0 = true; } } } } } else { validate55.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate55.errors = vErrors; return errors === 0; } validate55.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var Definitions = validate22; function validate22(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate22.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (!(data && typeof data == "object" && !Array.isArray(data))) { validate22.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } validate22.errors = vErrors; return errors === 0; } validate22.evaluated = { "dynamicProps": false, "dynamicItems": false }; var GeneralJwk = validate58; function validate58(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate58.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } const _errs1 = errors; let valid0 = false; let passing0 = null; const _errs2 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.crv === void 0 && (missing0 = "crv") || data.x === void 0 && (missing0 = "x")) { const err0 = { instancePath, schemaPath: "#/oneOf/0/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }; if (vErrors === null) { vErrors = [err0]; } else { vErrors.push(err0); } errors++; } else { if (data.kty !== void 0) { const _errs3 = errors; if ("EC" !== data.kty) { const err1 = { instancePath: instancePath + "/kty", schemaPath: "#/oneOf/0/properties/kty/const", keyword: "const", params: { allowedValue: "EC" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err1]; } else { vErrors.push(err1); } errors++; } var valid1 = _errs3 === errors; } else { var valid1 = true; } if (valid1) { if (data.crv !== void 0) { const _errs4 = errors; if (typeof data.crv !== "string") { const err22 = { instancePath: instancePath + "/crv", schemaPath: "#/oneOf/0/properties/crv/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err22]; } else { vErrors.push(err22); } errors++; } var valid1 = _errs4 === errors; } else { var valid1 = true; } if (valid1) { if (data.x !== void 0) { const _errs6 = errors; if (typeof data.x !== "string") { const err3 = { instancePath: instancePath + "/x", schemaPath: "#/oneOf/0/properties/x/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err3]; } else { vErrors.push(err3); } errors++; } var valid1 = _errs6 === errors; } else { var valid1 = true; } if (valid1) { if (data.y !== void 0) { const _errs8 = errors; if (typeof data.y !== "string") { const err4 = { instancePath: instancePath + "/y", schemaPath: "#/oneOf/0/properties/y/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err4]; } else { vErrors.push(err4); } errors++; } var valid1 = _errs8 === errors; } else { var valid1 = true; } if (valid1) { if (data.d !== void 0) { const _errs10 = errors; if (typeof data.d !== "string") { const err5 = { instancePath: instancePath + "/d", schemaPath: "#/oneOf/0/properties/d/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err5]; } else { vErrors.push(err5); } errors++; } var valid1 = _errs10 === errors; } else { var valid1 = true; } } } } } } } var _valid0 = _errs2 === errors; if (_valid0) { valid0 = true; passing0 = 0; var props0 = {}; props0.kty = true; props0.crv = true; props0.x = true; props0.y = true; props0.d = true; } const _errs12 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing1; if (data.crv === void 0 && (missing1 = "crv") || data.x === void 0 && (missing1 = "x")) { const err6 = { instancePath, schemaPath: "#/oneOf/1/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }; if (vErrors === null) { vErrors = [err6]; } else { vErrors.push(err6); } errors++; } else { if (data.kty !== void 0) { const _errs13 = errors; if ("OKP" !== data.kty) { const err7 = { instancePath: instancePath + "/kty", schemaPath: "#/oneOf/1/properties/kty/const", keyword: "const", params: { allowedValue: "OKP" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err7]; } else { vErrors.push(err7); } errors++; } var valid2 = _errs13 === errors; } else { var valid2 = true; } if (valid2) { if (data.crv !== void 0) { const _errs14 = errors; if (typeof data.crv !== "string") { const err8 = { instancePath: instancePath + "/crv", schemaPath: "#/oneOf/1/properties/crv/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err8]; } else { vErrors.push(err8); } errors++; } var valid2 = _errs14 === errors; } else { var valid2 = true; } if (valid2) { if (data.x !== void 0) { const _errs16 = errors; if (typeof data.x !== "string") { const err9 = { instancePath: instancePath + "/x", schemaPath: "#/oneOf/1/properties/x/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err9]; } else { vErrors.push(err9); } errors++; } var valid2 = _errs16 === errors; } else { var valid2 = true; } if (valid2) { if (data.d !== void 0) { const _errs18 = errors; if (typeof data.d !== "string") { const err10 = { instancePath: instancePath + "/d", schemaPath: "#/oneOf/1/properties/d/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err10]; } else { vErrors.push(err10); } errors++; } var valid2 = _errs18 === errors; } else { var valid2 = true; } } } } } } var _valid0 = _errs12 === errors; if (_valid0 && valid0) { valid0 = false; passing0 = [passing0, 1]; } else { if (_valid0) { valid0 = true; passing0 = 1; if (props0 !== true) { props0 = props0 || {}; props0.kty = true; props0.crv = true; props0.x = true; props0.d = true; } } const _errs20 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing2; if (data.n === void 0 && (missing2 = "n") || data.e === void 0 && (missing2 = "e")) { const err11 = { instancePath, schemaPath: "#/oneOf/2/required", keyword: "required", params: { missingProperty: missing2 }, message: "must have required property '" + missing2 + "'" }; if (vErrors === null) { vErrors = [err11]; } else { vErrors.push(err11); } errors++; } else { if (data.kty !== void 0) { const _errs21 = errors; if ("RSA" !== data.kty) { const err12 = { instancePath: instancePath + "/kty", schemaPath: "#/oneOf/2/properties/kty/const", keyword: "const", params: { allowedValue: "RSA" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err12]; } else { vErrors.push(err12); } errors++; } var valid3 = _errs21 === errors; } else { var valid3 = true; } if (valid3) { if (data.n !== void 0) { const _errs22 = errors; if (typeof data.n !== "string") { const err13 = { instancePath: instancePath + "/n", schemaPath: "#/oneOf/2/properties/n/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err13]; } else { vErrors.push(err13); } errors++; } var valid3 = _errs22 === errors; } else { var valid3 = true; } if (valid3) { if (data.e !== void 0) { const _errs24 = errors; if (typeof data.e !== "string") { const err14 = { instancePath: instancePath + "/e", schemaPath: "#/oneOf/2/properties/e/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err14]; } else { vErrors.push(err14); } errors++; } var valid3 = _errs24 === errors; } else { var valid3 = true; } if (valid3) { if (data.d !== void 0) { const _errs26 = errors; if (typeof data.d !== "string") { const err15 = { instancePath: instancePath + "/d", schemaPath: "#/oneOf/2/properties/d/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err15]; } else { vErrors.push(err15); } errors++; } var valid3 = _errs26 === errors; } else { var valid3 = true; } if (valid3) { if (data.p !== void 0) { const _errs28 = errors; if (typeof data.p !== "string") { const err16 = { instancePath: instancePath + "/p", schemaPath: "#/oneOf/2/properties/p/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err16]; } else { vErrors.push(err16); } errors++; } var valid3 = _errs28 === errors; } else { var valid3 = true; } if (valid3) { if (data.q !== void 0) { const _errs30 = errors; if (typeof data.q !== "string") { const err17 = { instancePath: instancePath + "/q", schemaPath: "#/oneOf/2/properties/q/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err17]; } else { vErrors.push(err17); } errors++; } var valid3 = _errs30 === errors; } else { var valid3 = true; } if (valid3) { if (data.dp !== void 0) { const _errs32 = errors; if (typeof data.dp !== "string") { const err18 = { instancePath: instancePath + "/dp", schemaPath: "#/oneOf/2/properties/dp/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err18]; } else { vErrors.push(err18); } errors++; } var valid3 = _errs32 === errors; } else { var valid3 = true; } if (valid3) { if (data.dq !== void 0) { const _errs34 = errors; if (typeof data.dq !== "string") { const err19 = { instancePath: instancePath + "/dq", schemaPath: "#/oneOf/2/properties/dq/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err19]; } else { vErrors.push(err19); } errors++; } var valid3 = _errs34 === errors; } else { var valid3 = true; } if (valid3) { if (data.qi !== void 0) { const _errs36 = errors; if (typeof data.qi !== "string") { const err20 = { instancePath: instancePath + "/qi", schemaPath: "#/oneOf/2/properties/qi/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err20]; } else { vErrors.push(err20); } errors++; } var valid3 = _errs36 === errors; } else { var valid3 = true; } if (valid3) { if (data.oth !== void 0) { let data18 = data.oth; const _errs38 = errors; if (!(data18 && typeof data18 == "object" && !Array.isArray(data18))) { const err21 = { instancePath: instancePath + "/oth", schemaPath: "#/oneOf/2/properties/oth/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err21]; } else { vErrors.push(err21); } errors++; } var valid3 = _errs38 === errors; } else { var valid3 = true; } } } } } } } } } } } } var _valid0 = _errs20 === errors; if (_valid0 && valid0) { valid0 = false; passing0 = [passing0, 2]; } else { if (_valid0) { valid0 = true; passing0 = 2; if (props0 !== true) { props0 = props0 || {}; props0.kty = true; props0.n = true; props0.e = true; props0.d = true; props0.p = true; props0.q = true; props0.dp = true; props0.dq = true; props0.qi = true; props0.oth = true; } } const _errs40 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing3; if (data.k === void 0 && (missing3 = "k")) { const err22 = { instancePath, schemaPath: "#/oneOf/3/required", keyword: "required", params: { missingProperty: missing3 }, message: "must have required property '" + missing3 + "'" }; if (vErrors === null) { vErrors = [err22]; } else { vErrors.push(err22); } errors++; } else { if (data.kty !== void 0) { const _errs41 = errors; if ("oct" !== data.kty) { const err23 = { instancePath: instancePath + "/kty", schemaPath: "#/oneOf/3/properties/kty/const", keyword: "const", params: { allowedValue: "oct" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err23]; } else { vErrors.push(err23); } errors++; } var valid4 = _errs41 === errors; } else { var valid4 = true; } if (valid4) { if (data.k !== void 0) { const _errs42 = errors; if (typeof data.k !== "string") { const err24 = { instancePath: instancePath + "/k", schemaPath: "#/oneOf/3/properties/k/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err24]; } else { vErrors.push(err24); } errors++; } var valid4 = _errs42 === errors; } else { var valid4 = true; } } } } var _valid0 = _errs40 === errors; if (_valid0 && valid0) { valid0 = false; passing0 = [passing0, 3]; } else { if (_valid0) { valid0 = true; passing0 = 3; if (props0 !== true) { props0 = props0 || {}; props0.kty = true; props0.k = true; } } } } } if (!valid0) { const err25 = { instancePath, schemaPath: "#/oneOf", keyword: "oneOf", params: { passingSchemas: passing0 }, message: "must match exactly one schema in oneOf" }; if (vErrors === null) { vErrors = [err25]; } else { vErrors.push(err25); } errors++; validate58.errors = vErrors; return false; } else { errors = _errs1; if (vErrors !== null) { if (_errs1) { vErrors.length = _errs1; } else { vErrors = null; } } } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing4; if (data.kty === void 0 && (missing4 = "kty")) { validate58.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing4 }, message: "must have required property '" + missing4 + "'" }]; return false; } else { if (props0 !== true) { props0 = props0 || {}; props0.alg = true; props0.kid = true; props0.kty = true; props0.crv = true; props0.use = true; props0.key_ops = true; props0.x5u = true; props0.x5c = true; props0.x5t = true; props0["x5t#S256"] = true; } if (data.alg !== void 0) { const _errs44 = errors; if (typeof data.alg !== "string") { validate58.errors = [{ instancePath: instancePath + "/alg", schemaPath: "#/properties/alg/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid5 = _errs44 === errors; } else { var valid5 = true; } if (valid5) { if (data.kid !== void 0) { const _errs46 = errors; if (typeof data.kid !== "string") { validate58.errors = [{ instancePath: instancePath + "/kid", schemaPath: "#/properties/kid/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid5 = _errs46 === errors; } else { var valid5 = true; } if (valid5) { if (data.kty !== void 0) { let data23 = data.kty; const _errs48 = errors; if (!(data23 === "EC" || data23 === "RSA" || data23 === "oct" || data23 === "OKP")) { validate58.errors = [{ instancePath: instancePath + "/kty", schemaPath: "#/properties/kty/enum", keyword: "enum", params: { allowedValues: schema43.properties.kty.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid5 = _errs48 === errors; } else { var valid5 = true; } if (valid5) { if (data.crv !== void 0) { const _errs49 = errors; if (typeof data.crv !== "string") { validate58.errors = [{ instancePath: instancePath + "/crv", schemaPath: "#/properties/crv/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid5 = _errs49 === errors; } else { var valid5 = true; } if (valid5) { if (data.use !== void 0) { const _errs51 = errors; if (typeof data.use !== "string") { validate58.errors = [{ instancePath: instancePath + "/use", schemaPath: "#/properties/use/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid5 = _errs51 === errors; } else { var valid5 = true; } if (valid5) { if (data.key_ops !== void 0) { const _errs53 = errors; if (typeof data.key_ops !== "string") { validate58.errors = [{ instancePath: instancePath + "/key_ops", schemaPath: "#/properties/key_ops/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid5 = _errs53 === errors; } else { var valid5 = true; } if (valid5) { if (data.x5u !== void 0) { const _errs55 = errors; if (typeof data.x5u !== "string") { validate58.errors = [{ instancePath: instancePath + "/x5u", schemaPath: "#/properties/x5u/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid5 = _errs55 === errors; } else { var valid5 = true; } if (valid5) { if (data.x5c !== void 0) { const _errs57 = errors; if (typeof data.x5c !== "string") { validate58.errors = [{ instancePath: instancePath + "/x5c", schemaPath: "#/properties/x5c/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid5 = _errs57 === errors; } else { var valid5 = true; } if (valid5) { if (data.x5t !== void 0) { const _errs59 = errors; if (typeof data.x5t !== "string") { validate58.errors = [{ instancePath: instancePath + "/x5t", schemaPath: "#/properties/x5t/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid5 = _errs59 === errors; } else { var valid5 = true; } if (valid5) { if (data["x5t#S256"] !== void 0) { const _errs61 = errors; if (typeof data["x5t#S256"] !== "string") { validate58.errors = [{ instancePath: instancePath + "/x5t#S256", schemaPath: "#/properties/x5t%23S256/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid5 = _errs61 === errors; } else { var valid5 = true; } } } } } } } } } } } } else { validate58.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate58.errors = vErrors; evaluated0.props = props0; return errors === 0; } validate58.evaluated = { "dynamicProps": true, "dynamicItems": false }; var GeneralJws = validate21; var JwkVerificationMethod = validate59; var schema88 = { "$id": "https://identity.foundation/dwn/json-schemas/jwk-verification-method.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "additionalProperties": false, "required": ["id", "type", "controller", "publicKeyJwk"], "properties": { "id": { "type": "string" }, "type": { "enum": ["JsonWebKey", "JsonWebKey2020"] }, "controller": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did" }, "publicKeyJwk": { "$ref": "https://identity.foundation/dwn/json-schemas/public-jwk.json" } } }; function validate59(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate59.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.id === void 0 && (missing0 = "id") || data.type === void 0 && (missing0 = "type") || data.controller === void 0 && (missing0 = "controller") || data.publicKeyJwk === void 0 && (missing0 = "publicKeyJwk")) { validate59.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "id" || key0 === "type" || key0 === "controller" || key0 === "publicKeyJwk")) { validate59.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.id !== void 0) { const _errs2 = errors; if (typeof data.id !== "string") { validate59.errors = [{ instancePath: instancePath + "/id", schemaPath: "#/properties/id/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.type !== void 0) { let data1 = data.type; const _errs4 = errors; if (!(data1 === "JsonWebKey" || data1 === "JsonWebKey2020")) { validate59.errors = [{ instancePath: instancePath + "/type", schemaPath: "#/properties/type/enum", keyword: "enum", params: { allowedValues: schema88.properties.type.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid0 = _errs4 === errors; } else { var valid0 = true; } if (valid0) { if (data.controller !== void 0) { let data2 = data.controller; const _errs5 = errors; const _errs6 = errors; if (errors === _errs6) { if (typeof data2 === "string") { if (!pattern12.test(data2)) { validate59.errors = [{ instancePath: instancePath + "/controller", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did/pattern", keyword: "pattern", params: { pattern: "^did:([a-z0-9]+):((?:(?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))*:)*((?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))+))((;[a-zA-Z0-9_.:%-]+=[a-zA-Z0-9_.:%-]*)*)(/[^#?]*)?([?][^#]*)?(#.*)?$" }, message: 'must match pattern "^did:([a-z0-9]+):((?:(?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))*:)*((?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))+))((;[a-zA-Z0-9_.:%-]+=[a-zA-Z0-9_.:%-]*)*)(/[^#?]*)?([?][^#]*)?(#.*)?$"' }]; return false; } } else { validate59.errors = [{ instancePath: instancePath + "/controller", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid0 = _errs5 === errors; } else { var valid0 = true; } if (valid0) { if (data.publicKeyJwk !== void 0) { const _errs8 = errors; if (!validate33(data.publicKeyJwk, { instancePath: instancePath + "/publicKeyJwk", parentData: data, parentDataProperty: "publicKeyJwk", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate33.errors : vErrors.concat(validate33.errors); errors = vErrors.length; } var valid0 = _errs8 === errors; } else { var valid0 = true; } } } } } } } else { validate59.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate59.errors = vErrors; return errors === 0; } validate59.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var MessagesGet = validate61; var schema90 = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://identity.foundation/dwn/json-schemas/messages-get.json", "type": "object", "additionalProperties": false, "required": ["authorization", "descriptor"], "properties": { "authorization": { "$ref": "https://identity.foundation/dwn/json-schemas/authorization.json" }, "descriptor": { "type": "object", "additionalProperties": false, "required": ["interface", "method", "messageTimestamp"], "properties": { "interface": { "enum": ["Messages"], "type": "string" }, "method": { "enum": ["Get"], "type": "string" }, "messageTimestamp": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" }, "messageCids": { "type": "array", "items": { "type": "string" }, "minItems": 1 } } } } }; function validate61(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate61.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.authorization === void 0 && (missing0 = "authorization") || data.descriptor === void 0 && (missing0 = "descriptor")) { validate61.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "authorization" || key0 === "descriptor")) { validate61.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.authorization !== void 0) { const _errs2 = errors; if (!validate20(data.authorization, { instancePath: instancePath + "/authorization", parentData: data, parentDataProperty: "authorization", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate20.errors : vErrors.concat(validate20.errors); errors = vErrors.length; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.descriptor !== void 0) { let data1 = data.descriptor; const _errs3 = errors; if (errors === _errs3) { if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { let missing1; if (data1.interface === void 0 && (missing1 = "interface") || data1.method === void 0 && (missing1 = "method") || data1.messageTimestamp === void 0 && (missing1 = "messageTimestamp")) { validate61.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }]; return false; } else { const _errs5 = errors; for (const key1 in data1) { if (!(key1 === "interface" || key1 === "method" || key1 === "messageTimestamp" || key1 === "messageCids")) { validate61.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs5 === errors) { if (data1.interface !== void 0) { let data2 = data1.interface; const _errs6 = errors; if (typeof data2 !== "string") { validate61.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data2 === "Messages")) { validate61.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/enum", keyword: "enum", params: { allowedValues: schema90.properties.descriptor.properties.interface.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs6 === errors; } else { var valid1 = true; } if (valid1) { if (data1.method !== void 0) { let data3 = data1.method; const _errs8 = errors; if (typeof data3 !== "string") { validate61.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data3 === "Get")) { validate61.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/enum", keyword: "enum", params: { allowedValues: schema90.properties.descriptor.properties.method.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs8 === errors; } else { var valid1 = true; } if (valid1) { if (data1.messageTimestamp !== void 0) { let data4 = data1.messageTimestamp; const _errs10 = errors; const _errs11 = errors; if (errors === _errs11) { if (typeof data4 === "string") { if (!pattern14.test(data4)) { validate61.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate61.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid1 = _errs10 === errors; } else { var valid1 = true; } if (valid1) { if (data1.messageCids !== void 0) { let data5 = data1.messageCids; const _errs13 = errors; if (errors === _errs13) { if (Array.isArray(data5)) { if (data5.length < 1) { validate61.errors = [{ instancePath: instancePath + "/descriptor/messageCids", schemaPath: "#/properties/descriptor/properties/messageCids/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; return false; } else { var valid3 = true; const len0 = data5.length; for (let i0 = 0; i0 < len0; i0++) { const _errs15 = errors; if (typeof data5[i0] !== "string") { validate61.errors = [{ instancePath: instancePath + "/descriptor/messageCids/" + i0, schemaPath: "#/properties/descriptor/properties/messageCids/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid3 = _errs15 === errors; if (!valid3) { break; } } } } else { validate61.errors = [{ instancePath: instancePath + "/descriptor/messageCids", schemaPath: "#/properties/descriptor/properties/messageCids/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; return false; } } var valid1 = _errs13 === errors; } else { var valid1 = true; } } } } } } } else { validate61.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs3 === errors; } else { var valid0 = true; } } } } } else { validate61.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate61.errors = vErrors; return errors === 0; } validate61.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var NumberRangeFilter = validate63; function validate63(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate63.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { if (Object.keys(data).length < 1) { validate63.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "gt" || key0 === "gte" || key0 === "lt" || key0 === "lte")) { validate63.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.gt !== void 0) { const _errs2 = errors; const _errs3 = errors; const _errs4 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.gte === void 0 && (missing0 = "gte")) { const err0 = {}; if (vErrors === null) { vErrors = [err0]; } else { vErrors.push(err0); } errors++; } } var valid1 = _errs4 === errors; if (valid1) { validate63.errors = [{ instancePath, schemaPath: "#/dependencies/gt/not", keyword: "not", params: {}, message: "must NOT be valid" }]; return false; } else { errors = _errs3; if (vErrors !== null) { if (_errs3) { vErrors.length = _errs3; } else { vErrors = null; } } } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.gte !== void 0) { const _errs5 = errors; const _errs6 = errors; const _errs7 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing1; if (data.gt === void 0 && (missing1 = "gt")) { const err1 = {}; if (vErrors === null) { vErrors = [err1]; } else { vErrors.push(err1); } errors++; } } var valid2 = _errs7 === errors; if (valid2) { validate63.errors = [{ instancePath, schemaPath: "#/dependencies/gte/not", keyword: "not", params: {}, message: "must NOT be valid" }]; return false; } else { errors = _errs6; if (vErrors !== null) { if (_errs6) { vErrors.length = _errs6; } else { vErrors = null; } } } var valid0 = _errs5 === errors; } else { var valid0 = true; } if (valid0) { if (data.lt !== void 0) { const _errs8 = errors; const _errs9 = errors; const _errs10 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing2; if (data.lte === void 0 && (missing2 = "lte")) { const err22 = {}; if (vErrors === null) { vErrors = [err22]; } else { vErrors.push(err22); } errors++; } } var valid3 = _errs10 === errors; if (valid3) { validate63.errors = [{ instancePath, schemaPath: "#/dependencies/lt/not", keyword: "not", params: {}, message: "must NOT be valid" }]; return false; } else { errors = _errs9; if (vErrors !== null) { if (_errs9) { vErrors.length = _errs9; } else { vErrors = null; } } } var valid0 = _errs8 === errors; } else { var valid0 = true; } if (valid0) { if (data.lte !== void 0) { const _errs11 = errors; const _errs12 = errors; const _errs13 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing3; if (data.lt === void 0 && (missing3 = "lt")) { const err3 = {}; if (vErrors === null) { vErrors = [err3]; } else { vErrors.push(err3); } errors++; } } var valid4 = _errs13 === errors; if (valid4) { validate63.errors = [{ instancePath, schemaPath: "#/dependencies/lte/not", keyword: "not", params: {}, message: "must NOT be valid" }]; return false; } else { errors = _errs12; if (vErrors !== null) { if (_errs12) { vErrors.length = _errs12; } else { vErrors = null; } } } var valid0 = _errs11 === errors; } else { var valid0 = true; } if (valid0) { if (data.gt !== void 0) { let data0 = data.gt; const _errs14 = errors; if (!(typeof data0 == "number" && isFinite(data0))) { validate63.errors = [{ instancePath: instancePath + "/gt", schemaPath: "#/properties/gt/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } var valid5 = _errs14 === errors; } else { var valid5 = true; } if (valid5) { if (data.gte !== void 0) { let data1 = data.gte; const _errs16 = errors; if (!(typeof data1 == "number" && isFinite(data1))) { validate63.errors = [{ instancePath: instancePath + "/gte", schemaPath: "#/properties/gte/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } var valid5 = _errs16 === errors; } else { var valid5 = true; } if (valid5) { if (data.lt !== void 0) { let data2 = data.lt; const _errs18 = errors; if (!(typeof data2 == "number" && isFinite(data2))) { validate63.errors = [{ instancePath: instancePath + "/lt", schemaPath: "#/properties/lt/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } var valid5 = _errs18 === errors; } else { var valid5 = true; } if (valid5) { if (data.lte !== void 0) { let data3 = data.lte; const _errs20 = errors; if (!(typeof data3 == "number" && isFinite(data3))) { validate63.errors = [{ instancePath: instancePath + "/lte", schemaPath: "#/properties/lte/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } var valid5 = _errs20 === errors; } else { var valid5 = true; } } } } } } } } } } } else { validate63.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate63.errors = vErrors; return errors === 0; } validate63.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var PaginationCursor = validate64; function validate64(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate64.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { if (Object.keys(data).length < 1) { validate64.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { let missing0; if (data.messageCid === void 0 && (missing0 = "messageCid") || data.value === void 0 && (missing0 = "value")) { validate64.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "messageCid" || key0 === "value")) { validate64.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.messageCid !== void 0) { const _errs2 = errors; if (typeof data.messageCid !== "string") { validate64.errors = [{ instancePath: instancePath + "/messageCid", schemaPath: "#/properties/messageCid/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.value !== void 0) { let data1 = data.value; const _errs4 = errors; if (typeof data1 !== "string" && !(typeof data1 == "number" && isFinite(data1))) { validate64.errors = [{ instancePath: instancePath + "/value", schemaPath: "#/properties/value/type", keyword: "type", params: { type: schema68.properties.value.type }, message: "must be string,number" }]; return false; } var valid0 = _errs4 === errors; } else { var valid0 = true; } } } } } } else { validate64.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate64.errors = vErrors; return errors === 0; } validate64.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var PermissionGrantData = validate65; var schema105 = { "type": "object", "additionalProperties": false, "properties": { "publication": { "enum": ["Required", "Prohibited"], "type": "string" } } }; function validate67(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { let vErrors = null; let errors = 0; const evaluated0 = validate67.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } const _errs0 = errors; let valid0 = false; let passing0 = null; const _errs1 = errors; const _errs2 = errors; if (errors === _errs2) { if (data && typeof data == "object" && !Array.isArray(data)) { if (data.interface !== void 0) { const _errs4 = errors; if ("Protocols" !== data.interface) { const err0 = { instancePath: instancePath + "/interface", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/protocols-query-scope/properties/interface/const", keyword: "const", params: { allowedValue: "Protocols" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err0]; } else { vErrors.push(err0); } errors++; } var valid2 = _errs4 === errors; } else { var valid2 = true; } if (valid2) { if (data.method !== void 0) { const _errs5 = errors; if ("Query" !== data.method) { const err1 = { instancePath: instancePath + "/method", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/protocols-query-scope/properties/method/const", keyword: "const", params: { allowedValue: "Query" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err1]; } else { vErrors.push(err1); } errors++; } var valid2 = _errs5 === errors; } else { var valid2 = true; } } } else { const err22 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/protocols-query-scope/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err22]; } else { vErrors.push(err22); } errors++; } } var _valid0 = _errs1 === errors; if (_valid0) { valid0 = true; passing0 = 0; var props0 = {}; props0.interface = true; props0.method = true; } const _errs6 = errors; const _errs7 = errors; if (errors === _errs7) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.interface === void 0 && (missing0 = "interface") || data.method === void 0 && (missing0 = "method")) { const err3 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-read-scope/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }; if (vErrors === null) { vErrors = [err3]; } else { vErrors.push(err3); } errors++; } else { if (data.interface !== void 0) { const _errs9 = errors; if ("Records" !== data.interface) { const err4 = { instancePath: instancePath + "/interface", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-read-scope/properties/interface/const", keyword: "const", params: { allowedValue: "Records" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err4]; } else { vErrors.push(err4); } errors++; } var valid4 = _errs9 === errors; } else { var valid4 = true; } if (valid4) { if (data.method !== void 0) { const _errs10 = errors; if ("Read" !== data.method) { const err5 = { instancePath: instancePath + "/method", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-read-scope/properties/method/const", keyword: "const", params: { allowedValue: "Read" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err5]; } else { vErrors.push(err5); } errors++; } var valid4 = _errs10 === errors; } else { var valid4 = true; } if (valid4) { if (data.schema !== void 0) { const _errs11 = errors; if (typeof data.schema !== "string") { const err6 = { instancePath: instancePath + "/schema", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-read-scope/properties/schema/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err6]; } else { vErrors.push(err6); } errors++; } var valid4 = _errs11 === errors; } else { var valid4 = true; } if (valid4) { if (data.protocol !== void 0) { const _errs13 = errors; if (typeof data.protocol !== "string") { const err7 = { instancePath: instancePath + "/protocol", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-read-scope/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err7]; } else { vErrors.push(err7); } errors++; } var valid4 = _errs13 === errors; } else { var valid4 = true; } if (valid4) { if (data.contextId !== void 0) { const _errs15 = errors; if (typeof data.contextId !== "string") { const err8 = { instancePath: instancePath + "/contextId", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-read-scope/properties/contextId/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err8]; } else { vErrors.push(err8); } errors++; } var valid4 = _errs15 === errors; } else { var valid4 = true; } if (valid4) { if (data.protocolPath !== void 0) { const _errs17 = errors; if (typeof data.protocolPath !== "string") { const err9 = { instancePath: instancePath + "/protocolPath", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-read-scope/properties/protocolPath/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err9]; } else { vErrors.push(err9); } errors++; } var valid4 = _errs17 === errors; } else { var valid4 = true; } } } } } } } } else { const err10 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-read-scope/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err10]; } else { vErrors.push(err10); } errors++; } } var _valid0 = _errs6 === errors; if (_valid0 && valid0) { valid0 = false; passing0 = [passing0, 1]; } else { if (_valid0) { valid0 = true; passing0 = 1; if (props0 !== true) { props0 = props0 || {}; props0.interface = true; props0.method = true; props0.schema = true; props0.protocol = true; props0.contextId = true; props0.protocolPath = true; } } const _errs19 = errors; const _errs20 = errors; if (errors === _errs20) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing1; if (data.interface === void 0 && (missing1 = "interface") || data.method === void 0 && (missing1 = "method")) { const err11 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-delete-scope/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }; if (vErrors === null) { vErrors = [err11]; } else { vErrors.push(err11); } errors++; } else { if (data.interface !== void 0) { const _errs22 = errors; if ("Records" !== data.interface) { const err12 = { instancePath: instancePath + "/interface", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-delete-scope/properties/interface/const", keyword: "const", params: { allowedValue: "Records" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err12]; } else { vErrors.push(err12); } errors++; } var valid6 = _errs22 === errors; } else { var valid6 = true; } if (valid6) { if (data.method !== void 0) { const _errs23 = errors; if ("Delete" !== data.method) { const err13 = { instancePath: instancePath + "/method", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-delete-scope/properties/method/const", keyword: "const", params: { allowedValue: "Delete" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err13]; } else { vErrors.push(err13); } errors++; } var valid6 = _errs23 === errors; } else { var valid6 = true; } if (valid6) { if (data.protocol !== void 0) { const _errs24 = errors; if (typeof data.protocol !== "string") { const err14 = { instancePath: instancePath + "/protocol", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-delete-scope/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err14]; } else { vErrors.push(err14); } errors++; } var valid6 = _errs24 === errors; } else { var valid6 = true; } if (valid6) { if (data.schema !== void 0) { const _errs26 = errors; if (typeof data.schema !== "string") { const err15 = { instancePath: instancePath + "/schema", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-delete-scope/properties/schema/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err15]; } else { vErrors.push(err15); } errors++; } var valid6 = _errs26 === errors; } else { var valid6 = true; } } } } } } else { const err16 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-delete-scope/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err16]; } else { vErrors.push(err16); } errors++; } } var _valid0 = _errs19 === errors; if (_valid0 && valid0) { valid0 = false; passing0 = [passing0, 2]; } else { if (_valid0) { valid0 = true; passing0 = 2; if (props0 !== true) { props0 = props0 || {}; props0.interface = true; props0.method = true; props0.protocol = true; props0.schema = true; } } const _errs28 = errors; const _errs29 = errors; if (errors === _errs29) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing2; if (data.interface === void 0 && (missing2 = "interface") || data.method === void 0 && (missing2 = "method")) { const err17 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-write-scope/required", keyword: "required", params: { missingProperty: missing2 }, message: "must have required property '" + missing2 + "'" }; if (vErrors === null) { vErrors = [err17]; } else { vErrors.push(err17); } errors++; } else { if (data.interface !== void 0) { const _errs31 = errors; if ("Records" !== data.interface) { const err18 = { instancePath: instancePath + "/interface", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-write-scope/properties/interface/const", keyword: "const", params: { allowedValue: "Records" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err18]; } else { vErrors.push(err18); } errors++; } var valid8 = _errs31 === errors; } else { var valid8 = true; } if (valid8) { if (data.method !== void 0) { const _errs32 = errors; if ("Write" !== data.method) { const err19 = { instancePath: instancePath + "/method", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-write-scope/properties/method/const", keyword: "const", params: { allowedValue: "Write" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err19]; } else { vErrors.push(err19); } errors++; } var valid8 = _errs32 === errors; } else { var valid8 = true; } if (valid8) { if (data.schema !== void 0) { const _errs33 = errors; if (typeof data.schema !== "string") { const err20 = { instancePath: instancePath + "/schema", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-write-scope/properties/schema/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err20]; } else { vErrors.push(err20); } errors++; } var valid8 = _errs33 === errors; } else { var valid8 = true; } if (valid8) { if (data.protocol !== void 0) { const _errs35 = errors; if (typeof data.protocol !== "string") { const err21 = { instancePath: instancePath + "/protocol", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-write-scope/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err21]; } else { vErrors.push(err21); } errors++; } var valid8 = _errs35 === errors; } else { var valid8 = true; } if (valid8) { if (data.contextId !== void 0) { const _errs37 = errors; if (typeof data.contextId !== "string") { const err22 = { instancePath: instancePath + "/contextId", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-write-scope/properties/contextId/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err22]; } else { vErrors.push(err22); } errors++; } var valid8 = _errs37 === errors; } else { var valid8 = true; } if (valid8) { if (data.protocolPath !== void 0) { const _errs39 = errors; if (typeof data.protocolPath !== "string") { const err23 = { instancePath: instancePath + "/protocolPath", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-write-scope/properties/protocolPath/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err23]; } else { vErrors.push(err23); } errors++; } var valid8 = _errs39 === errors; } else { var valid8 = true; } } } } } } } } else { const err24 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-write-scope/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err24]; } else { vErrors.push(err24); } errors++; } } var _valid0 = _errs28 === errors; if (_valid0 && valid0) { valid0 = false; passing0 = [passing0, 3]; } else { if (_valid0) { valid0 = true; passing0 = 3; if (props0 !== true) { props0 = props0 || {}; props0.interface = true; props0.method = true; props0.schema = true; props0.protocol = true; props0.contextId = true; props0.protocolPath = true; } } const _errs41 = errors; const _errs42 = errors; if (errors === _errs42) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing3; if (data.interface === void 0 && (missing3 = "interface") || data.method === void 0 && (missing3 = "method")) { const err25 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-query-scope/required", keyword: "required", params: { missingProperty: missing3 }, message: "must have required property '" + missing3 + "'" }; if (vErrors === null) { vErrors = [err25]; } else { vErrors.push(err25); } errors++; } else { if (data.interface !== void 0) { const _errs44 = errors; if ("Records" !== data.interface) { const err26 = { instancePath: instancePath + "/interface", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-query-scope/properties/interface/const", keyword: "const", params: { allowedValue: "Records" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err26]; } else { vErrors.push(err26); } errors++; } var valid10 = _errs44 === errors; } else { var valid10 = true; } if (valid10) { if (data.method !== void 0) { const _errs45 = errors; if ("Query" !== data.method) { const err27 = { instancePath: instancePath + "/method", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-query-scope/properties/method/const", keyword: "const", params: { allowedValue: "Query" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err27]; } else { vErrors.push(err27); } errors++; } var valid10 = _errs45 === errors; } else { var valid10 = true; } if (valid10) { if (data.protocol !== void 0) { const _errs46 = errors; if (typeof data.protocol !== "string") { const err28 = { instancePath: instancePath + "/protocol", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-query-scope/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err28]; } else { vErrors.push(err28); } errors++; } var valid10 = _errs46 === errors; } else { var valid10 = true; } } } } } else { const err29 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-query-scope/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err29]; } else { vErrors.push(err29); } errors++; } } var _valid0 = _errs41 === errors; if (_valid0 && valid0) { valid0 = false; passing0 = [passing0, 4]; } else { if (_valid0) { valid0 = true; passing0 = 4; if (props0 !== true) { props0 = props0 || {}; props0.interface = true; props0.method = true; props0.protocol = true; } } const _errs48 = errors; const _errs49 = errors; if (errors === _errs49) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing4; if (data.interface === void 0 && (missing4 = "interface") || data.method === void 0 && (missing4 = "method")) { const err30 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-subscribe-scope/required", keyword: "required", params: { missingProperty: missing4 }, message: "must have required property '" + missing4 + "'" }; if (vErrors === null) { vErrors = [err30]; } else { vErrors.push(err30); } errors++; } else { if (data.interface !== void 0) { const _errs51 = errors; if ("Records" !== data.interface) { const err31 = { instancePath: instancePath + "/interface", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-subscribe-scope/properties/interface/const", keyword: "const", params: { allowedValue: "Records" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err31]; } else { vErrors.push(err31); } errors++; } var valid12 = _errs51 === errors; } else { var valid12 = true; } if (valid12) { if (data.method !== void 0) { const _errs52 = errors; if ("Subscribe" !== data.method) { const err32 = { instancePath: instancePath + "/method", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-subscribe-scope/properties/method/const", keyword: "const", params: { allowedValue: "Subscribe" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err32]; } else { vErrors.push(err32); } errors++; } var valid12 = _errs52 === errors; } else { var valid12 = true; } if (valid12) { if (data.protocol !== void 0) { const _errs53 = errors; if (typeof data.protocol !== "string") { const err33 = { instancePath: instancePath + "/protocol", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-subscribe-scope/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err33]; } else { vErrors.push(err33); } errors++; } var valid12 = _errs53 === errors; } else { var valid12 = true; } } } } } else { const err34 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-subscribe-scope/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err34]; } else { vErrors.push(err34); } errors++; } } var _valid0 = _errs48 === errors; if (_valid0 && valid0) { valid0 = false; passing0 = [passing0, 5]; } else { if (_valid0) { valid0 = true; passing0 = 5; if (props0 !== true) { props0 = props0 || {}; props0.interface = true; props0.method = true; props0.protocol = true; } } } } } } } if (!valid0) { const err35 = { instancePath, schemaPath: "#/oneOf", keyword: "oneOf", params: { passingSchemas: passing0 }, message: "must match exactly one schema in oneOf" }; if (vErrors === null) { vErrors = [err35]; } else { vErrors.push(err35); } errors++; validate67.errors = vErrors; return false; } else { errors = _errs0; if (vErrors !== null) { if (_errs0) { vErrors.length = _errs0; } else { vErrors = null; } } } validate67.errors = vErrors; evaluated0.props = props0; return errors === 0; } validate67.evaluated = { "dynamicProps": true, "dynamicItems": false }; function validate65(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate65.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.dateExpires === void 0 && (missing0 = "dateExpires") || data.scope === void 0 && (missing0 = "scope")) { validate65.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "description" || key0 === "dateExpires" || key0 === "requestId" || key0 === "delegated" || key0 === "scope" || key0 === "conditions")) { validate65.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.description !== void 0) { const _errs2 = errors; if (typeof data.description !== "string") { validate65.errors = [{ instancePath: instancePath + "/description", schemaPath: "#/properties/description/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.dateExpires !== void 0) { let data1 = data.dateExpires; const _errs4 = errors; const _errs5 = errors; if (errors === _errs5) { if (typeof data1 === "string") { if (!pattern14.test(data1)) { validate65.errors = [{ instancePath: instancePath + "/dateExpires", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate65.errors = [{ instancePath: instancePath + "/dateExpires", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid0 = _errs4 === errors; } else { var valid0 = true; } if (valid0) { if (data.requestId !== void 0) { const _errs7 = errors; if (typeof data.requestId !== "string") { validate65.errors = [{ instancePath: instancePath + "/requestId", schemaPath: "#/properties/requestId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs7 === errors; } else { var valid0 = true; } if (valid0) { if (data.delegated !== void 0) { const _errs9 = errors; if (typeof data.delegated !== "boolean") { validate65.errors = [{ instancePath: instancePath + "/delegated", schemaPath: "#/properties/delegated/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } var valid0 = _errs9 === errors; } else { var valid0 = true; } if (valid0) { if (data.scope !== void 0) { const _errs11 = errors; if (!validate67(data.scope, { instancePath: instancePath + "/scope", parentData: data, parentDataProperty: "scope", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate67.errors : vErrors.concat(validate67.errors); errors = vErrors.length; } var valid0 = _errs11 === errors; } else { var valid0 = true; } if (valid0) { if (data.conditions !== void 0) { let data5 = data.conditions; const _errs12 = errors; const _errs13 = errors; if (errors === _errs13) { if (data5 && typeof data5 == "object" && !Array.isArray(data5)) { const _errs15 = errors; for (const key1 in data5) { if (!(key1 === "publication")) { validate65.errors = [{ instancePath: instancePath + "/conditions", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/defs.json#/$defs/conditions/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs15 === errors) { if (data5.publication !== void 0) { let data6 = data5.publication; if (typeof data6 !== "string") { validate65.errors = [{ instancePath: instancePath + "/conditions/publication", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/defs.json#/$defs/conditions/properties/publication/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data6 === "Required" || data6 === "Prohibited")) { validate65.errors = [{ instancePath: instancePath + "/conditions/publication", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/defs.json#/$defs/conditions/properties/publication/enum", keyword: "enum", params: { allowedValues: schema105.properties.publication.enum }, message: "must be equal to one of the allowed values" }]; return false; } } } } else { validate65.errors = [{ instancePath: instancePath + "/conditions", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/defs.json#/$defs/conditions/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs12 === errors; } else { var valid0 = true; } } } } } } } } } else { validate65.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate65.errors = vErrors; return errors === 0; } validate65.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var PermissionRequestData = validate70; function validate71(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { let vErrors = null; let errors = 0; const evaluated0 = validate71.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } const _errs0 = errors; let valid0 = false; let passing0 = null; const _errs1 = errors; const _errs2 = errors; if (errors === _errs2) { if (data && typeof data == "object" && !Array.isArray(data)) { if (data.interface !== void 0) { const _errs4 = errors; if ("Protocols" !== data.interface) { const err0 = { instancePath: instancePath + "/interface", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/protocols-query-scope/properties/interface/const", keyword: "const", params: { allowedValue: "Protocols" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err0]; } else { vErrors.push(err0); } errors++; } var valid2 = _errs4 === errors; } else { var valid2 = true; } if (valid2) { if (data.method !== void 0) { const _errs5 = errors; if ("Query" !== data.method) { const err1 = { instancePath: instancePath + "/method", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/protocols-query-scope/properties/method/const", keyword: "const", params: { allowedValue: "Query" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err1]; } else { vErrors.push(err1); } errors++; } var valid2 = _errs5 === errors; } else { var valid2 = true; } } } else { const err22 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/protocols-query-scope/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err22]; } else { vErrors.push(err22); } errors++; } } var _valid0 = _errs1 === errors; if (_valid0) { valid0 = true; passing0 = 0; var props0 = {}; props0.interface = true; props0.method = true; } const _errs6 = errors; const _errs7 = errors; if (errors === _errs7) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.interface === void 0 && (missing0 = "interface") || data.method === void 0 && (missing0 = "method")) { const err3 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-read-scope/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }; if (vErrors === null) { vErrors = [err3]; } else { vErrors.push(err3); } errors++; } else { if (data.interface !== void 0) { const _errs9 = errors; if ("Records" !== data.interface) { const err4 = { instancePath: instancePath + "/interface", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-read-scope/properties/interface/const", keyword: "const", params: { allowedValue: "Records" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err4]; } else { vErrors.push(err4); } errors++; } var valid4 = _errs9 === errors; } else { var valid4 = true; } if (valid4) { if (data.method !== void 0) { const _errs10 = errors; if ("Read" !== data.method) { const err5 = { instancePath: instancePath + "/method", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-read-scope/properties/method/const", keyword: "const", params: { allowedValue: "Read" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err5]; } else { vErrors.push(err5); } errors++; } var valid4 = _errs10 === errors; } else { var valid4 = true; } if (valid4) { if (data.schema !== void 0) { const _errs11 = errors; if (typeof data.schema !== "string") { const err6 = { instancePath: instancePath + "/schema", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-read-scope/properties/schema/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err6]; } else { vErrors.push(err6); } errors++; } var valid4 = _errs11 === errors; } else { var valid4 = true; } if (valid4) { if (data.protocol !== void 0) { const _errs13 = errors; if (typeof data.protocol !== "string") { const err7 = { instancePath: instancePath + "/protocol", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-read-scope/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err7]; } else { vErrors.push(err7); } errors++; } var valid4 = _errs13 === errors; } else { var valid4 = true; } if (valid4) { if (data.contextId !== void 0) { const _errs15 = errors; if (typeof data.contextId !== "string") { const err8 = { instancePath: instancePath + "/contextId", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-read-scope/properties/contextId/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err8]; } else { vErrors.push(err8); } errors++; } var valid4 = _errs15 === errors; } else { var valid4 = true; } if (valid4) { if (data.protocolPath !== void 0) { const _errs17 = errors; if (typeof data.protocolPath !== "string") { const err9 = { instancePath: instancePath + "/protocolPath", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-read-scope/properties/protocolPath/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err9]; } else { vErrors.push(err9); } errors++; } var valid4 = _errs17 === errors; } else { var valid4 = true; } } } } } } } } else { const err10 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-read-scope/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err10]; } else { vErrors.push(err10); } errors++; } } var _valid0 = _errs6 === errors; if (_valid0 && valid0) { valid0 = false; passing0 = [passing0, 1]; } else { if (_valid0) { valid0 = true; passing0 = 1; if (props0 !== true) { props0 = props0 || {}; props0.interface = true; props0.method = true; props0.schema = true; props0.protocol = true; props0.contextId = true; props0.protocolPath = true; } } const _errs19 = errors; const _errs20 = errors; if (errors === _errs20) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing1; if (data.interface === void 0 && (missing1 = "interface") || data.method === void 0 && (missing1 = "method")) { const err11 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-delete-scope/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }; if (vErrors === null) { vErrors = [err11]; } else { vErrors.push(err11); } errors++; } else { if (data.interface !== void 0) { const _errs22 = errors; if ("Records" !== data.interface) { const err12 = { instancePath: instancePath + "/interface", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-delete-scope/properties/interface/const", keyword: "const", params: { allowedValue: "Records" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err12]; } else { vErrors.push(err12); } errors++; } var valid6 = _errs22 === errors; } else { var valid6 = true; } if (valid6) { if (data.method !== void 0) { const _errs23 = errors; if ("Delete" !== data.method) { const err13 = { instancePath: instancePath + "/method", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-delete-scope/properties/method/const", keyword: "const", params: { allowedValue: "Delete" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err13]; } else { vErrors.push(err13); } errors++; } var valid6 = _errs23 === errors; } else { var valid6 = true; } if (valid6) { if (data.protocol !== void 0) { const _errs24 = errors; if (typeof data.protocol !== "string") { const err14 = { instancePath: instancePath + "/protocol", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-delete-scope/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err14]; } else { vErrors.push(err14); } errors++; } var valid6 = _errs24 === errors; } else { var valid6 = true; } if (valid6) { if (data.schema !== void 0) { const _errs26 = errors; if (typeof data.schema !== "string") { const err15 = { instancePath: instancePath + "/schema", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-delete-scope/properties/schema/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err15]; } else { vErrors.push(err15); } errors++; } var valid6 = _errs26 === errors; } else { var valid6 = true; } } } } } } else { const err16 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-delete-scope/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err16]; } else { vErrors.push(err16); } errors++; } } var _valid0 = _errs19 === errors; if (_valid0 && valid0) { valid0 = false; passing0 = [passing0, 2]; } else { if (_valid0) { valid0 = true; passing0 = 2; if (props0 !== true) { props0 = props0 || {}; props0.interface = true; props0.method = true; props0.protocol = true; props0.schema = true; } } const _errs28 = errors; const _errs29 = errors; if (errors === _errs29) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing2; if (data.interface === void 0 && (missing2 = "interface") || data.method === void 0 && (missing2 = "method")) { const err17 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-write-scope/required", keyword: "required", params: { missingProperty: missing2 }, message: "must have required property '" + missing2 + "'" }; if (vErrors === null) { vErrors = [err17]; } else { vErrors.push(err17); } errors++; } else { if (data.interface !== void 0) { const _errs31 = errors; if ("Records" !== data.interface) { const err18 = { instancePath: instancePath + "/interface", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-write-scope/properties/interface/const", keyword: "const", params: { allowedValue: "Records" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err18]; } else { vErrors.push(err18); } errors++; } var valid8 = _errs31 === errors; } else { var valid8 = true; } if (valid8) { if (data.method !== void 0) { const _errs32 = errors; if ("Write" !== data.method) { const err19 = { instancePath: instancePath + "/method", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-write-scope/properties/method/const", keyword: "const", params: { allowedValue: "Write" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err19]; } else { vErrors.push(err19); } errors++; } var valid8 = _errs32 === errors; } else { var valid8 = true; } if (valid8) { if (data.schema !== void 0) { const _errs33 = errors; if (typeof data.schema !== "string") { const err20 = { instancePath: instancePath + "/schema", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-write-scope/properties/schema/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err20]; } else { vErrors.push(err20); } errors++; } var valid8 = _errs33 === errors; } else { var valid8 = true; } if (valid8) { if (data.protocol !== void 0) { const _errs35 = errors; if (typeof data.protocol !== "string") { const err21 = { instancePath: instancePath + "/protocol", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-write-scope/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err21]; } else { vErrors.push(err21); } errors++; } var valid8 = _errs35 === errors; } else { var valid8 = true; } if (valid8) { if (data.contextId !== void 0) { const _errs37 = errors; if (typeof data.contextId !== "string") { const err22 = { instancePath: instancePath + "/contextId", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-write-scope/properties/contextId/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err22]; } else { vErrors.push(err22); } errors++; } var valid8 = _errs37 === errors; } else { var valid8 = true; } if (valid8) { if (data.protocolPath !== void 0) { const _errs39 = errors; if (typeof data.protocolPath !== "string") { const err23 = { instancePath: instancePath + "/protocolPath", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-write-scope/properties/protocolPath/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err23]; } else { vErrors.push(err23); } errors++; } var valid8 = _errs39 === errors; } else { var valid8 = true; } } } } } } } } else { const err24 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-write-scope/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err24]; } else { vErrors.push(err24); } errors++; } } var _valid0 = _errs28 === errors; if (_valid0 && valid0) { valid0 = false; passing0 = [passing0, 3]; } else { if (_valid0) { valid0 = true; passing0 = 3; if (props0 !== true) { props0 = props0 || {}; props0.interface = true; props0.method = true; props0.schema = true; props0.protocol = true; props0.contextId = true; props0.protocolPath = true; } } const _errs41 = errors; const _errs42 = errors; if (errors === _errs42) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing3; if (data.interface === void 0 && (missing3 = "interface") || data.method === void 0 && (missing3 = "method")) { const err25 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-query-scope/required", keyword: "required", params: { missingProperty: missing3 }, message: "must have required property '" + missing3 + "'" }; if (vErrors === null) { vErrors = [err25]; } else { vErrors.push(err25); } errors++; } else { if (data.interface !== void 0) { const _errs44 = errors; if ("Records" !== data.interface) { const err26 = { instancePath: instancePath + "/interface", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-query-scope/properties/interface/const", keyword: "const", params: { allowedValue: "Records" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err26]; } else { vErrors.push(err26); } errors++; } var valid10 = _errs44 === errors; } else { var valid10 = true; } if (valid10) { if (data.method !== void 0) { const _errs45 = errors; if ("Query" !== data.method) { const err27 = { instancePath: instancePath + "/method", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-query-scope/properties/method/const", keyword: "const", params: { allowedValue: "Query" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err27]; } else { vErrors.push(err27); } errors++; } var valid10 = _errs45 === errors; } else { var valid10 = true; } if (valid10) { if (data.protocol !== void 0) { const _errs46 = errors; if (typeof data.protocol !== "string") { const err28 = { instancePath: instancePath + "/protocol", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-query-scope/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err28]; } else { vErrors.push(err28); } errors++; } var valid10 = _errs46 === errors; } else { var valid10 = true; } } } } } else { const err29 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-query-scope/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err29]; } else { vErrors.push(err29); } errors++; } } var _valid0 = _errs41 === errors; if (_valid0 && valid0) { valid0 = false; passing0 = [passing0, 4]; } else { if (_valid0) { valid0 = true; passing0 = 4; if (props0 !== true) { props0 = props0 || {}; props0.interface = true; props0.method = true; props0.protocol = true; } } const _errs48 = errors; const _errs49 = errors; if (errors === _errs49) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing4; if (data.interface === void 0 && (missing4 = "interface") || data.method === void 0 && (missing4 = "method")) { const err30 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-subscribe-scope/required", keyword: "required", params: { missingProperty: missing4 }, message: "must have required property '" + missing4 + "'" }; if (vErrors === null) { vErrors = [err30]; } else { vErrors.push(err30); } errors++; } else { if (data.interface !== void 0) { const _errs51 = errors; if ("Records" !== data.interface) { const err31 = { instancePath: instancePath + "/interface", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-subscribe-scope/properties/interface/const", keyword: "const", params: { allowedValue: "Records" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err31]; } else { vErrors.push(err31); } errors++; } var valid12 = _errs51 === errors; } else { var valid12 = true; } if (valid12) { if (data.method !== void 0) { const _errs52 = errors; if ("Subscribe" !== data.method) { const err32 = { instancePath: instancePath + "/method", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-subscribe-scope/properties/method/const", keyword: "const", params: { allowedValue: "Subscribe" }, message: "must be equal to constant" }; if (vErrors === null) { vErrors = [err32]; } else { vErrors.push(err32); } errors++; } var valid12 = _errs52 === errors; } else { var valid12 = true; } if (valid12) { if (data.protocol !== void 0) { const _errs53 = errors; if (typeof data.protocol !== "string") { const err33 = { instancePath: instancePath + "/protocol", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-subscribe-scope/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err33]; } else { vErrors.push(err33); } errors++; } var valid12 = _errs53 === errors; } else { var valid12 = true; } } } } } else { const err34 = { instancePath, schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/scopes.json#/$defs/records-subscribe-scope/type", keyword: "type", params: { type: "object" }, message: "must be object" }; if (vErrors === null) { vErrors = [err34]; } else { vErrors.push(err34); } errors++; } } var _valid0 = _errs48 === errors; if (_valid0 && valid0) { valid0 = false; passing0 = [passing0, 5]; } else { if (_valid0) { valid0 = true; passing0 = 5; if (props0 !== true) { props0 = props0 || {}; props0.interface = true; props0.method = true; props0.protocol = true; } } } } } } } if (!valid0) { const err35 = { instancePath, schemaPath: "#/oneOf", keyword: "oneOf", params: { passingSchemas: passing0 }, message: "must match exactly one schema in oneOf" }; if (vErrors === null) { vErrors = [err35]; } else { vErrors.push(err35); } errors++; validate71.errors = vErrors; return false; } else { errors = _errs0; if (vErrors !== null) { if (_errs0) { vErrors.length = _errs0; } else { vErrors = null; } } } validate71.errors = vErrors; evaluated0.props = props0; return errors === 0; } validate71.evaluated = { "dynamicProps": true, "dynamicItems": false }; function validate70(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate70.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.delegated === void 0 && (missing0 = "delegated") || data.scope === void 0 && (missing0 = "scope")) { validate70.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "description" || key0 === "delegated" || key0 === "scope" || key0 === "conditions")) { validate70.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.description !== void 0) { const _errs2 = errors; if (typeof data.description !== "string") { validate70.errors = [{ instancePath: instancePath + "/description", schemaPath: "#/properties/description/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.delegated !== void 0) { const _errs4 = errors; if (typeof data.delegated !== "boolean") { validate70.errors = [{ instancePath: instancePath + "/delegated", schemaPath: "#/properties/delegated/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } var valid0 = _errs4 === errors; } else { var valid0 = true; } if (valid0) { if (data.scope !== void 0) { const _errs6 = errors; if (!validate71(data.scope, { instancePath: instancePath + "/scope", parentData: data, parentDataProperty: "scope", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate71.errors : vErrors.concat(validate71.errors); errors = vErrors.length; } var valid0 = _errs6 === errors; } else { var valid0 = true; } if (valid0) { if (data.conditions !== void 0) { let data3 = data.conditions; const _errs7 = errors; const _errs8 = errors; if (errors === _errs8) { if (data3 && typeof data3 == "object" && !Array.isArray(data3)) { const _errs10 = errors; for (const key1 in data3) { if (!(key1 === "publication")) { validate70.errors = [{ instancePath: instancePath + "/conditions", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/defs.json#/$defs/conditions/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs10 === errors) { if (data3.publication !== void 0) { let data4 = data3.publication; if (typeof data4 !== "string") { validate70.errors = [{ instancePath: instancePath + "/conditions/publication", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/defs.json#/$defs/conditions/properties/publication/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data4 === "Required" || data4 === "Prohibited")) { validate70.errors = [{ instancePath: instancePath + "/conditions/publication", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/defs.json#/$defs/conditions/properties/publication/enum", keyword: "enum", params: { allowedValues: schema105.properties.publication.enum }, message: "must be equal to one of the allowed values" }]; return false; } } } } else { validate70.errors = [{ instancePath: instancePath + "/conditions", schemaPath: "https://identity.foundation/dwn/json-schemas/permissions/defs.json#/$defs/conditions/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs7 === errors; } else { var valid0 = true; } } } } } } } else { validate70.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate70.errors = vErrors; return errors === 0; } validate70.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var PermissionRevocationData = validate73; function validate73(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate73.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "description")) { validate73.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.description !== void 0) { if (typeof data.description !== "string") { validate73.errors = [{ instancePath: instancePath + "/description", schemaPath: "#/properties/description/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } } } else { validate73.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate73.errors = vErrors; return errors === 0; } validate73.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var PermissionsDefinitions = validate66; function validate66(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate66.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (!(data && typeof data == "object" && !Array.isArray(data))) { validate66.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } validate66.errors = vErrors; return errors === 0; } validate66.evaluated = { "dynamicProps": false, "dynamicItems": false }; var PermissionsScopes = validate68; function validate68(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate68.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (!(data && typeof data == "object" && !Array.isArray(data))) { validate68.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } validate68.errors = vErrors; return errors === 0; } validate68.evaluated = { "dynamicProps": false, "dynamicItems": false }; var ProtocolDefinition = validate74; var pattern40 = new RegExp(".*", "u"); var schema117 = { "$id": "https://identity.foundation/dwn/json-schemas/protocol-rule-set.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "additionalProperties": false, "properties": { "$encryption": { "type": "object", "additionalProperties": false, "properties": { "rootKeyId": { "type": "string" }, "publicKeyJwk": { "$ref": "https://identity.foundation/dwn/json-schemas/public-jwk.json" } }, "required": ["rootKeyId", "publicKeyJwk"] }, "$actions": { "type": "array", "minItems": 1, "items": { "type": "object", "oneOf": [{ "required": ["who", "can"], "additionalProperties": false, "properties": { "who": { "type": "string", "enum": ["anyone", "author", "recipient"] }, "of": { "type": "string" }, "can": { "type": "array", "minItems": 1, "items": { "type": "string", "enum": ["co-delete", "co-prune", "co-update", "create", "delete", "prune", "read", "update"] } } } }, { "required": ["role", "can"], "properties": { "role": { "$comment": "Must be the protocol path of a role record type", "type": "string" }, "can": { "type": "array", "minItems": 1, "items": { "type": "string", "enum": ["co-delete", "co-update", "create", "delete", "query", "subscribe", "read", "update"] } } } }] } }, "$role": { "$comment": "When `true`, this turns a record into `role` that may be used within a context/sub-context", "type": "boolean" }, "$size": { "type": "object", "additionalProperties": false, "properties": { "min": { "type": "number", "minimum": 0 }, "max": { "type": "number", "minimum": 0 } } }, "$tags": { "type": "object", "minProperties": 1, "properties": { "$requiredTags": { "type": "array", "items": { "type": "string" } }, "$allowUndefinedTags": { "type": "boolean" } }, "patternProperties": { "^(?!\\$requiredTags$|\\$allowUndefinedTags$).*$": { "type": "object", "additionalProperties": false, "properties": { "type": { "enum": ["string", "number", "integer", "boolean", "array"] }, "items": { "type": "object", "properties": { "type": { "enum": ["string", "number", "integer"] } }, "patternProperties": { "^(enum|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength)$": {} } }, "contains": { "type": "object", "properties": { "type": { "enum": ["string", "number", "integer"] } }, "patternProperties": { "^(enum|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength)$": {} } } }, "patternProperties": { "^(enum|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength|minItems|maxItems|uniqueItems|minContains|maxContains)$": {} } } } } }, "patternProperties": { "^[^$].*$": { "$ref": "https://identity.foundation/dwn/json-schemas/protocol-rule-set.json" } } }; var pattern42 = new RegExp("^[^$].*$", "u"); var pattern43 = new RegExp("^(?!\\$requiredTags$|\\$allowUndefinedTags$).*$", "u"); var pattern44 = new RegExp("^(enum|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength|minItems|maxItems|uniqueItems|minContains|maxContains)$", "u"); var pattern45 = new RegExp("^(enum|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength)$", "u"); var wrapper2 = { validate: validate75 }; function validate75(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate75.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "$encryption" || key0 === "$actions" || key0 === "$role" || key0 === "$size" || key0 === "$tags" || pattern42.test(key0))) { validate75.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.$encryption !== void 0) { let data0 = data.$encryption; const _errs2 = errors; if (errors === _errs2) { if (data0 && typeof data0 == "object" && !Array.isArray(data0)) { let missing0; if (data0.rootKeyId === void 0 && (missing0 = "rootKeyId") || data0.publicKeyJwk === void 0 && (missing0 = "publicKeyJwk")) { validate75.errors = [{ instancePath: instancePath + "/$encryption", schemaPath: "#/properties/%24encryption/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs4 = errors; for (const key1 in data0) { if (!(key1 === "rootKeyId" || key1 === "publicKeyJwk")) { validate75.errors = [{ instancePath: instancePath + "/$encryption", schemaPath: "#/properties/%24encryption/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs4 === errors) { if (data0.rootKeyId !== void 0) { const _errs5 = errors; if (typeof data0.rootKeyId !== "string") { validate75.errors = [{ instancePath: instancePath + "/$encryption/rootKeyId", schemaPath: "#/properties/%24encryption/properties/rootKeyId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid1 = _errs5 === errors; } else { var valid1 = true; } if (valid1) { if (data0.publicKeyJwk !== void 0) { const _errs7 = errors; if (!validate33(data0.publicKeyJwk, { instancePath: instancePath + "/$encryption/publicKeyJwk", parentData: data0, parentDataProperty: "publicKeyJwk", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate33.errors : vErrors.concat(validate33.errors); errors = vErrors.length; } var valid1 = _errs7 === errors; } else { var valid1 = true; } } } } } else { validate75.errors = [{ instancePath: instancePath + "/$encryption", schemaPath: "#/properties/%24encryption/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.$actions !== void 0) { let data3 = data.$actions; const _errs8 = errors; if (errors === _errs8) { if (Array.isArray(data3)) { if (data3.length < 1) { validate75.errors = [{ instancePath: instancePath + "/$actions", schemaPath: "#/properties/%24actions/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; return false; } else { var valid2 = true; const len0 = data3.length; for (let i0 = 0; i0 < len0; i0++) { let data4 = data3[i0]; const _errs10 = errors; if (!(data4 && typeof data4 == "object" && !Array.isArray(data4))) { validate75.errors = [{ instancePath: instancePath + "/$actions/" + i0, schemaPath: "#/properties/%24actions/items/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } const _errs12 = errors; let valid3 = false; let passing0 = null; const _errs13 = errors; if (data4 && typeof data4 == "object" && !Array.isArray(data4)) { let missing1; if (data4.who === void 0 && (missing1 = "who") || data4.can === void 0 && (missing1 = "can")) { const err0 = { instancePath: instancePath + "/$actions/" + i0, schemaPath: "#/properties/%24actions/items/oneOf/0/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }; if (vErrors === null) { vErrors = [err0]; } else { vErrors.push(err0); } errors++; } else { const _errs14 = errors; for (const key2 in data4) { if (!(key2 === "who" || key2 === "of" || key2 === "can")) { const err1 = { instancePath: instancePath + "/$actions/" + i0, schemaPath: "#/properties/%24actions/items/oneOf/0/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }; if (vErrors === null) { vErrors = [err1]; } else { vErrors.push(err1); } errors++; break; } } if (_errs14 === errors) { if (data4.who !== void 0) { let data5 = data4.who; const _errs15 = errors; if (typeof data5 !== "string") { const err22 = { instancePath: instancePath + "/$actions/" + i0 + "/who", schemaPath: "#/properties/%24actions/items/oneOf/0/properties/who/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err22]; } else { vErrors.push(err22); } errors++; } if (!(data5 === "anyone" || data5 === "author" || data5 === "recipient")) { const err3 = { instancePath: instancePath + "/$actions/" + i0 + "/who", schemaPath: "#/properties/%24actions/items/oneOf/0/properties/who/enum", keyword: "enum", params: { allowedValues: schema117.properties.$actions.items.oneOf[0].properties.who.enum }, message: "must be equal to one of the allowed values" }; if (vErrors === null) { vErrors = [err3]; } else { vErrors.push(err3); } errors++; } var valid4 = _errs15 === errors; } else { var valid4 = true; } if (valid4) { if (data4.of !== void 0) { const _errs17 = errors; if (typeof data4.of !== "string") { const err4 = { instancePath: instancePath + "/$actions/" + i0 + "/of", schemaPath: "#/properties/%24actions/items/oneOf/0/properties/of/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err4]; } else { vErrors.push(err4); } errors++; } var valid4 = _errs17 === errors; } else { var valid4 = true; } if (valid4) { if (data4.can !== void 0) { let data7 = data4.can; const _errs19 = errors; if (errors === _errs19) { if (Array.isArray(data7)) { if (data7.length < 1) { const err5 = { instancePath: instancePath + "/$actions/" + i0 + "/can", schemaPath: "#/properties/%24actions/items/oneOf/0/properties/can/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }; if (vErrors === null) { vErrors = [err5]; } else { vErrors.push(err5); } errors++; } else { var valid5 = true; const len1 = data7.length; for (let i1 = 0; i1 < len1; i1++) { let data8 = data7[i1]; const _errs21 = errors; if (typeof data8 !== "string") { const err6 = { instancePath: instancePath + "/$actions/" + i0 + "/can/" + i1, schemaPath: "#/properties/%24actions/items/oneOf/0/properties/can/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err6]; } else { vErrors.push(err6); } errors++; } if (!(data8 === "co-delete" || data8 === "co-prune" || data8 === "co-update" || data8 === "create" || data8 === "delete" || data8 === "prune" || data8 === "read" || data8 === "update")) { const err7 = { instancePath: instancePath + "/$actions/" + i0 + "/can/" + i1, schemaPath: "#/properties/%24actions/items/oneOf/0/properties/can/items/enum", keyword: "enum", params: { allowedValues: schema117.properties.$actions.items.oneOf[0].properties.can.items.enum }, message: "must be equal to one of the allowed values" }; if (vErrors === null) { vErrors = [err7]; } else { vErrors.push(err7); } errors++; } var valid5 = _errs21 === errors; if (!valid5) { break; } } } } else { const err8 = { instancePath: instancePath + "/$actions/" + i0 + "/can", schemaPath: "#/properties/%24actions/items/oneOf/0/properties/can/type", keyword: "type", params: { type: "array" }, message: "must be array" }; if (vErrors === null) { vErrors = [err8]; } else { vErrors.push(err8); } errors++; } } var valid4 = _errs19 === errors; } else { var valid4 = true; } } } } } } var _valid0 = _errs13 === errors; if (_valid0) { valid3 = true; passing0 = 0; var props1 = true; } const _errs23 = errors; if (data4 && typeof data4 == "object" && !Array.isArray(data4)) { let missing2; if (data4.role === void 0 && (missing2 = "role") || data4.can === void 0 && (missing2 = "can")) { const err9 = { instancePath: instancePath + "/$actions/" + i0, schemaPath: "#/properties/%24actions/items/oneOf/1/required", keyword: "required", params: { missingProperty: missing2 }, message: "must have required property '" + missing2 + "'" }; if (vErrors === null) { vErrors = [err9]; } else { vErrors.push(err9); } errors++; } else { if (data4.role !== void 0) { const _errs24 = errors; if (typeof data4.role !== "string") { const err10 = { instancePath: instancePath + "/$actions/" + i0 + "/role", schemaPath: "#/properties/%24actions/items/oneOf/1/properties/role/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err10]; } else { vErrors.push(err10); } errors++; } var valid6 = _errs24 === errors; } else { var valid6 = true; } if (valid6) { if (data4.can !== void 0) { let data10 = data4.can; const _errs27 = errors; if (errors === _errs27) { if (Array.isArray(data10)) { if (data10.length < 1) { const err11 = { instancePath: instancePath + "/$actions/" + i0 + "/can", schemaPath: "#/properties/%24actions/items/oneOf/1/properties/can/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }; if (vErrors === null) { vErrors = [err11]; } else { vErrors.push(err11); } errors++; } else { var valid7 = true; const len2 = data10.length; for (let i2 = 0; i2 < len2; i2++) { let data11 = data10[i2]; const _errs29 = errors; if (typeof data11 !== "string") { const err12 = { instancePath: instancePath + "/$actions/" + i0 + "/can/" + i2, schemaPath: "#/properties/%24actions/items/oneOf/1/properties/can/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }; if (vErrors === null) { vErrors = [err12]; } else { vErrors.push(err12); } errors++; } if (!(data11 === "co-delete" || data11 === "co-update" || data11 === "create" || data11 === "delete" || data11 === "query" || data11 === "subscribe" || data11 === "read" || data11 === "update")) { const err13 = { instancePath: instancePath + "/$actions/" + i0 + "/can/" + i2, schemaPath: "#/properties/%24actions/items/oneOf/1/properties/can/items/enum", keyword: "enum", params: { allowedValues: schema117.properties.$actions.items.oneOf[1].properties.can.items.enum }, message: "must be equal to one of the allowed values" }; if (vErrors === null) { vErrors = [err13]; } else { vErrors.push(err13); } errors++; } var valid7 = _errs29 === errors; if (!valid7) { break; } } } } else { const err14 = { instancePath: instancePath + "/$actions/" + i0 + "/can", schemaPath: "#/properties/%24actions/items/oneOf/1/properties/can/type", keyword: "type", params: { type: "array" }, message: "must be array" }; if (vErrors === null) { vErrors = [err14]; } else { vErrors.push(err14); } errors++; } } var valid6 = _errs27 === errors; } else { var valid6 = true; } } } } var _valid0 = _errs23 === errors; if (_valid0 && valid3) { valid3 = false; passing0 = [passing0, 1]; } else { if (_valid0) { valid3 = true; passing0 = 1; if (props1 !== true) { props1 = props1 || {}; props1.role = true; props1.can = true; } } } if (!valid3) { const err15 = { instancePath: instancePath + "/$actions/" + i0, schemaPath: "#/properties/%24actions/items/oneOf", keyword: "oneOf", params: { passingSchemas: passing0 }, message: "must match exactly one schema in oneOf" }; if (vErrors === null) { vErrors = [err15]; } else { vErrors.push(err15); } errors++; validate75.errors = vErrors; return false; } else { errors = _errs12; if (vErrors !== null) { if (_errs12) { vErrors.length = _errs12; } else { vErrors = null; } } } var valid2 = _errs10 === errors; if (!valid2) { break; } } } } else { validate75.errors = [{ instancePath: instancePath + "/$actions", schemaPath: "#/properties/%24actions/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; return false; } } var valid0 = _errs8 === errors; } else { var valid0 = true; } if (valid0) { if (data.$role !== void 0) { const _errs31 = errors; if (typeof data.$role !== "boolean") { validate75.errors = [{ instancePath: instancePath + "/$role", schemaPath: "#/properties/%24role/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } var valid0 = _errs31 === errors; } else { var valid0 = true; } if (valid0) { if (data.$size !== void 0) { let data13 = data.$size; const _errs34 = errors; if (errors === _errs34) { if (data13 && typeof data13 == "object" && !Array.isArray(data13)) { const _errs36 = errors; for (const key3 in data13) { if (!(key3 === "min" || key3 === "max")) { validate75.errors = [{ instancePath: instancePath + "/$size", schemaPath: "#/properties/%24size/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key3 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs36 === errors) { if (data13.min !== void 0) { let data14 = data13.min; const _errs37 = errors; if (errors === _errs37) { if (typeof data14 == "number" && isFinite(data14)) { if (data14 < 0 || isNaN(data14)) { validate75.errors = [{ instancePath: instancePath + "/$size/min", schemaPath: "#/properties/%24size/properties/min/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; return false; } } else { validate75.errors = [{ instancePath: instancePath + "/$size/min", schemaPath: "#/properties/%24size/properties/min/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } } var valid8 = _errs37 === errors; } else { var valid8 = true; } if (valid8) { if (data13.max !== void 0) { let data15 = data13.max; const _errs39 = errors; if (errors === _errs39) { if (typeof data15 == "number" && isFinite(data15)) { if (data15 < 0 || isNaN(data15)) { validate75.errors = [{ instancePath: instancePath + "/$size/max", schemaPath: "#/properties/%24size/properties/max/minimum", keyword: "minimum", params: { comparison: ">=", limit: 0 }, message: "must be >= 0" }]; return false; } } else { validate75.errors = [{ instancePath: instancePath + "/$size/max", schemaPath: "#/properties/%24size/properties/max/type", keyword: "type", params: { type: "number" }, message: "must be number" }]; return false; } } var valid8 = _errs39 === errors; } else { var valid8 = true; } } } } else { validate75.errors = [{ instancePath: instancePath + "/$size", schemaPath: "#/properties/%24size/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs34 === errors; } else { var valid0 = true; } if (valid0) { if (data.$tags !== void 0) { let data16 = data.$tags; const _errs41 = errors; if (errors === _errs41) { if (data16 && typeof data16 == "object" && !Array.isArray(data16)) { if (Object.keys(data16).length < 1) { validate75.errors = [{ instancePath: instancePath + "/$tags", schemaPath: "#/properties/%24tags/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { if (data16.$requiredTags !== void 0) { let data17 = data16.$requiredTags; const _errs43 = errors; if (errors === _errs43) { if (Array.isArray(data17)) { var valid10 = true; const len3 = data17.length; for (let i3 = 0; i3 < len3; i3++) { const _errs45 = errors; if (typeof data17[i3] !== "string") { validate75.errors = [{ instancePath: instancePath + "/$tags/$requiredTags/" + i3, schemaPath: "#/properties/%24tags/properties/%24requiredTags/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid10 = _errs45 === errors; if (!valid10) { break; } } } else { validate75.errors = [{ instancePath: instancePath + "/$tags/$requiredTags", schemaPath: "#/properties/%24tags/properties/%24requiredTags/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; return false; } } var valid9 = _errs43 === errors; } else { var valid9 = true; } if (valid9) { if (data16.$allowUndefinedTags !== void 0) { const _errs47 = errors; if (typeof data16.$allowUndefinedTags !== "boolean") { validate75.errors = [{ instancePath: instancePath + "/$tags/$allowUndefinedTags", schemaPath: "#/properties/%24tags/properties/%24allowUndefinedTags/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } var valid9 = _errs47 === errors; } else { var valid9 = true; } if (valid9) { var props2 = {}; props2.$requiredTags = true; props2.$allowUndefinedTags = true; for (const key4 in data16) { if (pattern43.test(key4)) { let data20 = data16[key4]; const _errs49 = errors; if (errors === _errs49) { if (data20 && typeof data20 == "object" && !Array.isArray(data20)) { const _errs51 = errors; for (const key5 in data20) { if (!(key5 === "type" || key5 === "items" || key5 === "contains" || pattern44.test(key5))) { validate75.errors = [{ instancePath: instancePath + "/$tags/" + key4.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/%24tags/patternProperties/%5E(%3F!%5C%24requiredTags%24%7C%5C%24allowUndefinedTags%24).*%24/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key5 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs51 === errors) { if (data20.type !== void 0) { let data21 = data20.type; const _errs52 = errors; if (!(data21 === "string" || data21 === "number" || data21 === "integer" || data21 === "boolean" || data21 === "array")) { validate75.errors = [{ instancePath: instancePath + "/$tags/" + key4.replace(/~/g, "~0").replace(/\//g, "~1") + "/type", schemaPath: "#/properties/%24tags/patternProperties/%5E(%3F!%5C%24requiredTags%24%7C%5C%24allowUndefinedTags%24).*%24/properties/type/enum", keyword: "enum", params: { allowedValues: schema117.properties.$tags.patternProperties["^(?!\\$requiredTags$|\\$allowUndefinedTags$).*$"].properties.type.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid12 = _errs52 === errors; } else { var valid12 = true; } if (valid12) { if (data20.items !== void 0) { let data22 = data20.items; const _errs53 = errors; if (errors === _errs53) { if (data22 && typeof data22 == "object" && !Array.isArray(data22)) { if (data22.type !== void 0) { let data23 = data22.type; const _errs55 = errors; if (!(data23 === "string" || data23 === "number" || data23 === "integer")) { validate75.errors = [{ instancePath: instancePath + "/$tags/" + key4.replace(/~/g, "~0").replace(/\//g, "~1") + "/items/type", schemaPath: "#/properties/%24tags/patternProperties/%5E(%3F!%5C%24requiredTags%24%7C%5C%24allowUndefinedTags%24).*%24/properties/items/properties/type/enum", keyword: "enum", params: { allowedValues: schema117.properties.$tags.patternProperties["^(?!\\$requiredTags$|\\$allowUndefinedTags$).*$"].properties.items.properties.type.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid13 = _errs55 === errors; } else { var valid13 = true; } if (valid13) { var props3 = {}; props3.type = true; for (const key6 in data22) { if (pattern45.test(key6)) { props3[key6] = true; } } } } else { validate75.errors = [{ instancePath: instancePath + "/$tags/" + key4.replace(/~/g, "~0").replace(/\//g, "~1") + "/items", schemaPath: "#/properties/%24tags/patternProperties/%5E(%3F!%5C%24requiredTags%24%7C%5C%24allowUndefinedTags%24).*%24/properties/items/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid12 = _errs53 === errors; } else { var valid12 = true; } if (valid12) { if (data20.contains !== void 0) { let data24 = data20.contains; const _errs56 = errors; if (errors === _errs56) { if (data24 && typeof data24 == "object" && !Array.isArray(data24)) { if (data24.type !== void 0) { let data25 = data24.type; const _errs58 = errors; if (!(data25 === "string" || data25 === "number" || data25 === "integer")) { validate75.errors = [{ instancePath: instancePath + "/$tags/" + key4.replace(/~/g, "~0").replace(/\//g, "~1") + "/contains/type", schemaPath: "#/properties/%24tags/patternProperties/%5E(%3F!%5C%24requiredTags%24%7C%5C%24allowUndefinedTags%24).*%24/properties/contains/properties/type/enum", keyword: "enum", params: { allowedValues: schema117.properties.$tags.patternProperties["^(?!\\$requiredTags$|\\$allowUndefinedTags$).*$"].properties.contains.properties.type.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid15 = _errs58 === errors; } else { var valid15 = true; } if (valid15) { var props4 = {}; props4.type = true; for (const key7 in data24) { if (pattern45.test(key7)) { props4[key7] = true; } } } } else { validate75.errors = [{ instancePath: instancePath + "/$tags/" + key4.replace(/~/g, "~0").replace(/\//g, "~1") + "/contains", schemaPath: "#/properties/%24tags/patternProperties/%5E(%3F!%5C%24requiredTags%24%7C%5C%24allowUndefinedTags%24).*%24/properties/contains/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid12 = _errs56 === errors; } else { var valid12 = true; } } } } } else { validate75.errors = [{ instancePath: instancePath + "/$tags/" + key4.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/%24tags/patternProperties/%5E(%3F!%5C%24requiredTags%24%7C%5C%24allowUndefinedTags%24).*%24/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } props2[key4] = true; } } } } } } else { validate75.errors = [{ instancePath: instancePath + "/$tags", schemaPath: "#/properties/%24tags/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs41 === errors; } else { var valid0 = true; } if (valid0) { var valid17 = true; for (const key8 in data) { if (pattern42.test(key8)) { const _errs59 = errors; if (!wrapper2.validate(data[key8], { instancePath: instancePath + "/" + key8.replace(/~/g, "~0").replace(/\//g, "~1"), parentData: data, parentDataProperty: key8, rootData, dynamicAnchors })) { vErrors = vErrors === null ? wrapper2.validate.errors : vErrors.concat(wrapper2.validate.errors); errors = vErrors.length; } var valid17 = _errs59 === errors; if (!valid17) { break; } } } } } } } } } } else { validate75.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate75.errors = vErrors; return errors === 0; } validate75.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; function validate74(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate74.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.protocol === void 0 && (missing0 = "protocol") || data.published === void 0 && (missing0 = "published") || data.types === void 0 && (missing0 = "types") || data.structure === void 0 && (missing0 = "structure")) { validate74.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "protocol" || key0 === "published" || key0 === "types" || key0 === "structure")) { validate74.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.protocol !== void 0) { const _errs2 = errors; if (typeof data.protocol !== "string") { validate74.errors = [{ instancePath: instancePath + "/protocol", schemaPath: "#/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.published !== void 0) { const _errs4 = errors; if (typeof data.published !== "boolean") { validate74.errors = [{ instancePath: instancePath + "/published", schemaPath: "#/properties/published/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }]; return false; } var valid0 = _errs4 === errors; } else { var valid0 = true; } if (valid0) { if (data.types !== void 0) { let data2 = data.types; const _errs6 = errors; if (errors === _errs6) { if (data2 && typeof data2 == "object" && !Array.isArray(data2)) { var props0 = {}; for (const key1 in data2) { if (pattern40.test(key1)) { let data3 = data2[key1]; const _errs8 = errors; if (errors === _errs8) { if (data3 && typeof data3 == "object" && !Array.isArray(data3)) { const _errs10 = errors; for (const key2 in data3) { if (!(key2 === "schema" || key2 === "dataFormats")) { validate74.errors = [{ instancePath: instancePath + "/types/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/types/patternProperties/.*/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs10 === errors) { if (data3.schema !== void 0) { const _errs11 = errors; if (typeof data3.schema !== "string") { validate74.errors = [{ instancePath: instancePath + "/types/" + key1.replace(/~/g, "~0").replace(/\//g, "~1") + "/schema", schemaPath: "#/properties/types/patternProperties/.*/properties/schema/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid2 = _errs11 === errors; } else { var valid2 = true; } if (valid2) { if (data3.dataFormats !== void 0) { let data5 = data3.dataFormats; const _errs13 = errors; if (errors === _errs13) { if (Array.isArray(data5)) { if (data5.length < 1) { validate74.errors = [{ instancePath: instancePath + "/types/" + key1.replace(/~/g, "~0").replace(/\//g, "~1") + "/dataFormats", schemaPath: "#/properties/types/patternProperties/.*/properties/dataFormats/minItems", keyword: "minItems", params: { limit: 1 }, message: "must NOT have fewer than 1 items" }]; return false; } else { var valid3 = true; const len0 = data5.length; for (let i0 = 0; i0 < len0; i0++) { const _errs15 = errors; if (typeof data5[i0] !== "string") { validate74.errors = [{ instancePath: instancePath + "/types/" + key1.replace(/~/g, "~0").replace(/\//g, "~1") + "/dataFormats/" + i0, schemaPath: "#/properties/types/patternProperties/.*/properties/dataFormats/items/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid3 = _errs15 === errors; if (!valid3) { break; } } } } else { validate74.errors = [{ instancePath: instancePath + "/types/" + key1.replace(/~/g, "~0").replace(/\//g, "~1") + "/dataFormats", schemaPath: "#/properties/types/patternProperties/.*/properties/dataFormats/type", keyword: "type", params: { type: "array" }, message: "must be array" }]; return false; } } var valid2 = _errs13 === errors; } else { var valid2 = true; } } } } else { validate74.errors = [{ instancePath: instancePath + "/types/" + key1.replace(/~/g, "~0").replace(/\//g, "~1"), schemaPath: "#/properties/types/patternProperties/.*/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } props0[key1] = true; } } } else { validate74.errors = [{ instancePath: instancePath + "/types", schemaPath: "#/properties/types/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs6 === errors; } else { var valid0 = true; } if (valid0) { if (data.structure !== void 0) { let data7 = data.structure; const _errs17 = errors; if (errors === _errs17) { if (data7 && typeof data7 == "object" && !Array.isArray(data7)) { var props1 = {}; for (const key3 in data7) { if (pattern40.test(key3)) { if (!validate75(data7[key3], { instancePath: instancePath + "/structure/" + key3.replace(/~/g, "~0").replace(/\//g, "~1"), parentData: data7, parentDataProperty: key3, rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate75.errors : vErrors.concat(validate75.errors); errors = vErrors.length; } props1[key3] = true; } } } else { validate74.errors = [{ instancePath: instancePath + "/structure", schemaPath: "#/properties/structure/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs17 === errors; } else { var valid0 = true; } } } } } } } else { validate74.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate74.errors = vErrors; return errors === 0; } validate74.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var ProtocolRuleSet = validate75; var ProtocolsConfigure = validate78; var schema118 = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://identity.foundation/dwn/json-schemas/protocols-configure.json", "type": "object", "additionalProperties": false, "required": ["authorization", "descriptor"], "properties": { "authorization": { "$ref": "https://identity.foundation/dwn/json-schemas/authorization.json" }, "descriptor": { "type": "object", "additionalProperties": false, "required": ["interface", "method", "messageTimestamp", "definition"], "properties": { "interface": { "enum": ["Protocols"], "type": "string" }, "method": { "enum": ["Configure"], "type": "string" }, "messageTimestamp": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" }, "definition": { "$ref": "https://identity.foundation/dwn/json-schemas/protocol-definition.json" } } } } }; function validate78(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate78.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.authorization === void 0 && (missing0 = "authorization") || data.descriptor === void 0 && (missing0 = "descriptor")) { validate78.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "authorization" || key0 === "descriptor")) { validate78.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.authorization !== void 0) { const _errs2 = errors; if (!validate20(data.authorization, { instancePath: instancePath + "/authorization", parentData: data, parentDataProperty: "authorization", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate20.errors : vErrors.concat(validate20.errors); errors = vErrors.length; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.descriptor !== void 0) { let data1 = data.descriptor; const _errs3 = errors; if (errors === _errs3) { if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { let missing1; if (data1.interface === void 0 && (missing1 = "interface") || data1.method === void 0 && (missing1 = "method") || data1.messageTimestamp === void 0 && (missing1 = "messageTimestamp") || data1.definition === void 0 && (missing1 = "definition")) { validate78.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }]; return false; } else { const _errs5 = errors; for (const key1 in data1) { if (!(key1 === "interface" || key1 === "method" || key1 === "messageTimestamp" || key1 === "definition")) { validate78.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs5 === errors) { if (data1.interface !== void 0) { let data2 = data1.interface; const _errs6 = errors; if (typeof data2 !== "string") { validate78.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data2 === "Protocols")) { validate78.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/enum", keyword: "enum", params: { allowedValues: schema118.properties.descriptor.properties.interface.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs6 === errors; } else { var valid1 = true; } if (valid1) { if (data1.method !== void 0) { let data3 = data1.method; const _errs8 = errors; if (typeof data3 !== "string") { validate78.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data3 === "Configure")) { validate78.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/enum", keyword: "enum", params: { allowedValues: schema118.properties.descriptor.properties.method.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs8 === errors; } else { var valid1 = true; } if (valid1) { if (data1.messageTimestamp !== void 0) { let data4 = data1.messageTimestamp; const _errs10 = errors; const _errs11 = errors; if (errors === _errs11) { if (typeof data4 === "string") { if (!pattern14.test(data4)) { validate78.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate78.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid1 = _errs10 === errors; } else { var valid1 = true; } if (valid1) { if (data1.definition !== void 0) { const _errs13 = errors; if (!validate74(data1.definition, { instancePath: instancePath + "/descriptor/definition", parentData: data1, parentDataProperty: "definition", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate74.errors : vErrors.concat(validate74.errors); errors = vErrors.length; } var valid1 = _errs13 === errors; } else { var valid1 = true; } } } } } } } else { validate78.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs3 === errors; } else { var valid0 = true; } } } } } else { validate78.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate78.errors = vErrors; return errors === 0; } validate78.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var ProtocolsQuery = validate81; var schema120 = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://identity.foundation/dwn/json-schemas/protocols-query.json", "type": "object", "additionalProperties": false, "required": ["descriptor"], "properties": { "authorization": { "$ref": "https://identity.foundation/dwn/json-schemas/authorization.json" }, "descriptor": { "type": "object", "additionalProperties": false, "required": ["interface", "method", "messageTimestamp"], "properties": { "interface": { "enum": ["Protocols"], "type": "string" }, "method": { "enum": ["Query"], "type": "string" }, "messageTimestamp": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" }, "filter": { "type": "object", "minProperties": 1, "additionalProperties": false, "properties": { "protocol": { "type": "string" }, "recipient": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did" } } } } } } }; function validate81(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate81.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.descriptor === void 0 && (missing0 = "descriptor")) { validate81.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "authorization" || key0 === "descriptor")) { validate81.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.authorization !== void 0) { const _errs2 = errors; if (!validate20(data.authorization, { instancePath: instancePath + "/authorization", parentData: data, parentDataProperty: "authorization", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate20.errors : vErrors.concat(validate20.errors); errors = vErrors.length; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.descriptor !== void 0) { let data1 = data.descriptor; const _errs3 = errors; if (errors === _errs3) { if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { let missing1; if (data1.interface === void 0 && (missing1 = "interface") || data1.method === void 0 && (missing1 = "method") || data1.messageTimestamp === void 0 && (missing1 = "messageTimestamp")) { validate81.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }]; return false; } else { const _errs5 = errors; for (const key1 in data1) { if (!(key1 === "interface" || key1 === "method" || key1 === "messageTimestamp" || key1 === "filter")) { validate81.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs5 === errors) { if (data1.interface !== void 0) { let data2 = data1.interface; const _errs6 = errors; if (typeof data2 !== "string") { validate81.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data2 === "Protocols")) { validate81.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/enum", keyword: "enum", params: { allowedValues: schema120.properties.descriptor.properties.interface.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs6 === errors; } else { var valid1 = true; } if (valid1) { if (data1.method !== void 0) { let data3 = data1.method; const _errs8 = errors; if (typeof data3 !== "string") { validate81.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data3 === "Query")) { validate81.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/enum", keyword: "enum", params: { allowedValues: schema120.properties.descriptor.properties.method.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs8 === errors; } else { var valid1 = true; } if (valid1) { if (data1.messageTimestamp !== void 0) { let data4 = data1.messageTimestamp; const _errs10 = errors; const _errs11 = errors; if (errors === _errs11) { if (typeof data4 === "string") { if (!pattern14.test(data4)) { validate81.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate81.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid1 = _errs10 === errors; } else { var valid1 = true; } if (valid1) { if (data1.filter !== void 0) { let data5 = data1.filter; const _errs13 = errors; if (errors === _errs13) { if (data5 && typeof data5 == "object" && !Array.isArray(data5)) { if (Object.keys(data5).length < 1) { validate81.errors = [{ instancePath: instancePath + "/descriptor/filter", schemaPath: "#/properties/descriptor/properties/filter/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { const _errs15 = errors; for (const key2 in data5) { if (!(key2 === "protocol" || key2 === "recipient")) { validate81.errors = [{ instancePath: instancePath + "/descriptor/filter", schemaPath: "#/properties/descriptor/properties/filter/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key2 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs15 === errors) { if (data5.protocol !== void 0) { const _errs16 = errors; if (typeof data5.protocol !== "string") { validate81.errors = [{ instancePath: instancePath + "/descriptor/filter/protocol", schemaPath: "#/properties/descriptor/properties/filter/properties/protocol/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid3 = _errs16 === errors; } else { var valid3 = true; } if (valid3) { if (data5.recipient !== void 0) { let data7 = data5.recipient; const _errs18 = errors; const _errs19 = errors; if (errors === _errs19) { if (typeof data7 === "string") { if (!pattern12.test(data7)) { validate81.errors = [{ instancePath: instancePath + "/descriptor/filter/recipient", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did/pattern", keyword: "pattern", params: { pattern: "^did:([a-z0-9]+):((?:(?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))*:)*((?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))+))((;[a-zA-Z0-9_.:%-]+=[a-zA-Z0-9_.:%-]*)*)(/[^#?]*)?([?][^#]*)?(#.*)?$" }, message: 'must match pattern "^did:([a-z0-9]+):((?:(?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))*:)*((?:[a-zA-Z0-9._-]|(?:%[0-9a-fA-F]{2}))+))((;[a-zA-Z0-9_.:%-]+=[a-zA-Z0-9_.:%-]*)*)(/[^#?]*)?([?][^#]*)?(#.*)?$"' }]; return false; } } else { validate81.errors = [{ instancePath: instancePath + "/descriptor/filter/recipient", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/did/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid3 = _errs18 === errors; } else { var valid3 = true; } } } } } else { validate81.errors = [{ instancePath: instancePath + "/descriptor/filter", schemaPath: "#/properties/descriptor/properties/filter/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid1 = _errs13 === errors; } else { var valid1 = true; } } } } } } } else { validate81.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs3 === errors; } else { var valid0 = true; } } } } } else { validate81.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate81.errors = vErrors; return errors === 0; } validate81.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var RecordsRead = validate83; var schema123 = { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://identity.foundation/dwn/json-schemas/records-read.json", "type": "object", "additionalProperties": false, "required": ["descriptor"], "properties": { "authorization": { "$ref": "https://identity.foundation/dwn/json-schemas/authorization-delegated-grant.json" }, "descriptor": { "type": "object", "additionalProperties": false, "required": ["interface", "method", "messageTimestamp", "filter"], "properties": { "interface": { "enum": ["Records"], "type": "string" }, "method": { "enum": ["Read"], "type": "string" }, "messageTimestamp": { "$ref": "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time" }, "filter": { "$ref": "https://identity.foundation/dwn/json-schemas/records-filter.json" } } } } }; function validate83(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate83.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.descriptor === void 0 && (missing0 = "descriptor")) { validate83.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "authorization" || key0 === "descriptor")) { validate83.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.authorization !== void 0) { const _errs2 = errors; if (!validate24(data.authorization, { instancePath: instancePath + "/authorization", parentData: data, parentDataProperty: "authorization", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate24.errors : vErrors.concat(validate24.errors); errors = vErrors.length; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.descriptor !== void 0) { let data1 = data.descriptor; const _errs3 = errors; if (errors === _errs3) { if (data1 && typeof data1 == "object" && !Array.isArray(data1)) { let missing1; if (data1.interface === void 0 && (missing1 = "interface") || data1.method === void 0 && (missing1 = "method") || data1.messageTimestamp === void 0 && (missing1 = "messageTimestamp") || data1.filter === void 0 && (missing1 = "filter")) { validate83.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }]; return false; } else { const _errs5 = errors; for (const key1 in data1) { if (!(key1 === "interface" || key1 === "method" || key1 === "messageTimestamp" || key1 === "filter")) { validate83.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key1 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs5 === errors) { if (data1.interface !== void 0) { let data2 = data1.interface; const _errs6 = errors; if (typeof data2 !== "string") { validate83.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data2 === "Records")) { validate83.errors = [{ instancePath: instancePath + "/descriptor/interface", schemaPath: "#/properties/descriptor/properties/interface/enum", keyword: "enum", params: { allowedValues: schema123.properties.descriptor.properties.interface.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs6 === errors; } else { var valid1 = true; } if (valid1) { if (data1.method !== void 0) { let data3 = data1.method; const _errs8 = errors; if (typeof data3 !== "string") { validate83.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } if (!(data3 === "Read")) { validate83.errors = [{ instancePath: instancePath + "/descriptor/method", schemaPath: "#/properties/descriptor/properties/method/enum", keyword: "enum", params: { allowedValues: schema123.properties.descriptor.properties.method.enum }, message: "must be equal to one of the allowed values" }]; return false; } var valid1 = _errs8 === errors; } else { var valid1 = true; } if (valid1) { if (data1.messageTimestamp !== void 0) { let data4 = data1.messageTimestamp; const _errs10 = errors; const _errs11 = errors; if (errors === _errs11) { if (typeof data4 === "string") { if (!pattern14.test(data4)) { validate83.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/pattern", keyword: "pattern", params: { pattern: "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$" }, message: 'must match pattern "^\\d{4}-[0-1]\\d-[0-3]\\dT(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)\\.\\d{6}Z$"' }]; return false; } } else { validate83.errors = [{ instancePath: instancePath + "/descriptor/messageTimestamp", schemaPath: "https://identity.foundation/dwn/json-schemas/defs.json#/$defs/date-time/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } } var valid1 = _errs10 === errors; } else { var valid1 = true; } if (valid1) { if (data1.filter !== void 0) { const _errs13 = errors; if (!validate42(data1.filter, { instancePath: instancePath + "/descriptor/filter", parentData: data1, parentDataProperty: "filter", rootData, dynamicAnchors })) { vErrors = vErrors === null ? validate42.errors : vErrors.concat(validate42.errors); errors = vErrors.length; } var valid1 = _errs13 === errors; } else { var valid1 = true; } } } } } } } else { validate83.errors = [{ instancePath: instancePath + "/descriptor", schemaPath: "#/properties/descriptor/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } var valid0 = _errs3 === errors; } else { var valid0 = true; } } } } } else { validate83.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate83.errors = vErrors; return errors === 0; } validate83.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var RecordsFilter = validate42; var PublicJwk = validate33; var GenericSignaturePayload = validate86; function validate86(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate86.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.descriptorCid === void 0 && (missing0 = "descriptorCid")) { validate86.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "descriptorCid" || key0 === "delegatedGrantId" || key0 === "permissionGrantId" || key0 === "protocolRole")) { validate86.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.descriptorCid !== void 0) { const _errs2 = errors; if (typeof data.descriptorCid !== "string") { validate86.errors = [{ instancePath: instancePath + "/descriptorCid", schemaPath: "#/properties/descriptorCid/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.delegatedGrantId !== void 0) { const _errs4 = errors; if (typeof data.delegatedGrantId !== "string") { validate86.errors = [{ instancePath: instancePath + "/delegatedGrantId", schemaPath: "#/properties/delegatedGrantId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs4 === errors; } else { var valid0 = true; } if (valid0) { if (data.permissionGrantId !== void 0) { const _errs6 = errors; if (typeof data.permissionGrantId !== "string") { validate86.errors = [{ instancePath: instancePath + "/permissionGrantId", schemaPath: "#/properties/permissionGrantId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs6 === errors; } else { var valid0 = true; } if (valid0) { if (data.protocolRole !== void 0) { const _errs8 = errors; if (typeof data.protocolRole !== "string") { validate86.errors = [{ instancePath: instancePath + "/protocolRole", schemaPath: "#/properties/protocolRole/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs8 === errors; } else { var valid0 = true; } } } } } } } else { validate86.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate86.errors = vErrors; return errors === 0; } validate86.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var RecordsWriteSignaturePayload = validate87; function validate87(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate87.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.descriptorCid === void 0 && (missing0 = "descriptorCid") || data.recordId === void 0 && (missing0 = "recordId")) { validate87.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "descriptorCid" || key0 === "recordId" || key0 === "contextId" || key0 === "attestationCid" || key0 === "encryptionCid" || key0 === "delegatedGrantId" || key0 === "permissionGrantId" || key0 === "protocolRole")) { validate87.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.descriptorCid !== void 0) { const _errs2 = errors; if (typeof data.descriptorCid !== "string") { validate87.errors = [{ instancePath: instancePath + "/descriptorCid", schemaPath: "#/properties/descriptorCid/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.recordId !== void 0) { const _errs4 = errors; if (typeof data.recordId !== "string") { validate87.errors = [{ instancePath: instancePath + "/recordId", schemaPath: "#/properties/recordId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs4 === errors; } else { var valid0 = true; } if (valid0) { if (data.contextId !== void 0) { const _errs6 = errors; if (typeof data.contextId !== "string") { validate87.errors = [{ instancePath: instancePath + "/contextId", schemaPath: "#/properties/contextId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs6 === errors; } else { var valid0 = true; } if (valid0) { if (data.attestationCid !== void 0) { const _errs8 = errors; if (typeof data.attestationCid !== "string") { validate87.errors = [{ instancePath: instancePath + "/attestationCid", schemaPath: "#/properties/attestationCid/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs8 === errors; } else { var valid0 = true; } if (valid0) { if (data.encryptionCid !== void 0) { const _errs10 = errors; if (typeof data.encryptionCid !== "string") { validate87.errors = [{ instancePath: instancePath + "/encryptionCid", schemaPath: "#/properties/encryptionCid/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs10 === errors; } else { var valid0 = true; } if (valid0) { if (data.delegatedGrantId !== void 0) { const _errs12 = errors; if (typeof data.delegatedGrantId !== "string") { validate87.errors = [{ instancePath: instancePath + "/delegatedGrantId", schemaPath: "#/properties/delegatedGrantId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs12 === errors; } else { var valid0 = true; } if (valid0) { if (data.permissionGrantId !== void 0) { const _errs14 = errors; if (typeof data.permissionGrantId !== "string") { validate87.errors = [{ instancePath: instancePath + "/permissionGrantId", schemaPath: "#/properties/permissionGrantId/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs14 === errors; } else { var valid0 = true; } if (valid0) { if (data.protocolRole !== void 0) { const _errs16 = errors; if (typeof data.protocolRole !== "string") { validate87.errors = [{ instancePath: instancePath + "/protocolRole", schemaPath: "#/properties/protocolRole/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid0 = _errs16 === errors; } else { var valid0 = true; } } } } } } } } } } } else { validate87.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate87.errors = vErrors; return errors === 0; } validate87.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; var StringRangeFilter = validate88; function validate88(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { ; let vErrors = null; let errors = 0; const evaluated0 = validate88.evaluated; if (evaluated0.dynamicProps) { evaluated0.props = void 0; } if (evaluated0.dynamicItems) { evaluated0.items = void 0; } if (errors === 0) { if (data && typeof data == "object" && !Array.isArray(data)) { if (Object.keys(data).length < 1) { validate88.errors = [{ instancePath, schemaPath: "#/minProperties", keyword: "minProperties", params: { limit: 1 }, message: "must NOT have fewer than 1 properties" }]; return false; } else { const _errs1 = errors; for (const key0 in data) { if (!(key0 === "gt" || key0 === "gte" || key0 === "lt" || key0 === "lte")) { validate88.errors = [{ instancePath, schemaPath: "#/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" }]; return false; break; } } if (_errs1 === errors) { if (data.gt !== void 0) { const _errs2 = errors; const _errs3 = errors; const _errs4 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing0; if (data.gte === void 0 && (missing0 = "gte")) { const err0 = {}; if (vErrors === null) { vErrors = [err0]; } else { vErrors.push(err0); } errors++; } } var valid1 = _errs4 === errors; if (valid1) { validate88.errors = [{ instancePath, schemaPath: "#/dependencies/gt/not", keyword: "not", params: {}, message: "must NOT be valid" }]; return false; } else { errors = _errs3; if (vErrors !== null) { if (_errs3) { vErrors.length = _errs3; } else { vErrors = null; } } } var valid0 = _errs2 === errors; } else { var valid0 = true; } if (valid0) { if (data.gte !== void 0) { const _errs5 = errors; const _errs6 = errors; const _errs7 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing1; if (data.gt === void 0 && (missing1 = "gt")) { const err1 = {}; if (vErrors === null) { vErrors = [err1]; } else { vErrors.push(err1); } errors++; } } var valid2 = _errs7 === errors; if (valid2) { validate88.errors = [{ instancePath, schemaPath: "#/dependencies/gte/not", keyword: "not", params: {}, message: "must NOT be valid" }]; return false; } else { errors = _errs6; if (vErrors !== null) { if (_errs6) { vErrors.length = _errs6; } else { vErrors = null; } } } var valid0 = _errs5 === errors; } else { var valid0 = true; } if (valid0) { if (data.lt !== void 0) { const _errs8 = errors; const _errs9 = errors; const _errs10 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing2; if (data.lte === void 0 && (missing2 = "lte")) { const err22 = {}; if (vErrors === null) { vErrors = [err22]; } else { vErrors.push(err22); } errors++; } } var valid3 = _errs10 === errors; if (valid3) { validate88.errors = [{ instancePath, schemaPath: "#/dependencies/lt/not", keyword: "not", params: {}, message: "must NOT be valid" }]; return false; } else { errors = _errs9; if (vErrors !== null) { if (_errs9) { vErrors.length = _errs9; } else { vErrors = null; } } } var valid0 = _errs8 === errors; } else { var valid0 = true; } if (valid0) { if (data.lte !== void 0) { const _errs11 = errors; const _errs12 = errors; const _errs13 = errors; if (data && typeof data == "object" && !Array.isArray(data)) { let missing3; if (data.lt === void 0 && (missing3 = "lt")) { const err3 = {}; if (vErrors === null) { vErrors = [err3]; } else { vErrors.push(err3); } errors++; } } var valid4 = _errs13 === errors; if (valid4) { validate88.errors = [{ instancePath, schemaPath: "#/dependencies/lte/not", keyword: "not", params: {}, message: "must NOT be valid" }]; return false; } else { errors = _errs12; if (vErrors !== null) { if (_errs12) { vErrors.length = _errs12; } else { vErrors = null; } } } var valid0 = _errs11 === errors; } else { var valid0 = true; } if (valid0) { if (data.gt !== void 0) { const _errs14 = errors; if (typeof data.gt !== "string") { validate88.errors = [{ instancePath: instancePath + "/gt", schemaPath: "#/properties/gt/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid5 = _errs14 === errors; } else { var valid5 = true; } if (valid5) { if (data.gte !== void 0) { const _errs16 = errors; if (typeof data.gte !== "string") { validate88.errors = [{ instancePath: instancePath + "/gte", schemaPath: "#/properties/gte/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid5 = _errs16 === errors; } else { var valid5 = true; } if (valid5) { if (data.lt !== void 0) { const _errs18 = errors; if (typeof data.lt !== "string") { validate88.errors = [{ instancePath: instancePath + "/lt", schemaPath: "#/properties/lt/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid5 = _errs18 === errors; } else { var valid5 = true; } if (valid5) { if (data.lte !== void 0) { const _errs20 = errors; if (typeof data.lte !== "string") { validate88.errors = [{ instancePath: instancePath + "/lte", schemaPath: "#/properties/lte/type", keyword: "type", params: { type: "string" }, message: "must be string" }]; return false; } var valid5 = _errs20 === errors; } else { var valid5 = true; } } } } } } } } } } } else { validate88.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }]; return false; } } validate88.errors = vErrors; return errors === 0; } validate88.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": false }; // dist/esm/src/schema-validator.js function validateJsonSchema(schemaName, payload) { const validateFn = precompiled_validators_exports[schemaName]; if (!validateFn) { throw new DwnError(DwnErrorCode.SchemaValidatorSchemaNotFound, `schema for ${schemaName} not found.`); } validateFn(payload); if (!validateFn.errors) { return; } const [errorObj] = validateFn.errors; let { instancePath, message: message2, keyword } = errorObj; if (!instancePath) { instancePath = schemaName; } if (keyword === "additionalProperties") { const keyword2 = errorObj.params.additionalProperty; throw new DwnError(DwnErrorCode.SchemaValidatorAdditionalPropertyNotAllowed, `${message2}: ${instancePath}: ${keyword2}`); } if (keyword === "unevaluatedProperties") { const keyword2 = errorObj.params.unevaluatedProperty; throw new DwnError(DwnErrorCode.SchemaValidatorUnevaluatedPropertyNotAllowed, `${message2}: ${instancePath}: ${keyword2}`); } throw new DwnError(DwnErrorCode.SchemaValidatorFailure, `${instancePath}: ${message2}`); } // dist/esm/src/jose/jws/general/verifier.js var __awaiter7 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var GeneralJwsVerifier = class { constructor(cache5) { this.cache = cache5 || new MemoryCache(600); } static get singleton() { if (GeneralJwsVerifier._singleton === void 0) { GeneralJwsVerifier._singleton = new GeneralJwsVerifier(); } return GeneralJwsVerifier._singleton; } /** * Verifies the signatures of the given General JWS. * @returns the list of signers that have valid signatures. */ static verifySignatures(jws, didResolver) { return __awaiter7(this, void 0, void 0, function* () { return yield GeneralJwsVerifier.singleton.verifySignatures(jws, didResolver); }); } /** * Verifies the signatures of the given General JWS. * @returns the list of signers that have valid signatures. */ verifySignatures(jws, didResolver) { return __awaiter7(this, void 0, void 0, function* () { const signers = []; for (const signatureEntry of jws.signatures) { let isVerified; const kid = Jws.getKid(signatureEntry); const cacheKey = `${signatureEntry.protected}.${jws.payload}.${signatureEntry.signature}`; const cachedValue = yield this.cache.get(cacheKey); if (cachedValue === void 0) { const publicJwk = yield GeneralJwsVerifier.getPublicKey(kid, didResolver); isVerified = yield Jws.verifySignature(jws.payload, signatureEntry, publicJwk); yield this.cache.set(cacheKey, isVerified); } else { isVerified = cachedValue; } const did = Jws.extractDid(kid); if (isVerified) { signers.push(did); } else { throw new DwnError(DwnErrorCode.GeneralJwsVerifierInvalidSignature, `Signature verification failed for ${did}`); } } return { signers }; }); } /** * Gets the public key given a fully qualified key ID (`kid`) by resolving the DID to its DID Document. */ static getPublicKey(kid, didResolver) { return __awaiter7(this, void 0, void 0, function* () { const did = Jws.extractDid(kid); const { didDocument } = yield didResolver.resolve(did); const { verificationMethod: verificationMethods = [] } = didDocument || {}; let verificationMethod; for (const method of verificationMethods) { if (kid.endsWith(method.id)) { verificationMethod = method; break; } } if (!verificationMethod) { throw new DwnError(DwnErrorCode.GeneralJwsVerifierGetPublicKeyNotFound, "public key needed to verify signature not found in DID Document"); } validateJsonSchema("JwkVerificationMethod", verificationMethod); const { publicKeyJwk: publicJwk } = verificationMethod; return publicJwk; }); } }; // node_modules/@ipld/dag-cbor/src/index.js var src_exports = {}; __export(src_exports, { code: () => code3, decode: () => decode12, encode: () => encode9, name: () => name3 }); // node_modules/cborg/esm/lib/is.js var typeofs = [ "string", "number", "bigint", "symbol" ]; var objectTypeNames = [ "Function", "Generator", "AsyncGenerator", "GeneratorFunction", "AsyncGeneratorFunction", "AsyncFunction", "Observable", "Array", "Buffer", "Object", "RegExp", "Date", "Error", "Map", "Set", "WeakMap", "WeakSet", "ArrayBuffer", "SharedArrayBuffer", "DataView", "Promise", "URL", "HTMLElement", "Int8Array", "Uint8Array", "Uint8ClampedArray", "Int16Array", "Uint16Array", "Int32Array", "Uint32Array", "Float32Array", "Float64Array", "BigInt64Array", "BigUint64Array" ]; function is(value) { if (value === null) { return "null"; } if (value === void 0) { return "undefined"; } if (value === true || value === false) { return "boolean"; } const typeOf = typeof value; if (typeofs.includes(typeOf)) { return typeOf; } if (typeOf === "function") { return "Function"; } if (Array.isArray(value)) { return "Array"; } if (isBuffer(value)) { return "Buffer"; } const objectType = getObjectType(value); if (objectType) { return objectType; } return "Object"; } function isBuffer(value) { return value && value.constructor && value.constructor.isBuffer && value.constructor.isBuffer.call(null, value); } function getObjectType(value) { const objectTypeName = Object.prototype.toString.call(value).slice(8, -1); if (objectTypeNames.includes(objectTypeName)) { return objectTypeName; } return void 0; } // node_modules/cborg/esm/lib/token.js var Type = class { constructor(major, name5, terminal) { this.major = major; this.majorEncoded = major << 5; this.name = name5; this.terminal = terminal; } toString() { return `Type[${this.major}].${this.name}`; } compare(typ) { return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0; } }; Type.uint = new Type(0, "uint", true); Type.negint = new Type(1, "negint", true); Type.bytes = new Type(2, "bytes", true); Type.string = new Type(3, "string", true); Type.array = new Type(4, "array", false); Type.map = new Type(5, "map", false); Type.tag = new Type(6, "tag", false); Type.float = new Type(7, "float", true); Type.false = new Type(7, "false", true); Type.true = new Type(7, "true", true); Type.null = new Type(7, "null", true); Type.undefined = new Type(7, "undefined", true); Type.break = new Type(7, "break", true); var Token = class { constructor(type, value, encodedLength) { this.type = type; this.value = value; this.encodedLength = encodedLength; this.encodedBytes = void 0; this.byteValue = void 0; } toString() { return `Token[${this.type}].${this.value}`; } }; // node_modules/cborg/esm/lib/byte-utils.js var useBuffer = globalThis.process && !globalThis.process.browser && globalThis.Buffer && typeof globalThis.Buffer.isBuffer === "function"; var textDecoder3 = new TextDecoder(); var textEncoder3 = new TextEncoder(); function isBuffer2(buf2) { return useBuffer && globalThis.Buffer.isBuffer(buf2); } function asU8A(buf2) { if (!(buf2 instanceof Uint8Array)) { return Uint8Array.from(buf2); } return isBuffer2(buf2) ? new Uint8Array(buf2.buffer, buf2.byteOffset, buf2.byteLength) : buf2; } var toString3 = useBuffer ? (bytes2, start, end) => { return end - start > 64 ? globalThis.Buffer.from(bytes2.subarray(start, end)).toString("utf8") : utf8Slice(bytes2, start, end); } : (bytes2, start, end) => { return end - start > 64 ? textDecoder3.decode(bytes2.subarray(start, end)) : utf8Slice(bytes2, start, end); }; var fromString3 = useBuffer ? (string2) => { return string2.length > 64 ? globalThis.Buffer.from(string2) : utf8ToBytes3(string2); } : (string2) => { return string2.length > 64 ? textEncoder3.encode(string2) : utf8ToBytes3(string2); }; var fromArray = (arr) => { return Uint8Array.from(arr); }; var slice = useBuffer ? (bytes2, start, end) => { if (isBuffer2(bytes2)) { return new Uint8Array(bytes2.subarray(start, end)); } return bytes2.slice(start, end); } : (bytes2, start, end) => { return bytes2.slice(start, end); }; var concat2 = useBuffer ? (chunks, length5) => { chunks = chunks.map((c) => c instanceof Uint8Array ? c : globalThis.Buffer.from(c)); return asU8A(globalThis.Buffer.concat(chunks, length5)); } : (chunks, length5) => { const out = new Uint8Array(length5); let off = 0; for (let b of chunks) { if (off + b.length > out.length) { b = b.subarray(0, out.length - off); } out.set(b, off); off += b.length; } return out; }; var alloc2 = useBuffer ? (size) => { return globalThis.Buffer.allocUnsafe(size); } : (size) => { return new Uint8Array(size); }; function compare2(b1, b2) { if (isBuffer2(b1) && isBuffer2(b2)) { return b1.compare(b2); } for (let i = 0; i < b1.length; i++) { if (b1[i] === b2[i]) { continue; } return b1[i] < b2[i] ? -1 : 1; } return 0; } function utf8ToBytes3(string2, units = Infinity) { let codePoint; const length5 = string2.length; let leadSurrogate = null; const bytes2 = []; for (let i = 0; i < length5; ++i) { codePoint = string2.charCodeAt(i); if (codePoint > 55295 && codePoint < 57344) { if (!leadSurrogate) { if (codePoint > 56319) { if ((units -= 3) > -1) bytes2.push(239, 191, 189); continue; } else if (i + 1 === length5) { if ((units -= 3) > -1) bytes2.push(239, 191, 189); continue; } leadSurrogate = codePoint; continue; } if (codePoint < 56320) { if ((units -= 3) > -1) bytes2.push(239, 191, 189); leadSurrogate = codePoint; continue; } codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; } else if (leadSurrogate) { if ((units -= 3) > -1) bytes2.push(239, 191, 189); } leadSurrogate = null; if (codePoint < 128) { if ((units -= 1) < 0) break; bytes2.push(codePoint); } else if (codePoint < 2048) { if ((units -= 2) < 0) break; bytes2.push(codePoint >> 6 | 192, codePoint & 63 | 128); } else if (codePoint < 65536) { if ((units -= 3) < 0) break; bytes2.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128); } else if (codePoint < 1114112) { if ((units -= 4) < 0) break; bytes2.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128); } else { throw new Error("Invalid code point"); } } return bytes2; } function utf8Slice(buf2, offset, end) { const res = []; while (offset < end) { const firstByte = buf2[offset]; let codePoint = null; let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; if (offset + bytesPerSequence <= end) { let secondByte, thirdByte, fourthByte, tempCodePoint; switch (bytesPerSequence) { case 1: if (firstByte < 128) { codePoint = firstByte; } break; case 2: secondByte = buf2[offset + 1]; if ((secondByte & 192) === 128) { tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; if (tempCodePoint > 127) { codePoint = tempCodePoint; } } break; case 3: secondByte = buf2[offset + 1]; thirdByte = buf2[offset + 2]; if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { codePoint = tempCodePoint; } } break; case 4: secondByte = buf2[offset + 1]; thirdByte = buf2[offset + 2]; fourthByte = buf2[offset + 3]; if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; if (tempCodePoint > 65535 && tempCodePoint < 1114112) { codePoint = tempCodePoint; } } } } if (codePoint === null) { codePoint = 65533; bytesPerSequence = 1; } else if (codePoint > 65535) { codePoint -= 65536; res.push(codePoint >>> 10 & 1023 | 55296); codePoint = 56320 | codePoint & 1023; } res.push(codePoint); offset += bytesPerSequence; } return decodeCodePointsArray(res); } var MAX_ARGUMENTS_LENGTH = 4096; function decodeCodePointsArray(codePoints) { const len = codePoints.length; if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints); } let res = ""; let i = 0; while (i < len) { res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); } return res; } // node_modules/cborg/esm/lib/bl.js var defaultChunkSize = 256; var Bl = class { constructor(chunkSize = defaultChunkSize) { this.chunkSize = chunkSize; this.cursor = 0; this.maxCursor = -1; this.chunks = []; this._initReuseChunk = null; } reset() { this.cursor = 0; this.maxCursor = -1; if (this.chunks.length) { this.chunks = []; } if (this._initReuseChunk !== null) { this.chunks.push(this._initReuseChunk); this.maxCursor = this._initReuseChunk.length - 1; } } push(bytes2) { let topChunk = this.chunks[this.chunks.length - 1]; const newMax = this.cursor + bytes2.length; if (newMax <= this.maxCursor + 1) { const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1; topChunk.set(bytes2, chunkPos); } else { if (topChunk) { const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1; if (chunkPos < topChunk.length) { this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos); this.maxCursor = this.cursor - 1; } } if (bytes2.length < 64 && bytes2.length < this.chunkSize) { topChunk = alloc2(this.chunkSize); this.chunks.push(topChunk); this.maxCursor += topChunk.length; if (this._initReuseChunk === null) { this._initReuseChunk = topChunk; } topChunk.set(bytes2, 0); } else { this.chunks.push(bytes2); this.maxCursor += bytes2.length; } } this.cursor += bytes2.length; } toBytes(reset = false) { let byts; if (this.chunks.length === 1) { const chunk = this.chunks[0]; if (reset && this.cursor > chunk.length / 2) { byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor); this._initReuseChunk = null; this.chunks = []; } else { byts = slice(chunk, 0, this.cursor); } } else { byts = concat2(this.chunks, this.cursor); } if (reset) { this.reset(); } return byts; } }; // node_modules/cborg/esm/lib/common.js var decodeErrPrefix = "CBOR decode error:"; var encodeErrPrefix = "CBOR encode error:"; var uintMinorPrefixBytes = []; uintMinorPrefixBytes[23] = 1; uintMinorPrefixBytes[24] = 2; uintMinorPrefixBytes[25] = 3; uintMinorPrefixBytes[26] = 5; uintMinorPrefixBytes[27] = 9; function assertEnoughData(data, pos, need) { if (data.length - pos < need) { throw new Error(`${decodeErrPrefix} not enough data for type`); } } // node_modules/cborg/esm/lib/0uint.js var uintBoundaries = [ 24, 256, 65536, 4294967296, BigInt("18446744073709551616") ]; function readUint8(data, offset, options) { assertEnoughData(data, offset, 1); const value = data[offset]; if (options.strict === true && value < uintBoundaries[0]) { throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`); } return value; } function readUint16(data, offset, options) { assertEnoughData(data, offset, 2); const value = data[offset] << 8 | data[offset + 1]; if (options.strict === true && value < uintBoundaries[1]) { throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`); } return value; } function readUint32(data, offset, options) { assertEnoughData(data, offset, 4); const value = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]; if (options.strict === true && value < uintBoundaries[2]) { throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`); } return value; } function readUint64(data, offset, options) { assertEnoughData(data, offset, 8); const hi = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]; const lo = data[offset + 4] * 16777216 + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]; const value = (BigInt(hi) << BigInt(32)) + BigInt(lo); if (options.strict === true && value < uintBoundaries[3]) { throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`); } if (value <= Number.MAX_SAFE_INTEGER) { return Number(value); } if (options.allowBigInt === true) { return value; } throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`); } function decodeUint8(data, pos, _minor, options) { return new Token(Type.uint, readUint8(data, pos + 1, options), 2); } function decodeUint16(data, pos, _minor, options) { return new Token(Type.uint, readUint16(data, pos + 1, options), 3); } function decodeUint32(data, pos, _minor, options) { return new Token(Type.uint, readUint32(data, pos + 1, options), 5); } function decodeUint64(data, pos, _minor, options) { return new Token(Type.uint, readUint64(data, pos + 1, options), 9); } function encodeUint(buf2, token) { return encodeUintValue(buf2, 0, token.value); } function encodeUintValue(buf2, major, uint) { if (uint < uintBoundaries[0]) { const nuint = Number(uint); buf2.push([major | nuint]); } else if (uint < uintBoundaries[1]) { const nuint = Number(uint); buf2.push([ major | 24, nuint ]); } else if (uint < uintBoundaries[2]) { const nuint = Number(uint); buf2.push([ major | 25, nuint >>> 8, nuint & 255 ]); } else if (uint < uintBoundaries[3]) { const nuint = Number(uint); buf2.push([ major | 26, nuint >>> 24 & 255, nuint >>> 16 & 255, nuint >>> 8 & 255, nuint & 255 ]); } else { const buint = BigInt(uint); if (buint < uintBoundaries[4]) { const set = [ major | 27, 0, 0, 0, 0, 0, 0, 0 ]; let lo = Number(buint & BigInt(4294967295)); let hi = Number(buint >> BigInt(32) & BigInt(4294967295)); set[8] = lo & 255; lo = lo >> 8; set[7] = lo & 255; lo = lo >> 8; set[6] = lo & 255; lo = lo >> 8; set[5] = lo & 255; set[4] = hi & 255; hi = hi >> 8; set[3] = hi & 255; hi = hi >> 8; set[2] = hi & 255; hi = hi >> 8; set[1] = hi & 255; buf2.push(set); } else { throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`); } } } encodeUint.encodedSize = function encodedSize(token) { return encodeUintValue.encodedSize(token.value); }; encodeUintValue.encodedSize = function encodedSize2(uint) { if (uint < uintBoundaries[0]) { return 1; } if (uint < uintBoundaries[1]) { return 2; } if (uint < uintBoundaries[2]) { return 3; } if (uint < uintBoundaries[3]) { return 5; } return 9; }; encodeUint.compareTokens = function compareTokens(tok1, tok2) { return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0; }; // node_modules/cborg/esm/lib/1negint.js function decodeNegint8(data, pos, _minor, options) { return new Token(Type.negint, -1 - readUint8(data, pos + 1, options), 2); } function decodeNegint16(data, pos, _minor, options) { return new Token(Type.negint, -1 - readUint16(data, pos + 1, options), 3); } function decodeNegint32(data, pos, _minor, options) { return new Token(Type.negint, -1 - readUint32(data, pos + 1, options), 5); } var neg1b = BigInt(-1); var pos1b = BigInt(1); function decodeNegint64(data, pos, _minor, options) { const int = readUint64(data, pos + 1, options); if (typeof int !== "bigint") { const value = -1 - int; if (value >= Number.MIN_SAFE_INTEGER) { return new Token(Type.negint, value, 9); } } if (options.allowBigInt !== true) { throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`); } return new Token(Type.negint, neg1b - BigInt(int), 9); } function encodeNegint(buf2, token) { const negint = token.value; const unsigned = typeof negint === "bigint" ? negint * neg1b - pos1b : negint * -1 - 1; encodeUintValue(buf2, token.type.majorEncoded, unsigned); } encodeNegint.encodedSize = function encodedSize3(token) { const negint = token.value; const unsigned = typeof negint === "bigint" ? negint * neg1b - pos1b : negint * -1 - 1; if (unsigned < uintBoundaries[0]) { return 1; } if (unsigned < uintBoundaries[1]) { return 2; } if (unsigned < uintBoundaries[2]) { return 3; } if (unsigned < uintBoundaries[3]) { return 5; } return 9; }; encodeNegint.compareTokens = function compareTokens2(tok1, tok2) { return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0; }; // node_modules/cborg/esm/lib/2bytes.js function toToken(data, pos, prefix, length5) { assertEnoughData(data, pos, prefix + length5); const buf2 = slice(data, pos + prefix, pos + prefix + length5); return new Token(Type.bytes, buf2, prefix + length5); } function decodeBytesCompact(data, pos, minor, _options) { return toToken(data, pos, 1, minor); } function decodeBytes8(data, pos, _minor, options) { return toToken(data, pos, 2, readUint8(data, pos + 1, options)); } function decodeBytes16(data, pos, _minor, options) { return toToken(data, pos, 3, readUint16(data, pos + 1, options)); } function decodeBytes32(data, pos, _minor, options) { return toToken(data, pos, 5, readUint32(data, pos + 1, options)); } function decodeBytes64(data, pos, _minor, options) { const l = readUint64(data, pos + 1, options); if (typeof l === "bigint") { throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`); } return toToken(data, pos, 9, l); } function tokenBytes(token) { if (token.encodedBytes === void 0) { token.encodedBytes = token.type === Type.string ? fromString3(token.value) : token.value; } return token.encodedBytes; } function encodeBytes(buf2, token) { const bytes2 = tokenBytes(token); encodeUintValue(buf2, token.type.majorEncoded, bytes2.length); buf2.push(bytes2); } encodeBytes.encodedSize = function encodedSize4(token) { const bytes2 = tokenBytes(token); return encodeUintValue.encodedSize(bytes2.length) + bytes2.length; }; encodeBytes.compareTokens = function compareTokens3(tok1, tok2) { return compareBytes(tokenBytes(tok1), tokenBytes(tok2)); }; function compareBytes(b1, b2) { return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare2(b1, b2); } // node_modules/cborg/esm/lib/3string.js function toToken2(data, pos, prefix, length5, options) { const totLength = prefix + length5; assertEnoughData(data, pos, totLength); const tok = new Token(Type.string, toString3(data, pos + prefix, pos + totLength), totLength); if (options.retainStringBytes === true) { tok.byteValue = slice(data, pos + prefix, pos + totLength); } return tok; } function decodeStringCompact(data, pos, minor, options) { return toToken2(data, pos, 1, minor, options); } function decodeString8(data, pos, _minor, options) { return toToken2(data, pos, 2, readUint8(data, pos + 1, options), options); } function decodeString16(data, pos, _minor, options) { return toToken2(data, pos, 3, readUint16(data, pos + 1, options), options); } function decodeString32(data, pos, _minor, options) { return toToken2(data, pos, 5, readUint32(data, pos + 1, options), options); } function decodeString64(data, pos, _minor, options) { const l = readUint64(data, pos + 1, options); if (typeof l === "bigint") { throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`); } return toToken2(data, pos, 9, l, options); } var encodeString = encodeBytes; // node_modules/cborg/esm/lib/4array.js function toToken3(_data, _pos, prefix, length5) { return new Token(Type.array, length5, prefix); } function decodeArrayCompact(data, pos, minor, _options) { return toToken3(data, pos, 1, minor); } function decodeArray8(data, pos, _minor, options) { return toToken3(data, pos, 2, readUint8(data, pos + 1, options)); } function decodeArray16(data, pos, _minor, options) { return toToken3(data, pos, 3, readUint16(data, pos + 1, options)); } function decodeArray32(data, pos, _minor, options) { return toToken3(data, pos, 5, readUint32(data, pos + 1, options)); } function decodeArray64(data, pos, _minor, options) { const l = readUint64(data, pos + 1, options); if (typeof l === "bigint") { throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`); } return toToken3(data, pos, 9, l); } function decodeArrayIndefinite(data, pos, _minor, options) { if (options.allowIndefinite === false) { throw new Error(`${decodeErrPrefix} indefinite length items not allowed`); } return toToken3(data, pos, 1, Infinity); } function encodeArray(buf2, token) { encodeUintValue(buf2, Type.array.majorEncoded, token.value); } encodeArray.compareTokens = encodeUint.compareTokens; encodeArray.encodedSize = function encodedSize5(token) { return encodeUintValue.encodedSize(token.value); }; // node_modules/cborg/esm/lib/5map.js function toToken4(_data, _pos, prefix, length5) { return new Token(Type.map, length5, prefix); } function decodeMapCompact(data, pos, minor, _options) { return toToken4(data, pos, 1, minor); } function decodeMap8(data, pos, _minor, options) { return toToken4(data, pos, 2, readUint8(data, pos + 1, options)); } function decodeMap16(data, pos, _minor, options) { return toToken4(data, pos, 3, readUint16(data, pos + 1, options)); } function decodeMap32(data, pos, _minor, options) { return toToken4(data, pos, 5, readUint32(data, pos + 1, options)); } function decodeMap64(data, pos, _minor, options) { const l = readUint64(data, pos + 1, options); if (typeof l === "bigint") { throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`); } return toToken4(data, pos, 9, l); } function decodeMapIndefinite(data, pos, _minor, options) { if (options.allowIndefinite === false) { throw new Error(`${decodeErrPrefix} indefinite length items not allowed`); } return toToken4(data, pos, 1, Infinity); } function encodeMap(buf2, token) { encodeUintValue(buf2, Type.map.majorEncoded, token.value); } encodeMap.compareTokens = encodeUint.compareTokens; encodeMap.encodedSize = function encodedSize6(token) { return encodeUintValue.encodedSize(token.value); }; // node_modules/cborg/esm/lib/6tag.js function decodeTagCompact(_data, _pos, minor, _options) { return new Token(Type.tag, minor, 1); } function decodeTag8(data, pos, _minor, options) { return new Token(Type.tag, readUint8(data, pos + 1, options), 2); } function decodeTag16(data, pos, _minor, options) { return new Token(Type.tag, readUint16(data, pos + 1, options), 3); } function decodeTag32(data, pos, _minor, options) { return new Token(Type.tag, readUint32(data, pos + 1, options), 5); } function decodeTag64(data, pos, _minor, options) { return new Token(Type.tag, readUint64(data, pos + 1, options), 9); } function encodeTag(buf2, token) { encodeUintValue(buf2, Type.tag.majorEncoded, token.value); } encodeTag.compareTokens = encodeUint.compareTokens; encodeTag.encodedSize = function encodedSize7(token) { return encodeUintValue.encodedSize(token.value); }; // node_modules/cborg/esm/lib/7float.js var MINOR_FALSE = 20; var MINOR_TRUE = 21; var MINOR_NULL = 22; var MINOR_UNDEFINED = 23; function decodeUndefined(_data, _pos, _minor, options) { if (options.allowUndefined === false) { throw new Error(`${decodeErrPrefix} undefined values are not supported`); } else if (options.coerceUndefinedToNull === true) { return new Token(Type.null, null, 1); } return new Token(Type.undefined, void 0, 1); } function decodeBreak(_data, _pos, _minor, options) { if (options.allowIndefinite === false) { throw new Error(`${decodeErrPrefix} indefinite length items not allowed`); } return new Token(Type.break, void 0, 1); } function createToken(value, bytes2, options) { if (options) { if (options.allowNaN === false && Number.isNaN(value)) { throw new Error(`${decodeErrPrefix} NaN values are not supported`); } if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) { throw new Error(`${decodeErrPrefix} Infinity values are not supported`); } } return new Token(Type.float, value, bytes2); } function decodeFloat16(data, pos, _minor, options) { return createToken(readFloat16(data, pos + 1), 3, options); } function decodeFloat32(data, pos, _minor, options) { return createToken(readFloat32(data, pos + 1), 5, options); } function decodeFloat64(data, pos, _minor, options) { return createToken(readFloat64(data, pos + 1), 9, options); } function encodeFloat(buf2, token, options) { const float = token.value; if (float === false) { buf2.push([Type.float.majorEncoded | MINOR_FALSE]); } else if (float === true) { buf2.push([Type.float.majorEncoded | MINOR_TRUE]); } else if (float === null) { buf2.push([Type.float.majorEncoded | MINOR_NULL]); } else if (float === void 0) { buf2.push([Type.float.majorEncoded | MINOR_UNDEFINED]); } else { let decoded; let success = false; if (!options || options.float64 !== true) { encodeFloat16(float); decoded = readFloat16(ui8a, 1); if (float === decoded || Number.isNaN(float)) { ui8a[0] = 249; buf2.push(ui8a.slice(0, 3)); success = true; } else { encodeFloat32(float); decoded = readFloat32(ui8a, 1); if (float === decoded) { ui8a[0] = 250; buf2.push(ui8a.slice(0, 5)); success = true; } } } if (!success) { encodeFloat64(float); decoded = readFloat64(ui8a, 1); ui8a[0] = 251; buf2.push(ui8a.slice(0, 9)); } } } encodeFloat.encodedSize = function encodedSize8(token, options) { const float = token.value; if (float === false || float === true || float === null || float === void 0) { return 1; } if (!options || options.float64 !== true) { encodeFloat16(float); let decoded = readFloat16(ui8a, 1); if (float === decoded || Number.isNaN(float)) { return 3; } encodeFloat32(float); decoded = readFloat32(ui8a, 1); if (float === decoded) { return 5; } } return 9; }; var buffer = new ArrayBuffer(9); var dataView = new DataView(buffer, 1); var ui8a = new Uint8Array(buffer, 0); function encodeFloat16(inp) { if (inp === Infinity) { dataView.setUint16(0, 31744, false); } else if (inp === -Infinity) { dataView.setUint16(0, 64512, false); } else if (Number.isNaN(inp)) { dataView.setUint16(0, 32256, false); } else { dataView.setFloat32(0, inp); const valu32 = dataView.getUint32(0); const exponent = (valu32 & 2139095040) >> 23; const mantissa = valu32 & 8388607; if (exponent === 255) { dataView.setUint16(0, 31744, false); } else if (exponent === 0) { dataView.setUint16(0, (inp & 2147483648) >> 16 | mantissa >> 13, false); } else { const logicalExponent = exponent - 127; if (logicalExponent < -24) { dataView.setUint16(0, 0); } else if (logicalExponent < -14) { dataView.setUint16(0, (valu32 & 2147483648) >> 16 | 1 << 24 + logicalExponent, false); } else { dataView.setUint16(0, (valu32 & 2147483648) >> 16 | logicalExponent + 15 << 10 | mantissa >> 13, false); } } } } function readFloat16(ui8a2, pos) { if (ui8a2.length - pos < 2) { throw new Error(`${decodeErrPrefix} not enough data for float16`); } const half = (ui8a2[pos] << 8) + ui8a2[pos + 1]; if (half === 31744) { return Infinity; } if (half === 64512) { return -Infinity; } if (half === 32256) { return NaN; } const exp = half >> 10 & 31; const mant = half & 1023; let val; if (exp === 0) { val = mant * 2 ** -24; } else if (exp !== 31) { val = (mant + 1024) * 2 ** (exp - 25); } else { val = mant === 0 ? Infinity : NaN; } return half & 32768 ? -val : val; } function encodeFloat32(inp) { dataView.setFloat32(0, inp, false); } function readFloat32(ui8a2, pos) { if (ui8a2.length - pos < 4) { throw new Error(`${decodeErrPrefix} not enough data for float32`); } const offset = (ui8a2.byteOffset || 0) + pos; return new DataView(ui8a2.buffer, offset, 4).getFloat32(0, false); } function encodeFloat64(inp) { dataView.setFloat64(0, inp, false); } function readFloat64(ui8a2, pos) { if (ui8a2.length - pos < 8) { throw new Error(`${decodeErrPrefix} not enough data for float64`); } const offset = (ui8a2.byteOffset || 0) + pos; return new DataView(ui8a2.buffer, offset, 8).getFloat64(0, false); } encodeFloat.compareTokens = encodeUint.compareTokens; // node_modules/cborg/esm/lib/jump.js function invalidMinor(data, pos, minor) { throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`); } function errorer(msg) { return () => { throw new Error(`${decodeErrPrefix} ${msg}`); }; } var jump = []; for (let i = 0; i <= 23; i++) { jump[i] = invalidMinor; } jump[24] = decodeUint8; jump[25] = decodeUint16; jump[26] = decodeUint32; jump[27] = decodeUint64; jump[28] = invalidMinor; jump[29] = invalidMinor; jump[30] = invalidMinor; jump[31] = invalidMinor; for (let i = 32; i <= 55; i++) { jump[i] = invalidMinor; } jump[56] = decodeNegint8; jump[57] = decodeNegint16; jump[58] = decodeNegint32; jump[59] = decodeNegint64; jump[60] = invalidMinor; jump[61] = invalidMinor; jump[62] = invalidMinor; jump[63] = invalidMinor; for (let i = 64; i <= 87; i++) { jump[i] = decodeBytesCompact; } jump[88] = decodeBytes8; jump[89] = decodeBytes16; jump[90] = decodeBytes32; jump[91] = decodeBytes64; jump[92] = invalidMinor; jump[93] = invalidMinor; jump[94] = invalidMinor; jump[95] = errorer("indefinite length bytes/strings are not supported"); for (let i = 96; i <= 119; i++) { jump[i] = decodeStringCompact; } jump[120] = decodeString8; jump[121] = decodeString16; jump[122] = decodeString32; jump[123] = decodeString64; jump[124] = invalidMinor; jump[125] = invalidMinor; jump[126] = invalidMinor; jump[127] = errorer("indefinite length bytes/strings are not supported"); for (let i = 128; i <= 151; i++) { jump[i] = decodeArrayCompact; } jump[152] = decodeArray8; jump[153] = decodeArray16; jump[154] = decodeArray32; jump[155] = decodeArray64; jump[156] = invalidMinor; jump[157] = invalidMinor; jump[158] = invalidMinor; jump[159] = decodeArrayIndefinite; for (let i = 160; i <= 183; i++) { jump[i] = decodeMapCompact; } jump[184] = decodeMap8; jump[185] = decodeMap16; jump[186] = decodeMap32; jump[187] = decodeMap64; jump[188] = invalidMinor; jump[189] = invalidMinor; jump[190] = invalidMinor; jump[191] = decodeMapIndefinite; for (let i = 192; i <= 215; i++) { jump[i] = decodeTagCompact; } jump[216] = decodeTag8; jump[217] = decodeTag16; jump[218] = decodeTag32; jump[219] = decodeTag64; jump[220] = invalidMinor; jump[221] = invalidMinor; jump[222] = invalidMinor; jump[223] = invalidMinor; for (let i = 224; i <= 243; i++) { jump[i] = errorer("simple values are not supported"); } jump[244] = invalidMinor; jump[245] = invalidMinor; jump[246] = invalidMinor; jump[247] = decodeUndefined; jump[248] = errorer("simple values are not supported"); jump[249] = decodeFloat16; jump[250] = decodeFloat32; jump[251] = decodeFloat64; jump[252] = invalidMinor; jump[253] = invalidMinor; jump[254] = invalidMinor; jump[255] = decodeBreak; var quick = []; for (let i = 0; i < 24; i++) { quick[i] = new Token(Type.uint, i, 1); } for (let i = -1; i >= -24; i--) { quick[31 - i] = new Token(Type.negint, i, 1); } quick[64] = new Token(Type.bytes, new Uint8Array(0), 1); quick[96] = new Token(Type.string, "", 1); quick[128] = new Token(Type.array, 0, 1); quick[160] = new Token(Type.map, 0, 1); quick[244] = new Token(Type.false, false, 1); quick[245] = new Token(Type.true, true, 1); quick[246] = new Token(Type.null, null, 1); function quickEncodeToken(token) { switch (token.type) { case Type.false: return fromArray([244]); case Type.true: return fromArray([245]); case Type.null: return fromArray([246]); case Type.bytes: if (!token.value.length) { return fromArray([64]); } return; case Type.string: if (token.value === "") { return fromArray([96]); } return; case Type.array: if (token.value === 0) { return fromArray([128]); } return; case Type.map: if (token.value === 0) { return fromArray([160]); } return; case Type.uint: if (token.value < 24) { return fromArray([Number(token.value)]); } return; case Type.negint: if (token.value >= -24) { return fromArray([31 - Number(token.value)]); } } } // node_modules/cborg/esm/lib/encode.js var defaultEncodeOptions = { float64: false, mapSorter, quickEncodeToken }; function makeCborEncoders() { const encoders = []; encoders[Type.uint.major] = encodeUint; encoders[Type.negint.major] = encodeNegint; encoders[Type.bytes.major] = encodeBytes; encoders[Type.string.major] = encodeString; encoders[Type.array.major] = encodeArray; encoders[Type.map.major] = encodeMap; encoders[Type.tag.major] = encodeTag; encoders[Type.float.major] = encodeFloat; return encoders; } var cborEncoders = makeCborEncoders(); var buf = new Bl(); var Ref = class { constructor(obj, parent) { this.obj = obj; this.parent = parent; } includes(obj) { let p = this; do { if (p.obj === obj) { return true; } } while (p = p.parent); return false; } static createCheck(stack, obj) { if (stack && stack.includes(obj)) { throw new Error(`${encodeErrPrefix} object contains circular references`); } return new Ref(obj, stack); } }; var simpleTokens = { null: new Token(Type.null, null), undefined: new Token(Type.undefined, void 0), true: new Token(Type.true, true), false: new Token(Type.false, false), emptyArray: new Token(Type.array, 0), emptyMap: new Token(Type.map, 0) }; var typeEncoders = { number(obj, _typ, _options, _refStack) { if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) { return new Token(Type.float, obj); } else if (obj >= 0) { return new Token(Type.uint, obj); } else { return new Token(Type.negint, obj); } }, bigint(obj, _typ, _options, _refStack) { if (obj >= BigInt(0)) { return new Token(Type.uint, obj); } else { return new Token(Type.negint, obj); } }, Uint8Array(obj, _typ, _options, _refStack) { return new Token(Type.bytes, obj); }, string(obj, _typ, _options, _refStack) { return new Token(Type.string, obj); }, boolean(obj, _typ, _options, _refStack) { return obj ? simpleTokens.true : simpleTokens.false; }, null(_obj, _typ, _options, _refStack) { return simpleTokens.null; }, undefined(_obj, _typ, _options, _refStack) { return simpleTokens.undefined; }, ArrayBuffer(obj, _typ, _options, _refStack) { return new Token(Type.bytes, new Uint8Array(obj)); }, DataView(obj, _typ, _options, _refStack) { return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)); }, Array(obj, _typ, options, refStack) { if (!obj.length) { if (options.addBreakTokens === true) { return [ simpleTokens.emptyArray, new Token(Type.break) ]; } return simpleTokens.emptyArray; } refStack = Ref.createCheck(refStack, obj); const entries = []; let i = 0; for (const e of obj) { entries[i++] = objectToTokens(e, options, refStack); } if (options.addBreakTokens) { return [ new Token(Type.array, obj.length), entries, new Token(Type.break) ]; } return [ new Token(Type.array, obj.length), entries ]; }, Object(obj, typ, options, refStack) { const isMap = typ !== "Object"; const keys = isMap ? obj.keys() : Object.keys(obj); const length5 = isMap ? obj.size : keys.length; if (!length5) { if (options.addBreakTokens === true) { return [ simpleTokens.emptyMap, new Token(Type.break) ]; } return simpleTokens.emptyMap; } refStack = Ref.createCheck(refStack, obj); const entries = []; let i = 0; for (const key of keys) { entries[i++] = [ objectToTokens(key, options, refStack), objectToTokens(isMap ? obj.get(key) : obj[key], options, refStack) ]; } sortMapEntries(entries, options); if (options.addBreakTokens) { return [ new Token(Type.map, length5), entries, new Token(Type.break) ]; } return [ new Token(Type.map, length5), entries ]; } }; typeEncoders.Map = typeEncoders.Object; typeEncoders.Buffer = typeEncoders.Uint8Array; for (const typ of "Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" ")) { typeEncoders[`${typ}Array`] = typeEncoders.DataView; } function objectToTokens(obj, options = {}, refStack) { const typ = is(obj); const customTypeEncoder = options && options.typeEncoders && options.typeEncoders[typ] || typeEncoders[typ]; if (typeof customTypeEncoder === "function") { const tokens = customTypeEncoder(obj, typ, options, refStack); if (tokens != null) { return tokens; } } const typeEncoder = typeEncoders[typ]; if (!typeEncoder) { throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`); } return typeEncoder(obj, typ, options, refStack); } function sortMapEntries(entries, options) { if (options.mapSorter) { entries.sort(options.mapSorter); } } function mapSorter(e1, e2) { const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]; const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]; if (keyToken1.type !== keyToken2.type) { return keyToken1.type.compare(keyToken2.type); } const major = keyToken1.type.major; const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2); if (tcmp === 0) { console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"); } return tcmp; } function tokensToEncoded(buf2, tokens, encoders, options) { if (Array.isArray(tokens)) { for (const token of tokens) { tokensToEncoded(buf2, token, encoders, options); } } else { encoders[tokens.type.major](buf2, tokens, options); } } function encodeCustom(data, encoders, options) { const tokens = objectToTokens(data, options); if (!Array.isArray(tokens) && options.quickEncodeToken) { const quickBytes = options.quickEncodeToken(tokens); if (quickBytes) { return quickBytes; } const encoder = encoders[tokens.type.major]; if (encoder.encodedSize) { const size = encoder.encodedSize(tokens, options); const buf2 = new Bl(size); encoder(buf2, tokens, options); if (buf2.chunks.length !== 1) { throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`); } return asU8A(buf2.chunks[0]); } } buf.reset(); tokensToEncoded(buf, tokens, encoders, options); return buf.toBytes(true); } function encode6(data, options) { options = Object.assign({}, defaultEncodeOptions, options); return encodeCustom(data, cborEncoders, options); } // node_modules/cborg/esm/lib/decode.js var defaultDecodeOptions = { strict: false, allowIndefinite: true, allowUndefined: true, allowBigInt: true }; var Tokeniser = class { constructor(data, options = {}) { this.pos = 0; this.data = data; this.options = options; } done() { return this.pos >= this.data.length; } next() { const byt = this.data[this.pos]; let token = quick[byt]; if (token === void 0) { const decoder = jump[byt]; if (!decoder) { throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, "0")})`); } const minor = byt & 31; token = decoder(this.data, this.pos, minor, this.options); } this.pos += token.encodedLength; return token; } }; var DONE = Symbol.for("DONE"); var BREAK = Symbol.for("BREAK"); function tokenToArray(token, tokeniser, options) { const arr = []; for (let i = 0; i < token.value; i++) { const value = tokensToObject(tokeniser, options); if (value === BREAK) { if (token.value === Infinity) { break; } throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`); } if (value === DONE) { throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`); } arr[i] = value; } return arr; } function tokenToMap(token, tokeniser, options) { const useMaps = options.useMaps === true; const obj = useMaps ? void 0 : {}; const m = useMaps ? /* @__PURE__ */ new Map() : void 0; for (let i = 0; i < token.value; i++) { const key = tokensToObject(tokeniser, options); if (key === BREAK) { if (token.value === Infinity) { break; } throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`); } if (key === DONE) { throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`); } if (useMaps !== true && typeof key !== "string") { throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`); } if (options.rejectDuplicateMapKeys === true) { if (useMaps && m.has(key) || !useMaps && key in obj) { throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`); } } const value = tokensToObject(tokeniser, options); if (value === DONE) { throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`); } if (useMaps) { m.set(key, value); } else { obj[key] = value; } } return useMaps ? m : obj; } function tokensToObject(tokeniser, options) { if (tokeniser.done()) { return DONE; } const token = tokeniser.next(); if (token.type === Type.break) { return BREAK; } if (token.type.terminal) { return token.value; } if (token.type === Type.array) { return tokenToArray(token, tokeniser, options); } if (token.type === Type.map) { return tokenToMap(token, tokeniser, options); } if (token.type === Type.tag) { if (options.tags && typeof options.tags[token.value] === "function") { const tagged = tokensToObject(tokeniser, options); return options.tags[token.value](tagged); } throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`); } throw new Error("unsupported"); } function decode7(data, options) { if (!(data instanceof Uint8Array)) { throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`); } options = Object.assign({}, defaultDecodeOptions, options); const tokeniser = options.tokenizer || new Tokeniser(data, options); const decoded = tokensToObject(tokeniser, options); if (decoded === DONE) { throw new Error(`${decodeErrPrefix} did not find any content to decode`); } if (decoded === BREAK) { throw new Error(`${decodeErrPrefix} got unexpected break`); } if (!tokeniser.done()) { throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`); } return decoded; } // node_modules/@ipld/dag-cbor/node_modules/multiformats/vendor/varint.js var encode_12 = encode7; var MSB2 = 128; var REST2 = 127; var MSBALL2 = ~REST2; var INT2 = Math.pow(2, 31); function encode7(num, out, offset) { out = out || []; offset = offset || 0; var oldOffset = offset; while (num >= INT2) { out[offset++] = num & 255 | MSB2; num /= 128; } while (num & MSBALL2) { out[offset++] = num & 255 | MSB2; num >>>= 7; } out[offset] = num | 0; encode7.bytes = offset - oldOffset + 1; return out; } var decode8 = read2; var MSB$12 = 128; var REST$12 = 127; function read2(buf2, offset) { var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf2.length; do { if (counter >= l) { read2.bytes = 0; throw new RangeError("Could not decode varint"); } b = buf2[counter++]; res += shift < 28 ? (b & REST$12) << shift : (b & REST$12) * Math.pow(2, shift); shift += 7; } while (b >= MSB$12); read2.bytes = counter - offset; return res; } var N12 = Math.pow(2, 7); var N23 = Math.pow(2, 14); var N32 = Math.pow(2, 21); var N42 = Math.pow(2, 28); var N52 = Math.pow(2, 35); var N62 = Math.pow(2, 42); var N72 = Math.pow(2, 49); var N82 = Math.pow(2, 56); var N92 = Math.pow(2, 63); var length2 = function(value) { return value < N12 ? 1 : value < N23 ? 2 : value < N32 ? 3 : value < N42 ? 4 : value < N52 ? 5 : value < N62 ? 6 : value < N72 ? 7 : value < N82 ? 8 : value < N92 ? 9 : 10; }; var varint2 = { encode: encode_12, decode: decode8, encodingLength: length2 }; var _brrp_varint2 = varint2; var varint_default2 = _brrp_varint2; // node_modules/@ipld/dag-cbor/node_modules/multiformats/src/varint.js var decode9 = (data, offset = 0) => { const code5 = varint_default2.decode(data, offset); return [code5, varint_default2.decode.bytes]; }; var encodeTo2 = (int, target, offset = 0) => { varint_default2.encode(int, target, offset); return target; }; var encodingLength2 = (int) => { return varint_default2.encodingLength(int); }; // node_modules/@ipld/dag-cbor/node_modules/multiformats/src/bytes.js var empty2 = new Uint8Array(0); var equals4 = (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; }; var coerce2 = (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"); }; // node_modules/@ipld/dag-cbor/node_modules/multiformats/src/hashes/digest.js var create2 = (code5, digest2) => { const size = digest2.byteLength; const sizeOffset = encodingLength2(code5); const digestOffset = sizeOffset + encodingLength2(size); const bytes2 = new Uint8Array(digestOffset + size); encodeTo2(code5, bytes2, 0); encodeTo2(size, bytes2, sizeOffset); bytes2.set(digest2, digestOffset); return new Digest2(code5, size, digest2, bytes2); }; var decode10 = (multihash) => { const bytes2 = coerce2(multihash); const [code5, sizeOffset] = decode9(bytes2); const [size, digestOffset] = decode9(bytes2.subarray(sizeOffset)); const digest2 = bytes2.subarray(sizeOffset + digestOffset); if (digest2.byteLength !== size) { throw new Error("Incorrect length"); } return new Digest2(code5, size, digest2, bytes2); }; var equals5 = (a, b) => { if (a === b) { return true; } else { const data = ( /** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */ b ); return a.code === data.code && a.size === data.size && data.bytes instanceof Uint8Array && equals4(a.bytes, data.bytes); } }; var Digest2 = class { /** * Creates a multihash digest. * * @param {Code} code * @param {Size} size * @param {Uint8Array} digest * @param {Uint8Array} bytes */ constructor(code5, size, digest2, bytes2) { this.code = code5; this.size = size; this.digest = digest2; this.bytes = bytes2; } }; // node_modules/@ipld/dag-cbor/node_modules/multiformats/vendor/base-x.js function base3(ALPHABET, name5) { 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 encode16(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 length5 = 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 < length5) && 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"); } length5 = i2; pbegin++; } var it2 = size - length5; while (it2 !== size && b58[it2] === 0) { it2++; } var str3 = LEADER.repeat(zeroes); for (; it2 < size; ++it2) { str3 += ALPHABET.charAt(b58[it2]); } return str3; } 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 length5 = 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 < length5) && 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"); } length5 = i2; psz++; } if (source[psz] === " ") { return; } var it4 = size - length5; 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 decode23(string2) { var buffer2 = decodeUnsafe(string2); if (buffer2) { return buffer2; } throw new Error(`Non-${name5} character`); } return { encode: encode16, decodeUnsafe, decode: decode23 }; } var src2 = base3; var _brrp__multiformats_scope_baseX2 = src2; var base_x_default2 = _brrp__multiformats_scope_baseX2; // node_modules/@ipld/dag-cbor/node_modules/multiformats/src/bases/base.js var Encoder3 = class { /** * @param {Base} name * @param {Prefix} prefix * @param {(bytes:Uint8Array) => string} baseEncode */ constructor(name5, prefix, baseEncode) { this.name = name5; this.prefix = prefix; this.baseEncode = baseEncode; } /** * @param {Uint8Array} bytes * @returns {API.Multibase} */ encode(bytes2) { if (bytes2 instanceof Uint8Array) { return `${this.prefix}${this.baseEncode(bytes2)}`; } else { throw Error("Unknown type, must be binary type"); } } }; var Decoder2 = class { /** * @param {Base} name * @param {Prefix} prefix * @param {(text:string) => Uint8Array} baseDecode */ constructor(name5, prefix, baseDecode) { this.name = name5; this.prefix = prefix; if (prefix.codePointAt(0) === void 0) { throw new Error("Invalid prefix character"); } this.prefixCodePoint = /** @type {number} */ prefix.codePointAt(0); this.baseDecode = baseDecode; } /** * @param {string} text */ 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"); } } /** * @template {string} OtherPrefix * @param {API.UnibaseDecoder|ComposedDecoder} decoder * @returns {ComposedDecoder} */ or(decoder) { return or2(this, decoder); } }; var ComposedDecoder2 = class { /** * @param {Decoders} decoders */ constructor(decoders) { this.decoders = decoders; } /** * @template {string} OtherPrefix * @param {API.UnibaseDecoder|ComposedDecoder} decoder * @returns {ComposedDecoder} */ or(decoder) { return or2(this, decoder); } /** * @param {string} input * @returns {Uint8Array} */ decode(input) { const prefix = ( /** @type {Prefix} */ input[0] ); const decoder = this.decoders[prefix]; if (decoder) { return decoder.decode(input); } else { throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); } } }; var or2 = (left, right) => new ComposedDecoder2( /** @type {Decoders} */ { ...left.decoders || { [ /** @type API.UnibaseDecoder */ left.prefix ]: left }, ...right.decoders || { [ /** @type API.UnibaseDecoder */ right.prefix ]: right } } ); var Codec2 = class { /** * @param {Base} name * @param {Prefix} prefix * @param {(bytes:Uint8Array) => string} baseEncode * @param {(text:string) => Uint8Array} baseDecode */ constructor(name5, prefix, baseEncode, baseDecode) { this.name = name5; this.prefix = prefix; this.baseEncode = baseEncode; this.baseDecode = baseDecode; this.encoder = new Encoder3(name5, prefix, baseEncode); this.decoder = new Decoder2(name5, prefix, baseDecode); } /** * @param {Uint8Array} input */ encode(input) { return this.encoder.encode(input); } /** * @param {string} input */ decode(input) { return this.decoder.decode(input); } }; var from3 = ({ name: name5, prefix, encode: encode16, decode: decode23 }) => new Codec2(name5, prefix, encode16, decode23); var baseX2 = ({ prefix, name: name5, alphabet: alphabet2 }) => { const { encode: encode16, decode: decode23 } = base_x_default2(alphabet2, name5); return from3({ prefix, name: name5, encode: encode16, /** * @param {string} text */ decode: (text) => coerce2(decode23(text)) }); }; var decode11 = (string2, alphabet2, bitsPerChar, name5) => { const codes = {}; for (let i = 0; i < alphabet2.length; ++i) { codes[alphabet2[i]] = i; } let end = string2.length; while (string2[end - 1] === "=") { --end; } const out = new Uint8Array(end * bitsPerChar / 8 | 0); let bits = 0; let buffer2 = 0; let written = 0; for (let i = 0; i < end; ++i) { const value = codes[string2[i]]; if (value === void 0) { throw new SyntaxError(`Non-${name5} character`); } buffer2 = buffer2 << bitsPerChar | value; bits += bitsPerChar; if (bits >= 8) { bits -= 8; out[written++] = 255 & buffer2 >> bits; } } if (bits >= bitsPerChar || 255 & buffer2 << 8 - bits) { throw new SyntaxError("Unexpected end of data"); } return out; }; var encode8 = (data, alphabet2, bitsPerChar) => { const pad = alphabet2[alphabet2.length - 1] === "="; const mask = (1 << bitsPerChar) - 1; let out = ""; let bits = 0; let buffer2 = 0; for (let i = 0; i < data.length; ++i) { buffer2 = buffer2 << 8 | data[i]; bits += 8; while (bits > bitsPerChar) { bits -= bitsPerChar; out += alphabet2[mask & buffer2 >> bits]; } } if (bits) { out += alphabet2[mask & buffer2 << bitsPerChar - bits]; } if (pad) { while (out.length * bitsPerChar & 7) { out += "="; } } return out; }; var rfc46482 = ({ name: name5, prefix, bitsPerChar, alphabet: alphabet2 }) => { return from3({ prefix, name: name5, encode(input) { return encode8(input, alphabet2, bitsPerChar); }, decode(input) { return decode11(input, alphabet2, bitsPerChar, name5); } }); }; // node_modules/@ipld/dag-cbor/node_modules/multiformats/src/bases/base58.js var base58btc2 = baseX2({ name: "base58btc", prefix: "z", alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" }); var base58flickr2 = baseX2({ name: "base58flickr", prefix: "Z", alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" }); // node_modules/@ipld/dag-cbor/node_modules/multiformats/src/bases/base32.js var base322 = rfc46482({ prefix: "b", name: "base32", alphabet: "abcdefghijklmnopqrstuvwxyz234567", bitsPerChar: 5 }); var base32upper2 = rfc46482({ prefix: "B", name: "base32upper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", bitsPerChar: 5 }); var base32pad2 = rfc46482({ prefix: "c", name: "base32pad", alphabet: "abcdefghijklmnopqrstuvwxyz234567=", bitsPerChar: 5 }); var base32padupper2 = rfc46482({ prefix: "C", name: "base32padupper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", bitsPerChar: 5 }); var base32hex2 = rfc46482({ prefix: "v", name: "base32hex", alphabet: "0123456789abcdefghijklmnopqrstuv", bitsPerChar: 5 }); var base32hexupper2 = rfc46482({ prefix: "V", name: "base32hexupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", bitsPerChar: 5 }); var base32hexpad2 = rfc46482({ prefix: "t", name: "base32hexpad", alphabet: "0123456789abcdefghijklmnopqrstuv=", bitsPerChar: 5 }); var base32hexpadupper2 = rfc46482({ prefix: "T", name: "base32hexpadupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", bitsPerChar: 5 }); var base32z2 = rfc46482({ prefix: "h", name: "base32z", alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", bitsPerChar: 5 }); // node_modules/@ipld/dag-cbor/node_modules/multiformats/src/cid.js var format2 = (link, base6) => { const { bytes: bytes2, version } = link; switch (version) { case 0: return toStringV02( bytes2, baseCache2(link), /** @type {API.MultibaseEncoder<"z">} */ base6 || base58btc2.encoder ); default: return toStringV12( bytes2, baseCache2(link), /** @type {API.MultibaseEncoder} */ base6 || base322.encoder ); } }; var cache2 = /* @__PURE__ */ new WeakMap(); var baseCache2 = (cid) => { const baseCache5 = cache2.get(cid); if (baseCache5 == null) { const baseCache6 = /* @__PURE__ */ new Map(); cache2.set(cid, baseCache6); return baseCache6; } return baseCache5; }; var CID2 = class { /** * @param {Version} version - Version of the CID * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv * @param {API.MultihashDigest} multihash - (Multi)hash of the of the content. * @param {Uint8Array} bytes * */ constructor(version, code5, multihash, bytes2) { this.code = code5; this.version = version; this.multihash = multihash; this.bytes = bytes2; this["/"] = bytes2; } /** * 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; } /** * @returns {CID} */ toV0() { switch (this.version) { case 0: { return ( /** @type {CID} */ this ); } case 1: { const { code: code5, multihash } = this; if (code5 !== DAG_PB_CODE2) { throw new Error("Cannot convert a non dag-pb CID to CIDv0"); } if (multihash.code !== SHA_256_CODE2) { throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0"); } return ( /** @type {CID} */ CID2.createV0( /** @type {API.MultihashDigest} */ multihash ) ); } default: { throw Error( `Can not convert CID version ${this.version} to version 0. This is a bug please report` ); } } } /** * @returns {CID} */ toV1() { switch (this.version) { case 0: { const { code: code5, digest: digest2 } = this.multihash; const multihash = create2(code5, digest2); return ( /** @type {CID} */ CID2.createV1(this.code, multihash) ); } case 1: { return ( /** @type {CID} */ this ); } default: { throw Error( `Can not convert CID version ${this.version} to version 1. This is a bug please report` ); } } } /** * @param {unknown} other * @returns {other is CID} */ equals(other) { return CID2.equals(this, other); } /** * @template {unknown} Data * @template {number} Format * @template {number} Alg * @template {API.Version} Version * @param {API.Link} self * @param {unknown} other * @returns {other is CID} */ static equals(self2, other) { const unknown = ( /** @type {{code?:unknown, version?:unknown, multihash?:unknown}} */ other ); return unknown && self2.code === unknown.code && self2.version === unknown.version && equals5(self2.multihash, unknown.multihash); } /** * @param {API.MultibaseEncoder} [base] * @returns {string} */ toString(base6) { return format2(this, base6); } toJSON() { return { "/": format2(this) }; } link() { return this; } get [Symbol.toStringTag]() { return "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. * * @template {unknown} Data * @template {number} Format * @template {number} Alg * @template {API.Version} Version * @template {unknown} U * @param {API.Link|U} input * @returns {CID|null} */ static asCID(input) { if (input == null) { return null; } const value = ( /** @type {any} */ input ); if (value instanceof CID2) { return value; } else if (value["/"] != null && value["/"] === value.bytes || value.asCID === value) { const { version, code: code5, multihash, bytes: bytes2 } = value; return new CID2( version, code5, /** @type {API.MultihashDigest} */ multihash, bytes2 || encodeCID2(version, code5, multihash.bytes) ); } else if (value[cidSymbol2] === true) { const { version, multihash, code: code5 } = value; const digest2 = ( /** @type {API.MultihashDigest} */ decode10(multihash) ); return CID2.create(version, code5, digest2); } else { return null; } } /** * * @template {unknown} Data * @template {number} Format * @template {number} Alg * @template {API.Version} Version * @param {Version} version - Version of the CID * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv * @param {API.MultihashDigest} digest - (Multi)hash of the of the content. * @returns {CID} */ static create(version, code5, digest2) { if (typeof code5 !== "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 (code5 !== DAG_PB_CODE2) { throw new Error( `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE2}) block encoding` ); } else { return new CID2(version, code5, digest2, digest2.bytes); } } case 1: { const bytes2 = encodeCID2(version, code5, digest2.bytes); return new CID2(version, code5, digest2, bytes2); } default: { throw new Error("Invalid version"); } } } /** * Simplified version of `create` for CIDv0. * * @template {unknown} [T=unknown] * @param {API.MultihashDigest} digest - Multihash. * @returns {CID} */ static createV0(digest2) { return CID2.create(0, DAG_PB_CODE2, digest2); } /** * Simplified version of `create` for CIDv1. * * @template {unknown} Data * @template {number} Code * @template {number} Alg * @param {Code} code - Content encoding format code. * @param {API.MultihashDigest} digest - Miltihash of the content. * @returns {CID} */ static createV1(code5, digest2) { return CID2.create(1, code5, 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. * * @template {unknown} Data * @template {number} Code * @template {number} Alg * @template {API.Version} Ver * @param {API.ByteView>} bytes * @returns {CID} */ static decode(bytes2) { const [cid, remainder] = CID2.decodeFirst(bytes2); if (remainder.length) { 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. * * @template {unknown} T * @template {number} C * @template {number} A * @template {API.Version} V * @param {API.ByteView>} bytes * @returns {[CID, Uint8Array]} */ static decodeFirst(bytes2) { const specs = CID2.inspectBytes(bytes2); const prefixSize = specs.size - specs.multihashSize; const multihashBytes = coerce2( bytes2.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 Digest2( specs.multihashCode, specs.digestSize, digestBytes, multihashBytes ); const cid = specs.version === 0 ? CID2.createV0( /** @type {API.MultihashDigest} */ digest2 ) : CID2.createV1(specs.codec, digest2); return [ /** @type {CID} */ cid, bytes2.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. * * @template {unknown} T * @template {number} C * @template {number} A * @template {API.Version} V * @param {API.ByteView>} initialBytes * @returns {{ version:V, codec:C, multihashCode:A, digestSize:number, multihashSize:number, size:number }} */ static inspectBytes(initialBytes) { let offset = 0; const next = () => { const [i, length5] = decode9(initialBytes.subarray(offset)); offset += length5; return i; }; let version = ( /** @type {V} */ next() ); let codec = ( /** @type {C} */ DAG_PB_CODE2 ); if ( /** @type {number} */ version === 18 ) { version = /** @type {V} */ 0; offset = 0; } else { codec = /** @type {C} */ next(); } if (version !== 0 && version !== 1) { throw new RangeError(`Invalid CID version ${version}`); } const prefixSize = offset; const multihashCode = ( /** @type {A} */ 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). * * @template {string} Prefix * @template {unknown} Data * @template {number} Code * @template {number} Alg * @template {API.Version} Ver * @param {API.ToString, Prefix>} source * @param {API.MultibaseDecoder} [base] * @returns {CID} */ static parse(source, base6) { const [prefix, bytes2] = parseCIDtoBytes2(source, base6); const cid = CID2.decode(bytes2); if (cid.version === 0 && source[0] !== "Q") { throw Error("Version 0 CID string must not include multibase prefix"); } baseCache2(cid).set(prefix, source); return cid; } }; var parseCIDtoBytes2 = (source, base6) => { switch (source[0]) { case "Q": { const decoder = base6 || base58btc2; return [ /** @type {Prefix} */ base58btc2.prefix, decoder.decode(`${base58btc2.prefix}${source}`) ]; } case base58btc2.prefix: { const decoder = base6 || base58btc2; return [ /** @type {Prefix} */ base58btc2.prefix, decoder.decode(source) ]; } case base322.prefix: { const decoder = base6 || base322; return [ /** @type {Prefix} */ base322.prefix, decoder.decode(source) ]; } default: { if (base6 == null) { throw Error( "To parse non base32 or base58btc encoded CID multibase decoder must be provided" ); } return [ /** @type {Prefix} */ source[0], base6.decode(source) ]; } } }; var toStringV02 = (bytes2, cache5, base6) => { const { prefix } = base6; if (prefix !== base58btc2.prefix) { throw Error(`Cannot string encode V0 in ${base6.name} encoding`); } const cid = cache5.get(prefix); if (cid == null) { const cid2 = base6.encode(bytes2).slice(1); cache5.set(prefix, cid2); return cid2; } else { return cid; } }; var toStringV12 = (bytes2, cache5, base6) => { const { prefix } = base6; const cid = cache5.get(prefix); if (cid == null) { const cid2 = base6.encode(bytes2); cache5.set(prefix, cid2); return cid2; } else { return cid; } }; var DAG_PB_CODE2 = 112; var SHA_256_CODE2 = 18; var encodeCID2 = (version, code5, multihash) => { const codeOffset = encodingLength2(version); const hashOffset = codeOffset + encodingLength2(code5); const bytes2 = new Uint8Array(hashOffset + multihash.byteLength); encodeTo2(version, bytes2, 0); encodeTo2(code5, bytes2, codeOffset); bytes2.set(multihash, hashOffset); return bytes2; }; var cidSymbol2 = Symbol.for("@ipld/js-cid/CID"); // node_modules/@ipld/dag-cbor/src/index.js var CID_CBOR_TAG = 42; function cidEncoder(obj) { if (obj.asCID !== obj && obj["/"] !== obj.bytes) { return null; } const cid = CID2.asCID(obj); if (!cid) { return null; } const bytes2 = new Uint8Array(cid.bytes.byteLength + 1); bytes2.set(cid.bytes, 1); return [ new Token(Type.tag, CID_CBOR_TAG), new Token(Type.bytes, bytes2) ]; } function undefinedEncoder() { throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded"); } function numberEncoder(num) { if (Number.isNaN(num)) { throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded"); } if (num === Infinity || num === -Infinity) { throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded"); } return null; } var encodeOptions = { float64: true, typeEncoders: { Object: cidEncoder, undefined: undefinedEncoder, number: numberEncoder } }; function cidDecoder(bytes2) { if (bytes2[0] !== 0) { throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00"); } return CID2.decode(bytes2.subarray(1)); } var decodeOptions = { allowIndefinite: false, coerceUndefinedToNull: true, allowNaN: false, allowInfinity: false, allowBigInt: true, // this will lead to BigInt for ints outside of // safe-integer range, which may surprise users strict: true, useMaps: false, rejectDuplicateMapKeys: true, /** @type {import('cborg').TagDecoder[]} */ tags: [] }; decodeOptions.tags[CID_CBOR_TAG] = cidDecoder; var name3 = "dag-cbor"; var code3 = 113; var encode9 = (node) => encode6(node, encodeOptions); var decode12 = (data) => decode7(data, decodeOptions); // dist/esm/src/store/blockstore-mock.js var __awaiter8 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __asyncValues = function(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i); function verb(n) { i[n] = o[n] && function(v) { return new Promise(function(resolve5, reject) { v = o[n](v), settle(resolve5, reject, v.done, v.value); }); }; } function settle(resolve5, reject, d, v) { Promise.resolve(v).then(function(v2) { resolve5({ value: v2, done: d }); }, reject); } }; var __await = function(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }; var __asyncGenerator = function(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i; function verb(n) { if (g[n]) i[n] = function(v) { return new Promise(function(a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var BlockstoreMock = class { open() { return __awaiter8(this, void 0, void 0, function* () { }); } close() { return __awaiter8(this, void 0, void 0, function* () { }); } put(key, _val, _options) { return __awaiter8(this, void 0, void 0, function* () { return key; }); } get(_key, _options) { return __awaiter8(this, void 0, void 0, function* () { return new Uint8Array(); }); } has(_key, _options) { return __awaiter8(this, void 0, void 0, function* () { return false; }); } delete(_key, _options) { return __awaiter8(this, void 0, void 0, function* () { }); } isEmpty(_options) { return __awaiter8(this, void 0, void 0, function* () { return true; }); } putMany(source, options) { return __asyncGenerator(this, arguments, function* putMany_1() { var _a, e_1, _b, _c; try { for (var _d = true, source_1 = __asyncValues(source), source_1_1; source_1_1 = yield __await(source_1.next()), _a = source_1_1.done, !_a; _d = true) { _c = source_1_1.value; _d = false; const entry = _c; yield __await(this.put(entry.cid, entry.block, options)); yield yield __await(entry.cid); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (!_d && !_a && (_b = source_1.return)) yield __await(_b.call(source_1)); } finally { if (e_1) throw e_1.error; } } }); } getMany(source, options) { return __asyncGenerator(this, arguments, function* getMany_1() { var _a, e_2, _b, _c; try { for (var _d = true, source_2 = __asyncValues(source), source_2_1; source_2_1 = yield __await(source_2.next()), _a = source_2_1.done, !_a; _d = true) { _c = source_2_1.value; _d = false; const key = _c; yield yield __await({ cid: key, block: yield __await(this.get(key, options)) }); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (!_d && !_a && (_b = source_2.return)) yield __await(_b.call(source_2)); } finally { if (e_2) throw e_2.error; } } }); } getAll(options) { return __asyncGenerator(this, arguments, function* getAll_1() { var _a, e_3, _b, _c; const li = this.db.iterator({ keys: true, keyEncoding: "buffer" }, options); try { for (var _d = true, li_1 = __asyncValues(li), li_1_1; li_1_1 = yield __await(li_1.next()), _a = li_1_1.done, !_a; _d = true) { _c = li_1_1.value; _d = false; const [key, value] = _c; yield yield __await({ cid: CID.decode(key), block: value }); } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (!_d && !_a && (_b = li_1.return)) yield __await(_b.call(li_1)); } finally { if (e_3) throw e_3.error; } } }); } deleteMany(source, options) { return __asyncGenerator(this, arguments, function* deleteMany_1() { var _a, e_4, _b, _c; try { for (var _d = true, source_3 = __asyncValues(source), source_3_1; source_3_1 = yield __await(source_3.next()), _a = source_3_1.done, !_a; _d = true) { _c = source_3_1.value; _d = false; const key = _c; yield __await(this.delete(key, options)); yield yield __await(key); } } catch (e_4_1) { e_4 = { error: e_4_1 }; } finally { try { if (!_d && !_a && (_b = source_3.return)) yield __await(_b.call(source_3)); } finally { if (e_4) throw e_4.error; } } }); } /** * deletes all entries */ clear() { return __awaiter8(this, void 0, void 0, function* () { }); } }; // node_modules/ipfs-unixfs-importer/dist/src/index.js var import_err_code4 = __toESM(require_err_code(), 1); // node_modules/it-batch/dist/src/index.js function isAsyncIterable(thing) { return thing[Symbol.asyncIterator] != null; } function batch(source, size = 1) { size = Number(size); if (isAsyncIterable(source)) { return async function* () { let things = []; if (size < 1) { size = 1; } if (size !== Math.round(size)) { throw new Error("Batch size must be an integer"); } for await (const thing of source) { things.push(thing); while (things.length >= size) { yield things.slice(0, size); things = things.slice(size); } } while (things.length > 0) { yield things.slice(0, size); things = things.slice(size); } }(); } return function* () { let things = []; if (size < 1) { size = 1; } if (size !== Math.round(size)) { throw new Error("Batch size must be an integer"); } for (const thing of source) { things.push(thing); while (things.length >= size) { yield things.slice(0, size); things = things.slice(size); } } while (things.length > 0) { yield things.slice(0, size); things = things.slice(size); } }(); } var src_default = batch; // node_modules/it-parallel-batch/dist/src/index.js async function* parallelBatch(source, size = 1) { for await (const tasks of src_default(source, size)) { const things = tasks.map(async (p) => { return p().then((value) => ({ ok: true, value }), (err3) => ({ ok: false, err: err3 })); }); for (let i = 0; i < things.length; i++) { const result = await things[i]; if (result.ok) { yield result.value; } else { throw result.err; } } } } // node_modules/uint8arraylist/dist/src/index.js var symbol = Symbol.for("@achingbrain/uint8arraylist"); function findBufAndOffset(bufs, index) { if (index == null || index < 0) { throw new RangeError("index is out of bounds"); } let offset = 0; for (const buf2 of bufs) { const bufEnd = offset + buf2.byteLength; if (index < bufEnd) { return { buf: buf2, index: index - offset }; } offset = bufEnd; } throw new RangeError("index is out of bounds"); } function isUint8ArrayList(value) { return Boolean(value?.[symbol]); } var Uint8ArrayList = class { constructor(...data) { Object.defineProperty(this, symbol, { value: true }); this.bufs = []; this.length = 0; if (data.length > 0) { this.appendAll(data); } } *[Symbol.iterator]() { yield* this.bufs; } get byteLength() { return this.length; } /** * Add one or more `bufs` to the end of this Uint8ArrayList */ append(...bufs) { this.appendAll(bufs); } /** * Add all `bufs` to the end of this Uint8ArrayList */ appendAll(bufs) { let length5 = 0; for (const buf2 of bufs) { if (buf2 instanceof Uint8Array) { length5 += buf2.byteLength; this.bufs.push(buf2); } else if (isUint8ArrayList(buf2)) { length5 += buf2.byteLength; this.bufs.push(...buf2.bufs); } else { throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList"); } } this.length += length5; } /** * Add one or more `bufs` to the start of this Uint8ArrayList */ prepend(...bufs) { this.prependAll(bufs); } /** * Add all `bufs` to the start of this Uint8ArrayList */ prependAll(bufs) { let length5 = 0; for (const buf2 of bufs.reverse()) { if (buf2 instanceof Uint8Array) { length5 += buf2.byteLength; this.bufs.unshift(buf2); } else if (isUint8ArrayList(buf2)) { length5 += buf2.byteLength; this.bufs.unshift(...buf2.bufs); } else { throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList"); } } this.length += length5; } /** * Read the value at `index` */ get(index) { const res = findBufAndOffset(this.bufs, index); return res.buf[res.index]; } /** * Set the value at `index` to `value` */ set(index, value) { const res = findBufAndOffset(this.bufs, index); res.buf[res.index] = value; } /** * Copy bytes from `buf` to the index specified by `offset` */ write(buf2, offset = 0) { if (buf2 instanceof Uint8Array) { for (let i = 0; i < buf2.length; i++) { this.set(offset + i, buf2[i]); } } else if (isUint8ArrayList(buf2)) { for (let i = 0; i < buf2.length; i++) { this.set(offset + i, buf2.get(i)); } } else { throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList"); } } /** * Remove bytes from the front of the pool */ consume(bytes2) { bytes2 = Math.trunc(bytes2); if (Number.isNaN(bytes2) || bytes2 <= 0) { return; } if (bytes2 === this.byteLength) { this.bufs = []; this.length = 0; return; } while (this.bufs.length > 0) { if (bytes2 >= this.bufs[0].byteLength) { bytes2 -= this.bufs[0].byteLength; this.length -= this.bufs[0].byteLength; this.bufs.shift(); } else { this.bufs[0] = this.bufs[0].subarray(bytes2); this.length -= bytes2; break; } } } /** * Extracts a section of an array and returns a new array. * * This is a copy operation as it is with Uint8Arrays and Arrays * - note this is different to the behaviour of Node Buffers. */ slice(beginInclusive, endExclusive) { const { bufs, length: length5 } = this._subList(beginInclusive, endExclusive); return concat(bufs, length5); } /** * Returns a alloc from the given start and end element index. * * In the best case where the data extracted comes from a single Uint8Array * internally this is a no-copy operation otherwise it is a copy operation. */ subarray(beginInclusive, endExclusive) { const { bufs, length: length5 } = this._subList(beginInclusive, endExclusive); if (bufs.length === 1) { return bufs[0]; } return concat(bufs, length5); } /** * Returns a allocList from the given start and end element index. * * This is a no-copy operation. */ sublist(beginInclusive, endExclusive) { const { bufs, length: length5 } = this._subList(beginInclusive, endExclusive); const list = new Uint8ArrayList(); list.length = length5; list.bufs = bufs; return list; } _subList(beginInclusive, endExclusive) { beginInclusive = beginInclusive ?? 0; endExclusive = endExclusive ?? this.length; if (beginInclusive < 0) { beginInclusive = this.length + beginInclusive; } if (endExclusive < 0) { endExclusive = this.length + endExclusive; } if (beginInclusive < 0 || endExclusive > this.length) { throw new RangeError("index is out of bounds"); } if (beginInclusive === endExclusive) { return { bufs: [], length: 0 }; } if (beginInclusive === 0 && endExclusive === this.length) { return { bufs: [...this.bufs], length: this.length }; } const bufs = []; let offset = 0; for (let i = 0; i < this.bufs.length; i++) { const buf2 = this.bufs[i]; const bufStart = offset; const bufEnd = bufStart + buf2.byteLength; offset = bufEnd; if (beginInclusive >= bufEnd) { continue; } const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd; const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd; if (sliceStartInBuf && sliceEndsInBuf) { if (beginInclusive === bufStart && endExclusive === bufEnd) { bufs.push(buf2); break; } const start = beginInclusive - bufStart; bufs.push(buf2.subarray(start, start + (endExclusive - beginInclusive))); break; } if (sliceStartInBuf) { if (beginInclusive === 0) { bufs.push(buf2); continue; } bufs.push(buf2.subarray(beginInclusive - bufStart)); continue; } if (sliceEndsInBuf) { if (endExclusive === bufEnd) { bufs.push(buf2); break; } bufs.push(buf2.subarray(0, endExclusive - bufStart)); break; } bufs.push(buf2); } return { bufs, length: endExclusive - beginInclusive }; } indexOf(search, offset = 0) { if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) { throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array'); } const needle = search instanceof Uint8Array ? search : search.subarray(); offset = Number(offset ?? 0); if (isNaN(offset)) { offset = 0; } if (offset < 0) { offset = this.length + offset; } if (offset < 0) { offset = 0; } if (search.length === 0) { return offset > this.length ? this.length : offset; } const M = needle.byteLength; if (M === 0) { throw new TypeError("search must be at least 1 byte long"); } const radix = 256; const rightmostPositions = new Int32Array(radix); for (let c = 0; c < radix; c++) { rightmostPositions[c] = -1; } for (let j = 0; j < M; j++) { rightmostPositions[needle[j]] = j; } const right = rightmostPositions; const lastIndex = this.byteLength - needle.byteLength; const lastPatIndex = needle.byteLength - 1; let skip; for (let i = offset; i <= lastIndex; i += skip) { skip = 0; for (let j = lastPatIndex; j >= 0; j--) { const char = this.get(i + j); if (needle[j] !== char) { skip = Math.max(1, j - right[char]); break; } } if (skip === 0) { return i; } } return -1; } getInt8(byteOffset) { const buf2 = this.subarray(byteOffset, byteOffset + 1); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); return view.getInt8(0); } setInt8(byteOffset, value) { const buf2 = allocUnsafe(1); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); view.setInt8(0, value); this.write(buf2, byteOffset); } getInt16(byteOffset, littleEndian) { const buf2 = this.subarray(byteOffset, byteOffset + 2); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); return view.getInt16(0, littleEndian); } setInt16(byteOffset, value, littleEndian) { const buf2 = alloc(2); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); view.setInt16(0, value, littleEndian); this.write(buf2, byteOffset); } getInt32(byteOffset, littleEndian) { const buf2 = this.subarray(byteOffset, byteOffset + 4); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); return view.getInt32(0, littleEndian); } setInt32(byteOffset, value, littleEndian) { const buf2 = alloc(4); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); view.setInt32(0, value, littleEndian); this.write(buf2, byteOffset); } getBigInt64(byteOffset, littleEndian) { const buf2 = this.subarray(byteOffset, byteOffset + 8); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); return view.getBigInt64(0, littleEndian); } setBigInt64(byteOffset, value, littleEndian) { const buf2 = alloc(8); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); view.setBigInt64(0, value, littleEndian); this.write(buf2, byteOffset); } getUint8(byteOffset) { const buf2 = this.subarray(byteOffset, byteOffset + 1); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); return view.getUint8(0); } setUint8(byteOffset, value) { const buf2 = allocUnsafe(1); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); view.setUint8(0, value); this.write(buf2, byteOffset); } getUint16(byteOffset, littleEndian) { const buf2 = this.subarray(byteOffset, byteOffset + 2); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); return view.getUint16(0, littleEndian); } setUint16(byteOffset, value, littleEndian) { const buf2 = alloc(2); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); view.setUint16(0, value, littleEndian); this.write(buf2, byteOffset); } getUint32(byteOffset, littleEndian) { const buf2 = this.subarray(byteOffset, byteOffset + 4); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); return view.getUint32(0, littleEndian); } setUint32(byteOffset, value, littleEndian) { const buf2 = alloc(4); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); view.setUint32(0, value, littleEndian); this.write(buf2, byteOffset); } getBigUint64(byteOffset, littleEndian) { const buf2 = this.subarray(byteOffset, byteOffset + 8); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); return view.getBigUint64(0, littleEndian); } setBigUint64(byteOffset, value, littleEndian) { const buf2 = alloc(8); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); view.setBigUint64(0, value, littleEndian); this.write(buf2, byteOffset); } getFloat32(byteOffset, littleEndian) { const buf2 = this.subarray(byteOffset, byteOffset + 4); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); return view.getFloat32(0, littleEndian); } setFloat32(byteOffset, value, littleEndian) { const buf2 = alloc(4); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); view.setFloat32(0, value, littleEndian); this.write(buf2, byteOffset); } getFloat64(byteOffset, littleEndian) { const buf2 = this.subarray(byteOffset, byteOffset + 8); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); return view.getFloat64(0, littleEndian); } setFloat64(byteOffset, value, littleEndian) { const buf2 = alloc(8); const view = new DataView(buf2.buffer, buf2.byteOffset, buf2.byteLength); view.setFloat64(0, value, littleEndian); this.write(buf2, byteOffset); } equals(other) { if (other == null) { return false; } if (!(other instanceof Uint8ArrayList)) { return false; } if (other.bufs.length !== this.bufs.length) { return false; } for (let i = 0; i < this.bufs.length; i++) { if (!equals3(this.bufs[i], other.bufs[i])) { return false; } } return true; } /** * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this * method if you know the total size of all the Uint8Arrays ahead of time. */ static fromUint8Arrays(bufs, length5) { const list = new Uint8ArrayList(); list.bufs = bufs; if (length5 == null) { length5 = bufs.reduce((acc, curr) => acc + curr.byteLength, 0); } list.length = length5; return list; } }; // node_modules/ipfs-unixfs-importer/dist/src/chunker/fixed-size.js var DEFAULT_CHUNK_SIZE = 262144; var fixedSize = (options = {}) => { const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE; return async function* fixedSizeChunker(source) { let list = new Uint8ArrayList(); let currentLength = 0; let emitted = false; for await (const buffer2 of source) { list.append(buffer2); currentLength += buffer2.length; while (currentLength >= chunkSize) { yield list.slice(0, chunkSize); emitted = true; if (chunkSize === list.length) { list = new Uint8ArrayList(); currentLength = 0; } else { const newBl = new Uint8ArrayList(); newBl.append(list.sublist(chunkSize)); list = newBl; currentLength -= chunkSize; } } } if (!emitted || currentLength > 0) { yield list.subarray(0, currentLength); } }; }; // node_modules/@ipld/dag-pb/src/index.js var src_exports2 = {}; __export(src_exports2, { code: () => code4, createLink: () => createLink, createNode: () => createNode, decode: () => decode17, encode: () => encode12, name: () => name4, prepare: () => prepare, validate: () => validate }); // node_modules/@ipld/dag-pb/node_modules/multiformats/vendor/varint.js var encode_13 = encode10; var MSB3 = 128; var REST3 = 127; var MSBALL3 = ~REST3; var INT3 = Math.pow(2, 31); function encode10(num, out, offset) { out = out || []; offset = offset || 0; var oldOffset = offset; while (num >= INT3) { out[offset++] = num & 255 | MSB3; num /= 128; } while (num & MSBALL3) { out[offset++] = num & 255 | MSB3; num >>>= 7; } out[offset] = num | 0; encode10.bytes = offset - oldOffset + 1; return out; } var decode13 = read3; var MSB$13 = 128; var REST$13 = 127; function read3(buf2, offset) { var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf2.length; do { if (counter >= l) { read3.bytes = 0; throw new RangeError("Could not decode varint"); } b = buf2[counter++]; res += shift < 28 ? (b & REST$13) << shift : (b & REST$13) * Math.pow(2, shift); shift += 7; } while (b >= MSB$13); read3.bytes = counter - offset; return res; } var N13 = Math.pow(2, 7); var N24 = Math.pow(2, 14); var N33 = Math.pow(2, 21); var N43 = Math.pow(2, 28); var N53 = Math.pow(2, 35); var N63 = Math.pow(2, 42); var N73 = Math.pow(2, 49); var N83 = Math.pow(2, 56); var N93 = Math.pow(2, 63); var length3 = function(value) { return value < N13 ? 1 : value < N24 ? 2 : value < N33 ? 3 : value < N43 ? 4 : value < N53 ? 5 : value < N63 ? 6 : value < N73 ? 7 : value < N83 ? 8 : value < N93 ? 9 : 10; }; var varint3 = { encode: encode_13, decode: decode13, encodingLength: length3 }; var _brrp_varint3 = varint3; var varint_default3 = _brrp_varint3; // node_modules/@ipld/dag-pb/node_modules/multiformats/src/varint.js var decode14 = (data, offset = 0) => { const code5 = varint_default3.decode(data, offset); return [code5, varint_default3.decode.bytes]; }; var encodeTo3 = (int, target, offset = 0) => { varint_default3.encode(int, target, offset); return target; }; var encodingLength3 = (int) => { return varint_default3.encodingLength(int); }; // node_modules/@ipld/dag-pb/node_modules/multiformats/src/bytes.js var empty3 = new Uint8Array(0); var equals6 = (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; }; var coerce3 = (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"); }; // node_modules/@ipld/dag-pb/node_modules/multiformats/src/hashes/digest.js var create3 = (code5, digest2) => { const size = digest2.byteLength; const sizeOffset = encodingLength3(code5); const digestOffset = sizeOffset + encodingLength3(size); const bytes2 = new Uint8Array(digestOffset + size); encodeTo3(code5, bytes2, 0); encodeTo3(size, bytes2, sizeOffset); bytes2.set(digest2, digestOffset); return new Digest3(code5, size, digest2, bytes2); }; var decode15 = (multihash) => { const bytes2 = coerce3(multihash); const [code5, sizeOffset] = decode14(bytes2); const [size, digestOffset] = decode14(bytes2.subarray(sizeOffset)); const digest2 = bytes2.subarray(sizeOffset + digestOffset); if (digest2.byteLength !== size) { throw new Error("Incorrect length"); } return new Digest3(code5, size, digest2, bytes2); }; var equals7 = (a, b) => { if (a === b) { return true; } else { const data = ( /** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */ b ); return a.code === data.code && a.size === data.size && data.bytes instanceof Uint8Array && equals6(a.bytes, data.bytes); } }; var Digest3 = class { /** * Creates a multihash digest. * * @param {Code} code * @param {Size} size * @param {Uint8Array} digest * @param {Uint8Array} bytes */ constructor(code5, size, digest2, bytes2) { this.code = code5; this.size = size; this.digest = digest2; this.bytes = bytes2; } }; // node_modules/@ipld/dag-pb/node_modules/multiformats/vendor/base-x.js function base4(ALPHABET, name5) { 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 encode16(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 length5 = 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 < length5) && 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"); } length5 = i2; pbegin++; } var it2 = size - length5; while (it2 !== size && b58[it2] === 0) { it2++; } var str3 = LEADER.repeat(zeroes); for (; it2 < size; ++it2) { str3 += ALPHABET.charAt(b58[it2]); } return str3; } 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 length5 = 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 < length5) && 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"); } length5 = i2; psz++; } if (source[psz] === " ") { return; } var it4 = size - length5; 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 decode23(string2) { var buffer2 = decodeUnsafe(string2); if (buffer2) { return buffer2; } throw new Error(`Non-${name5} character`); } return { encode: encode16, decodeUnsafe, decode: decode23 }; } var src3 = base4; var _brrp__multiformats_scope_baseX3 = src3; var base_x_default3 = _brrp__multiformats_scope_baseX3; // node_modules/@ipld/dag-pb/node_modules/multiformats/src/bases/base.js var Encoder4 = class { /** * @param {Base} name * @param {Prefix} prefix * @param {(bytes:Uint8Array) => string} baseEncode */ constructor(name5, prefix, baseEncode) { this.name = name5; this.prefix = prefix; this.baseEncode = baseEncode; } /** * @param {Uint8Array} bytes * @returns {API.Multibase} */ encode(bytes2) { if (bytes2 instanceof Uint8Array) { return `${this.prefix}${this.baseEncode(bytes2)}`; } else { throw Error("Unknown type, must be binary type"); } } }; var Decoder3 = class { /** * @param {Base} name * @param {Prefix} prefix * @param {(text:string) => Uint8Array} baseDecode */ constructor(name5, prefix, baseDecode) { this.name = name5; this.prefix = prefix; if (prefix.codePointAt(0) === void 0) { throw new Error("Invalid prefix character"); } this.prefixCodePoint = /** @type {number} */ prefix.codePointAt(0); this.baseDecode = baseDecode; } /** * @param {string} text */ 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"); } } /** * @template {string} OtherPrefix * @param {API.UnibaseDecoder|ComposedDecoder} decoder * @returns {ComposedDecoder} */ or(decoder) { return or3(this, decoder); } }; var ComposedDecoder3 = class { /** * @param {Decoders} decoders */ constructor(decoders) { this.decoders = decoders; } /** * @template {string} OtherPrefix * @param {API.UnibaseDecoder|ComposedDecoder} decoder * @returns {ComposedDecoder} */ or(decoder) { return or3(this, decoder); } /** * @param {string} input * @returns {Uint8Array} */ decode(input) { const prefix = ( /** @type {Prefix} */ input[0] ); const decoder = this.decoders[prefix]; if (decoder) { return decoder.decode(input); } else { throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); } } }; var or3 = (left, right) => new ComposedDecoder3( /** @type {Decoders} */ { ...left.decoders || { [ /** @type API.UnibaseDecoder */ left.prefix ]: left }, ...right.decoders || { [ /** @type API.UnibaseDecoder */ right.prefix ]: right } } ); var Codec3 = class { /** * @param {Base} name * @param {Prefix} prefix * @param {(bytes:Uint8Array) => string} baseEncode * @param {(text:string) => Uint8Array} baseDecode */ constructor(name5, prefix, baseEncode, baseDecode) { this.name = name5; this.prefix = prefix; this.baseEncode = baseEncode; this.baseDecode = baseDecode; this.encoder = new Encoder4(name5, prefix, baseEncode); this.decoder = new Decoder3(name5, prefix, baseDecode); } /** * @param {Uint8Array} input */ encode(input) { return this.encoder.encode(input); } /** * @param {string} input */ decode(input) { return this.decoder.decode(input); } }; var from4 = ({ name: name5, prefix, encode: encode16, decode: decode23 }) => new Codec3(name5, prefix, encode16, decode23); var baseX3 = ({ prefix, name: name5, alphabet: alphabet2 }) => { const { encode: encode16, decode: decode23 } = base_x_default3(alphabet2, name5); return from4({ prefix, name: name5, encode: encode16, /** * @param {string} text */ decode: (text) => coerce3(decode23(text)) }); }; var decode16 = (string2, alphabet2, bitsPerChar, name5) => { const codes = {}; for (let i = 0; i < alphabet2.length; ++i) { codes[alphabet2[i]] = i; } let end = string2.length; while (string2[end - 1] === "=") { --end; } const out = new Uint8Array(end * bitsPerChar / 8 | 0); let bits = 0; let buffer2 = 0; let written = 0; for (let i = 0; i < end; ++i) { const value = codes[string2[i]]; if (value === void 0) { throw new SyntaxError(`Non-${name5} character`); } buffer2 = buffer2 << bitsPerChar | value; bits += bitsPerChar; if (bits >= 8) { bits -= 8; out[written++] = 255 & buffer2 >> bits; } } if (bits >= bitsPerChar || 255 & buffer2 << 8 - bits) { throw new SyntaxError("Unexpected end of data"); } return out; }; var encode11 = (data, alphabet2, bitsPerChar) => { const pad = alphabet2[alphabet2.length - 1] === "="; const mask = (1 << bitsPerChar) - 1; let out = ""; let bits = 0; let buffer2 = 0; for (let i = 0; i < data.length; ++i) { buffer2 = buffer2 << 8 | data[i]; bits += 8; while (bits > bitsPerChar) { bits -= bitsPerChar; out += alphabet2[mask & buffer2 >> bits]; } } if (bits) { out += alphabet2[mask & buffer2 << bitsPerChar - bits]; } if (pad) { while (out.length * bitsPerChar & 7) { out += "="; } } return out; }; var rfc46483 = ({ name: name5, prefix, bitsPerChar, alphabet: alphabet2 }) => { return from4({ prefix, name: name5, encode(input) { return encode11(input, alphabet2, bitsPerChar); }, decode(input) { return decode16(input, alphabet2, bitsPerChar, name5); } }); }; // node_modules/@ipld/dag-pb/node_modules/multiformats/src/bases/base58.js var base58btc3 = baseX3({ name: "base58btc", prefix: "z", alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" }); var base58flickr3 = baseX3({ name: "base58flickr", prefix: "Z", alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" }); // node_modules/@ipld/dag-pb/node_modules/multiformats/src/bases/base32.js var base323 = rfc46483({ prefix: "b", name: "base32", alphabet: "abcdefghijklmnopqrstuvwxyz234567", bitsPerChar: 5 }); var base32upper3 = rfc46483({ prefix: "B", name: "base32upper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", bitsPerChar: 5 }); var base32pad3 = rfc46483({ prefix: "c", name: "base32pad", alphabet: "abcdefghijklmnopqrstuvwxyz234567=", bitsPerChar: 5 }); var base32padupper3 = rfc46483({ prefix: "C", name: "base32padupper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", bitsPerChar: 5 }); var base32hex3 = rfc46483({ prefix: "v", name: "base32hex", alphabet: "0123456789abcdefghijklmnopqrstuv", bitsPerChar: 5 }); var base32hexupper3 = rfc46483({ prefix: "V", name: "base32hexupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", bitsPerChar: 5 }); var base32hexpad3 = rfc46483({ prefix: "t", name: "base32hexpad", alphabet: "0123456789abcdefghijklmnopqrstuv=", bitsPerChar: 5 }); var base32hexpadupper3 = rfc46483({ prefix: "T", name: "base32hexpadupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", bitsPerChar: 5 }); var base32z3 = rfc46483({ prefix: "h", name: "base32z", alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", bitsPerChar: 5 }); // node_modules/@ipld/dag-pb/node_modules/multiformats/src/cid.js var format3 = (link, base6) => { const { bytes: bytes2, version } = link; switch (version) { case 0: return toStringV03( bytes2, baseCache3(link), /** @type {API.MultibaseEncoder<"z">} */ base6 || base58btc3.encoder ); default: return toStringV13( bytes2, baseCache3(link), /** @type {API.MultibaseEncoder} */ base6 || base323.encoder ); } }; var cache3 = /* @__PURE__ */ new WeakMap(); var baseCache3 = (cid) => { const baseCache5 = cache3.get(cid); if (baseCache5 == null) { const baseCache6 = /* @__PURE__ */ new Map(); cache3.set(cid, baseCache6); return baseCache6; } return baseCache5; }; var CID3 = class { /** * @param {Version} version - Version of the CID * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv * @param {API.MultihashDigest} multihash - (Multi)hash of the of the content. * @param {Uint8Array} bytes * */ constructor(version, code5, multihash, bytes2) { this.code = code5; this.version = version; this.multihash = multihash; this.bytes = bytes2; this["/"] = bytes2; } /** * 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; } /** * @returns {CID} */ toV0() { switch (this.version) { case 0: { return ( /** @type {CID} */ this ); } case 1: { const { code: code5, multihash } = this; if (code5 !== DAG_PB_CODE3) { throw new Error("Cannot convert a non dag-pb CID to CIDv0"); } if (multihash.code !== SHA_256_CODE3) { throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0"); } return ( /** @type {CID} */ CID3.createV0( /** @type {API.MultihashDigest} */ multihash ) ); } default: { throw Error( `Can not convert CID version ${this.version} to version 0. This is a bug please report` ); } } } /** * @returns {CID} */ toV1() { switch (this.version) { case 0: { const { code: code5, digest: digest2 } = this.multihash; const multihash = create3(code5, digest2); return ( /** @type {CID} */ CID3.createV1(this.code, multihash) ); } case 1: { return ( /** @type {CID} */ this ); } default: { throw Error( `Can not convert CID version ${this.version} to version 1. This is a bug please report` ); } } } /** * @param {unknown} other * @returns {other is CID} */ equals(other) { return CID3.equals(this, other); } /** * @template {unknown} Data * @template {number} Format * @template {number} Alg * @template {API.Version} Version * @param {API.Link} self * @param {unknown} other * @returns {other is CID} */ static equals(self2, other) { const unknown = ( /** @type {{code?:unknown, version?:unknown, multihash?:unknown}} */ other ); return unknown && self2.code === unknown.code && self2.version === unknown.version && equals7(self2.multihash, unknown.multihash); } /** * @param {API.MultibaseEncoder} [base] * @returns {string} */ toString(base6) { return format3(this, base6); } toJSON() { return { "/": format3(this) }; } link() { return this; } get [Symbol.toStringTag]() { return "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. * * @template {unknown} Data * @template {number} Format * @template {number} Alg * @template {API.Version} Version * @template {unknown} U * @param {API.Link|U} input * @returns {CID|null} */ static asCID(input) { if (input == null) { return null; } const value = ( /** @type {any} */ input ); if (value instanceof CID3) { return value; } else if (value["/"] != null && value["/"] === value.bytes || value.asCID === value) { const { version, code: code5, multihash, bytes: bytes2 } = value; return new CID3( version, code5, /** @type {API.MultihashDigest} */ multihash, bytes2 || encodeCID3(version, code5, multihash.bytes) ); } else if (value[cidSymbol3] === true) { const { version, multihash, code: code5 } = value; const digest2 = ( /** @type {API.MultihashDigest} */ decode15(multihash) ); return CID3.create(version, code5, digest2); } else { return null; } } /** * * @template {unknown} Data * @template {number} Format * @template {number} Alg * @template {API.Version} Version * @param {Version} version - Version of the CID * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv * @param {API.MultihashDigest} digest - (Multi)hash of the of the content. * @returns {CID} */ static create(version, code5, digest2) { if (typeof code5 !== "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 (code5 !== DAG_PB_CODE3) { throw new Error( `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE3}) block encoding` ); } else { return new CID3(version, code5, digest2, digest2.bytes); } } case 1: { const bytes2 = encodeCID3(version, code5, digest2.bytes); return new CID3(version, code5, digest2, bytes2); } default: { throw new Error("Invalid version"); } } } /** * Simplified version of `create` for CIDv0. * * @template {unknown} [T=unknown] * @param {API.MultihashDigest} digest - Multihash. * @returns {CID} */ static createV0(digest2) { return CID3.create(0, DAG_PB_CODE3, digest2); } /** * Simplified version of `create` for CIDv1. * * @template {unknown} Data * @template {number} Code * @template {number} Alg * @param {Code} code - Content encoding format code. * @param {API.MultihashDigest} digest - Miltihash of the content. * @returns {CID} */ static createV1(code5, digest2) { return CID3.create(1, code5, 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. * * @template {unknown} Data * @template {number} Code * @template {number} Alg * @template {API.Version} Ver * @param {API.ByteView>} bytes * @returns {CID} */ static decode(bytes2) { const [cid, remainder] = CID3.decodeFirst(bytes2); if (remainder.length) { 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. * * @template {unknown} T * @template {number} C * @template {number} A * @template {API.Version} V * @param {API.ByteView>} bytes * @returns {[CID, Uint8Array]} */ static decodeFirst(bytes2) { const specs = CID3.inspectBytes(bytes2); const prefixSize = specs.size - specs.multihashSize; const multihashBytes = coerce3( bytes2.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 Digest3( specs.multihashCode, specs.digestSize, digestBytes, multihashBytes ); const cid = specs.version === 0 ? CID3.createV0( /** @type {API.MultihashDigest} */ digest2 ) : CID3.createV1(specs.codec, digest2); return [ /** @type {CID} */ cid, bytes2.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. * * @template {unknown} T * @template {number} C * @template {number} A * @template {API.Version} V * @param {API.ByteView>} initialBytes * @returns {{ version:V, codec:C, multihashCode:A, digestSize:number, multihashSize:number, size:number }} */ static inspectBytes(initialBytes) { let offset = 0; const next = () => { const [i, length5] = decode14(initialBytes.subarray(offset)); offset += length5; return i; }; let version = ( /** @type {V} */ next() ); let codec = ( /** @type {C} */ DAG_PB_CODE3 ); if ( /** @type {number} */ version === 18 ) { version = /** @type {V} */ 0; offset = 0; } else { codec = /** @type {C} */ next(); } if (version !== 0 && version !== 1) { throw new RangeError(`Invalid CID version ${version}`); } const prefixSize = offset; const multihashCode = ( /** @type {A} */ 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). * * @template {string} Prefix * @template {unknown} Data * @template {number} Code * @template {number} Alg * @template {API.Version} Ver * @param {API.ToString, Prefix>} source * @param {API.MultibaseDecoder} [base] * @returns {CID} */ static parse(source, base6) { const [prefix, bytes2] = parseCIDtoBytes3(source, base6); const cid = CID3.decode(bytes2); if (cid.version === 0 && source[0] !== "Q") { throw Error("Version 0 CID string must not include multibase prefix"); } baseCache3(cid).set(prefix, source); return cid; } }; var parseCIDtoBytes3 = (source, base6) => { switch (source[0]) { case "Q": { const decoder = base6 || base58btc3; return [ /** @type {Prefix} */ base58btc3.prefix, decoder.decode(`${base58btc3.prefix}${source}`) ]; } case base58btc3.prefix: { const decoder = base6 || base58btc3; return [ /** @type {Prefix} */ base58btc3.prefix, decoder.decode(source) ]; } case base323.prefix: { const decoder = base6 || base323; return [ /** @type {Prefix} */ base323.prefix, decoder.decode(source) ]; } default: { if (base6 == null) { throw Error( "To parse non base32 or base58btc encoded CID multibase decoder must be provided" ); } return [ /** @type {Prefix} */ source[0], base6.decode(source) ]; } } }; var toStringV03 = (bytes2, cache5, base6) => { const { prefix } = base6; if (prefix !== base58btc3.prefix) { throw Error(`Cannot string encode V0 in ${base6.name} encoding`); } const cid = cache5.get(prefix); if (cid == null) { const cid2 = base6.encode(bytes2).slice(1); cache5.set(prefix, cid2); return cid2; } else { return cid; } }; var toStringV13 = (bytes2, cache5, base6) => { const { prefix } = base6; const cid = cache5.get(prefix); if (cid == null) { const cid2 = base6.encode(bytes2); cache5.set(prefix, cid2); return cid2; } else { return cid; } }; var DAG_PB_CODE3 = 112; var SHA_256_CODE3 = 18; var encodeCID3 = (version, code5, multihash) => { const codeOffset = encodingLength3(version); const hashOffset = codeOffset + encodingLength3(code5); const bytes2 = new Uint8Array(hashOffset + multihash.byteLength); encodeTo3(version, bytes2, 0); encodeTo3(code5, bytes2, codeOffset); bytes2.set(multihash, hashOffset); return bytes2; }; var cidSymbol3 = Symbol.for("@ipld/js-cid/CID"); // node_modules/@ipld/dag-pb/src/pb-decode.js var textDecoder4 = new TextDecoder(); function decodeVarint(bytes2, offset) { let v = 0; for (let shift = 0; ; shift += 7) { if (shift >= 64) { throw new Error("protobuf: varint overflow"); } if (offset >= bytes2.length) { throw new Error("protobuf: unexpected end of data"); } const b = bytes2[offset++]; v += shift < 28 ? (b & 127) << shift : (b & 127) * 2 ** shift; if (b < 128) { break; } } return [v, offset]; } function decodeBytes(bytes2, offset) { let byteLen; [byteLen, offset] = decodeVarint(bytes2, offset); const postOffset = offset + byteLen; if (byteLen < 0 || postOffset < 0) { throw new Error("protobuf: invalid length"); } if (postOffset > bytes2.length) { throw new Error("protobuf: unexpected end of data"); } return [bytes2.subarray(offset, postOffset), postOffset]; } function decodeKey(bytes2, index) { let wire; [wire, index] = decodeVarint(bytes2, index); return [wire & 7, wire >> 3, index]; } function decodeLink(bytes2) { const link = {}; const l = bytes2.length; let index = 0; while (index < l) { let wireType, fieldNum; [wireType, fieldNum, index] = decodeKey(bytes2, index); if (fieldNum === 1) { if (link.Hash) { throw new Error("protobuf: (PBLink) duplicate Hash section"); } if (wireType !== 2) { throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Hash`); } if (link.Name !== void 0) { throw new Error("protobuf: (PBLink) invalid order, found Name before Hash"); } if (link.Tsize !== void 0) { throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash"); } [link.Hash, index] = decodeBytes(bytes2, index); } else if (fieldNum === 2) { if (link.Name !== void 0) { throw new Error("protobuf: (PBLink) duplicate Name section"); } if (wireType !== 2) { throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Name`); } if (link.Tsize !== void 0) { throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name"); } let byts; [byts, index] = decodeBytes(bytes2, index); link.Name = textDecoder4.decode(byts); } else if (fieldNum === 3) { if (link.Tsize !== void 0) { throw new Error("protobuf: (PBLink) duplicate Tsize section"); } if (wireType !== 0) { throw new Error(`protobuf: (PBLink) wrong wireType (${wireType}) for Tsize`); } [link.Tsize, index] = decodeVarint(bytes2, index); } else { throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${fieldNum}`); } } if (index > l) { throw new Error("protobuf: (PBLink) unexpected end of data"); } return link; } function decodeNode(bytes2) { const l = bytes2.length; let index = 0; let links2; let linksBeforeData = false; let data; while (index < l) { let wireType, fieldNum; [wireType, fieldNum, index] = decodeKey(bytes2, index); if (wireType !== 2) { throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${wireType}`); } if (fieldNum === 1) { if (data) { throw new Error("protobuf: (PBNode) duplicate Data section"); } [data, index] = decodeBytes(bytes2, index); if (links2) { linksBeforeData = true; } } else if (fieldNum === 2) { if (linksBeforeData) { throw new Error("protobuf: (PBNode) duplicate Links section"); } else if (!links2) { links2 = []; } let byts; [byts, index] = decodeBytes(bytes2, index); links2.push(decodeLink(byts)); } else { throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${fieldNum}`); } } if (index > l) { throw new Error("protobuf: (PBNode) unexpected end of data"); } const node = {}; if (data) { node.Data = data; } node.Links = links2 || []; return node; } // node_modules/@ipld/dag-pb/src/pb-encode.js var textEncoder4 = new TextEncoder(); var maxInt32 = 2 ** 32; var maxUInt32 = 2 ** 31; function encodeLink(link, bytes2) { let i = bytes2.length; if (typeof link.Tsize === "number") { if (link.Tsize < 0) { throw new Error("Tsize cannot be negative"); } if (!Number.isSafeInteger(link.Tsize)) { throw new Error("Tsize too large for encoding"); } i = encodeVarint(bytes2, i, link.Tsize) - 1; bytes2[i] = 24; } if (typeof link.Name === "string") { const nameBytes = textEncoder4.encode(link.Name); i -= nameBytes.length; bytes2.set(nameBytes, i); i = encodeVarint(bytes2, i, nameBytes.length) - 1; bytes2[i] = 18; } if (link.Hash) { i -= link.Hash.length; bytes2.set(link.Hash, i); i = encodeVarint(bytes2, i, link.Hash.length) - 1; bytes2[i] = 10; } return bytes2.length - i; } function encodeNode(node) { const size = sizeNode(node); const bytes2 = new Uint8Array(size); let i = size; if (node.Data) { i -= node.Data.length; bytes2.set(node.Data, i); i = encodeVarint(bytes2, i, node.Data.length) - 1; bytes2[i] = 10; } if (node.Links) { for (let index = node.Links.length - 1; index >= 0; index--) { const size2 = encodeLink(node.Links[index], bytes2.subarray(0, i)); i -= size2; i = encodeVarint(bytes2, i, size2) - 1; bytes2[i] = 18; } } return bytes2; } function sizeLink(link) { let n = 0; if (link.Hash) { const l = link.Hash.length; n += 1 + l + sov(l); } if (typeof link.Name === "string") { const l = textEncoder4.encode(link.Name).length; n += 1 + l + sov(l); } if (typeof link.Tsize === "number") { n += 1 + sov(link.Tsize); } return n; } function sizeNode(node) { let n = 0; if (node.Data) { const l = node.Data.length; n += 1 + l + sov(l); } if (node.Links) { for (const link of node.Links) { const l = sizeLink(link); n += 1 + l + sov(l); } } return n; } function encodeVarint(bytes2, offset, v) { offset -= sov(v); const base6 = offset; while (v >= maxUInt32) { bytes2[offset++] = v & 127 | 128; v /= 128; } while (v >= 128) { bytes2[offset++] = v & 127 | 128; v >>>= 7; } bytes2[offset] = v; return base6; } function sov(x) { if (x % 2 === 0) { x++; } return Math.floor((len64(x) + 6) / 7); } function len64(x) { let n = 0; if (x >= maxInt32) { x = Math.floor(x / maxInt32); n = 32; } if (x >= 1 << 16) { x >>>= 16; n += 16; } if (x >= 1 << 8) { x >>>= 8; n += 8; } return n + len8tab[x]; } var len8tab = [ 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 ]; // node_modules/@ipld/dag-pb/src/util.js var pbNodeProperties = ["Data", "Links"]; var pbLinkProperties = ["Hash", "Name", "Tsize"]; var textEncoder5 = new TextEncoder(); function linkComparator(a, b) { if (a === b) { return 0; } const abuf = a.Name ? textEncoder5.encode(a.Name) : []; const bbuf = b.Name ? textEncoder5.encode(b.Name) : []; let x = abuf.length; let y = bbuf.length; for (let i = 0, len = Math.min(x, y); i < len; ++i) { if (abuf[i] !== bbuf[i]) { x = abuf[i]; y = bbuf[i]; break; } } return x < y ? -1 : y < x ? 1 : 0; } function hasOnlyProperties(node, properties) { return !Object.keys(node).some((p) => !properties.includes(p)); } function asLink(link) { if (typeof link.asCID === "object") { const Hash2 = CID3.asCID(link); if (!Hash2) { throw new TypeError("Invalid DAG-PB form"); } return { Hash: Hash2 }; } if (typeof link !== "object" || Array.isArray(link)) { throw new TypeError("Invalid DAG-PB form"); } const pbl = {}; if (link.Hash) { let cid = CID3.asCID(link.Hash); try { if (!cid) { if (typeof link.Hash === "string") { cid = CID3.parse(link.Hash); } else if (link.Hash instanceof Uint8Array) { cid = CID3.decode(link.Hash); } } } catch (e) { throw new TypeError(`Invalid DAG-PB form: ${e.message}`); } if (cid) { pbl.Hash = cid; } } if (!pbl.Hash) { throw new TypeError("Invalid DAG-PB form"); } if (typeof link.Name === "string") { pbl.Name = link.Name; } if (typeof link.Tsize === "number") { pbl.Tsize = link.Tsize; } return pbl; } function prepare(node) { if (node instanceof Uint8Array || typeof node === "string") { node = { Data: node }; } if (typeof node !== "object" || Array.isArray(node)) { throw new TypeError("Invalid DAG-PB form"); } const pbn = {}; if (node.Data !== void 0) { if (typeof node.Data === "string") { pbn.Data = textEncoder5.encode(node.Data); } else if (node.Data instanceof Uint8Array) { pbn.Data = node.Data; } else { throw new TypeError("Invalid DAG-PB form"); } } if (node.Links !== void 0) { if (Array.isArray(node.Links)) { pbn.Links = node.Links.map(asLink); pbn.Links.sort(linkComparator); } else { throw new TypeError("Invalid DAG-PB form"); } } else { pbn.Links = []; } return pbn; } function validate(node) { if (!node || typeof node !== "object" || Array.isArray(node) || node instanceof Uint8Array || node["/"] && node["/"] === node.bytes) { throw new TypeError("Invalid DAG-PB form"); } if (!hasOnlyProperties(node, pbNodeProperties)) { throw new TypeError("Invalid DAG-PB form (extraneous properties)"); } if (node.Data !== void 0 && !(node.Data instanceof Uint8Array)) { throw new TypeError("Invalid DAG-PB form (Data must be bytes)"); } if (!Array.isArray(node.Links)) { throw new TypeError("Invalid DAG-PB form (Links must be a list)"); } for (let i = 0; i < node.Links.length; i++) { const link = node.Links[i]; if (!link || typeof link !== "object" || Array.isArray(link) || link instanceof Uint8Array || link["/"] && link["/"] === link.bytes) { throw new TypeError("Invalid DAG-PB form (bad link)"); } if (!hasOnlyProperties(link, pbLinkProperties)) { throw new TypeError("Invalid DAG-PB form (extraneous properties on link)"); } if (link.Hash === void 0) { throw new TypeError("Invalid DAG-PB form (link must have a Hash)"); } if (link.Hash == null || !link.Hash["/"] || link.Hash["/"] !== link.Hash.bytes) { throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)"); } if (link.Name !== void 0 && typeof link.Name !== "string") { throw new TypeError("Invalid DAG-PB form (link Name must be a string)"); } if (link.Tsize !== void 0) { if (typeof link.Tsize !== "number" || link.Tsize % 1 !== 0) { throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)"); } if (link.Tsize < 0) { throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)"); } } if (i > 0 && linkComparator(link, node.Links[i - 1]) === -1) { throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)"); } } } function createNode(data, links2 = []) { return prepare({ Data: data, Links: links2 }); } function createLink(name5, size, cid) { return asLink({ Hash: cid, Name: name5, Tsize: size }); } // node_modules/@ipld/dag-pb/src/index.js var name4 = "dag-pb"; var code4 = 112; function encode12(node) { validate(node); const pbn = {}; if (node.Links) { pbn.Links = node.Links.map((l) => { const link = {}; if (l.Hash) { link.Hash = l.Hash.bytes; } if (l.Name !== void 0) { link.Name = l.Name; } if (l.Tsize !== void 0) { link.Tsize = l.Tsize; } return link; }); } if (node.Data) { pbn.Data = node.Data; } return encodeNode(pbn); } function decode17(bytes2) { const pbn = decodeNode(bytes2); const node = {}; if (pbn.Data) { node.Data = pbn.Data; } if (pbn.Links) { node.Links = pbn.Links.map((l) => { const link = {}; try { link.Hash = CID3.decode(l.Hash); } catch (e) { } if (!link.Hash) { throw new Error("Invalid Hash field found in link, expected CID"); } if (l.Name !== void 0) { link.Name = l.Name; } if (l.Tsize !== void 0) { link.Tsize = l.Tsize; } return link; }); } return node; } // node_modules/ipfs-unixfs/dist/src/index.js var import_err_code = __toESM(require_err_code(), 1); // node_modules/protons-runtime/dist/src/utils.js var import_reader = __toESM(require_reader(), 1); var import_reader_buffer = __toESM(require_reader_buffer(), 1); var import_minimal = __toESM(require_minimal(), 1); var import_writer = __toESM(require_writer(), 1); var import_writer_buffer = __toESM(require_writer_buffer(), 1); function configure() { import_minimal.default._configure(); import_reader.default._configure(import_reader_buffer.default); import_writer.default._configure(import_writer_buffer.default); } configure(); var methods = [ "uint64", "int64", "sint64", "fixed64", "sfixed64" ]; function patchReader(obj) { for (const method of methods) { if (obj[method] == null) { continue; } const original = obj[method]; obj[method] = function() { return BigInt(original.call(this).toString()); }; } return obj; } function reader(buf2) { return patchReader(new import_reader.default(buf2)); } function patchWriter(obj) { for (const method of methods) { if (obj[method] == null) { continue; } const original = obj[method]; obj[method] = function(val) { return original.call(this, val.toString()); }; } return obj; } function writer() { return patchWriter(import_writer.default.create()); } // node_modules/protons-runtime/dist/src/decode.js function decodeMessage(buf2, codec) { const r = reader(buf2 instanceof Uint8Array ? buf2 : buf2.subarray()); return codec.decode(r); } // node_modules/protons-runtime/dist/src/encode.js function encodeMessage(message2, codec) { const w = writer(); codec.encode(message2, w, { lengthDelimited: false }); return w.finish(); } // node_modules/protons-runtime/dist/src/codec.js var CODEC_TYPES; (function(CODEC_TYPES2) { CODEC_TYPES2[CODEC_TYPES2["VARINT"] = 0] = "VARINT"; CODEC_TYPES2[CODEC_TYPES2["BIT64"] = 1] = "BIT64"; CODEC_TYPES2[CODEC_TYPES2["LENGTH_DELIMITED"] = 2] = "LENGTH_DELIMITED"; CODEC_TYPES2[CODEC_TYPES2["START_GROUP"] = 3] = "START_GROUP"; CODEC_TYPES2[CODEC_TYPES2["END_GROUP"] = 4] = "END_GROUP"; CODEC_TYPES2[CODEC_TYPES2["BIT32"] = 5] = "BIT32"; })(CODEC_TYPES || (CODEC_TYPES = {})); function createCodec2(name5, type, encode16, decode23) { return { name: name5, type, encode: encode16, decode: decode23 }; } // node_modules/protons-runtime/dist/src/codecs/enum.js function enumeration(v) { function findValue(val) { if (v[val.toString()] == null) { throw new Error("Invalid enum value"); } return v[val]; } const encode16 = function enumEncode(val, writer2) { const enumValue = findValue(val); writer2.int32(enumValue); }; const decode23 = function enumDecode(reader2) { const val = reader2.int32(); return findValue(val); }; return createCodec2("enum", CODEC_TYPES.VARINT, encode16, decode23); } // node_modules/protons-runtime/dist/src/codecs/message.js function message(encode16, decode23) { return createCodec2("message", CODEC_TYPES.LENGTH_DELIMITED, encode16, decode23); } // node_modules/ipfs-unixfs/dist/src/unixfs.js var Data; (function(Data2) { let DataType; (function(DataType2) { DataType2["Raw"] = "Raw"; DataType2["Directory"] = "Directory"; DataType2["File"] = "File"; DataType2["Metadata"] = "Metadata"; DataType2["Symlink"] = "Symlink"; DataType2["HAMTShard"] = "HAMTShard"; })(DataType = Data2.DataType || (Data2.DataType = {})); let __DataTypeValues; (function(__DataTypeValues2) { __DataTypeValues2[__DataTypeValues2["Raw"] = 0] = "Raw"; __DataTypeValues2[__DataTypeValues2["Directory"] = 1] = "Directory"; __DataTypeValues2[__DataTypeValues2["File"] = 2] = "File"; __DataTypeValues2[__DataTypeValues2["Metadata"] = 3] = "Metadata"; __DataTypeValues2[__DataTypeValues2["Symlink"] = 4] = "Symlink"; __DataTypeValues2[__DataTypeValues2["HAMTShard"] = 5] = "HAMTShard"; })(__DataTypeValues || (__DataTypeValues = {})); (function(DataType2) { DataType2.codec = () => { return enumeration(__DataTypeValues); }; })(DataType = Data2.DataType || (Data2.DataType = {})); let _codec; Data2.codec = () => { if (_codec == null) { _codec = message((obj, w, opts = {}) => { if (opts.lengthDelimited !== false) { w.fork(); } if (obj.Type != null) { w.uint32(8); Data2.DataType.codec().encode(obj.Type, w); } if (obj.Data != null) { w.uint32(18); w.bytes(obj.Data); } if (obj.filesize != null) { w.uint32(24); w.uint64(obj.filesize); } if (obj.blocksizes != null) { for (const value of obj.blocksizes) { w.uint32(32); w.uint64(value); } } if (obj.hashType != null) { w.uint32(40); w.uint64(obj.hashType); } if (obj.fanout != null) { w.uint32(48); w.uint64(obj.fanout); } if (obj.mode != null) { w.uint32(56); w.uint32(obj.mode); } if (obj.mtime != null) { w.uint32(66); UnixTime.codec().encode(obj.mtime, w); } if (opts.lengthDelimited !== false) { w.ldelim(); } }, (reader2, length5) => { const obj = { blocksizes: [] }; const end = length5 == null ? reader2.len : reader2.pos + length5; while (reader2.pos < end) { const tag = reader2.uint32(); switch (tag >>> 3) { case 1: obj.Type = Data2.DataType.codec().decode(reader2); break; case 2: obj.Data = reader2.bytes(); break; case 3: obj.filesize = reader2.uint64(); break; case 4: obj.blocksizes.push(reader2.uint64()); break; case 5: obj.hashType = reader2.uint64(); break; case 6: obj.fanout = reader2.uint64(); break; case 7: obj.mode = reader2.uint32(); break; case 8: obj.mtime = UnixTime.codec().decode(reader2, reader2.uint32()); break; default: reader2.skipType(tag & 7); break; } } return obj; }); } return _codec; }; Data2.encode = (obj) => { return encodeMessage(obj, Data2.codec()); }; Data2.decode = (buf2) => { return decodeMessage(buf2, Data2.codec()); }; })(Data || (Data = {})); var UnixTime; (function(UnixTime2) { let _codec; UnixTime2.codec = () => { if (_codec == null) { _codec = message((obj, w, opts = {}) => { if (opts.lengthDelimited !== false) { w.fork(); } if (obj.Seconds != null) { w.uint32(8); w.int64(obj.Seconds); } if (obj.FractionalNanoseconds != null) { w.uint32(21); w.fixed32(obj.FractionalNanoseconds); } if (opts.lengthDelimited !== false) { w.ldelim(); } }, (reader2, length5) => { const obj = {}; const end = length5 == null ? reader2.len : reader2.pos + length5; while (reader2.pos < end) { const tag = reader2.uint32(); switch (tag >>> 3) { case 1: obj.Seconds = reader2.int64(); break; case 2: obj.FractionalNanoseconds = reader2.fixed32(); break; default: reader2.skipType(tag & 7); break; } } return obj; }); } return _codec; }; UnixTime2.encode = (obj) => { return encodeMessage(obj, UnixTime2.codec()); }; UnixTime2.decode = (buf2) => { return decodeMessage(buf2, UnixTime2.codec()); }; })(UnixTime || (UnixTime = {})); var Metadata; (function(Metadata2) { let _codec; Metadata2.codec = () => { if (_codec == null) { _codec = message((obj, w, opts = {}) => { if (opts.lengthDelimited !== false) { w.fork(); } if (obj.MimeType != null) { w.uint32(10); w.string(obj.MimeType); } if (opts.lengthDelimited !== false) { w.ldelim(); } }, (reader2, length5) => { const obj = {}; const end = length5 == null ? reader2.len : reader2.pos + length5; while (reader2.pos < end) { const tag = reader2.uint32(); switch (tag >>> 3) { case 1: obj.MimeType = reader2.string(); break; default: reader2.skipType(tag & 7); break; } } return obj; }); } return _codec; }; Metadata2.encode = (obj) => { return encodeMessage(obj, Metadata2.codec()); }; Metadata2.decode = (buf2) => { return decodeMessage(buf2, Metadata2.codec()); }; })(Metadata || (Metadata = {})); // node_modules/ipfs-unixfs/dist/src/index.js var types = { Raw: "raw", Directory: "directory", File: "file", Metadata: "metadata", Symlink: "symlink", HAMTShard: "hamt-sharded-directory" }; var dirTypes = [ "directory", "hamt-sharded-directory" ]; var DEFAULT_FILE_MODE = parseInt("0644", 8); var DEFAULT_DIRECTORY_MODE = parseInt("0755", 8); var UnixFS = class { /** * Decode from protobuf https://github.com/ipfs/specs/blob/master/UNIXFS.md */ static unmarshal(marshaled) { const message2 = Data.decode(marshaled); const data = new UnixFS({ type: types[message2.Type != null ? message2.Type.toString() : "File"], data: message2.Data, blockSizes: message2.blocksizes, mode: message2.mode, mtime: message2.mtime != null ? { secs: message2.mtime.Seconds ?? 0n, nsecs: message2.mtime.FractionalNanoseconds } : void 0 }); data._originalMode = message2.mode ?? 0; return data; } type; data; blockSizes; hashType; fanout; mtime; _mode; _originalMode; constructor(options = { type: "file" }) { const { type, data, blockSizes, hashType, fanout, mtime, mode } = options; if (type != null && !Object.values(types).includes(type)) { throw (0, import_err_code.default)(new Error("Type: " + type + " is not valid"), "ERR_INVALID_TYPE"); } this.type = type ?? "file"; this.data = data; this.hashType = hashType; this.fanout = fanout; this.blockSizes = blockSizes ?? []; this._originalMode = 0; this.mode = mode; this.mtime = mtime; } set mode(mode) { if (mode == null) { this._mode = this.isDirectory() ? DEFAULT_DIRECTORY_MODE : DEFAULT_FILE_MODE; } else { this._mode = mode & 4095; } } get mode() { return this._mode; } isDirectory() { return dirTypes.includes(this.type); } addBlockSize(size) { this.blockSizes.push(size); } removeBlockSize(index) { this.blockSizes.splice(index, 1); } /** * Returns `0n` for directories or `data.length + sum(blockSizes)` for everything else */ fileSize() { if (this.isDirectory()) { return 0n; } let sum = 0n; this.blockSizes.forEach((size) => { sum += size; }); if (this.data != null) { sum += BigInt(this.data.length); } return sum; } /** * encode to protobuf Uint8Array */ marshal() { let type; switch (this.type) { case "raw": type = Data.DataType.Raw; break; case "directory": type = Data.DataType.Directory; break; case "file": type = Data.DataType.File; break; case "metadata": type = Data.DataType.Metadata; break; case "symlink": type = Data.DataType.Symlink; break; case "hamt-sharded-directory": type = Data.DataType.HAMTShard; break; default: throw (0, import_err_code.default)(new Error(`Type: ${type} is not valid`), "ERR_INVALID_TYPE"); } let data = this.data; if (this.data == null || this.data.length === 0) { data = void 0; } let mode; if (this.mode != null) { mode = this._originalMode & 4294963200 | (this.mode ?? 0); if (mode === DEFAULT_FILE_MODE && !this.isDirectory()) { mode = void 0; } if (mode === DEFAULT_DIRECTORY_MODE && this.isDirectory()) { mode = void 0; } } let mtime; if (this.mtime != null) { mtime = { Seconds: this.mtime.secs, FractionalNanoseconds: this.mtime.nsecs }; } return Data.encode({ Type: type, Data: data, filesize: this.isDirectory() ? void 0 : this.fileSize(), blocksizes: this.blockSizes, hashType: this.hashType, fanout: this.fanout, mode, mtime }); } }; // node_modules/progress-events/dist/src/index.js var CustomProgressEvent = class extends Event { constructor(type, detail) { super(type); this.detail = detail; } }; // node_modules/ipfs-unixfs-importer/dist/src/utils/persist.js var persist = async (buffer2, blockstore, options) => { if (options.codec == null) { options.codec = src_exports2; } const multihash = await sha256.digest(buffer2); const cid = CID.create(options.cidVersion, options.codec.code, multihash); await blockstore.put(cid, buffer2, options); return cid; }; // node_modules/ipfs-unixfs-importer/dist/src/dag-builder/buffer-importer.js function defaultBufferImporter(options) { return async function* bufferImporter(file, blockstore) { let bytesWritten = 0n; for await (let block of file.content) { yield async () => { let unixfs; const opts = { codec: src_exports2, cidVersion: options.cidVersion, onProgress: options.onProgress }; if (options.rawLeaves) { opts.codec = raw_exports; opts.cidVersion = 1; } else { unixfs = new UnixFS({ type: options.leafType, data: block }); block = encode12({ Data: unixfs.marshal(), Links: [] }); } const cid = await persist(block, blockstore, opts); bytesWritten += BigInt(block.byteLength); options.onProgress?.(new CustomProgressEvent("unixfs:importer:progress:file:write", { bytesWritten, cid, path: file.path })); return { cid, unixfs, size: BigInt(block.length), block }; }; } }; } // node_modules/ipfs-unixfs-importer/dist/src/dag-builder/index.js var import_err_code2 = __toESM(require_err_code(), 1); // node_modules/ipfs-unixfs-importer/dist/src/dag-builder/dir.js var dirBuilder = async (dir, blockstore, options) => { const unixfs = new UnixFS({ type: "directory", mtime: dir.mtime, mode: dir.mode }); const block = encode12(prepare({ Data: unixfs.marshal() })); const cid = await persist(block, blockstore, options); const path = dir.path; return { cid, path, unixfs, size: BigInt(block.length), originalPath: dir.originalPath, block }; }; // node_modules/ipfs-unixfs-importer/dist/src/dag-builder/file.js async function* buildFileBatch(file, blockstore, options) { let count = -1; let previous; for await (const entry of parallelBatch(options.bufferImporter(file, blockstore), options.blockWriteConcurrency)) { count++; if (count === 0) { previous = { ...entry, single: true }; continue; } else if (count === 1 && previous != null) { yield { ...previous, block: void 0, single: void 0 }; previous = void 0; } yield { ...entry, block: void 0 }; } if (previous != null) { yield previous; } } function isSingleBlockImport(result) { return result.single === true; } var reduce = (file, blockstore, options) => { const reducer = async function(leaves) { if (leaves.length === 1 && isSingleBlockImport(leaves[0]) && options.reduceSingleLeafToSelf) { const leaf = leaves[0]; let node2 = leaf.block; if (isSingleBlockImport(leaf) && (file.mtime !== void 0 || file.mode !== void 0)) { leaf.unixfs = new UnixFS({ type: "file", mtime: file.mtime, mode: file.mode, data: leaf.block }); node2 = { Data: leaf.unixfs.marshal(), Links: [] }; leaf.block = encode12(prepare(node2)); leaf.cid = await persist(leaf.block, blockstore, { ...options, cidVersion: options.cidVersion }); leaf.size = BigInt(leaf.block.length); } options.onProgress?.(new CustomProgressEvent("unixfs:importer:progress:file:layout", { cid: leaf.cid, path: leaf.originalPath })); return { cid: leaf.cid, path: file.path, unixfs: leaf.unixfs, size: leaf.size, originalPath: leaf.originalPath }; } const f = new UnixFS({ type: "file", mtime: file.mtime, mode: file.mode }); const links2 = leaves.filter((leaf) => { if (leaf.cid.code === code2 && leaf.size > 0) { return true; } if (leaf.unixfs != null && leaf.unixfs.data == null && leaf.unixfs.fileSize() > 0n) { return true; } return Boolean(leaf.unixfs?.data?.length); }).map((leaf) => { if (leaf.cid.code === code2) { f.addBlockSize(leaf.size); return { Name: "", Tsize: Number(leaf.size), Hash: leaf.cid }; } if (leaf.unixfs == null || leaf.unixfs.data == null) { f.addBlockSize(leaf.unixfs?.fileSize() ?? 0n); } else { f.addBlockSize(BigInt(leaf.unixfs.data.length)); } return { Name: "", Tsize: Number(leaf.size), Hash: leaf.cid }; }); const node = { Data: f.marshal(), Links: links2 }; const block = encode12(prepare(node)); const cid = await persist(block, blockstore, options); options.onProgress?.(new CustomProgressEvent("unixfs:importer:progress:file:layout", { cid, path: file.originalPath })); return { cid, path: file.path, unixfs: f, size: BigInt(block.length + node.Links.reduce((acc, curr) => acc + (curr.Tsize ?? 0), 0)), originalPath: file.originalPath, block }; }; return reducer; }; var fileBuilder = async (file, block, options) => { return options.layout(buildFileBatch(file, block, options), reduce(file, block, options)); }; // node_modules/ipfs-unixfs-importer/dist/src/dag-builder/index.js function isIterable(thing) { return Symbol.iterator in thing; } function isAsyncIterable2(thing) { return Symbol.asyncIterator in thing; } function contentAsAsyncIterable(content) { try { if (content instanceof Uint8Array) { return async function* () { yield content; }(); } else if (isIterable(content)) { return async function* () { yield* content; }(); } else if (isAsyncIterable2(content)) { return content; } } catch { throw (0, import_err_code2.default)(new Error("Content was invalid"), "ERR_INVALID_CONTENT"); } throw (0, import_err_code2.default)(new Error("Content was invalid"), "ERR_INVALID_CONTENT"); } function defaultDagBuilder(options) { return async function* dagBuilder(source, blockstore) { for await (const entry of source) { let originalPath; if (entry.path != null) { originalPath = entry.path; entry.path = entry.path.split("/").filter((path) => path != null && path !== ".").join("/"); } if (isFileCandidate(entry)) { const file = { path: entry.path, mtime: entry.mtime, mode: entry.mode, content: async function* () { let bytesRead = 0n; for await (const chunk of options.chunker(options.chunkValidator(contentAsAsyncIterable(entry.content)))) { const currentChunkSize = BigInt(chunk.byteLength); bytesRead += currentChunkSize; options.onProgress?.(new CustomProgressEvent("unixfs:importer:progress:file:read", { bytesRead, chunkSize: currentChunkSize, path: entry.path })); yield chunk; } }(), originalPath }; yield async () => fileBuilder(file, blockstore, options); } else if (entry.path != null) { const dir = { path: entry.path, mtime: entry.mtime, mode: entry.mode, originalPath }; yield async () => dirBuilder(dir, blockstore, options); } else { throw new Error("Import candidate must have content or path or both"); } } }; } function isFileCandidate(entry) { return entry.content != null; } // node_modules/ipfs-unixfs-importer/dist/src/dag-builder/validate-chunks.js var import_err_code3 = __toESM(require_err_code(), 1); var defaultChunkValidator = () => { return async function* validateChunks(source) { for await (const content of source) { if (content.length === void 0) { throw (0, import_err_code3.default)(new Error("Content was invalid"), "ERR_INVALID_CONTENT"); } if (typeof content === "string" || content instanceof String) { yield fromString2(content.toString()); } else if (Array.isArray(content)) { yield Uint8Array.from(content); } else if (content instanceof Uint8Array) { yield content; } else { throw (0, import_err_code3.default)(new Error("Content was invalid"), "ERR_INVALID_CONTENT"); } } }; }; // node_modules/ipfs-unixfs-importer/dist/src/layout/balanced.js var DEFAULT_MAX_CHILDREN_PER_NODE = 174; function balanced(options) { const maxChildrenPerNode = options?.maxChildrenPerNode ?? DEFAULT_MAX_CHILDREN_PER_NODE; return async function balancedLayout(source, reduce2) { const roots = []; for await (const chunked of src_default(source, maxChildrenPerNode)) { roots.push(await reduce2(chunked)); } if (roots.length > 1) { return balancedLayout(roots, reduce2); } return roots[0]; }; } // node_modules/ipfs-unixfs-importer/dist/src/dir.js var Dir = class { options; root; dir; path; dirty; flat; parent; parentKey; unixfs; mode; mtime; cid; size; nodeSize; constructor(props, options) { this.options = options ?? {}; this.root = props.root; this.dir = props.dir; this.path = props.path; this.dirty = props.dirty; this.flat = props.flat; this.parent = props.parent; this.parentKey = props.parentKey; this.unixfs = props.unixfs; this.mode = props.mode; this.mtime = props.mtime; } }; var CID_V0 = CID.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"); var CID_V1 = CID.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi"); // node_modules/ipfs-unixfs-importer/dist/src/dir-flat.js var DirFlat = class extends Dir { _children; constructor(props, options) { super(props, options); this._children = /* @__PURE__ */ new Map(); } async put(name5, value) { this.cid = void 0; this.size = void 0; this.nodeSize = void 0; this._children.set(name5, value); } async get(name5) { return Promise.resolve(this._children.get(name5)); } childCount() { return this._children.size; } directChildrenCount() { return this.childCount(); } onlyChild() { return this._children.values().next().value; } async *eachChildSeries() { for (const [key, child] of this._children.entries()) { yield { key, child }; } } estimateNodeSize() { if (this.nodeSize !== void 0) { return this.nodeSize; } this.nodeSize = 0; for (const [name5, child] of this._children.entries()) { if (child.size != null && child.cid != null) { this.nodeSize += name5.length + (this.options.cidVersion === 1 ? CID_V1.bytes.byteLength : CID_V0.bytes.byteLength); } } return this.nodeSize; } async *flush(block) { const links2 = []; for (const [name5, child] of this._children.entries()) { let result = child; if (child instanceof Dir) { for await (const entry of child.flush(block)) { result = entry; yield entry; } } if (result.size != null && result.cid != null) { links2.push({ Name: name5, Tsize: Number(result.size), Hash: result.cid }); } } const unixfs = new UnixFS({ type: "directory", mtime: this.mtime, mode: this.mode }); const node = { Data: unixfs.marshal(), Links: links2 }; const buffer2 = encode12(prepare(node)); const cid = await persist(buffer2, block, this.options); const size = buffer2.length + node.Links.reduce( /** * @param {number} acc * @param {PBLink} curr */ (acc, curr) => acc + (curr.Tsize == null ? 0 : curr.Tsize), 0 ); this.cid = cid; this.size = size; yield { cid, unixfs, path: this.path, size: BigInt(size) }; } }; // node_modules/@multiformats/murmur3/node_modules/multiformats/vendor/varint.js var encode_14 = encode13; var MSB4 = 128; var REST4 = 127; var MSBALL4 = ~REST4; var INT4 = Math.pow(2, 31); function encode13(num, out, offset) { out = out || []; offset = offset || 0; var oldOffset = offset; while (num >= INT4) { out[offset++] = num & 255 | MSB4; num /= 128; } while (num & MSBALL4) { out[offset++] = num & 255 | MSB4; num >>>= 7; } out[offset] = num | 0; encode13.bytes = offset - oldOffset + 1; return out; } var decode18 = read4; var MSB$14 = 128; var REST$14 = 127; function read4(buf2, offset) { var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf2.length; do { if (counter >= l) { read4.bytes = 0; throw new RangeError("Could not decode varint"); } b = buf2[counter++]; res += shift < 28 ? (b & REST$14) << shift : (b & REST$14) * Math.pow(2, shift); shift += 7; } while (b >= MSB$14); read4.bytes = counter - offset; return res; } var N14 = Math.pow(2, 7); var N25 = Math.pow(2, 14); var N34 = Math.pow(2, 21); var N44 = Math.pow(2, 28); var N54 = Math.pow(2, 35); var N64 = Math.pow(2, 42); var N74 = Math.pow(2, 49); var N84 = Math.pow(2, 56); var N94 = Math.pow(2, 63); var length4 = function(value) { return value < N14 ? 1 : value < N25 ? 2 : value < N34 ? 3 : value < N44 ? 4 : value < N54 ? 5 : value < N64 ? 6 : value < N74 ? 7 : value < N84 ? 8 : value < N94 ? 9 : 10; }; var varint4 = { encode: encode_14, decode: decode18, encodingLength: length4 }; var _brrp_varint4 = varint4; var varint_default4 = _brrp_varint4; // node_modules/@multiformats/murmur3/node_modules/multiformats/src/varint.js var decode19 = (data, offset = 0) => { const code5 = varint_default4.decode(data, offset); return [code5, varint_default4.decode.bytes]; }; var encodeTo4 = (int, target, offset = 0) => { varint_default4.encode(int, target, offset); return target; }; var encodingLength4 = (int) => { return varint_default4.encodingLength(int); }; // node_modules/@multiformats/murmur3/node_modules/multiformats/src/bytes.js var bytes_exports3 = {}; __export(bytes_exports3, { coerce: () => coerce4, empty: () => empty4, equals: () => equals8, fromHex: () => fromHex, fromString: () => fromString4, isBinary: () => isBinary, toHex: () => toHex, toString: () => toString4 }); var empty4 = new Uint8Array(0); var toHex = (d) => d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, "0"), ""); var fromHex = (hex) => { const hexes2 = hex.match(/../g); return hexes2 ? new Uint8Array(hexes2.map((b) => parseInt(b, 16))) : empty4; }; var equals8 = (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; }; var coerce4 = (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"); }; var isBinary = (o) => o instanceof ArrayBuffer || ArrayBuffer.isView(o); var fromString4 = (str3) => new TextEncoder().encode(str3); var toString4 = (b) => new TextDecoder().decode(b); // node_modules/@multiformats/murmur3/node_modules/multiformats/src/hashes/digest.js var create4 = (code5, digest2) => { const size = digest2.byteLength; const sizeOffset = encodingLength4(code5); const digestOffset = sizeOffset + encodingLength4(size); const bytes2 = new Uint8Array(digestOffset + size); encodeTo4(code5, bytes2, 0); encodeTo4(size, bytes2, sizeOffset); bytes2.set(digest2, digestOffset); return new Digest4(code5, size, digest2, bytes2); }; var decode20 = (multihash) => { const bytes2 = coerce4(multihash); const [code5, sizeOffset] = decode19(bytes2); const [size, digestOffset] = decode19(bytes2.subarray(sizeOffset)); const digest2 = bytes2.subarray(sizeOffset + digestOffset); if (digest2.byteLength !== size) { throw new Error("Incorrect length"); } return new Digest4(code5, size, digest2, bytes2); }; var equals9 = (a, b) => { if (a === b) { return true; } else { const data = ( /** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */ b ); return a.code === data.code && a.size === data.size && data.bytes instanceof Uint8Array && equals8(a.bytes, data.bytes); } }; var Digest4 = class { /** * Creates a multihash digest. * * @param {Code} code * @param {Size} size * @param {Uint8Array} digest * @param {Uint8Array} bytes */ constructor(code5, size, digest2, bytes2) { this.code = code5; this.size = size; this.digest = digest2; this.bytes = bytes2; } }; // node_modules/@multiformats/murmur3/node_modules/multiformats/vendor/base-x.js function base5(ALPHABET, name5) { 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 encode16(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 length5 = 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 < length5) && 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"); } length5 = i2; pbegin++; } var it2 = size - length5; while (it2 !== size && b58[it2] === 0) { it2++; } var str3 = LEADER.repeat(zeroes); for (; it2 < size; ++it2) { str3 += ALPHABET.charAt(b58[it2]); } return str3; } 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 length5 = 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 < length5) && 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"); } length5 = i2; psz++; } if (source[psz] === " ") { return; } var it4 = size - length5; 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 decode23(string2) { var buffer2 = decodeUnsafe(string2); if (buffer2) { return buffer2; } throw new Error(`Non-${name5} character`); } return { encode: encode16, decodeUnsafe, decode: decode23 }; } var src4 = base5; var _brrp__multiformats_scope_baseX4 = src4; var base_x_default4 = _brrp__multiformats_scope_baseX4; // node_modules/@multiformats/murmur3/node_modules/multiformats/src/bases/base.js var Encoder5 = class { /** * @param {Base} name * @param {Prefix} prefix * @param {(bytes:Uint8Array) => string} baseEncode */ constructor(name5, prefix, baseEncode) { this.name = name5; this.prefix = prefix; this.baseEncode = baseEncode; } /** * @param {Uint8Array} bytes * @returns {API.Multibase} */ encode(bytes2) { if (bytes2 instanceof Uint8Array) { return `${this.prefix}${this.baseEncode(bytes2)}`; } else { throw Error("Unknown type, must be binary type"); } } }; var Decoder4 = class { /** * @param {Base} name * @param {Prefix} prefix * @param {(text:string) => Uint8Array} baseDecode */ constructor(name5, prefix, baseDecode) { this.name = name5; this.prefix = prefix; if (prefix.codePointAt(0) === void 0) { throw new Error("Invalid prefix character"); } this.prefixCodePoint = /** @type {number} */ prefix.codePointAt(0); this.baseDecode = baseDecode; } /** * @param {string} text */ 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"); } } /** * @template {string} OtherPrefix * @param {API.UnibaseDecoder|ComposedDecoder} decoder * @returns {ComposedDecoder} */ or(decoder) { return or4(this, decoder); } }; var ComposedDecoder4 = class { /** * @param {Decoders} decoders */ constructor(decoders) { this.decoders = decoders; } /** * @template {string} OtherPrefix * @param {API.UnibaseDecoder|ComposedDecoder} decoder * @returns {ComposedDecoder} */ or(decoder) { return or4(this, decoder); } /** * @param {string} input * @returns {Uint8Array} */ decode(input) { const prefix = ( /** @type {Prefix} */ input[0] ); const decoder = this.decoders[prefix]; if (decoder) { return decoder.decode(input); } else { throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); } } }; var or4 = (left, right) => new ComposedDecoder4( /** @type {Decoders} */ { ...left.decoders || { [ /** @type API.UnibaseDecoder */ left.prefix ]: left }, ...right.decoders || { [ /** @type API.UnibaseDecoder */ right.prefix ]: right } } ); var Codec4 = class { /** * @param {Base} name * @param {Prefix} prefix * @param {(bytes:Uint8Array) => string} baseEncode * @param {(text:string) => Uint8Array} baseDecode */ constructor(name5, prefix, baseEncode, baseDecode) { this.name = name5; this.prefix = prefix; this.baseEncode = baseEncode; this.baseDecode = baseDecode; this.encoder = new Encoder5(name5, prefix, baseEncode); this.decoder = new Decoder4(name5, prefix, baseDecode); } /** * @param {Uint8Array} input */ encode(input) { return this.encoder.encode(input); } /** * @param {string} input */ decode(input) { return this.decoder.decode(input); } }; var from5 = ({ name: name5, prefix, encode: encode16, decode: decode23 }) => new Codec4(name5, prefix, encode16, decode23); var baseX4 = ({ prefix, name: name5, alphabet: alphabet2 }) => { const { encode: encode16, decode: decode23 } = base_x_default4(alphabet2, name5); return from5({ prefix, name: name5, encode: encode16, /** * @param {string} text */ decode: (text) => coerce4(decode23(text)) }); }; var decode21 = (string2, alphabet2, bitsPerChar, name5) => { const codes = {}; for (let i = 0; i < alphabet2.length; ++i) { codes[alphabet2[i]] = i; } let end = string2.length; while (string2[end - 1] === "=") { --end; } const out = new Uint8Array(end * bitsPerChar / 8 | 0); let bits = 0; let buffer2 = 0; let written = 0; for (let i = 0; i < end; ++i) { const value = codes[string2[i]]; if (value === void 0) { throw new SyntaxError(`Non-${name5} character`); } buffer2 = buffer2 << bitsPerChar | value; bits += bitsPerChar; if (bits >= 8) { bits -= 8; out[written++] = 255 & buffer2 >> bits; } } if (bits >= bitsPerChar || 255 & buffer2 << 8 - bits) { throw new SyntaxError("Unexpected end of data"); } return out; }; var encode14 = (data, alphabet2, bitsPerChar) => { const pad = alphabet2[alphabet2.length - 1] === "="; const mask = (1 << bitsPerChar) - 1; let out = ""; let bits = 0; let buffer2 = 0; for (let i = 0; i < data.length; ++i) { buffer2 = buffer2 << 8 | data[i]; bits += 8; while (bits > bitsPerChar) { bits -= bitsPerChar; out += alphabet2[mask & buffer2 >> bits]; } } if (bits) { out += alphabet2[mask & buffer2 << bitsPerChar - bits]; } if (pad) { while (out.length * bitsPerChar & 7) { out += "="; } } return out; }; var rfc46484 = ({ name: name5, prefix, bitsPerChar, alphabet: alphabet2 }) => { return from5({ prefix, name: name5, encode(input) { return encode14(input, alphabet2, bitsPerChar); }, decode(input) { return decode21(input, alphabet2, bitsPerChar, name5); } }); }; // node_modules/@multiformats/murmur3/node_modules/multiformats/src/bases/base58.js var base58btc4 = baseX4({ name: "base58btc", prefix: "z", alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" }); var base58flickr4 = baseX4({ name: "base58flickr", prefix: "Z", alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" }); // node_modules/@multiformats/murmur3/node_modules/multiformats/src/bases/base32.js var base324 = rfc46484({ prefix: "b", name: "base32", alphabet: "abcdefghijklmnopqrstuvwxyz234567", bitsPerChar: 5 }); var base32upper4 = rfc46484({ prefix: "B", name: "base32upper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", bitsPerChar: 5 }); var base32pad4 = rfc46484({ prefix: "c", name: "base32pad", alphabet: "abcdefghijklmnopqrstuvwxyz234567=", bitsPerChar: 5 }); var base32padupper4 = rfc46484({ prefix: "C", name: "base32padupper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", bitsPerChar: 5 }); var base32hex4 = rfc46484({ prefix: "v", name: "base32hex", alphabet: "0123456789abcdefghijklmnopqrstuv", bitsPerChar: 5 }); var base32hexupper4 = rfc46484({ prefix: "V", name: "base32hexupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", bitsPerChar: 5 }); var base32hexpad4 = rfc46484({ prefix: "t", name: "base32hexpad", alphabet: "0123456789abcdefghijklmnopqrstuv=", bitsPerChar: 5 }); var base32hexpadupper4 = rfc46484({ prefix: "T", name: "base32hexpadupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", bitsPerChar: 5 }); var base32z4 = rfc46484({ prefix: "h", name: "base32z", alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", bitsPerChar: 5 }); // node_modules/@multiformats/murmur3/node_modules/multiformats/src/cid.js var format4 = (link, base6) => { const { bytes: bytes2, version } = link; switch (version) { case 0: return toStringV04( bytes2, baseCache4(link), /** @type {API.MultibaseEncoder<"z">} */ base6 || base58btc4.encoder ); default: return toStringV14( bytes2, baseCache4(link), /** @type {API.MultibaseEncoder} */ base6 || base324.encoder ); } }; var cache4 = /* @__PURE__ */ new WeakMap(); var baseCache4 = (cid) => { const baseCache5 = cache4.get(cid); if (baseCache5 == null) { const baseCache6 = /* @__PURE__ */ new Map(); cache4.set(cid, baseCache6); return baseCache6; } return baseCache5; }; var CID4 = class { /** * @param {Version} version - Version of the CID * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv * @param {API.MultihashDigest} multihash - (Multi)hash of the of the content. * @param {Uint8Array} bytes * */ constructor(version, code5, multihash, bytes2) { this.code = code5; this.version = version; this.multihash = multihash; this.bytes = bytes2; this["/"] = bytes2; } /** * 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; } /** * @returns {CID} */ toV0() { switch (this.version) { case 0: { return ( /** @type {CID} */ this ); } case 1: { const { code: code5, multihash } = this; if (code5 !== DAG_PB_CODE4) { throw new Error("Cannot convert a non dag-pb CID to CIDv0"); } if (multihash.code !== SHA_256_CODE4) { throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0"); } return ( /** @type {CID} */ CID4.createV0( /** @type {API.MultihashDigest} */ multihash ) ); } default: { throw Error( `Can not convert CID version ${this.version} to version 0. This is a bug please report` ); } } } /** * @returns {CID} */ toV1() { switch (this.version) { case 0: { const { code: code5, digest: digest2 } = this.multihash; const multihash = create4(code5, digest2); return ( /** @type {CID} */ CID4.createV1(this.code, multihash) ); } case 1: { return ( /** @type {CID} */ this ); } default: { throw Error( `Can not convert CID version ${this.version} to version 1. This is a bug please report` ); } } } /** * @param {unknown} other * @returns {other is CID} */ equals(other) { return CID4.equals(this, other); } /** * @template {unknown} Data * @template {number} Format * @template {number} Alg * @template {API.Version} Version * @param {API.Link} self * @param {unknown} other * @returns {other is CID} */ static equals(self2, other) { const unknown = ( /** @type {{code?:unknown, version?:unknown, multihash?:unknown}} */ other ); return unknown && self2.code === unknown.code && self2.version === unknown.version && equals9(self2.multihash, unknown.multihash); } /** * @param {API.MultibaseEncoder} [base] * @returns {string} */ toString(base6) { return format4(this, base6); } toJSON() { return { "/": format4(this) }; } link() { return this; } get [Symbol.toStringTag]() { return "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. * * @template {unknown} Data * @template {number} Format * @template {number} Alg * @template {API.Version} Version * @template {unknown} U * @param {API.Link|U} input * @returns {CID|null} */ static asCID(input) { if (input == null) { return null; } const value = ( /** @type {any} */ input ); if (value instanceof CID4) { return value; } else if (value["/"] != null && value["/"] === value.bytes || value.asCID === value) { const { version, code: code5, multihash, bytes: bytes2 } = value; return new CID4( version, code5, /** @type {API.MultihashDigest} */ multihash, bytes2 || encodeCID4(version, code5, multihash.bytes) ); } else if (value[cidSymbol4] === true) { const { version, multihash, code: code5 } = value; const digest2 = ( /** @type {API.MultihashDigest} */ decode20(multihash) ); return CID4.create(version, code5, digest2); } else { return null; } } /** * * @template {unknown} Data * @template {number} Format * @template {number} Alg * @template {API.Version} Version * @param {Version} version - Version of the CID * @param {Format} code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv * @param {API.MultihashDigest} digest - (Multi)hash of the of the content. * @returns {CID} */ static create(version, code5, digest2) { if (typeof code5 !== "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 (code5 !== DAG_PB_CODE4) { throw new Error( `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE4}) block encoding` ); } else { return new CID4(version, code5, digest2, digest2.bytes); } } case 1: { const bytes2 = encodeCID4(version, code5, digest2.bytes); return new CID4(version, code5, digest2, bytes2); } default: { throw new Error("Invalid version"); } } } /** * Simplified version of `create` for CIDv0. * * @template {unknown} [T=unknown] * @param {API.MultihashDigest} digest - Multihash. * @returns {CID} */ static createV0(digest2) { return CID4.create(0, DAG_PB_CODE4, digest2); } /** * Simplified version of `create` for CIDv1. * * @template {unknown} Data * @template {number} Code * @template {number} Alg * @param {Code} code - Content encoding format code. * @param {API.MultihashDigest} digest - Miltihash of the content. * @returns {CID} */ static createV1(code5, digest2) { return CID4.create(1, code5, 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. * * @template {unknown} Data * @template {number} Code * @template {number} Alg * @template {API.Version} Ver * @param {API.ByteView>} bytes * @returns {CID} */ static decode(bytes2) { const [cid, remainder] = CID4.decodeFirst(bytes2); if (remainder.length) { 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. * * @template {unknown} T * @template {number} C * @template {number} A * @template {API.Version} V * @param {API.ByteView>} bytes * @returns {[CID, Uint8Array]} */ static decodeFirst(bytes2) { const specs = CID4.inspectBytes(bytes2); const prefixSize = specs.size - specs.multihashSize; const multihashBytes = coerce4( bytes2.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 Digest4( specs.multihashCode, specs.digestSize, digestBytes, multihashBytes ); const cid = specs.version === 0 ? CID4.createV0( /** @type {API.MultihashDigest} */ digest2 ) : CID4.createV1(specs.codec, digest2); return [ /** @type {CID} */ cid, bytes2.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. * * @template {unknown} T * @template {number} C * @template {number} A * @template {API.Version} V * @param {API.ByteView>} initialBytes * @returns {{ version:V, codec:C, multihashCode:A, digestSize:number, multihashSize:number, size:number }} */ static inspectBytes(initialBytes) { let offset = 0; const next = () => { const [i, length5] = decode19(initialBytes.subarray(offset)); offset += length5; return i; }; let version = ( /** @type {V} */ next() ); let codec = ( /** @type {C} */ DAG_PB_CODE4 ); if ( /** @type {number} */ version === 18 ) { version = /** @type {V} */ 0; offset = 0; } else { codec = /** @type {C} */ next(); } if (version !== 0 && version !== 1) { throw new RangeError(`Invalid CID version ${version}`); } const prefixSize = offset; const multihashCode = ( /** @type {A} */ 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). * * @template {string} Prefix * @template {unknown} Data * @template {number} Code * @template {number} Alg * @template {API.Version} Ver * @param {API.ToString, Prefix>} source * @param {API.MultibaseDecoder} [base] * @returns {CID} */ static parse(source, base6) { const [prefix, bytes2] = parseCIDtoBytes4(source, base6); const cid = CID4.decode(bytes2); if (cid.version === 0 && source[0] !== "Q") { throw Error("Version 0 CID string must not include multibase prefix"); } baseCache4(cid).set(prefix, source); return cid; } }; var parseCIDtoBytes4 = (source, base6) => { switch (source[0]) { case "Q": { const decoder = base6 || base58btc4; return [ /** @type {Prefix} */ base58btc4.prefix, decoder.decode(`${base58btc4.prefix}${source}`) ]; } case base58btc4.prefix: { const decoder = base6 || base58btc4; return [ /** @type {Prefix} */ base58btc4.prefix, decoder.decode(source) ]; } case base324.prefix: { const decoder = base6 || base324; return [ /** @type {Prefix} */ base324.prefix, decoder.decode(source) ]; } default: { if (base6 == null) { throw Error( "To parse non base32 or base58btc encoded CID multibase decoder must be provided" ); } return [ /** @type {Prefix} */ source[0], base6.decode(source) ]; } } }; var toStringV04 = (bytes2, cache5, base6) => { const { prefix } = base6; if (prefix !== base58btc4.prefix) { throw Error(`Cannot string encode V0 in ${base6.name} encoding`); } const cid = cache5.get(prefix); if (cid == null) { const cid2 = base6.encode(bytes2).slice(1); cache5.set(prefix, cid2); return cid2; } else { return cid; } }; var toStringV14 = (bytes2, cache5, base6) => { const { prefix } = base6; const cid = cache5.get(prefix); if (cid == null) { const cid2 = base6.encode(bytes2); cache5.set(prefix, cid2); return cid2; } else { return cid; } }; var DAG_PB_CODE4 = 112; var SHA_256_CODE4 = 18; var encodeCID4 = (version, code5, multihash) => { const codeOffset = encodingLength4(version); const hashOffset = codeOffset + encodingLength4(code5); const bytes2 = new Uint8Array(hashOffset + multihash.byteLength); encodeTo4(version, bytes2, 0); encodeTo4(code5, bytes2, codeOffset); bytes2.set(multihash, hashOffset); return bytes2; }; var cidSymbol4 = Symbol.for("@ipld/js-cid/CID"); // node_modules/@multiformats/murmur3/node_modules/multiformats/src/hashes/hasher.js var from6 = ({ name: name5, code: code5, encode: encode16 }) => new Hasher2(name5, code5, encode16); var Hasher2 = class { /** * * @param {Name} name * @param {Code} code * @param {(input: Uint8Array) => Await} encode */ constructor(name5, code5, encode16) { this.name = name5; this.code = code5; this.encode = encode16; } /** * @param {Uint8Array} input * @returns {Await>} */ digest(input) { if (input instanceof Uint8Array) { const result = this.encode(input); return result instanceof Uint8Array ? create4(this.code, result) : result.then((digest2) => create4(this.code, digest2)); } else { throw Error("Unknown type, must be binary type"); } } }; // node_modules/@multiformats/murmur3/src/index.js var import_murmurhash3js_revisited = __toESM(require_murmurhash3js_revisited(), 1); function fromNumberTo32BitBuf(number2) { const bytes2 = new Array(4); for (let i = 0; i < 4; i++) { bytes2[i] = number2 & 255; number2 = number2 >> 8; } return new Uint8Array(bytes2); } var murmur332 = from6({ name: "murmur3-32", code: 35, encode: (input) => fromNumberTo32BitBuf(import_murmurhash3js_revisited.default.x86.hash32(input)) }); var murmur3128 = from6({ name: "murmur3-128", code: 34, encode: (input) => bytes_exports3.fromHex(import_murmurhash3js_revisited.default.x64.hash128(input)) }); var murmur364 = from6({ name: "murmur3-x64-64", code: 34, encode: (input) => bytes_exports3.fromHex(import_murmurhash3js_revisited.default.x64.hash128(input)).subarray(0, 8) }); // node_modules/hamt-sharding/dist/src/bucket.js var import_sparse_array = __toESM(require_sparse_array(), 1); var Bucket = class { constructor(options, parent, posAtParent = 0) { this._options = options; this._popCount = 0; this._parent = parent; this._posAtParent = posAtParent; this._children = new import_sparse_array.default(); this.key = null; } async put(key, value) { const place = await this._findNewBucketAndPos(key); await place.bucket._putAt(place, key, value); } async get(key) { const child = await this._findChild(key); if (child != null) { return child.value; } } async del(key) { const place = await this._findPlace(key); const child = place.bucket._at(place.pos); if (child != null && child.key === key) { place.bucket._delAt(place.pos); } } leafCount() { const children = this._children.compactArray(); return children.reduce((acc, child) => { if (child instanceof Bucket) { return acc + child.leafCount(); } return acc + 1; }, 0); } childrenCount() { return this._children.length; } onlyChild() { return this._children.get(0); } *eachLeafSeries() { const children = this._children.compactArray(); for (const child of children) { if (child instanceof Bucket) { yield* child.eachLeafSeries(); } else { yield child; } } } serialize(map2, reduce2) { const acc = []; return reduce2(this._children.reduce((acc2, child, index) => { if (child != null) { if (child instanceof Bucket) { acc2.push(child.serialize(map2, reduce2)); } else { acc2.push(map2(child, index)); } } return acc2; }, acc)); } async asyncTransform(asyncMap, asyncReduce) { return await asyncTransformBucket(this, asyncMap, asyncReduce); } toJSON() { return this.serialize(mapNode, reduceNodes); } prettyPrint() { return JSON.stringify(this.toJSON(), null, " "); } tableSize() { return Math.pow(2, this._options.bits); } async _findChild(key) { const result = await this._findPlace(key); const child = result.bucket._at(result.pos); if (child instanceof Bucket) { return void 0; } if (child != null && child.key === key) { return child; } } async _findPlace(key) { const hashValue = this._options.hash(typeof key === "string" ? fromString2(key) : key); const index = await hashValue.take(this._options.bits); const child = this._children.get(index); if (child instanceof Bucket) { return await child._findPlace(hashValue); } return { bucket: this, pos: index, hash: hashValue, existingChild: child }; } async _findNewBucketAndPos(key) { const place = await this._findPlace(key); if (place.existingChild != null && place.existingChild.key !== key) { const bucket = new Bucket(this._options, place.bucket, place.pos); place.bucket._putObjectAt(place.pos, bucket); const newPlace = await bucket._findPlace(place.existingChild.hash); newPlace.bucket._putAt(newPlace, place.existingChild.key, place.existingChild.value); return await bucket._findNewBucketAndPos(place.hash); } return place; } _putAt(place, key, value) { this._putObjectAt(place.pos, { key, value, hash: place.hash }); } _putObjectAt(pos, object) { if (this._children.get(pos) == null) { this._popCount++; } this._children.set(pos, object); } _delAt(pos) { if (pos === -1) { throw new Error("Invalid position"); } if (this._children.get(pos) != null) { this._popCount--; } this._children.unset(pos); this._level(); } _level() { if (this._parent != null && this._popCount <= 1) { if (this._popCount === 1) { const onlyChild = this._children.find(exists2); if (onlyChild != null && !(onlyChild instanceof Bucket)) { const hash2 = onlyChild.hash; hash2.untake(this._options.bits); const place = { pos: this._posAtParent, hash: hash2, bucket: this._parent }; this._parent._putAt(place, onlyChild.key, onlyChild.value); } } else { this._parent._delAt(this._posAtParent); } } } _at(index) { return this._children.get(index); } }; function exists2(o) { return Boolean(o); } function mapNode(node, _) { return node.key; } function reduceNodes(nodes) { return nodes; } async function asyncTransformBucket(bucket, asyncMap, asyncReduce) { const output2 = []; for (const child of bucket._children.compactArray()) { if (child instanceof Bucket) { await asyncTransformBucket(child, asyncMap, asyncReduce); } else { const mappedChildren = await asyncMap(child); output2.push({ bitField: bucket._children.bitField(), children: mappedChildren }); } } return await asyncReduce(output2); } // node_modules/hamt-sharding/dist/src/consumable-buffer.js var START_MASKS = [ 255, 254, 252, 248, 240, 224, 192, 128 ]; var STOP_MASKS = [ 1, 3, 7, 15, 31, 63, 127, 255 ]; var ConsumableBuffer = class { constructor(value) { this._value = value; this._currentBytePos = value.length - 1; this._currentBitPos = 7; } availableBits() { return this._currentBitPos + 1 + this._currentBytePos * 8; } totalBits() { return this._value.length * 8; } take(bits) { let pendingBits = bits; let result = 0; while (pendingBits > 0 && this._haveBits()) { const byte = this._value[this._currentBytePos]; const availableBits = this._currentBitPos + 1; const taking = Math.min(availableBits, pendingBits); const value = byteBitsToInt(byte, availableBits - taking, taking); result = (result << taking) + value; pendingBits -= taking; this._currentBitPos -= taking; if (this._currentBitPos < 0) { this._currentBitPos = 7; this._currentBytePos--; } } return result; } untake(bits) { this._currentBitPos += bits; while (this._currentBitPos > 7) { this._currentBitPos -= 8; this._currentBytePos += 1; } } _haveBits() { return this._currentBytePos >= 0; } }; function byteBitsToInt(byte, start, length5) { const mask = maskFor(start, length5); return (byte & mask) >>> start; } function maskFor(start, length5) { return START_MASKS[start] & STOP_MASKS[Math.min(length5 + start - 1, 7)]; } // node_modules/hamt-sharding/dist/src/consumable-hash.js function wrapHash(hashFn2) { function hashing(value) { if (value instanceof InfiniteHash) { return value; } else { return new InfiniteHash(value, hashFn2); } } return hashing; } var InfiniteHash = class { constructor(value, hashFn2) { if (!(value instanceof Uint8Array)) { throw new Error("can only hash Uint8Arrays"); } this._value = value; this._hashFn = hashFn2; this._depth = -1; this._availableBits = 0; this._currentBufferIndex = 0; this._buffers = []; } async take(bits) { let pendingBits = bits; while (this._availableBits < pendingBits) { await this._produceMoreBits(); } let result = 0; while (pendingBits > 0) { const hash2 = this._buffers[this._currentBufferIndex]; const available = Math.min(hash2.availableBits(), pendingBits); const took = hash2.take(available); result = (result << available) + took; pendingBits -= available; this._availableBits -= available; if (hash2.availableBits() === 0) { this._currentBufferIndex++; } } return result; } untake(bits) { let pendingBits = bits; while (pendingBits > 0) { const hash2 = this._buffers[this._currentBufferIndex]; const availableForUntake = Math.min(hash2.totalBits() - hash2.availableBits(), pendingBits); hash2.untake(availableForUntake); pendingBits -= availableForUntake; this._availableBits += availableForUntake; if (this._currentBufferIndex > 0 && hash2.totalBits() === hash2.availableBits()) { this._depth--; this._currentBufferIndex--; } } } async _produceMoreBits() { this._depth++; const value = this._depth > 0 ? concat([this._value, Uint8Array.from([this._depth])]) : this._value; const hashValue = await this._hashFn(value); const buffer2 = new ConsumableBuffer(hashValue); this._buffers.push(buffer2); this._availableBits += buffer2.availableBits(); } }; // node_modules/hamt-sharding/dist/src/index.js function createHAMT(options) { if (options == null || options.hashFn == null) { throw new Error("please define an options.hashFn"); } const bucketOptions = { bits: options.bits ?? 8, hash: wrapHash(options.hashFn) }; return new Bucket(bucketOptions); } // node_modules/ipfs-unixfs-importer/dist/src/dir-sharded.js async function hamtHashFn(buf2) { return (await murmur3128.encode(buf2)).slice(0, 8).reverse(); } var HAMT_HASH_CODE = BigInt(34); var DirSharded = class extends Dir { _bucket; constructor(props, options) { super(props, options); this._bucket = createHAMT({ hashFn: hamtHashFn, bits: 8 }); } async put(name5, value) { this.cid = void 0; this.size = void 0; this.nodeSize = void 0; await this._bucket.put(name5, value); } async get(name5) { return this._bucket.get(name5); } childCount() { return this._bucket.leafCount(); } directChildrenCount() { return this._bucket.childrenCount(); } onlyChild() { return this._bucket.onlyChild(); } async *eachChildSeries() { for await (const { key, value } of this._bucket.eachLeafSeries()) { yield { key, child: value }; } } estimateNodeSize() { if (this.nodeSize !== void 0) { return this.nodeSize; } this.nodeSize = calculateSize(this._bucket, this, this.options); return this.nodeSize; } async *flush(blockstore) { for await (const entry of flush(this._bucket, blockstore, this, this.options)) { yield { ...entry, path: this.path }; } } }; var dir_sharded_default = DirSharded; async function* flush(bucket, blockstore, shardRoot, options) { const children = bucket._children; const links2 = []; let childrenSize = 0n; for (let i = 0; i < children.length; i++) { const child = children.get(i); if (child == null) { continue; } const labelPrefix = i.toString(16).toUpperCase().padStart(2, "0"); if (child instanceof Bucket) { let shard; for await (const subShard of flush(child, blockstore, null, options)) { shard = subShard; } if (shard == null) { throw new Error("Could not flush sharded directory, no subshard found"); } links2.push({ Name: labelPrefix, Tsize: Number(shard.size), Hash: shard.cid }); childrenSize += shard.size; } else if (isDir(child.value)) { const dir2 = child.value; let flushedDir; for await (const entry of dir2.flush(blockstore)) { flushedDir = entry; yield flushedDir; } if (flushedDir == null) { throw new Error("Did not flush dir"); } const label = labelPrefix + child.key; links2.push({ Name: label, Tsize: Number(flushedDir.size), Hash: flushedDir.cid }); childrenSize += flushedDir.size; } else { const value = child.value; if (value.cid == null) { continue; } const label = labelPrefix + child.key; const size2 = value.size; links2.push({ Name: label, Tsize: Number(size2), Hash: value.cid }); childrenSize += BigInt(size2 ?? 0); } } const data = Uint8Array.from(children.bitField().reverse()); const dir = new UnixFS({ type: "hamt-sharded-directory", data, fanout: BigInt(bucket.tableSize()), hashType: HAMT_HASH_CODE, mtime: shardRoot?.mtime, mode: shardRoot?.mode }); const node = { Data: dir.marshal(), Links: links2 }; const buffer2 = encode12(prepare(node)); const cid = await persist(buffer2, blockstore, options); const size = BigInt(buffer2.byteLength) + childrenSize; yield { cid, unixfs: dir, size }; } function isDir(obj) { return typeof obj.flush === "function"; } function calculateSize(bucket, shardRoot, options) { const children = bucket._children; const links2 = []; for (let i = 0; i < children.length; i++) { const child = children.get(i); if (child == null) { continue; } const labelPrefix = i.toString(16).toUpperCase().padStart(2, "0"); if (child instanceof Bucket) { const size = calculateSize(child, null, options); links2.push({ Name: labelPrefix, Tsize: Number(size), Hash: options.cidVersion === 0 ? CID_V0 : CID_V1 }); } else if (typeof child.value.flush === "function") { const dir2 = child.value; const size = dir2.nodeSize(); links2.push({ Name: labelPrefix + child.key, Tsize: Number(size), Hash: options.cidVersion === 0 ? CID_V0 : CID_V1 }); } else { const value = child.value; if (value.cid == null) { continue; } const label = labelPrefix + child.key; const size = value.size; links2.push({ Name: label, Tsize: Number(size), Hash: value.cid }); } } const data = Uint8Array.from(children.bitField().reverse()); const dir = new UnixFS({ type: "hamt-sharded-directory", data, fanout: BigInt(bucket.tableSize()), hashType: HAMT_HASH_CODE, mtime: shardRoot?.mtime, mode: shardRoot?.mode }); const buffer2 = encode12(prepare({ Data: dir.marshal(), Links: links2 })); return buffer2.length; } // node_modules/ipfs-unixfs-importer/dist/src/flat-to-shard.js async function flatToShard(child, dir, threshold, options) { let newDir = dir; if (dir instanceof DirFlat && dir.estimateNodeSize() > threshold) { newDir = await convertToShard(dir, options); } const parent = newDir.parent; if (parent != null) { if (newDir !== dir) { if (child != null) { child.parent = newDir; } if (newDir.parentKey == null) { throw new Error("No parent key found"); } await parent.put(newDir.parentKey, newDir); } return flatToShard(newDir, parent, threshold, options); } return newDir; } async function convertToShard(oldDir, options) { const newDir = new dir_sharded_default({ root: oldDir.root, dir: true, parent: oldDir.parent, parentKey: oldDir.parentKey, path: oldDir.path, dirty: oldDir.dirty, flat: false, mtime: oldDir.mtime, mode: oldDir.mode }, options); for await (const { key, child } of oldDir.eachChildSeries()) { await newDir.put(key, child); } return newDir; } // node_modules/ipfs-unixfs-importer/dist/src/utils/to-path-components.js var toPathComponents = (path = "") => { return (path.trim().match(/([^\\/]|\\\/)+/g) ?? []).filter(Boolean); }; // node_modules/ipfs-unixfs-importer/dist/src/tree-builder.js async function addToTree(elem, tree2, options) { const pathElems = toPathComponents(elem.path ?? ""); const lastIndex = pathElems.length - 1; let parent = tree2; let currentPath = ""; for (let i = 0; i < pathElems.length; i++) { const pathElem = pathElems[i]; currentPath += `${currentPath !== "" ? "/" : ""}${pathElem}`; const last2 = i === lastIndex; parent.dirty = true; parent.cid = void 0; parent.size = void 0; if (last2) { await parent.put(pathElem, elem); tree2 = await flatToShard(null, parent, options.shardSplitThresholdBytes, options); } else { let dir = await parent.get(pathElem); if (dir == null || !(dir instanceof Dir)) { dir = new DirFlat({ root: false, dir: true, parent, parentKey: pathElem, path: currentPath, dirty: true, flat: true, mtime: dir?.unixfs?.mtime, mode: dir?.unixfs?.mode }, options); } await parent.put(pathElem, dir); parent = dir; } } return tree2; } async function* flushAndYield(tree2, blockstore) { if (!(tree2 instanceof Dir)) { if (tree2.unixfs?.isDirectory() === true) { yield tree2; } return; } yield* tree2.flush(blockstore); } function defaultTreeBuilder(options) { return async function* treeBuilder(source, block) { let tree2 = new DirFlat({ root: true, dir: true, path: "", dirty: true, flat: true }, options); let rootDir; let singleRoot = false; for await (const entry of source) { if (entry == null) { continue; } const dir = `${entry.originalPath ?? ""}`.split("/")[0]; if (dir != null && dir !== "") { if (rootDir == null) { rootDir = dir; singleRoot = true; } else if (rootDir !== dir) { singleRoot = false; } } tree2 = await addToTree(entry, tree2, options); if (entry.unixfs == null || !entry.unixfs.isDirectory()) { yield entry; } } if (options.wrapWithDirectory || singleRoot && tree2.childCount() > 1) { yield* flushAndYield(tree2, block); } else { for await (const unwrapped of tree2.eachChildSeries()) { if (unwrapped == null) { continue; } yield* flushAndYield(unwrapped.child, block); } } }; } // node_modules/ipfs-unixfs-importer/dist/src/index.js async function* importer(source, blockstore, options = {}) { let candidates; if (Symbol.asyncIterator in source || Symbol.iterator in source) { candidates = source; } else { candidates = [source]; } const wrapWithDirectory = options.wrapWithDirectory ?? false; const shardSplitThresholdBytes = options.shardSplitThresholdBytes ?? 262144; const cidVersion = options.cidVersion ?? 1; const rawLeaves = options.rawLeaves ?? true; const leafType = options.leafType ?? "file"; const fileImportConcurrency = options.fileImportConcurrency ?? 50; const blockWriteConcurrency = options.blockWriteConcurrency ?? 10; const reduceSingleLeafToSelf = options.reduceSingleLeafToSelf ?? true; const chunker = options.chunker ?? fixedSize(); const chunkValidator = options.chunkValidator ?? defaultChunkValidator(); const buildDag = options.dagBuilder ?? defaultDagBuilder({ chunker, chunkValidator, wrapWithDirectory, layout: options.layout ?? balanced(), bufferImporter: options.bufferImporter ?? defaultBufferImporter({ cidVersion, rawLeaves, leafType, onProgress: options.onProgress }), blockWriteConcurrency, reduceSingleLeafToSelf, cidVersion, onProgress: options.onProgress }); const buildTree = options.treeBuilder ?? defaultTreeBuilder({ wrapWithDirectory, shardSplitThresholdBytes, cidVersion, onProgress: options.onProgress }); for await (const entry of buildTree(parallelBatch(buildDag(candidates, blockstore), fileImportConcurrency), blockstore)) { yield { cid: entry.cid, path: entry.path, unixfs: entry.unixfs, size: entry.size }; } } // dist/esm/src/utils/cid.js var __awaiter9 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __asyncValues2 = function(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i); function verb(n) { i[n] = o[n] && function(v) { return new Promise(function(resolve5, reject) { v = o[n](v), settle(resolve5, reject, v.done, v.value); }); }; } function settle(resolve5, reject, d, v) { Promise.resolve(v).then(function(v2) { resolve5({ value: v2, done: d }); }, reject); } }; var hashers = { [sha256.code]: sha256 }; var codecs = { [code3]: src_exports }; var Cid = class { /** * Computes a V1 CID for the provided payload * @param codecCode - the codec to use. Defaults to cbor * @param multihashCode - the multihasher to use. Defaults to sha256 * @returns payload CID * @throws {Error} codec is not supported * @throws {Error} encoding fails * @throws {Error} if hasher is not supported */ static computeCid(payload, codecCode = code3, multihashCode = sha256.code) { return __awaiter9(this, void 0, void 0, function* () { const codec = codecs[codecCode]; if (!codec) { throw new DwnError(DwnErrorCode.ComputeCidCodecNotSupported, `codec [${codecCode}] not supported`); } const hasher = hashers[multihashCode]; if (!hasher) { throw new DwnError(DwnErrorCode.ComputeCidMultihashNotSupported, `multihash code [${multihashCode}] not supported`); } const payloadBytes = codec.encode(payload); const payloadHash = yield hasher.digest(payloadBytes); const cid = yield CID.createV1(codec.code, payloadHash); return cid.toString(); }); } /** * Parses the given CID string into a {CID}. */ static parseCid(str3) { const cid = CID.parse(str3).toV1(); if (!codecs[cid.code]) { throw new DwnError(DwnErrorCode.ParseCidCodecNotSupported, `codec [${cid.code}] not supported`); } if (!hashers[cid.multihash.code]) { throw new DwnError(DwnErrorCode.ParseCidMultihashNotSupported, `multihash code [${cid.multihash.code}] not supported`); } return cid; } /** * @returns V1 CID of the DAG comprised by chunking data into unixfs DAG-PB encoded blocks */ static computeDagPbCidFromBytes(content) { var _a, e_1, _b, _c; return __awaiter9(this, void 0, void 0, function* () { const asyncDataBlocks = importer([{ content }], new BlockstoreMock(), { cidVersion: 1 }); let block; try { for (var _d = true, asyncDataBlocks_1 = __asyncValues2(asyncDataBlocks), asyncDataBlocks_1_1; asyncDataBlocks_1_1 = yield asyncDataBlocks_1.next(), _a = asyncDataBlocks_1_1.done, !_a; _d = true) { _c = asyncDataBlocks_1_1.value; _d = false; block = _c; ; } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (!_d && !_a && (_b = asyncDataBlocks_1.return)) yield _b.call(asyncDataBlocks_1); } finally { if (e_1) throw e_1.error; } } return block ? block.cid.toString() : ""; }); } /** * @returns V1 CID of the DAG comprised by chunking data into unixfs DAG-PB encoded blocks */ static computeDagPbCidFromStream(dataStream) { var _a, e_2, _b, _c; return __awaiter9(this, void 0, void 0, function* () { const asyncDataBlocks = importer([{ content: dataStream }], new BlockstoreMock(), { cidVersion: 1 }); let block; try { for (var _d = true, asyncDataBlocks_2 = __asyncValues2(asyncDataBlocks), asyncDataBlocks_2_1; asyncDataBlocks_2_1 = yield asyncDataBlocks_2.next(), _a = asyncDataBlocks_2_1.done, !_a; _d = true) { _c = asyncDataBlocks_2_1.value; _d = false; block = _c; ; } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (!_d && !_a && (_b = asyncDataBlocks_2.return)) yield _b.call(asyncDataBlocks_2); } finally { if (e_2) throw e_2.error; } } return block ? block.cid.toString() : ""; }); } }; // dist/esm/src/utils/encryption.js var crypto4 = __toESM(require("crypto"), 1); var eciesjs = __toESM(require("eciesjs"), 1); var import_readable_stream = require("readable-stream"); var __awaiter10 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; eciesjs.ECIES_CONFIG.isEphemeralKeyCompressed = true; var Encryption = class { /** * Encrypts the given plaintext stream using AES-256-CTR algorithm. */ static aes256CtrEncrypt(key, initializationVector, plaintextStream) { return __awaiter10(this, void 0, void 0, function* () { const cipher = crypto4.createCipheriv("aes-256-ctr", key, initializationVector); const cipherStream = new import_readable_stream.Readable({ read() { } }); plaintextStream.on("data", (chunk) => { const encryptedChunk = cipher.update(chunk); cipherStream.push(encryptedChunk); }); plaintextStream.on("end", () => { const finalChunk = cipher.final(); cipherStream.push(finalChunk); cipherStream.push(null); }); plaintextStream.on("error", (err3) => { cipherStream.emit("error", err3); }); return cipherStream; }); } /** * Decrypts the given cipher stream using AES-256-CTR algorithm. */ static aes256CtrDecrypt(key, initializationVector, cipherStream) { return __awaiter10(this, void 0, void 0, function* () { const decipher = crypto4.createDecipheriv("aes-256-ctr", key, initializationVector); const plaintextStream = new import_readable_stream.Readable({ read() { } }); cipherStream.on("data", (chunk) => { const decryptedChunk = decipher.update(chunk); plaintextStream.push(decryptedChunk); }); cipherStream.on("end", () => { const finalChunk = decipher.final(); plaintextStream.push(finalChunk); plaintextStream.push(null); }); cipherStream.on("error", (err3) => { plaintextStream.emit("error", err3); }); return plaintextStream; }); } /** * Encrypts the given plaintext using ECIES (Elliptic Curve Integrated Encryption Scheme) * with SECP256K1 for the asymmetric calculations, HKDF as the key-derivation function, * and AES-GCM for the symmetric encryption and MAC algorithms. */ static eciesSecp256k1Encrypt(publicKeyBytes, plaintext) { return __awaiter10(this, void 0, void 0, function* () { const publicKey = Buffer.from(publicKeyBytes); const plaintextBuffer = Buffer.from(plaintext); const cryptogram = eciesjs.encrypt(publicKey, plaintextBuffer); let start = 0; let end = Encryption.isEphemeralKeyCompressed ? 33 : 65; const ephemeralPublicKey = cryptogram.subarray(start, end); start = end; end += eciesjs.ECIES_CONFIG.symmetricNonceLength; const initializationVector = cryptogram.subarray(start, end); start = end; end += 16; const messageAuthenticationCode = cryptogram.subarray(start, end); const ciphertext = cryptogram.subarray(end); return { ciphertext, ephemeralPublicKey, initializationVector, messageAuthenticationCode }; }); } /** * Decrypt the given plaintext using ECIES (Elliptic Curve Integrated Encryption Scheme) * with SECP256K1 for the asymmetric calculations, HKDF as the key-derivation function, * and AES-GCM for the symmetric encryption and MAC algorithms. */ static eciesSecp256k1Decrypt(input) { return __awaiter10(this, void 0, void 0, function* () { const privateKeyBuffer = Buffer.from(input.privateKey); const eciesEncryptionOutput = Buffer.concat([ input.ephemeralPublicKey, input.initializationVector, input.messageAuthenticationCode, input.ciphertext ]); const plaintext = eciesjs.decrypt(privateKeyBuffer, eciesEncryptionOutput); return plaintext; }); } /** * Expose eciesjs library configuration */ static get isEphemeralKeyCompressed() { return eciesjs.ECIES_CONFIG.isEphemeralKeyCompressed; } }; var EncryptionAlgorithm; (function(EncryptionAlgorithm2) { EncryptionAlgorithm2["Aes256Ctr"] = "A256CTR"; EncryptionAlgorithm2["EciesSecp256k1"] = "ECIES-ES256K"; })(EncryptionAlgorithm || (EncryptionAlgorithm = {})); // dist/esm/src/jose/jws/general/builder.js var __awaiter11 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var GeneralJwsBuilder = class { constructor(jws) { this.jws = jws; } static create(payload, signers = []) { return __awaiter11(this, void 0, void 0, function* () { const jws = { payload: Encoder2.bytesToBase64Url(payload), signatures: [] }; const builder = new GeneralJwsBuilder(jws); for (const signer of signers) { yield builder.addSignature(signer); } return builder; }); } addSignature(signer) { return __awaiter11(this, void 0, void 0, function* () { const protectedHeader = { kid: signer.keyId, alg: signer.algorithm }; const protectedHeaderString = JSON.stringify(protectedHeader); const protectedHeaderBase64UrlString = Encoder2.stringToBase64Url(protectedHeaderString); const signingInputString = `${protectedHeaderBase64UrlString}.${this.jws.payload}`; const signingInputBytes = Encoder2.stringToBytes(signingInputString); const signatureBytes = yield signer.sign(signingInputBytes); const signature = Encoder2.bytesToBase64Url(signatureBytes); this.jws.signatures.push({ protected: protectedHeaderBase64UrlString, signature }); }); } getJws() { return this.jws; } }; // dist/esm/src/utils/hd-key.js var import_webcrypto = require("@noble/ciphers/webcrypto"); var __awaiter12 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var KeyDerivationScheme; (function(KeyDerivationScheme2) { KeyDerivationScheme2["DataFormats"] = "dataFormats"; KeyDerivationScheme2["ProtocolContext"] = "protocolContext"; KeyDerivationScheme2["ProtocolPath"] = "protocolPath"; KeyDerivationScheme2["Schemas"] = "schemas"; })(KeyDerivationScheme || (KeyDerivationScheme = {})); var HdKey = class { /** * Derives a descendant private key. * NOTE: currently only supports SECP256K1 keys. */ static derivePrivateKey(ancestorKey, subDerivationPath) { var _a; return __awaiter12(this, void 0, void 0, function* () { const ancestorPrivateKey = Secp256k1.privateJwkToBytes(ancestorKey.derivedPrivateKey); const ancestorPrivateKeyDerivationPath = (_a = ancestorKey.derivationPath) !== null && _a !== void 0 ? _a : []; const derivedPrivateKeyBytes = yield HdKey.derivePrivateKeyBytes(ancestorPrivateKey, subDerivationPath); const derivedPrivateJwk = yield Secp256k1.privateKeyToJwk(derivedPrivateKeyBytes); const derivedDescendantPrivateKey = { rootKeyId: ancestorKey.rootKeyId, derivationScheme: ancestorKey.derivationScheme, derivationPath: [...ancestorPrivateKeyDerivationPath, ...subDerivationPath], derivedPrivateKey: derivedPrivateJwk }; return derivedDescendantPrivateKey; }); } /** * Derives a descendant public key from an ancestor private key. * NOTE: currently only supports SECP256K1 keys. */ static derivePublicKey(ancestorKey, subDerivationPath) { return __awaiter12(this, void 0, void 0, function* () { const derivedDescendantPrivateKey = yield HdKey.derivePrivateKey(ancestorKey, subDerivationPath); const derivedDescendantPublicKey = yield Secp256k1.getPublicJwk(derivedDescendantPrivateKey.derivedPrivateKey); return derivedDescendantPublicKey; }); } /** * Derives a hardened hierarchical deterministic private key. */ static derivePrivateKeyBytes(privateKey, relativePath) { return __awaiter12(this, void 0, void 0, function* () { HdKey.validateKeyDerivationPath(relativePath); let currentPrivateKey = privateKey; for (const segment of relativePath) { const segmentBytes = Encoder2.stringToBytes(segment); currentPrivateKey = yield HdKey.deriveKeyUsingHkdf({ hashAlgorithm: "SHA-256", initialKeyMaterial: currentPrivateKey, info: segmentBytes, keyLengthInBytes: 32 // 32 bytes = 256 bits }); } return currentPrivateKey; }); } /** * Derives a key using HMAC-based Extract-and-Expand Key Derivation Function (HKDF) as defined in RFC 5869. * TODO: Consolidate HKDF implementation and usage with web5-js - https://github.com/TBD54566975/dwn-sdk-js/issues/742 */ static deriveKeyUsingHkdf(params) { return __awaiter12(this, void 0, void 0, function* () { const { hashAlgorithm, initialKeyMaterial, info, keyLengthInBytes } = params; const webCrypto = (0, import_webcrypto.getWebcryptoSubtle)(); const webCryptoKey = yield webCrypto.importKey("raw", initialKeyMaterial, { name: "HKDF" }, false, ["deriveBits"]); const derivedKeyBuffer = yield crypto.subtle.deriveBits( { name: "HKDF", hash: hashAlgorithm, salt: new Uint8Array(0), info }, webCryptoKey, keyLengthInBytes * 8 // convert from bytes to bits ); const derivedKeyBytes = new Uint8Array(derivedKeyBuffer); return derivedKeyBytes; }); } /** * Validates that no empty strings exist within the derivation path segments array. * @throws {DwnError} with `DwnErrorCode.HdKeyDerivationPathInvalid` if derivation path fails validation. */ static validateKeyDerivationPath(pathSegments) { if (pathSegments.includes("")) { throw new DwnError(DwnErrorCode.HdKeyDerivationPathInvalid, `Invalid key derivation path: ${pathSegments}`); } } }; // dist/esm/src/utils/string.js function lexicographicalCompare(a, b) { if (a > b) { return 1; } else if (a < b) { return -1; } else { return 0; } } // dist/esm/src/utils/object.js function isEmptyObject(obj) { if (typeof obj !== "object") { return false; } for (const _ in obj) { return false; } return true; } function removeUndefinedProperties(obj) { Object.keys(obj).forEach((key) => { if (obj[key] === void 0) { delete obj[key]; } else if (typeof obj[key] === "object") { removeUndefinedProperties(obj[key]); } }); } // dist/esm/src/core/message.js var __awaiter13 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var Message = class { /** * Validates the given message against the corresponding JSON schema. * @throws {Error} if fails validation. */ static validateJsonSchema(rawMessage) { const dwnInterface = rawMessage.descriptor.interface; const dwnMethod = rawMessage.descriptor.method; const schemaLookupKey = dwnInterface + dwnMethod; validateJsonSchema(schemaLookupKey, rawMessage); } /** * Gets the DID of the signer of the given message, returns `undefined` if message is not signed. */ static getSigner(message2) { if (message2.authorization === void 0) { return void 0; } const signer = Jws.getSignerDid(message2.authorization.signature.signatures[0]); return signer; } /** * Gets the CID of the given message. */ static getCid(message2) { return __awaiter13(this, void 0, void 0, function* () { const rawMessage = Object.assign({}, message2); if (rawMessage.encodedData) { delete rawMessage.encodedData; } const cid = yield Cid.computeCid(rawMessage); return cid; }); } /** * Compares message CID in lexicographical order according to the spec. * @returns 1 if `a` is larger than `b`; -1 if `a` is smaller/older than `b`; 0 otherwise (same message) */ static compareCid(a, b) { return __awaiter13(this, void 0, void 0, function* () { const cidA = yield Message.getCid(a); const cidB = yield Message.getCid(b); return lexicographicalCompare(cidA, cidB); }); } /** * Creates the `authorization` property to be included in a DWN message. * @param signer Message signer. * @returns {AuthorizationModel} used as an `authorization` property. */ static createAuthorization(input) { return __awaiter13(this, void 0, void 0, function* () { const { descriptor, signer, delegatedGrant, permissionGrantId, protocolRole } = input; let delegatedGrantId; if (delegatedGrant !== void 0) { delegatedGrantId = yield Message.getCid(delegatedGrant); } const signature = yield Message.createSignature(descriptor, signer, { delegatedGrantId, permissionGrantId, protocolRole }); const authorization = { signature }; if (delegatedGrant !== void 0) { authorization.authorDelegatedGrant = delegatedGrant; } return authorization; }); } /** * Creates a generic signature from the given DWN message descriptor by including `descriptorCid` as the required property in the signature payload. * NOTE: there is an opportunity to consolidate RecordsWrite.createSignerSignature() wth this method */ static createSignature(descriptor, signer, additionalPayloadProperties) { return __awaiter13(this, void 0, void 0, function* () { const descriptorCid = yield Cid.computeCid(descriptor); const signaturePayload = Object.assign({ descriptorCid }, additionalPayloadProperties); removeUndefinedProperties(signaturePayload); const signaturePayloadBytes = Encoder2.objectToBytes(signaturePayload); const builder = yield GeneralJwsBuilder.create(signaturePayloadBytes, [signer]); const signature = builder.getJws(); return signature; }); } /** * @returns newest message in the array. `undefined` if given array is empty. */ static getNewestMessage(messages) { return __awaiter13(this, void 0, void 0, function* () { let currentNewestMessage = void 0; for (const message2 of messages) { if (currentNewestMessage === void 0 || (yield Message.isNewer(message2, currentNewestMessage))) { currentNewestMessage = message2; } } return currentNewestMessage; }); } /** * @returns oldest message in the array. `undefined` if given array is empty. */ static getOldestMessage(messages) { return __awaiter13(this, void 0, void 0, function* () { let currentOldestMessage = void 0; for (const message2 of messages) { if (currentOldestMessage === void 0 || (yield Message.isOlder(message2, currentOldestMessage))) { currentOldestMessage = message2; } } return currentOldestMessage; }); } /** * Checks if first message is newer than second message. * @returns `true` if `a` is newer than `b`; `false` otherwise */ static isNewer(a, b) { return __awaiter13(this, void 0, void 0, function* () { const aIsNewer = (yield Message.compareMessageTimestamp(a, b)) > 0; return aIsNewer; }); } /** * Checks if first message is older than second message. * @returns `true` if `a` is older than `b`; `false` otherwise */ static isOlder(a, b) { return __awaiter13(this, void 0, void 0, function* () { const aIsOlder = (yield Message.compareMessageTimestamp(a, b)) < 0; return aIsOlder; }); } /** * See if the given message is signed by an author-delegate. */ static isSignedByAuthorDelegate(message2) { var _a; return ((_a = message2.authorization) === null || _a === void 0 ? void 0 : _a.authorDelegatedGrant) !== void 0; } /** * See if the given message is signed by an owner-delegate. */ static isSignedByOwnerDelegate(message2) { var _a; return ((_a = message2.authorization) === null || _a === void 0 ? void 0 : _a.ownerDelegatedGrant) !== void 0; } /** * Compares the `messageTimestamp` of the given messages with a fallback to message CID according to the spec. * @returns 1 if `a` is larger/newer than `b`; -1 if `a` is smaller/older than `b`; 0 otherwise (same age) */ static compareMessageTimestamp(a, b) { return __awaiter13(this, void 0, void 0, function* () { if (a.descriptor.messageTimestamp > b.descriptor.messageTimestamp) { return 1; } else if (a.descriptor.messageTimestamp < b.descriptor.messageTimestamp) { return -1; } return Message.compareCid(a, b); }); } /** * Validates the structural integrity of the message signature given: * 1. The message signature must contain exactly 1 signature * 2. Passes JSON schema validation * 3. The `descriptorCid` property matches the CID of the message descriptor * NOTE: signature is NOT verified. * @param payloadJsonSchemaKey The key to look up the JSON schema referenced in `compile-validators.js` and perform payload schema validation on. * @returns the parsed JSON payload object if validation succeeds. */ static validateSignatureStructure(messageSignature, messageDescriptor, payloadJsonSchemaKey = "GenericSignaturePayload") { return __awaiter13(this, void 0, void 0, function* () { if (messageSignature.signatures.length !== 1) { throw new DwnError(DwnErrorCode.AuthenticationMoreThanOneSignatureNotSupported, "expected no more than 1 signature for authorization purpose"); } const payloadJson = Jws.decodePlainObjectPayload(messageSignature); validateJsonSchema(payloadJsonSchemaKey, payloadJson); const { descriptorCid } = payloadJson; const expectedDescriptorCid = yield Cid.computeCid(messageDescriptor); if (descriptorCid !== expectedDescriptorCid) { throw new DwnError(DwnErrorCode.AuthenticateDescriptorCidMismatch, `provided descriptorCid ${descriptorCid} does not match expected CID ${expectedDescriptorCid}`); } return payloadJson; }); } }; // dist/esm/src/protocols/permission-grant.js var __awaiter14 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var PermissionGrant = class { static parse(message2) { return __awaiter14(this, void 0, void 0, function* () { const permissionGrant = new PermissionGrant(message2); return permissionGrant; }); } /** * Creates a Permission Grant abstraction for */ constructor(message2) { this.id = message2.recordId; this.grantor = Message.getSigner(message2); this.grantee = message2.descriptor.recipient; this.dateGranted = message2.descriptor.dateCreated; const permissionGrantEncoded = message2.encodedData; const permissionGrant = Encoder2.base64UrlToObject(permissionGrantEncoded); this.dateExpires = permissionGrant.dateExpires; this.delegated = permissionGrant.delegated; this.description = permissionGrant.description; this.requestId = permissionGrant.requestId; this.scope = permissionGrant.scope; this.conditions = permissionGrant.conditions; } }; // dist/esm/src/types/records-types.js var DateSort; (function(DateSort2) { DateSort2["CreatedAscending"] = "createdAscending"; DateSort2["CreatedDescending"] = "createdDescending"; DateSort2["PublishedAscending"] = "publishedAscending"; DateSort2["PublishedDescending"] = "publishedDescending"; })(DateSort || (DateSort = {})); // dist/esm/src/utils/filter.js var __rest2 = function(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var FilterUtility = class { /** * Matches the given key values against an array of filters, if any of the filters match, returns true. * * @returns true if any of the filters match. */ static matchAnyFilter(keyValues, orFilters) { if (orFilters.length === 0) { return true; } for (const filter2 of orFilters) { if (this.matchFilter(keyValues, filter2)) { return true; } } return false; } /** * Evaluates the given filter against the indexed values. * * @param indexedValues the indexed values for an item. * @param filter * @returns true if all of the filter properties match. */ static matchFilter(indexedValues, filter2) { for (const filterProperty in filter2) { const filterValue = filter2[filterProperty]; const indexValue = indexedValues[filterProperty]; if (indexValue === void 0) { return false; } const matched = Array.isArray(indexValue) ? this.matchAnyIndexValue(filterValue, indexValue) : this.matchIndexValue(filterValue, indexValue); if (!matched) { return false; } } return true; } /** * Returns true if any of the index values match the filter. * * @param filterValue the filter for a particular property. * @param indexValues an array of values to match the filter against. */ static matchAnyIndexValue(filterValue, indexValues) { for (const indexValue of indexValues) { if (this.matchIndexValue(filterValue, indexValue)) { return true; } } return false; } /** * Returns true if the filter matches the given index value. * * @param filterValue the filter for a particular property. * @param indexValue a single value to match the filter against. */ static matchIndexValue(filterValue, indexValue) { if (typeof filterValue === "object") { if (Array.isArray(filterValue)) { if (this.matchOneOf(filterValue, indexValue)) { return true; } } else { if (this.matchRange(filterValue, indexValue)) { return true; } } } else { if (indexValue === filterValue) { return true; } } return false; } /** * Evaluates a OneOfFilter given an indexedValue extracted from the index. * * @param filter An array of EqualFilters. Treated as an OR. * @param indexedValue the indexed value being compared. * @returns true if any of the given filters match the indexedValue */ static matchOneOf(filter2, indexedValue) { for (const orFilterValue of filter2) { if (indexedValue === orFilterValue) { return true; } } return false; } /** * Evaluates if the given indexedValue is within the range given by the RangeFilter. * * @returns true if all of the range filter conditions are met. */ static matchRange(rangeFilter, indexedValue) { if (rangeFilter.lt !== void 0 && indexedValue >= rangeFilter.lt) { return false; } if (rangeFilter.lte !== void 0 && indexedValue > rangeFilter.lte) { return false; } if (rangeFilter.gt !== void 0 && indexedValue <= rangeFilter.gt) { return false; } if (rangeFilter.gte !== void 0 && indexedValue < rangeFilter.gte) { return false; } return true; } static isEqualFilter(filter2) { if (typeof filter2 !== "object") { return true; } return false; } static isRangeFilter(filter2) { if (typeof filter2 === "object" && !Array.isArray(filter2)) { return "gt" in filter2 || "lt" in filter2 || "lte" in filter2 || "gte" in filter2; } ; return false; } static isOneOfFilter(filter2) { if (typeof filter2 === "object" && Array.isArray(filter2)) { return true; } ; return false; } static convertRangeCriterion(inputFilter) { let rangeFilter; if (inputFilter.to !== void 0 && inputFilter.from !== void 0) { rangeFilter = { gte: inputFilter.from, lt: inputFilter.to }; } else if (inputFilter.to !== void 0) { rangeFilter = { lt: inputFilter.to }; } else if (inputFilter.from !== void 0) { rangeFilter = { gte: inputFilter.from }; } return rangeFilter; } static constructPrefixFilterAsRangeFilter(prefix) { return { gte: prefix, lt: prefix + "\uFFFF" }; } }; var FilterSelector = class { /** * Reduce Filter so that it is a filter that can be quickly executed against the DB. */ static reduceFilter(filter2) { const filterProperties = Object.keys(filter2); if (filterProperties.length <= 1) { return filter2; } const { recordId, attester, parentId, recipient, contextId, author, protocolPath, schema, protocol } = filter2, remainingProperties = __rest2(filter2, ["recordId", "attester", "parentId", "recipient", "contextId", "author", "protocolPath", "schema", "protocol"]); if (recordId !== void 0) { return { recordId }; } if (attester !== void 0) { return { attester }; } if (parentId !== void 0) { return { parentId }; } if (recipient !== void 0) { return { recipient }; } if (contextId !== void 0) { return { contextId }; } if (protocolPath !== void 0) { return { protocolPath }; } if (schema !== void 0) { return { schema }; } if (protocol !== void 0) { return { protocol }; } const remainingPropertyNames = Object.keys(remainingProperties); const firstRemainingProperty = remainingPropertyNames[0]; const singlePropertyFilter = {}; singlePropertyFilter[firstRemainingProperty] = filter2[firstRemainingProperty]; return singlePropertyFilter; } }; // dist/esm/src/enums/dwn-interface-method.js var DwnInterfaceName; (function(DwnInterfaceName2) { DwnInterfaceName2["Events"] = "Events"; DwnInterfaceName2["Messages"] = "Messages"; DwnInterfaceName2["Protocols"] = "Protocols"; DwnInterfaceName2["Records"] = "Records"; })(DwnInterfaceName || (DwnInterfaceName = {})); var DwnMethodName; (function(DwnMethodName2) { DwnMethodName2["Configure"] = "Configure"; DwnMethodName2["Create"] = "Create"; DwnMethodName2["Get"] = "Get"; DwnMethodName2["Grant"] = "Grant"; DwnMethodName2["Query"] = "Query"; DwnMethodName2["Read"] = "Read"; DwnMethodName2["Request"] = "Request"; DwnMethodName2["Revoke"] = "Revoke"; DwnMethodName2["Write"] = "Write"; DwnMethodName2["Delete"] = "Delete"; DwnMethodName2["Subscribe"] = "Subscribe"; })(DwnMethodName || (DwnMethodName = {})); // dist/esm/src/utils/url.js function validateProtocolUrlNormalized(url) { let normalized; try { normalized = normalizeProtocolUrl(url); } catch (_a) { normalized = void 0; } if (url !== normalized) { throw new DwnError(DwnErrorCode.UrlProtocolNotNormalized, `Protocol URI ${url} must be normalized.`); } } function normalizeProtocolUrl(url) { return normalizeUrl(url); } function validateSchemaUrlNormalized(url) { let normalized; try { normalized = normalizeSchemaUrl(url); } catch (_a) { normalized = void 0; } if (url !== normalized) { throw new DwnError(DwnErrorCode.UrlSchemaNotNormalized, `Schema URI ${url} must be normalized.`); } } function normalizeSchemaUrl(url) { return normalizeUrl(url); } function normalizeUrl(url) { let fullUrl; if (/^[^:]+:(\/{2})?[^\/].*/.test(url)) { fullUrl = url; } else { fullUrl = `http://${url}`; } try { const result = new URL(fullUrl); result.search = ""; result.hash = ""; return removeTrailingSlash(result.href); } catch (e) { throw new DwnError(DwnErrorCode.UrlProtocolNotNormalizable, "Could not normalize protocol URI"); } } function removeTrailingSlash(str3) { if (str3.endsWith("/")) { return str3.slice(0, -1); } else { return str3; } } // dist/esm/src/utils/records.js var __awaiter15 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __rest3 = function(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var Records = class { /** * Checks if the given message is a `RecordsWriteMessage`. */ static isRecordsWrite(message2) { const isRecordsWrite = message2.descriptor.interface === DwnInterfaceName.Records && message2.descriptor.method === DwnMethodName.Write; return isRecordsWrite; } /** * Gets the DID of the author of the given message. */ static getAuthor(message2) { let author; if (message2.authorization.authorDelegatedGrant !== void 0) { author = Message.getSigner(message2.authorization.authorDelegatedGrant); } else { author = Message.getSigner(message2); } return author; } /** * Decrypts the encrypted data in a message reply using the given ancestor private key. * @param ancestorPrivateKey Any ancestor private key in the key derivation path. */ static decrypt(recordsWrite, ancestorPrivateKey, cipherStream) { return __awaiter15(this, void 0, void 0, function* () { const { encryption } = recordsWrite; const matchingEncryptedKey = encryption.keyEncryption.find((key) => key.rootKeyId === ancestorPrivateKey.rootKeyId && key.derivationScheme === ancestorPrivateKey.derivationScheme); if (matchingEncryptedKey === void 0) { throw new DwnError(DwnErrorCode.RecordsDecryptNoMatchingKeyEncryptedFound, `Unable to find a symmetric key encrypted using key with ID '${ancestorPrivateKey.rootKeyId}' and '${ancestorPrivateKey.derivationScheme}' derivation scheme.`); } const fullDerivationPath = Records.constructKeyDerivationPath(matchingEncryptedKey.derivationScheme, recordsWrite); const leafPrivateKey = yield Records.derivePrivateKey(ancestorPrivateKey, fullDerivationPath); const encryptedKeyBytes = Encoder2.base64UrlToBytes(matchingEncryptedKey.encryptedKey); const ephemeralPublicKey = Secp256k1.publicJwkToBytes(matchingEncryptedKey.ephemeralPublicKey); const keyEncryptionInitializationVector = Encoder2.base64UrlToBytes(matchingEncryptedKey.initializationVector); const messageAuthenticationCode = Encoder2.base64UrlToBytes(matchingEncryptedKey.messageAuthenticationCode); const dataEncryptionKey = yield Encryption.eciesSecp256k1Decrypt({ ciphertext: encryptedKeyBytes, ephemeralPublicKey, initializationVector: keyEncryptionInitializationVector, messageAuthenticationCode, privateKey: leafPrivateKey }); const dataEncryptionInitializationVector = Encoder2.base64UrlToBytes(encryption.initializationVector); const plaintextStream = yield Encryption.aes256CtrDecrypt(dataEncryptionKey, dataEncryptionInitializationVector, cipherStream); return plaintextStream; }); } /** * Constructs full key derivation path using the specified scheme. */ static constructKeyDerivationPath(keyDerivationScheme, recordsWriteMessage) { const descriptor = recordsWriteMessage.descriptor; const contextId = recordsWriteMessage.contextId; let fullDerivationPath; if (keyDerivationScheme === KeyDerivationScheme.DataFormats) { fullDerivationPath = Records.constructKeyDerivationPathUsingDataFormatsScheme(descriptor.schema, descriptor.dataFormat); } else if (keyDerivationScheme === KeyDerivationScheme.ProtocolPath) { fullDerivationPath = Records.constructKeyDerivationPathUsingProtocolPathScheme(descriptor); } else if (keyDerivationScheme === KeyDerivationScheme.ProtocolContext) { fullDerivationPath = Records.constructKeyDerivationPathUsingProtocolContextScheme(contextId); } else { fullDerivationPath = Records.constructKeyDerivationPathUsingSchemasScheme(descriptor.schema); } return fullDerivationPath; } /** * Constructs the full key derivation path using `dataFormats` scheme. */ static constructKeyDerivationPathUsingDataFormatsScheme(schema, dataFormat) { if (schema !== void 0) { return [ KeyDerivationScheme.DataFormats, schema, dataFormat ]; } else { return [ KeyDerivationScheme.DataFormats, dataFormat ]; } } /** * Constructs the full key derivation path using `protocolPath` scheme. */ static constructKeyDerivationPathUsingProtocolPathScheme(descriptor) { if (descriptor.protocol === void 0) { throw new DwnError(DwnErrorCode.RecordsProtocolPathDerivationSchemeMissingProtocol, "Unable to construct key derivation path using `protocols` scheme because `protocol` is missing."); } const protocolPathSegments = descriptor.protocolPath.split("/"); const fullDerivationPath = [ KeyDerivationScheme.ProtocolPath, descriptor.protocol, ...protocolPathSegments ]; return fullDerivationPath; } /** * Constructs the full key derivation path using `protocolContext` scheme. */ static constructKeyDerivationPathUsingProtocolContextScheme(contextId) { if (contextId === void 0) { throw new DwnError(DwnErrorCode.RecordsProtocolContextDerivationSchemeMissingContextId, "Unable to construct key derivation path using `protocolContext` scheme because `contextId` is missing."); } const firstContextSegment = contextId.split("/")[0]; const fullDerivationPath = [ KeyDerivationScheme.ProtocolContext, firstContextSegment ]; return fullDerivationPath; } /** * Constructs the full key derivation path using `schemas` scheme. */ static constructKeyDerivationPathUsingSchemasScheme(schema) { if (schema === void 0) { throw new DwnError(DwnErrorCode.RecordsSchemasDerivationSchemeMissingSchema, "Unable to construct key derivation path using `schemas` scheme because `schema` is missing."); } const fullDerivationPath = [ KeyDerivationScheme.Schemas, schema ]; return fullDerivationPath; } /** * Derives a descendant private key given an ancestor private key and the full absolute derivation path. * NOTE: right now only `ECIES-ES256K` algorithm is supported for asymmetric encryption, * so we will only derive SECP256K1 key without additional conditional checks */ static derivePrivateKey(ancestorPrivateKey, fullDescendantDerivationPath) { var _a; return __awaiter15(this, void 0, void 0, function* () { if (ancestorPrivateKey.derivedPrivateKey.crv !== "secp256k1") { throw new DwnError(DwnErrorCode.RecordsDerivePrivateKeyUnSupportedCurve, `Curve ${ancestorPrivateKey.derivedPrivateKey.crv} is not supported.`); } const ancestorPrivateKeyDerivationPath = (_a = ancestorPrivateKey.derivationPath) !== null && _a !== void 0 ? _a : []; Records.validateAncestorKeyAndDescentKeyDerivationPathsMatch(ancestorPrivateKeyDerivationPath, fullDescendantDerivationPath); const subDerivationPath = fullDescendantDerivationPath.slice(ancestorPrivateKeyDerivationPath.length); const ancestorPrivateKeyBytes = Secp256k1.privateJwkToBytes(ancestorPrivateKey.derivedPrivateKey); const leafPrivateKey = yield HdKey.derivePrivateKeyBytes(ancestorPrivateKeyBytes, subDerivationPath); return leafPrivateKey; }); } /** * Validates that ancestor derivation path matches the descendant derivation path completely. * @throws {DwnError} with `DwnErrorCode.RecordsInvalidAncestorKeyDerivationSegment` if fails validation. */ static validateAncestorKeyAndDescentKeyDerivationPathsMatch(ancestorKeyDerivationPath, descendantKeyDerivationPath) { for (let i = 0; i < ancestorKeyDerivationPath.length; i++) { const ancestorSegment = ancestorKeyDerivationPath[i]; const descendantSegment = descendantKeyDerivationPath[i]; if (ancestorSegment !== descendantSegment) { throw new DwnError(DwnErrorCode.RecordsInvalidAncestorKeyDerivationSegment, `Ancestor key derivation segment '${ancestorSegment}' mismatches against the descendant key derivation segment '${descendantSegment}'.`); } } } /** * Extracts the parent context ID from the given context ID. */ static getParentContextFromOfContextId(contextId) { if (contextId === void 0) { return void 0; } const lastIndex = contextId.lastIndexOf("/"); if (lastIndex === -1) { return ""; } else { return contextId.substring(0, lastIndex); } } /** * Normalizes the protocol and schema URLs within a provided RecordsFilter and returns a copy of RecordsFilter with the modified values. * * @param filter incoming RecordsFilter to normalize. * @returns {RecordsFilter} a copy of the incoming RecordsFilter with the normalized properties. */ static normalizeFilter(filter2) { let protocol; if (filter2.protocol === void 0) { protocol = void 0; } else { protocol = normalizeProtocolUrl(filter2.protocol); } let schema; if (filter2.schema === void 0) { schema = void 0; } else { schema = normalizeSchemaUrl(filter2.schema); } const filterCopy = Object.assign(Object.assign({}, filter2), { protocol, schema }); removeUndefinedProperties(filterCopy); return filterCopy; } static isStartsWithFilter(filter2) { return typeof filter2 === "object" && ("startsWith" in filter2 && typeof filter2.startsWith === "string"); } /** * This will create individual keys for each of the tags that look like `tag.tag_property` */ static buildTagIndexes(tags) { const tagValues = {}; for (const property in tags) { const value = tags[property]; tagValues[`tag.${property}`] = value; } return tagValues; } /** * This will create individual keys for each of the tag filters that look like `tag.tag_filter_property` */ static convertTagsFilter(tags) { const tagValues = {}; for (const property in tags) { const value = tags[property]; tagValues[`tag.${property}`] = this.isStartsWithFilter(value) ? FilterUtility.constructPrefixFilterAsRangeFilter(value.startsWith) : value; } return tagValues; } /** * Converts an incoming RecordsFilter into a Filter usable by MessageStore. * * @param filter A RecordsFilter * @returns {Filter} a generic Filter able to be used with MessageStore. */ static convertFilter(filter2, dateSort) { const { tags } = filter2, remainingFilter = __rest3(filter2, ["tags"]); let tagsFilter = {}; if (tags !== void 0) { tagsFilter = Object.assign({}, this.convertTagsFilter(tags)); } const filterCopy = Object.assign(Object.assign({}, remainingFilter), tagsFilter); const { dateCreated, datePublished, dateUpdated, contextId } = filter2; const dateCreatedFilter = dateCreated ? FilterUtility.convertRangeCriterion(dateCreated) : void 0; if (dateCreatedFilter) { filterCopy.dateCreated = dateCreatedFilter; } const datePublishedFilter = datePublished ? FilterUtility.convertRangeCriterion(datePublished) : void 0; if (datePublishedFilter) { filterCopy.published = true; filterCopy.datePublished = datePublishedFilter; } if (filterCopy.published !== true && (dateSort === DateSort.PublishedAscending || dateSort === DateSort.PublishedDescending)) { filterCopy.published = true; } const messageTimestampFilter = dateUpdated ? FilterUtility.convertRangeCriterion(dateUpdated) : void 0; if (messageTimestampFilter) { filterCopy.messageTimestamp = messageTimestampFilter; delete filterCopy.dateUpdated; } const contextIdPrefixFilter = contextId ? FilterUtility.constructPrefixFilterAsRangeFilter(contextId) : void 0; if (contextIdPrefixFilter) { filterCopy.contextId = contextIdPrefixFilter; } return filterCopy; } /** * Validates the referential integrity of both author-delegated grant and owner-delegated grant. * @param authorSignaturePayload Decoded payload of the author signature of the message. Pass `undefined` if message is not signed. * Passed purely as a performance optimization so we don't have to decode the signature payload again. * @param ownerSignaturePayload Decoded payload of the owner signature of the message. Pass `undefined` if no owner signature is present. * Passed purely as a performance optimization so we don't have to decode the owner signature payload again. */ static validateDelegatedGrantReferentialIntegrity(message2, authorSignaturePayload, ownerSignaturePayload) { var _a, _b; return __awaiter15(this, void 0, void 0, function* () { const authorDelegatedGrantIdDefined = (authorSignaturePayload === null || authorSignaturePayload === void 0 ? void 0 : authorSignaturePayload.delegatedGrantId) !== void 0; const authorDelegatedGrantDefined = ((_a = message2.authorization) === null || _a === void 0 ? void 0 : _a.authorDelegatedGrant) !== void 0; if (authorDelegatedGrantIdDefined !== authorDelegatedGrantDefined) { throw new DwnError(DwnErrorCode.RecordsAuthorDelegatedGrantAndIdExistenceMismatch, `delegatedGrantId in message (author) signature and authorDelegatedGrant must both exist or be undefined. delegatedGrantId in message (author) signature defined: ${authorDelegatedGrantIdDefined}, authorDelegatedGrant defined: ${authorDelegatedGrantDefined}`); } if (authorDelegatedGrantDefined) { const delegatedGrant = message2.authorization.authorDelegatedGrant; const permissionGrant = yield PermissionGrant.parse(delegatedGrant); if (permissionGrant.delegated !== true) { throw new DwnError(DwnErrorCode.RecordsAuthorDelegatedGrantNotADelegatedGrant, `The owner delegated grant given is not a delegated grant.`); } const grantedTo = delegatedGrant.descriptor.recipient; const signer = Message.getSigner(message2); if (grantedTo !== signer) { throw new DwnError(DwnErrorCode.RecordsAuthorDelegatedGrantGrantedToAndOwnerSignatureMismatch, `grantedTo ${grantedTo} in author delegated grant must be the same as the signer ${signer} of the message signature.`); } const delegateGrantCid = yield Message.getCid(delegatedGrant); if (delegateGrantCid !== authorSignaturePayload.delegatedGrantId) { throw new DwnError(DwnErrorCode.RecordsAuthorDelegatedGrantCidMismatch, `CID of the author delegated grant ${delegateGrantCid} must be the same as the delegatedGrantId ${authorSignaturePayload.delegatedGrantId} in the message signature.`); } } const ownerDelegatedGrantIdDefined = (ownerSignaturePayload === null || ownerSignaturePayload === void 0 ? void 0 : ownerSignaturePayload.delegatedGrantId) !== void 0; const ownerDelegatedGrantDefined = ((_b = message2.authorization) === null || _b === void 0 ? void 0 : _b.ownerDelegatedGrant) !== void 0; if (ownerDelegatedGrantIdDefined !== ownerDelegatedGrantDefined) { throw new DwnError(DwnErrorCode.RecordsOwnerDelegatedGrantAndIdExistenceMismatch, `delegatedGrantId in owner signature and ownerDelegatedGrant must both exist or be undefined. delegatedGrantId in owner signature defined: ${ownerDelegatedGrantIdDefined}, ownerDelegatedGrant defined: ${ownerDelegatedGrantDefined}`); } if (ownerDelegatedGrantDefined) { const delegatedGrant = message2.authorization.ownerDelegatedGrant; const permissionGrant = yield PermissionGrant.parse(delegatedGrant); if (permissionGrant.delegated !== true) { throw new DwnError(DwnErrorCode.RecordsOwnerDelegatedGrantNotADelegatedGrant, `The owner delegated grant given is not a delegated grant.`); } const grantedTo = delegatedGrant.descriptor.recipient; const signer = Jws.getSignerDid(message2.authorization.ownerSignature.signatures[0]); if (grantedTo !== signer) { throw new DwnError(DwnErrorCode.RecordsOwnerDelegatedGrantGrantedToAndOwnerSignatureMismatch, `grantedTo ${grantedTo} in owner delegated grant must be the same as the signer ${signer} of the owner signature.`); } const delegateGrantCid = yield Message.getCid(delegatedGrant); if (delegateGrantCid !== ownerSignaturePayload.delegatedGrantId) { throw new DwnError(DwnErrorCode.RecordsOwnerDelegatedGrantCidMismatch, `CID of the owner delegated grant ${delegateGrantCid} must be the same as the delegatedGrantId ${ownerSignaturePayload.delegatedGrantId} in the owner signature.`); } } }); } /** * Determines if signature payload contains a protocolRole and should be authorized as such. */ static shouldProtocolAuthorize(signaturePayload) { return signaturePayload.protocolRole !== void 0; } /** * Checks if the filter supports returning published records. */ static filterIncludesPublishedRecords(filter2) { return filter2.datePublished !== void 0 || filter2.published !== false; } /** * Checks if the filter supports returning unpublished records. */ static filterIncludesUnpublishedRecords(filter2) { if (filter2.datePublished === void 0 && filter2.published === void 0) { return true; } return filter2.published === false; } }; // dist/esm/src/core/grant-authorization.js var __awaiter16 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var GrantAuthorization = class { /** * Performs base permissions-grant-based authorization against the given message: * 1. Validates the `expectedGrantor` and `expectedGrantee` values against the actual values in given permission grant. * 2. Verifies that the incoming message is within the allowed time frame of the grant, and the grant has not been revoked. * 3. Verifies that the `interface` and `method` grant scopes match the incoming message. * * NOTE: Does not validate grant `conditions` or `scope` beyond `interface` and `method` * * @param messageStore Used to check if the grant has been revoked. * @throws {DwnError} if validation fails */ static performBaseValidation(input) { return __awaiter16(this, void 0, void 0, function* () { const { incomingMessage, expectedGrantor, expectedGrantee, permissionGrant, messageStore } = input; const incomingMessageDescriptor = incomingMessage.descriptor; GrantAuthorization.verifyExpectedGrantorAndGrantee(expectedGrantor, expectedGrantee, permissionGrant); const grantedFor = expectedGrantor; yield GrantAuthorization.verifyGrantActive(grantedFor, incomingMessageDescriptor.messageTimestamp, permissionGrant, messageStore); yield GrantAuthorization.verifyGrantScopeInterfaceAndMethod(incomingMessageDescriptor.interface, incomingMessageDescriptor.method, permissionGrant); }); } /** * Verifies the given `expectedGrantor` and `expectedGrantee` values against * the actual signer and recipient in given permission grant. * @throws {DwnError} if `expectedGrantor` or `expectedGrantee` do not match the actual values in the grant. */ static verifyExpectedGrantorAndGrantee(expectedGrantor, expectedGrantee, permissionGrant) { const actualGrantee = permissionGrant.grantee; if (expectedGrantee !== actualGrantee) { throw new DwnError(DwnErrorCode.GrantAuthorizationNotGrantedToAuthor, `Permission grant is granted to ${actualGrantee}, but need to be granted to ${expectedGrantee}`); } const actualGrantor = permissionGrant.grantor; if (expectedGrantor !== actualGrantor) { throw new DwnError(DwnErrorCode.GrantAuthorizationNotGrantedForTenant, `Permission grant is granted by ${actualGrantor}, but need to be granted by ${expectedGrantor}`); } } /** * Verify that the incoming message is within the allowed time frame of the grant, * and the grant has not been revoked. * @param messageStore Used to check if the grant has been revoked. * @throws {DwnError} if incomingMessage has timestamp for a time in which the grant is not active. */ static verifyGrantActive(grantedFor, incomingMessageTimestamp, permissionGrant, messageStore) { return __awaiter16(this, void 0, void 0, function* () { if (incomingMessageTimestamp < permissionGrant.dateGranted) { throw new DwnError(DwnErrorCode.GrantAuthorizationGrantNotYetActive, `The message has a timestamp before the associated permission grant becomes active`); } if (incomingMessageTimestamp >= permissionGrant.dateExpires) { throw new DwnError(DwnErrorCode.GrantAuthorizationGrantExpired, `The message has timestamp after the expiry of the associated permission grant`); } const query = { parentId: permissionGrant.id, protocolPath: `grant/revocation`, isLatestBaseState: true }; const { messages: revokes } = yield messageStore.query(grantedFor, [query]); const oldestExistingRevoke = yield Message.getOldestMessage(revokes); if (oldestExistingRevoke !== void 0 && oldestExistingRevoke.descriptor.messageTimestamp <= incomingMessageTimestamp) { throw new DwnError(DwnErrorCode.GrantAuthorizationGrantRevoked, `Permission grant with CID ${permissionGrant.id} has been revoked`); } }); } /** * Verify that the `interface` and `method` grant scopes match the incoming message * @param permissionGrantId Purely being passed for logging purposes. * @throws {DwnError} if the `interface` and `method` of the incoming message do not match the scope of the permission grant. */ static verifyGrantScopeInterfaceAndMethod(dwnInterface, dwnMethod, permissionGrant) { return __awaiter16(this, void 0, void 0, function* () { if (dwnInterface !== permissionGrant.scope.interface) { throw new DwnError(DwnErrorCode.GrantAuthorizationInterfaceMismatch, `DWN Interface of incoming message is outside the scope of permission grant with ID ${permissionGrant.id}`); } else if (dwnMethod !== permissionGrant.scope.method) { throw new DwnError(DwnErrorCode.GrantAuthorizationMethodMismatch, `DWN Method of incoming message is outside the scope of permission grant with ID ${permissionGrant.id}`); } }); } }; // dist/esm/src/types/permission-types.js var PermissionConditionPublication; (function(PermissionConditionPublication2) { PermissionConditionPublication2["Required"] = "Required"; PermissionConditionPublication2["Prohibited"] = "Prohibited"; })(PermissionConditionPublication || (PermissionConditionPublication = {})); // dist/esm/src/core/records-grant-authorization.js var __awaiter17 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var RecordsGrantAuthorization = class { /** * Authorizes the given RecordsWrite in the scope of the DID given. */ static authorizeWrite(input) { return __awaiter17(this, void 0, void 0, function* () { const { recordsWriteMessage, expectedGrantor, expectedGrantee, permissionGrant, messageStore } = input; yield GrantAuthorization.performBaseValidation({ incomingMessage: recordsWriteMessage, expectedGrantor, expectedGrantee, permissionGrant, messageStore }); RecordsGrantAuthorization.verifyScope(recordsWriteMessage, permissionGrant.scope); RecordsGrantAuthorization.verifyConditions(recordsWriteMessage, permissionGrant.conditions); }); } /** * Authorizes a RecordsReadMessage using the given permission grant. * @param messageStore Used to check if the given grant has been revoked. */ static authorizeRead(input) { return __awaiter17(this, void 0, void 0, function* () { const { recordsReadMessage, recordsWriteMessageToBeRead, expectedGrantor, expectedGrantee, permissionGrant, messageStore } = input; yield GrantAuthorization.performBaseValidation({ incomingMessage: recordsReadMessage, expectedGrantor, expectedGrantee, permissionGrant, messageStore }); RecordsGrantAuthorization.verifyScope(recordsWriteMessageToBeRead, permissionGrant.scope); }); } /** * Authorizes the scope of a permission grant for RecordsQuery or RecordsSubscribe. * @param messageStore Used to check if the grant has been revoked. */ static authorizeQueryOrSubscribe(input) { return __awaiter17(this, void 0, void 0, function* () { const { incomingMessage, expectedGrantor, expectedGrantee, permissionGrant, messageStore } = input; yield GrantAuthorization.performBaseValidation({ incomingMessage, expectedGrantor, expectedGrantee, permissionGrant, messageStore }); const permissionScope = permissionGrant.scope; const protocolInGrant = permissionScope.protocol; const protocolInMessage = incomingMessage.descriptor.filter.protocol; if (protocolInGrant !== void 0 && protocolInMessage !== protocolInGrant) { throw new DwnError(DwnErrorCode.RecordsGrantAuthorizationQueryOrSubscribeProtocolScopeMismatch, `Grant protocol scope ${protocolInGrant} does not match protocol in message ${protocolInMessage}`); } }); } /** * Authorizes the scope of a permission grant for RecordsDelete. * @param messageStore Used to check if the grant has been revoked. */ static authorizeDelete(input) { return __awaiter17(this, void 0, void 0, function* () { const { recordsDeleteMessage, recordsWriteToDelete, expectedGrantor, expectedGrantee, permissionGrant, messageStore } = input; yield GrantAuthorization.performBaseValidation({ incomingMessage: recordsDeleteMessage, expectedGrantor, expectedGrantee, permissionGrant, messageStore }); const permissionScope = permissionGrant.scope; const protocolInGrant = permissionScope.protocol; const protocolOfRecordToDelete = recordsWriteToDelete.descriptor.protocol; if (protocolInGrant !== void 0 && protocolOfRecordToDelete !== protocolInGrant) { throw new DwnError(DwnErrorCode.RecordsGrantAuthorizationDeleteProtocolScopeMismatch, `Grant protocol scope ${protocolInGrant} does not match protocol in record to delete ${protocolOfRecordToDelete}`); } }); } /** * Verifies the given record against the scope of the given grant. */ static verifyScope(recordsWriteMessage, grantScope) { if (RecordsGrantAuthorization.isUnrestrictedScope(grantScope)) { return; } else if (recordsWriteMessage.descriptor.protocol !== void 0) { RecordsGrantAuthorization.verifyProtocolRecordScope(recordsWriteMessage, grantScope); } else { RecordsGrantAuthorization.verifyFlatRecordScope(recordsWriteMessage, grantScope); } } /** * Verifies a protocol record against the scope of the given grant. */ static verifyProtocolRecordScope(recordsWriteMessage, grantScope) { if (grantScope.protocol === void 0) { throw new DwnError(DwnErrorCode.RecordsGrantAuthorizationScopeMissingProtocol, "Grant for protocol record must specify protocol in its scope"); } if (grantScope.protocol !== recordsWriteMessage.descriptor.protocol) { throw new DwnError(DwnErrorCode.RecordsGrantAuthorizationScopeProtocolMismatch, `Grant scope specifies different protocol than what appears in the record`); } if (grantScope.contextId !== void 0) { if (recordsWriteMessage.contextId === void 0 || !recordsWriteMessage.contextId.startsWith(grantScope.contextId)) { throw new DwnError(DwnErrorCode.RecordsGrantAuthorizationScopeContextIdMismatch, `Grant scope specifies different contextId than what appears in the record`); } } if (grantScope.protocolPath !== void 0 && grantScope.protocolPath !== recordsWriteMessage.descriptor.protocolPath) { throw new DwnError(DwnErrorCode.RecordsGrantAuthorizationScopeProtocolPathMismatch, `Grant scope specifies different protocolPath than what appears in the record`); } } /** * Verifies a non-protocol record against the scope of the given grant. */ static verifyFlatRecordScope(recordsWriteMessage, grantScope) { if (grantScope.schema !== void 0) { if (grantScope.schema !== recordsWriteMessage.descriptor.schema) { throw new DwnError(DwnErrorCode.RecordsGrantAuthorizationScopeSchema, `Record does not have schema in permission grant scope with schema '${grantScope.schema}'`); } } } /** * Verifies grant `conditions`. * Currently the only condition is `published` which only applies to RecordsWrites */ static verifyConditions(recordsWriteMessage, conditions) { if ((conditions === null || conditions === void 0 ? void 0 : conditions.publication) === PermissionConditionPublication.Required && !recordsWriteMessage.descriptor.published) { throw new DwnError(DwnErrorCode.RecordsGrantAuthorizationConditionPublicationRequired, "Permission grant requires message to be published"); } if ((conditions === null || conditions === void 0 ? void 0 : conditions.publication) === PermissionConditionPublication.Prohibited && recordsWriteMessage.descriptor.published) { throw new DwnError(DwnErrorCode.RecordsGrantAuthorizationConditionPublicationProhibited, "Permission grant prohibits message from being published"); } } /** * Checks if scope has no restrictions beyond interface and method. * Grant-holder is authorized to access any record. */ static isUnrestrictedScope(grantScope) { return grantScope.protocol === void 0 && grantScope.schema === void 0; } }; // dist/esm/src/utils/time.js var import_polyfill = require("@js-temporal/polyfill"); var __awaiter18 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var Time = class { /** * sleeps for the desired duration * @param durationInMillisecond the desired amount of sleep time * @returns when the provided duration has passed */ static sleep(durationInMillisecond) { return __awaiter18(this, void 0, void 0, function* () { return new Promise((resolve5) => setTimeout(resolve5, durationInMillisecond)); }); } /** * We must sleep for at least 2ms to avoid timestamp collisions during testing. * https://github.com/TBD54566975/dwn-sdk-js/issues/481 */ static minimalSleep() { return __awaiter18(this, void 0, void 0, function* () { yield Time.sleep(2); }); } /** * Returns an UTC ISO-8601 timestamp with microsecond precision accepted by DWN. * using @js-temporal/polyfill */ static getCurrentTimestamp() { return import_polyfill.Temporal.Now.instant().toString({ smallestUnit: "microseconds" }); } /** * Creates a UTC ISO-8601 timestamp in microsecond precision accepted by DWN. * @param options - Options for creating the timestamp. * @returns string */ static createTimestamp(options) { const { year, month, day, hour, minute, second, millisecond, microsecond } = options; return import_polyfill.Temporal.ZonedDateTime.from({ timeZone: "UTC", year, month, day, hour, minute, second, millisecond, microsecond }).toInstant().toString({ smallestUnit: "microseconds" }); } /** * Creates a UTC ISO-8601 timestamp offset from now or given timestamp accepted by DWN. * @param offset Negative number means offset into the past. */ static createOffsetTimestamp(offset, timestamp) { const timestampInstant = timestamp ? import_polyfill.Temporal.Instant.from(timestamp) : import_polyfill.Temporal.Now.instant(); const offsetDuration = import_polyfill.Temporal.Duration.from(offset); const offsetInstant = timestampInstant.add(offsetDuration); return offsetInstant.toString({ smallestUnit: "microseconds" }); } /** * Validates that the provided timestamp is a valid number * @param timestamp the timestamp to validate * @throws DwnError if timestamp is not a valid number */ static validateTimestamp(timestamp) { try { import_polyfill.Temporal.Instant.from(timestamp); } catch (_a) { throw new DwnError(DwnErrorCode.TimestampInvalid, `Invalid timestamp: ${timestamp}`); } } }; // dist/esm/src/interfaces/records-write.js var __awaiter19 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __rest4 = function(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var RecordsWrite2 = class { /** * Valid JSON message representing this RecordsWrite. * @throws `DwnErrorCode.RecordsWriteMissingSigner` if the message is not signed yet. */ get message() { if (this._message.authorization === void 0) { throw new DwnError(DwnErrorCode.RecordsWriteMissingSigner, "This RecordsWrite is not yet signed, JSON message cannot be generated from an incomplete state."); } return this._message; } get author() { return this._author; } get signaturePayload() { return this._signaturePayload; } /** * The owner DID of the message if owner signature is present in the message; `undefined` otherwise. * This is the logical owner of the message, not to be confused with the actual signer of the owner signature, * this is because the signer of the owner signature may not be the actual DWN owner, but a delegate authorized by the owner. */ get owner() { return this._owner; } /** * Decoded owner signature payload. */ get ownerSignaturePayload() { return this._ownerSignaturePayload; } /** * If this message is signed by an author-delegate. */ get isSignedByAuthorDelegate() { return Message.isSignedByAuthorDelegate(this._message); } /** * If this message is signed by an owner-delegate. */ get isSignedByOwnerDelegate() { return Message.isSignedByOwnerDelegate(this._message); } /** * Gets the signer of this message. * This is not to be confused with the logical author of the message. */ get signer() { return Message.getSigner(this._message); } /** * Gets the signer of owner signature; `undefined` if owner signature is not present in the message. * This is not to be confused with the logical owner {@link #owner} of the message, * this is because the signer of the owner signature may not be the actual DWN owner, but a delegate authorized by the owner. * In the case that the owner signature is signed by the actual DWN owner, this value will be the same as {@link #owner}. */ get ownerSignatureSigner() { var _a; if (((_a = this._message.authorization) === null || _a === void 0 ? void 0 : _a.ownerSignature) === void 0) { return void 0; } const signer = Jws.getSignerDid(this._message.authorization.ownerSignature.signatures[0]); return signer; } constructor(message2, parentContextId) { this.parentContextId = parentContextId; this._message = message2; if (message2.authorization !== void 0) { this._author = Records.getAuthor(message2); this._signaturePayload = Jws.decodePlainObjectPayload(message2.authorization.signature); if (message2.authorization.ownerSignature !== void 0) { if (message2.authorization.ownerDelegatedGrant !== void 0) { this._owner = Message.getSigner(message2.authorization.ownerDelegatedGrant); } else { this._owner = Jws.getSignerDid(message2.authorization.ownerSignature.signatures[0]); } this._ownerSignaturePayload = Jws.decodePlainObjectPayload(message2.authorization.ownerSignature); } } this.attesters = RecordsWrite2.getAttesters(message2); } /** * Parses a RecordsWrite message and returns a {RecordsWrite} instance. */ static parse(recordsWriteMessage) { return __awaiter19(this, void 0, void 0, function* () { const message2 = JSON.parse(JSON.stringify(recordsWriteMessage)); yield Message.validateSignatureStructure(message2.authorization.signature, message2.descriptor, "RecordsWriteSignaturePayload"); if (message2.authorization.ownerSignature !== void 0) { yield Message.validateSignatureStructure(message2.authorization.ownerSignature, message2.descriptor); } yield RecordsWrite2.validateAttestationIntegrity(message2); const recordsWrite = new RecordsWrite2(message2); yield recordsWrite.validateIntegrity(); return recordsWrite; }); } /** * Creates a RecordsWrite message. * @param options.recordId If `undefined`, will be auto-filled as the initial message as convenience for developer. * @param options.data Data used to compute the `dataCid`, must be the encrypted data bytes if `options.encryptionInput` is given. * Must specify `options.dataCid` if `undefined`. * @param options.dataCid CID of the data that is already stored in the DWN. Must specify `options.data` if `undefined`. * @param options.dataSize Size of data in number of bytes. Must be defined if `options.dataCid` is defined; must be `undefined` otherwise. * @param options.dateCreated If `undefined`, it will be auto-filled with current time. * @param options.messageTimestamp If `undefined`, it will be auto-filled with current time. * @param options.parentContextId Must be given if this message is for a non-root protocol record. * If not given, it either means this write is for a root protocol record or a flat-space record. */ static create(options) { var _a, _b, _c, _d; return __awaiter19(this, void 0, void 0, function* () { if (options.protocol === void 0 && options.protocolPath !== void 0 || options.protocol !== void 0 && options.protocolPath === void 0) { throw new DwnError(DwnErrorCode.RecordsWriteCreateProtocolAndProtocolPathMutuallyInclusive, "`protocol` and `protocolPath` must both be defined or undefined at the same time"); } if (options.data === void 0 && options.dataCid === void 0 || options.data !== void 0 && options.dataCid !== void 0) { throw new DwnError(DwnErrorCode.RecordsWriteCreateDataAndDataCidMutuallyExclusive, "one and only one parameter between `data` and `dataCid` is required"); } if (options.dataCid === void 0 && options.dataSize !== void 0 || options.dataCid !== void 0 && options.dataSize === void 0) { throw new DwnError(DwnErrorCode.RecordsWriteCreateDataCidAndDataSizeMutuallyInclusive, "`dataCid` and `dataSize` must both be defined or undefined at the same time"); } if (options.signer === void 0 && options.delegatedGrant !== void 0) { throw new DwnError(DwnErrorCode.RecordsWriteCreateMissingSigner, "`signer` must be given when `delegatedGrant` is given"); } const dataCid = (_a = options.dataCid) !== null && _a !== void 0 ? _a : yield Cid.computeDagPbCidFromBytes(options.data); const dataSize = (_b = options.dataSize) !== null && _b !== void 0 ? _b : options.data.length; const currentTime = Time.getCurrentTimestamp(); const descriptor = { interface: DwnInterfaceName.Records, method: DwnMethodName.Write, protocol: options.protocol !== void 0 ? normalizeProtocolUrl(options.protocol) : void 0, protocolPath: options.protocolPath, recipient: options.recipient, schema: options.schema !== void 0 ? normalizeSchemaUrl(options.schema) : void 0, tags: options.tags, parentId: RecordsWrite2.getRecordIdFromContextId(options.parentContextId), dataCid, dataSize, dateCreated: (_c = options.dateCreated) !== null && _c !== void 0 ? _c : currentTime, messageTimestamp: (_d = options.messageTimestamp) !== null && _d !== void 0 ? _d : currentTime, published: options.published, datePublished: options.datePublished, dataFormat: options.dataFormat }; if (options.published === true && options.datePublished === void 0) { descriptor.datePublished = currentTime; } removeUndefinedProperties(descriptor); const recordId = options.recordId; const descriptorCid = yield Cid.computeCid(descriptor); const attestation = yield RecordsWrite2.createAttestation(descriptorCid, options.attestationSigners); const encryption = yield RecordsWrite2.createEncryptionProperty(descriptor, options.encryptionInput); const message2 = { recordId, descriptor }; if (attestation !== void 0) { message2.attestation = attestation; } if (encryption !== void 0) { message2.encryption = encryption; } const recordsWrite = new RecordsWrite2(message2, options.parentContextId); if (options.signer !== void 0) { yield recordsWrite.sign({ signer: options.signer, delegatedGrant: options.delegatedGrant, permissionGrantId: options.permissionGrantId, protocolRole: options.protocolRole }); } return recordsWrite; }); } static getRecordIdFromContextId(contextId) { return contextId === null || contextId === void 0 ? void 0 : contextId.split("/").filter((segment) => segment !== "").pop(); } /** * Convenience method that creates a message by: * 1. Copying over immutable properties from the given source message * 2. Copying over mutable properties that are not overwritten from the given source message * 3. Replace the mutable properties that are given new value * @param options.recordsWriteMessage Message that the new RecordsWrite will be based from. * @param options.messageTimestamp The new date the record is modified. If not given, current time will be used . * @param options.data The new data or the record. If not given, data from given message will be used. * @param options.published The new published state. If not given, then will be set to `true` if {options.messageTimestamp} is given; * else the state from given message will be used. * @param options.publishedDate The new date the record is modified. If not given, then: * - will not be set if the record will be unpublished as the result of this RecordsWrite; else * - will be set to the same published date as the given message if it wss already published; else * - will be set to current time (because this is a toggle from unpublished to published) */ static createFrom(options) { var _a, _b, _c, _d; return __awaiter19(this, void 0, void 0, function* () { const sourceMessage = options.recordsWriteMessage; const sourceRecordsWrite = yield RecordsWrite2.parse(sourceMessage); const currentTime = Time.getCurrentTimestamp(); const published = (_a = options.published) !== null && _a !== void 0 ? _a : options.datePublished ? true : sourceMessage.descriptor.published; let datePublished = void 0; if (options.datePublished) { datePublished = options.datePublished; } else { if (published) { if (sourceMessage.descriptor.published) { datePublished = sourceMessage.descriptor.datePublished; } else { datePublished = currentTime; } } } const createOptions = { // immutable properties below, just copy from the source message recipient: sourceMessage.descriptor.recipient, recordId: sourceMessage.recordId, dateCreated: sourceMessage.descriptor.dateCreated, protocol: sourceMessage.descriptor.protocol, protocolPath: sourceMessage.descriptor.protocolPath, schema: sourceMessage.descriptor.schema, parentContextId: Records.getParentContextFromOfContextId(sourceMessage.contextId), // mutable properties below messageTimestamp: (_b = options.messageTimestamp) !== null && _b !== void 0 ? _b : currentTime, published, datePublished, tags: options.tags, data: options.data, dataCid: options.data ? void 0 : sourceMessage.descriptor.dataCid, dataSize: options.data ? void 0 : sourceMessage.descriptor.dataSize, dataFormat: (_c = options.dataFormat) !== null && _c !== void 0 ? _c : sourceMessage.descriptor.dataFormat, protocolRole: (_d = options.protocolRole) !== null && _d !== void 0 ? _d : sourceRecordsWrite.signaturePayload.protocolRole, delegatedGrant: options.delegatedGrant, // finally still need signers signer: options.signer, attestationSigners: options.attestationSigners }; const recordsWrite = yield RecordsWrite2.create(createOptions); return recordsWrite; }); } /** * Called by `JSON.stringify(...)` automatically. */ toJSON() { return this.message; } /** * Encrypts the symmetric encryption key using the public keys given and attach the resulting `encryption` property to the RecordsWrite. */ encryptSymmetricEncryptionKey(encryptionInput) { return __awaiter19(this, void 0, void 0, function* () { this._message.encryption = yield RecordsWrite2.createEncryptionProperty(this._message.descriptor, encryptionInput); delete this._message.authorization; this._signaturePayload = void 0; this._author = void 0; }); } /** * Signs the RecordsWrite, the signer is commonly the author, but can also be a delegate. */ sign(options) { var _a; return __awaiter19(this, void 0, void 0, function* () { const { signer, delegatedGrant, permissionGrantId, protocolRole } = options; let delegatedGrantId; let authorDid; if (delegatedGrant !== void 0) { delegatedGrantId = yield Message.getCid(delegatedGrant); authorDid = Jws.getSignerDid(delegatedGrant.authorization.signature.signatures[0]); } else { authorDid = Jws.extractDid(signer.keyId); } const descriptor = this._message.descriptor; const descriptorCid = yield Cid.computeCid(descriptor); this._message.recordId = (_a = this._message.recordId) !== null && _a !== void 0 ? _a : yield RecordsWrite2.getEntryId(authorDid, descriptor); if (this._message.descriptor.protocol !== void 0) { if (this.parentContextId === void 0 || this.parentContextId === "") { this._message.contextId = this._message.recordId; } else { this._message.contextId = this.parentContextId + "/" + this._message.recordId; } } const signature = yield RecordsWrite2.createSignerSignature({ recordId: this._message.recordId, contextId: this._message.contextId, descriptorCid, attestation: this._message.attestation, encryption: this._message.encryption, signer, delegatedGrantId, permissionGrantId, protocolRole }); this._message.authorization = { signature }; if (delegatedGrant !== void 0) { this._message.authorization.authorDelegatedGrant = delegatedGrant; } this._signaturePayload = Jws.decodePlainObjectPayload(signature); this._author = authorDid; }); } /** * Signs the `RecordsWrite` as the DWN owner. * This is used when the DWN owner wants to retain a copy of a message that the owner did not author. * NOTE: requires the `RecordsWrite` to already have the author's signature. */ signAsOwner(signer) { return __awaiter19(this, void 0, void 0, function* () { if (this._author === void 0) { throw new DwnError(DwnErrorCode.RecordsWriteSignAsOwnerUnknownAuthor, "Unable to sign as owner without message signature because owner needs to sign over `recordId` which depends on author DID."); } const descriptor = this._message.descriptor; const ownerSignature = yield Message.createSignature(descriptor, signer); this._message.authorization.ownerSignature = ownerSignature; this._ownerSignaturePayload = Jws.decodePlainObjectPayload(ownerSignature); this._owner = Jws.extractDid(signer.keyId); ; }); } /** * Signs the `RecordsWrite` as the DWN owner-delegate. * This is used when a DWN owner-delegate wants to retain a copy of a message that the owner did not author. * NOTE: requires the `RecordsWrite` to already have the author's signature. */ signAsOwnerDelegate(signer, delegatedGrant) { return __awaiter19(this, void 0, void 0, function* () { if (this._author === void 0) { throw new DwnError(DwnErrorCode.RecordsWriteSignAsOwnerDelegateUnknownAuthor, "Unable to sign as owner delegate without message signature because owner delegate needs to sign over `recordId` which depends on author DID."); } const delegatedGrantId = yield Message.getCid(delegatedGrant); const descriptor = this._message.descriptor; const ownerSignature = yield Message.createSignature(descriptor, signer, { delegatedGrantId }); this._message.authorization.ownerSignature = ownerSignature; this._message.authorization.ownerDelegatedGrant = delegatedGrant; this._ownerSignaturePayload = Jws.decodePlainObjectPayload(ownerSignature); this._owner = Jws.getSignerDid(delegatedGrant.authorization.signature.signatures[0]); }); } /** * Validates the integrity of the RecordsWrite message assuming the message passed basic schema validation. * There is opportunity to integrate better with `validateSchema(...)` */ validateIntegrity() { return __awaiter19(this, void 0, void 0, function* () { const isInitialWrite = yield this.isInitialWrite(); if (isInitialWrite) { const dateRecordCreated = this.message.descriptor.dateCreated; const messageTimestamp = this.message.descriptor.messageTimestamp; if (messageTimestamp !== dateRecordCreated) { throw new DwnError(DwnErrorCode.RecordsWriteValidateIntegrityDateCreatedMismatch, `messageTimestamp ${messageTimestamp} must match dateCreated ${dateRecordCreated} for the initial write`); } if (this.message.descriptor.protocol !== void 0 && this.message.descriptor.parentId === void 0) { const expectedContextId = yield this.getEntryId(); if (this.message.contextId !== expectedContextId) { throw new DwnError(DwnErrorCode.RecordsWriteValidateIntegrityContextIdMismatch, `contextId in message: ${this.message.contextId} does not match deterministic contextId: ${expectedContextId}`); } } } const signaturePayload = this.signaturePayload; if (this.message.recordId !== signaturePayload.recordId) { throw new DwnError(DwnErrorCode.RecordsWriteValidateIntegrityRecordIdUnauthorized, `recordId in message ${this.message.recordId} does not match recordId in authorization: ${signaturePayload.recordId}`); } if (this.message.contextId !== signaturePayload.contextId) { throw new DwnError(DwnErrorCode.RecordsWriteValidateIntegrityContextIdNotInSignerSignaturePayload, `contextId in message ${this.message.contextId} does not match contextId in authorization: ${signaturePayload.contextId}`); } yield Records.validateDelegatedGrantReferentialIntegrity(this.message, signaturePayload, this.ownerSignaturePayload); if (signaturePayload.attestationCid !== void 0) { const expectedAttestationCid = yield Cid.computeCid(this.message.attestation); const actualAttestationCid = signaturePayload.attestationCid; if (actualAttestationCid !== expectedAttestationCid) { throw new DwnError(DwnErrorCode.RecordsWriteValidateIntegrityAttestationMismatch, `CID ${expectedAttestationCid} of attestation property in message does not match attestationCid in authorization: ${actualAttestationCid}`); } } if (signaturePayload.encryptionCid !== void 0) { const expectedEncryptionCid = yield Cid.computeCid(this.message.encryption); const actualEncryptionCid = signaturePayload.encryptionCid; if (actualEncryptionCid !== expectedEncryptionCid) { throw new DwnError(DwnErrorCode.RecordsWriteValidateIntegrityEncryptionCidMismatch, `CID ${expectedEncryptionCid} of encryption property in message does not match encryptionCid in authorization: ${actualEncryptionCid}`); } } if (this.message.descriptor.protocol !== void 0) { validateProtocolUrlNormalized(this.message.descriptor.protocol); } if (this.message.descriptor.schema !== void 0) { validateSchemaUrlNormalized(this.message.descriptor.schema); } Time.validateTimestamp(this.message.descriptor.messageTimestamp); Time.validateTimestamp(this.message.descriptor.dateCreated); if (this.message.descriptor.datePublished) { Time.validateTimestamp(this.message.descriptor.datePublished); } }); } /** * Validates the structural integrity of the `attestation` property. * NOTE: signature is not verified. */ static validateAttestationIntegrity(message2) { return __awaiter19(this, void 0, void 0, function* () { if (message2.attestation === void 0) { return; } if (message2.attestation.signatures.length !== 1) { throw new DwnError(DwnErrorCode.RecordsWriteAttestationIntegrityMoreThanOneSignature, `Currently implementation only supports 1 attester, but got ${message2.attestation.signatures.length}`); } const payloadJson = Jws.decodePlainObjectPayload(message2.attestation); const { descriptorCid } = payloadJson; const expectedDescriptorCid = yield Cid.computeCid(message2.descriptor); if (descriptorCid !== expectedDescriptorCid) { throw new DwnError(DwnErrorCode.RecordsWriteAttestationIntegrityDescriptorCidMismatch, `descriptorCid ${descriptorCid} does not match expected descriptorCid ${expectedDescriptorCid}`); } const propertyCount = Object.keys(payloadJson).length; if (propertyCount > 1) { throw new DwnError(DwnErrorCode.RecordsWriteAttestationIntegrityInvalidPayloadProperty, `Only 'descriptorCid' is allowed in attestation payload, but got ${propertyCount} properties.`); } }); } /** * Computes the deterministic Entry ID of this message. */ getEntryId() { return __awaiter19(this, void 0, void 0, function* () { const entryId = yield RecordsWrite2.getEntryId(this.author, this.message.descriptor); return entryId; }); } /** * Computes the deterministic Entry ID of this message. */ static getEntryId(author, descriptor) { return __awaiter19(this, void 0, void 0, function* () { if (author === void 0) { throw new DwnError(DwnErrorCode.RecordsWriteGetEntryIdUndefinedAuthor, "Property `author` is needed to compute entry ID."); } const entryIdInput = Object.assign({}, descriptor); entryIdInput.author = author; const cid = yield Cid.computeCid(entryIdInput); return cid; }); } /** * Checks if the given message is the initial entry of a record. */ isInitialWrite() { return __awaiter19(this, void 0, void 0, function* () { const entryId = yield this.getEntryId(); return entryId === this.message.recordId; }); } constructIndexes(isLatestBaseState) { return __awaiter19(this, void 0, void 0, function* () { const message2 = this.message; const _a = message2.descriptor, { tags } = _a, descriptor = __rest4(_a, ["tags"]); delete descriptor.published; let indexes = Object.assign(Object.assign({}, descriptor), { isLatestBaseState, published: !!message2.descriptor.published, author: this.author, recordId: message2.recordId, entryId: yield RecordsWrite2.getEntryId(this.author, this.message.descriptor) }); if (tags !== void 0 && isLatestBaseState === true) { const flattenedTags = Records.buildTagIndexes(Object.assign({}, tags)); indexes = Object.assign(Object.assign({}, indexes), flattenedTags); } if (this.attesters.length > 0) { indexes.attester = this.attesters[0]; } if (message2.contextId !== void 0) { indexes.contextId = message2.contextId; } return indexes; }); } /** * Authorizes the author-delegate who signed this message. * @param messageStore Used to check if the grant has been revoked. */ authorizeAuthorDelegate(messageStore) { return __awaiter19(this, void 0, void 0, function* () { const delegatedGrant = yield PermissionGrant.parse(this.message.authorization.authorDelegatedGrant); yield RecordsGrantAuthorization.authorizeWrite({ recordsWriteMessage: this.message, expectedGrantor: this.author, expectedGrantee: this.signer, permissionGrant: delegatedGrant, messageStore }); }); } /** * Authorizes the owner-delegate who signed this message. * @param messageStore Used to check if the grant has been revoked. */ authorizeOwnerDelegate(messageStore) { return __awaiter19(this, void 0, void 0, function* () { const delegatedGrant = yield PermissionGrant.parse(this.message.authorization.ownerDelegatedGrant); yield RecordsGrantAuthorization.authorizeWrite({ recordsWriteMessage: this.message, expectedGrantor: this.owner, expectedGrantee: this.ownerSignatureSigner, permissionGrant: delegatedGrant, messageStore }); }); } /** * Checks if the given message is the initial entry of a record. */ static isInitialWrite(message2) { return __awaiter19(this, void 0, void 0, function* () { if (message2.descriptor.interface !== DwnInterfaceName.Records || message2.descriptor.method !== DwnMethodName.Write) { return false; } const recordsWriteMessage = message2; const author = Records.getAuthor(recordsWriteMessage); const entryId = yield RecordsWrite2.getEntryId(author, recordsWriteMessage.descriptor); return entryId === recordsWriteMessage.recordId; }); } /** * Creates the `encryption` property if encryption input is given. Else `undefined` is returned. * @param descriptor Descriptor of the `RecordsWrite` message which contains the information need by key path derivation schemes. */ static createEncryptionProperty(descriptor, encryptionInput) { var _a, _b; return __awaiter19(this, void 0, void 0, function* () { if (encryptionInput === void 0) { return void 0; } const keyEncryption = []; for (const keyEncryptionInput of encryptionInput.keyEncryptionInputs) { if (keyEncryptionInput.derivationScheme === KeyDerivationScheme.ProtocolPath && descriptor.protocol === void 0) { throw new DwnError(DwnErrorCode.RecordsWriteMissingProtocol, "`protocols` encryption scheme cannot be applied to record without the `protocol` property."); } if (keyEncryptionInput.derivationScheme === KeyDerivationScheme.Schemas && descriptor.schema === void 0) { throw new DwnError(DwnErrorCode.RecordsWriteMissingSchema, "`schemas` encryption scheme cannot be applied to record without the `schema` property."); } const publicKeyBytes = Secp256k1.publicJwkToBytes(keyEncryptionInput.publicKey); const keyEncryptionOutput = yield Encryption.eciesSecp256k1Encrypt(publicKeyBytes, encryptionInput.key); const encryptedKey = Encoder2.bytesToBase64Url(keyEncryptionOutput.ciphertext); const ephemeralPublicKey = yield Secp256k1.publicKeyToJwk(keyEncryptionOutput.ephemeralPublicKey); const keyEncryptionInitializationVector = Encoder2.bytesToBase64Url(keyEncryptionOutput.initializationVector); const messageAuthenticationCode = Encoder2.bytesToBase64Url(keyEncryptionOutput.messageAuthenticationCode); const encryptedKeyData = { rootKeyId: keyEncryptionInput.publicKeyId, algorithm: (_a = keyEncryptionInput.algorithm) !== null && _a !== void 0 ? _a : EncryptionAlgorithm.EciesSecp256k1, derivationScheme: keyEncryptionInput.derivationScheme, ephemeralPublicKey, initializationVector: keyEncryptionInitializationVector, messageAuthenticationCode, encryptedKey }; if (keyEncryptionInput.derivationScheme === KeyDerivationScheme.ProtocolContext) { encryptedKeyData.derivedPublicKey = keyEncryptionInput.publicKey; } keyEncryption.push(encryptedKeyData); } const encryption = { algorithm: (_b = encryptionInput.algorithm) !== null && _b !== void 0 ? _b : EncryptionAlgorithm.Aes256Ctr, initializationVector: Encoder2.bytesToBase64Url(encryptionInput.initializationVector), keyEncryption }; return encryption; }); } /** * Creates the `attestation` property of a RecordsWrite message if given signature inputs; returns `undefined` otherwise. */ static createAttestation(descriptorCid, signers) { return __awaiter19(this, void 0, void 0, function* () { if (signers === void 0 || signers.length === 0) { return void 0; } const attestationPayload = { descriptorCid }; const attestationPayloadBytes = Encoder2.objectToBytes(attestationPayload); const builder = yield GeneralJwsBuilder.create(attestationPayloadBytes, signers); return builder.getJws(); }); } /** * Creates the `signature` property in the `authorization` of a `RecordsWrite` message. */ static createSignerSignature(input) { return __awaiter19(this, void 0, void 0, function* () { const { recordId, contextId, descriptorCid, attestation, encryption, signer, delegatedGrantId, permissionGrantId, protocolRole } = input; const attestationCid = attestation ? yield Cid.computeCid(attestation) : void 0; const encryptionCid = encryption ? yield Cid.computeCid(encryption) : void 0; const signaturePayload = { recordId, descriptorCid, contextId, attestationCid, encryptionCid, delegatedGrantId, permissionGrantId, protocolRole }; removeUndefinedProperties(signaturePayload); const signaturePayloadBytes = Encoder2.objectToBytes(signaturePayload); const builder = yield GeneralJwsBuilder.create(signaturePayloadBytes, [signer]); const signature = builder.getJws(); return signature; }); } /** * Gets the initial write from the given list of `RecordsWrite`. */ static getInitialWrite(messages) { return __awaiter19(this, void 0, void 0, function* () { for (const message2 of messages) { if (yield RecordsWrite2.isInitialWrite(message2)) { return message2; } } throw new DwnError(DwnErrorCode.RecordsWriteGetInitialWriteNotFound, `Initial write is not found.`); }); } /** * Verifies that immutable properties of the two given messages are identical. * @throws {Error} if immutable properties between two RecordsWrite message */ static verifyEqualityOfImmutableProperties(existingWriteMessage, newMessage) { const mutableDescriptorProperties = ["dataCid", "dataSize", "dataFormat", "datePublished", "published", "messageTimestamp", "tags"]; let descriptorPropertyNames = []; descriptorPropertyNames.push(...Object.keys(existingWriteMessage.descriptor)); descriptorPropertyNames.push(...Object.keys(newMessage.descriptor)); descriptorPropertyNames = [...new Set(descriptorPropertyNames)]; for (const descriptorPropertyName of descriptorPropertyNames) { if (mutableDescriptorProperties.indexOf(descriptorPropertyName) === -1) { const valueInExistingWrite = existingWriteMessage.descriptor[descriptorPropertyName]; const valueInNewMessage = newMessage.descriptor[descriptorPropertyName]; if (valueInNewMessage !== valueInExistingWrite) { throw new DwnError(DwnErrorCode.RecordsWriteImmutablePropertyChanged, `${descriptorPropertyName} is an immutable property: cannot change '${valueInExistingWrite}' to '${valueInNewMessage}'`); } } } return true; } /** * Gets the DID of the attesters of the given message. */ static getAttesters(message2) { var _a, _b; const attestationSignatures = (_b = (_a = message2.attestation) === null || _a === void 0 ? void 0 : _a.signatures) !== null && _b !== void 0 ? _b : []; const attesters = attestationSignatures.map((signature) => Jws.getSignerDid(signature)); return attesters; } /** * Fetches the initial RecordsWrite of a record. * @returns The initial RecordsWrite if found; `undefined` if the record is not found. */ static fetchInitialRecordsWrite(messageStore, tenant, recordId) { return __awaiter19(this, void 0, void 0, function* () { const query = { entryId: recordId }; const { messages } = yield messageStore.query(tenant, [query]); if (messages.length === 0) { return void 0; } const initialRecordsWrite = yield RecordsWrite2.parse(messages[0]); return initialRecordsWrite; }); } }; // dist/esm/src/core/auth.js var __awaiter20 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; function authenticate(authorizationModel, didResolver) { return __awaiter20(this, void 0, void 0, function* () { if (authorizationModel === void 0) { throw new DwnError(DwnErrorCode.AuthenticateJwsMissing, "Missing JWS."); } yield GeneralJwsVerifier.verifySignatures(authorizationModel.signature, didResolver); if (authorizationModel.ownerSignature !== void 0) { yield GeneralJwsVerifier.verifySignatures(authorizationModel.ownerSignature, didResolver); } if (authorizationModel.authorDelegatedGrant !== void 0) { const authorDelegatedGrant = yield RecordsWrite2.parse(authorizationModel.authorDelegatedGrant); yield GeneralJwsVerifier.verifySignatures(authorDelegatedGrant.message.authorization.signature, didResolver); } if (authorizationModel.ownerDelegatedGrant !== void 0) { const ownerDelegatedGrant = yield RecordsWrite2.parse(authorizationModel.ownerDelegatedGrant); yield GeneralJwsVerifier.verifySignatures(ownerDelegatedGrant.message.authorization.signature, didResolver); } }); } function authorizeOwner(tenant, incomingMessage) { return __awaiter20(this, void 0, void 0, function* () { if (incomingMessage.author === tenant) { return; } else { throw new DwnError(DwnErrorCode.AuthorizationAuthorNotOwner, `Message authored by ${incomingMessage.author}, not authored by expected owner ${tenant}.`); } }); } // dist/esm/src/core/tenant-gate.js var __awaiter21 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var AllowAllTenantGate = class { isActiveTenant(_did) { return __awaiter21(this, void 0, void 0, function* () { return { isActiveTenant: true }; }); } }; // dist/esm/src/core/abstract-message.js var AbstractMessage = class { get message() { return this._message; } get signer() { return this._signer; } get author() { return this._author; } get signaturePayload() { return this._signaturePayload; } constructor(message2) { this._message = message2; if (message2.authorization !== void 0) { this._signer = Message.getSigner(message2); if (message2.authorization.authorDelegatedGrant !== void 0) { this._author = Message.getSigner(message2.authorization.authorDelegatedGrant); } else { this._author = this._signer; } this._signaturePayload = Jws.decodePlainObjectPayload(message2.authorization.signature); } } /** * Called by `JSON.stringify(...)` automatically. */ toJSON() { return this.message; } }; // dist/esm/src/interfaces/records-query.js var __awaiter22 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var RecordsQuery2 = class extends AbstractMessage { static parse(message2) { return __awaiter22(this, void 0, void 0, function* () { if (message2.descriptor.filter.published === false) { if (message2.descriptor.dateSort === DateSort.PublishedAscending || message2.descriptor.dateSort === DateSort.PublishedDescending) { throw new DwnError(DwnErrorCode.RecordsQueryParseFilterPublishedSortInvalid, `queries must not filter for \`published:false\` and sort by ${message2.descriptor.dateSort}`); } } let signaturePayload; if (message2.authorization !== void 0) { signaturePayload = yield Message.validateSignatureStructure(message2.authorization.signature, message2.descriptor); } yield Records.validateDelegatedGrantReferentialIntegrity(message2, signaturePayload); if ((signaturePayload === null || signaturePayload === void 0 ? void 0 : signaturePayload.protocolRole) !== void 0) { if (message2.descriptor.filter.protocolPath === void 0) { throw new DwnError(DwnErrorCode.RecordsQueryFilterMissingRequiredProperties, "Role-authorized queries must include `protocolPath` in the filter"); } } if (message2.descriptor.filter.protocol !== void 0) { validateProtocolUrlNormalized(message2.descriptor.filter.protocol); } if (message2.descriptor.filter.schema !== void 0) { validateSchemaUrlNormalized(message2.descriptor.filter.schema); } Time.validateTimestamp(message2.descriptor.messageTimestamp); return new RecordsQuery2(message2); }); } static create(options) { var _a; return __awaiter22(this, void 0, void 0, function* () { const descriptor = { interface: DwnInterfaceName.Records, method: DwnMethodName.Query, messageTimestamp: (_a = options.messageTimestamp) !== null && _a !== void 0 ? _a : Time.getCurrentTimestamp(), filter: Records.normalizeFilter(options.filter), dateSort: options.dateSort, pagination: options.pagination }; if (options.filter.published === false) { if (options.dateSort === DateSort.PublishedAscending || options.dateSort === DateSort.PublishedDescending) { throw new DwnError(DwnErrorCode.RecordsQueryCreateFilterPublishedSortInvalid, `queries must not filter for \`published:false\` and sort by ${options.dateSort}`); } } removeUndefinedProperties(descriptor); const signer = options.signer; let authorization; if (signer) { authorization = yield Message.createAuthorization({ descriptor, signer, protocolRole: options.protocolRole, delegatedGrant: options.delegatedGrant }); } const message2 = { descriptor, authorization }; Message.validateJsonSchema(message2); return new RecordsQuery2(message2); }); } /** * Authorizes the delegate who signed this message. * @param messageStore Used to check if the grant has been revoked. */ authorizeDelegate(messageStore) { return __awaiter22(this, void 0, void 0, function* () { const delegatedGrant = yield PermissionGrant.parse(this.message.authorization.authorDelegatedGrant); yield RecordsGrantAuthorization.authorizeQueryOrSubscribe({ incomingMessage: this.message, expectedGrantee: this.signer, expectedGrantor: this.author, permissionGrant: delegatedGrant, messageStore }); }); } }; // dist/esm/src/utils/data-stream.js var import_readable_stream2 = require("readable-stream"); var __awaiter23 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var DataStream = class { /** * Reads the entire readable stream given into array of bytes. */ static toBytes(readableStream) { return __awaiter23(this, void 0, void 0, function* () { return new Promise((resolve5, reject) => { const chunks = []; readableStream.on("data", (chunk) => { chunks.push(chunk); }); readableStream.on("end", () => { const uint8Array = DataStream.concatenateArrayOfBytes(chunks); resolve5(uint8Array); }); readableStream.on("error", reject); }); }); } /** * Reads the entire readable stream and JSON parses it into an object. */ static toObject(readableStream) { return __awaiter23(this, void 0, void 0, function* () { const contentBytes = yield DataStream.toBytes(readableStream); const contentObject = Encoder2.bytesToObject(contentBytes); return contentObject; }); } /** * Concatenates the array of bytes given into one Uint8Array. */ static concatenateArrayOfBytes(arrayOfBytes) { const totalLength = arrayOfBytes.reduce((accumulatedValue, currentValue) => accumulatedValue + currentValue.length, 0); const result = new Uint8Array(totalLength); let length5 = 0; for (const bytes2 of arrayOfBytes) { result.set(bytes2, length5); length5 += bytes2.length; } return result; } /** * Creates a readable stream from the bytes given. */ static fromBytes(bytes2) { const chunkLength = 1e5; let currentIndex = 0; const readableStream = new import_readable_stream2.Readable({ read(_size) { if (currentIndex + chunkLength > bytes2.length) { this.push(bytes2.subarray(currentIndex)); this.push(null); } else { this.push(bytes2.subarray(currentIndex, currentIndex + chunkLength)); currentIndex = currentIndex + chunkLength; } } }); return readableStream; } /** * Creates a readable stream from the object given. */ static fromObject(object) { const bytes2 = Encoder2.objectToBytes(object); return DataStream.fromBytes(bytes2); } /** * Duplicates the given data stream into the number of streams specified so that multiple handlers can consume the same data stream. */ static duplicateDataStream(dataStream, count) { const streams = []; for (let i = 0; i < count; i++) { const passThrough = new import_readable_stream2.PassThrough(); dataStream.pipe(passThrough); streams.push(passThrough); } return streams; } }; // dist/esm/src/interfaces/events-get.js var __awaiter24 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var EventsGet2 = class extends AbstractMessage { static parse(message2) { return __awaiter24(this, void 0, void 0, function* () { Message.validateJsonSchema(message2); yield Message.validateSignatureStructure(message2.authorization.signature, message2.descriptor); Time.validateTimestamp(message2.descriptor.messageTimestamp); return new EventsGet2(message2); }); } static create(options) { var _a; return __awaiter24(this, void 0, void 0, function* () { const descriptor = { interface: DwnInterfaceName.Events, method: DwnMethodName.Get, messageTimestamp: (_a = options.messageTimestamp) !== null && _a !== void 0 ? _a : Time.getCurrentTimestamp() }; if (options.cursor) { descriptor.cursor = options.cursor; } const authorization = yield Message.createAuthorization({ descriptor, signer: options.signer }); const message2 = { descriptor, authorization }; Message.validateJsonSchema(message2); return new EventsGet2(message2); }); } }; // dist/esm/src/core/message-reply.js function messageReplyFromError(e, code5) { const detail = e instanceof Error ? e.message : "Error"; return { status: { code: code5, detail } }; } // dist/esm/src/handlers/events-get.js var __awaiter25 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var EventsGetHandler = class { constructor(didResolver, eventLog) { this.didResolver = didResolver; this.eventLog = eventLog; } handle({ tenant, message: message2 }) { return __awaiter25(this, void 0, void 0, function* () { let eventsGet; try { eventsGet = yield EventsGet2.parse(message2); } catch (e) { return messageReplyFromError(e, 400); } try { yield authenticate(message2.authorization, this.didResolver); yield authorizeOwner(tenant, eventsGet); } catch (e) { return messageReplyFromError(e, 401); } const { cursor: queryCursor } = message2.descriptor; const { events, cursor } = yield this.eventLog.getEvents(tenant, queryCursor); return { status: { code: 200, detail: "OK" }, entries: events, cursor }; }); } }; // dist/esm/src/utils/events.js var Events = class { /** * Normalizes/fixes the formatting of the given filters (such as URLs) so that they provide a consistent search experience. */ static normalizeFilters(filters) { const eventsQueryFilters = []; for (const filter2 of filters) { let eventsFilter; if (this.isRecordsFilter(filter2)) { eventsFilter = Records.normalizeFilter(filter2); } else { eventsFilter = filter2; } removeUndefinedProperties(eventsFilter); if (!isEmptyObject(eventsFilter)) { eventsQueryFilters.push(eventsFilter); } } return eventsQueryFilters; } /** * Converts an incoming array of EventsFilter into an array of Filter usable by EventLog. * * @param filters An array of EventsFilter * @returns {Filter[]} an array of generic Filter able to be used when querying. */ static convertFilters(filters) { const eventsQueryFilters = []; for (const filter2 of filters) { if (this.isRecordsFilter(filter2)) { eventsQueryFilters.push(Records.convertFilter(filter2)); } else { eventsQueryFilters.push(this.convertFilter(filter2)); } } return eventsQueryFilters; } /** * Converts an external-facing filter model into an internal-facing filer model used by data store. */ static convertFilter(filter2) { const filterCopy = Object.assign({}, filter2); const { dateUpdated } = filter2; const messageTimestampFilter = dateUpdated ? FilterUtility.convertRangeCriterion(dateUpdated) : void 0; if (messageTimestampFilter) { filterCopy.messageTimestamp = messageTimestampFilter; delete filterCopy.dateUpdated; } return filterCopy; } // we deliberately do not check for `dateUpdated` in this filter. // if it were the only property that matched, it could be handled by `EventsFilter` static isRecordsFilter(filter2) { return "author" in filter2 || "dateCreated" in filter2 || "dataFormat" in filter2 || "dataSize" in filter2 || "parentId" in filter2 || "recordId" in filter2 || "schema" in filter2 || "protocol" in filter2 || "protocolPath" in filter2 || "recipient" in filter2; } }; // dist/esm/src/interfaces/events-query.js var __awaiter26 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var EventsQuery2 = class extends AbstractMessage { static parse(message2) { return __awaiter26(this, void 0, void 0, function* () { Message.validateJsonSchema(message2); yield Message.validateSignatureStructure(message2.authorization.signature, message2.descriptor); for (const filter2 of message2.descriptor.filters) { if ("protocol" in filter2 && filter2.protocol !== void 0) { validateProtocolUrlNormalized(filter2.protocol); } if ("schema" in filter2 && filter2.schema !== void 0) { validateSchemaUrlNormalized(filter2.schema); } } return new EventsQuery2(message2); }); } static create(options) { var _a; return __awaiter26(this, void 0, void 0, function* () { const descriptor = { interface: DwnInterfaceName.Events, method: DwnMethodName.Query, filters: Events.normalizeFilters(options.filters), messageTimestamp: (_a = options.messageTimestamp) !== null && _a !== void 0 ? _a : Time.getCurrentTimestamp(), cursor: options.cursor }; removeUndefinedProperties(descriptor); const authorization = yield Message.createAuthorization({ descriptor, signer: options.signer }); const message2 = { descriptor, authorization }; Message.validateJsonSchema(message2); return new EventsQuery2(message2); }); } }; // dist/esm/src/handlers/events-query.js var __awaiter27 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var EventsQueryHandler = class { constructor(didResolver, eventLog) { this.didResolver = didResolver; this.eventLog = eventLog; } handle({ tenant, message: message2 }) { return __awaiter27(this, void 0, void 0, function* () { let eventsQuery; try { eventsQuery = yield EventsQuery2.parse(message2); } catch (e) { return messageReplyFromError(e, 400); } try { yield authenticate(message2.authorization, this.didResolver); yield authorizeOwner(tenant, eventsQuery); } catch (e) { return messageReplyFromError(e, 401); } const eventFilters = Events.convertFilters(message2.descriptor.filters); const { events, cursor } = yield this.eventLog.queryEvents(tenant, eventFilters, message2.descriptor.cursor); return { status: { code: 200, detail: "OK" }, entries: events, cursor }; }); } }; // dist/esm/src/interfaces/events-subscribe.js var __awaiter28 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var EventsSubscribe2 = class extends AbstractMessage { static parse(message2) { return __awaiter28(this, void 0, void 0, function* () { Message.validateJsonSchema(message2); yield Message.validateSignatureStructure(message2.authorization.signature, message2.descriptor); for (const filter2 of message2.descriptor.filters) { if ("protocol" in filter2 && filter2.protocol !== void 0) { validateProtocolUrlNormalized(filter2.protocol); } if ("schema" in filter2 && filter2.schema !== void 0) { validateSchemaUrlNormalized(filter2.schema); } } Time.validateTimestamp(message2.descriptor.messageTimestamp); return new EventsSubscribe2(message2); }); } /** * Creates a EventsSubscribe message. * * @throws {DwnError} if json schema validation fails. */ static create(options) { var _a, _b; return __awaiter28(this, void 0, void 0, function* () { const currentTime = Time.getCurrentTimestamp(); const descriptor = { interface: DwnInterfaceName.Events, method: DwnMethodName.Subscribe, filters: (_a = options.filters) !== null && _a !== void 0 ? _a : [], messageTimestamp: (_b = options.messageTimestamp) !== null && _b !== void 0 ? _b : currentTime }; removeUndefinedProperties(descriptor); const authorization = yield Message.createAuthorization({ descriptor, signer: options.signer }); const message2 = { descriptor, authorization }; Message.validateJsonSchema(message2); return new EventsSubscribe2(message2); }); } }; // dist/esm/src/handlers/events-subscribe.js var __awaiter29 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var EventsSubscribeHandler = class { constructor(didResolver, eventStream) { this.didResolver = didResolver; this.eventStream = eventStream; } handle({ tenant, message: message2, subscriptionHandler }) { return __awaiter29(this, void 0, void 0, function* () { if (this.eventStream === void 0) { return messageReplyFromError(new DwnError(DwnErrorCode.EventsSubscribeEventStreamUnimplemented, "Subscriptions are not supported"), 501); } let eventsSubscribe; try { eventsSubscribe = yield EventsSubscribe2.parse(message2); } catch (e) { return messageReplyFromError(e, 400); } try { yield authenticate(message2.authorization, this.didResolver); yield authorizeOwner(tenant, eventsSubscribe); } catch (error) { return messageReplyFromError(error, 401); } const { filters } = message2.descriptor; const eventsFilters = Events.convertFilters(filters); const messageCid = yield Message.getCid(message2); const listener = (eventTenant, event, eventIndexes) => { if (tenant === eventTenant && FilterUtility.matchAnyFilter(eventIndexes, eventsFilters)) { subscriptionHandler(event); } }; const subscription = yield this.eventStream.subscribe(tenant, messageCid, listener); return { status: { code: 200, detail: "OK" }, subscription }; }); } }; // dist/esm/src/interfaces/messages-get.js var __awaiter30 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var MessagesGet2 = class extends AbstractMessage { static parse(message2) { return __awaiter30(this, void 0, void 0, function* () { Message.validateJsonSchema(message2); this.validateMessageCids(message2.descriptor.messageCids); yield Message.validateSignatureStructure(message2.authorization.signature, message2.descriptor); Time.validateTimestamp(message2.descriptor.messageTimestamp); return new MessagesGet2(message2); }); } static create(options) { var _a; return __awaiter30(this, void 0, void 0, function* () { const descriptor = { interface: DwnInterfaceName.Messages, method: DwnMethodName.Get, messageCids: options.messageCids, messageTimestamp: (_a = options === null || options === void 0 ? void 0 : options.messageTimestamp) !== null && _a !== void 0 ? _a : Time.getCurrentTimestamp() }; const authorization = yield Message.createAuthorization({ descriptor, signer: options.signer }); const message2 = { descriptor, authorization }; Message.validateJsonSchema(message2); MessagesGet2.validateMessageCids(options.messageCids); return new MessagesGet2(message2); }); } /** * validates the provided cids * @param messageCids - the cids in question * @throws {DwnError} if an invalid cid is found. */ static validateMessageCids(messageCids) { for (const cid of messageCids) { try { Cid.parseCid(cid); } catch (_) { throw new DwnError(DwnErrorCode.MessageGetInvalidCid, `${cid} is not a valid CID`); } } } }; // dist/esm/src/handlers/messages-get.js var __awaiter31 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var MessagesGetHandler = class { constructor(didResolver, messageStore, dataStore) { this.didResolver = didResolver; this.messageStore = messageStore; this.dataStore = dataStore; } handle({ tenant, message: message2 }) { return __awaiter31(this, void 0, void 0, function* () { let messagesGet; try { messagesGet = yield MessagesGet2.parse(message2); } catch (e) { return messageReplyFromError(e, 400); } try { yield authenticate(message2.authorization, this.didResolver); yield authorizeOwner(tenant, messagesGet); } catch (e) { return messageReplyFromError(e, 401); } const promises = []; const messageCids = new Set(message2.descriptor.messageCids); for (const messageCid of messageCids) { const promise = this.messageStore.get(tenant, messageCid).then((message3) => { return { messageCid, message: message3 }; }).catch((_) => { return { messageCid, message: void 0, error: `Failed to get message ${messageCid}` }; }); promises.push(promise); } const messages = yield Promise.all(promises); for (const entry of messages) { const { message: message3 } = entry; if (!message3) { continue; } const { interface: messageInterface, method } = message3.descriptor; if (messageInterface !== DwnInterfaceName.Records || method !== DwnMethodName.Write) { continue; } const recordsWrite = message3; if (recordsWrite.encodedData !== void 0) { entry.encodedData = recordsWrite.encodedData; delete recordsWrite.encodedData; } } return { status: { code: 200, detail: "OK" }, entries: messages }; }); } }; // dist/esm/src/interfaces/protocols-configure.js var import__ = __toESM(require("ajv/dist/2020.js"), 1); // dist/esm/src/types/protocols-types.js var ProtocolActor; (function(ProtocolActor2) { ProtocolActor2["Anyone"] = "anyone"; ProtocolActor2["Author"] = "author"; ProtocolActor2["Recipient"] = "recipient"; })(ProtocolActor || (ProtocolActor = {})); var ProtocolAction; (function(ProtocolAction2) { ProtocolAction2["CoDelete"] = "co-delete"; ProtocolAction2["CoPrune"] = "co-prune"; ProtocolAction2["CoUpdate"] = "co-update"; ProtocolAction2["Create"] = "create"; ProtocolAction2["Delete"] = "delete"; ProtocolAction2["Prune"] = "prune"; ProtocolAction2["Query"] = "query"; ProtocolAction2["Read"] = "read"; ProtocolAction2["Subscribe"] = "subscribe"; ProtocolAction2["Update"] = "update"; })(ProtocolAction || (ProtocolAction = {})); // dist/esm/src/interfaces/protocols-configure.js var __awaiter32 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __rest5 = function(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var ProtocolsConfigure2 = class extends AbstractMessage { static parse(message2) { return __awaiter32(this, void 0, void 0, function* () { Message.validateJsonSchema(message2); ProtocolsConfigure2.validateProtocolDefinition(message2.descriptor.definition); yield Message.validateSignatureStructure(message2.authorization.signature, message2.descriptor); Time.validateTimestamp(message2.descriptor.messageTimestamp); return new ProtocolsConfigure2(message2); }); } static create(options) { var _a; return __awaiter32(this, void 0, void 0, function* () { const descriptor = { interface: DwnInterfaceName.Protocols, method: DwnMethodName.Configure, messageTimestamp: (_a = options.messageTimestamp) !== null && _a !== void 0 ? _a : Time.getCurrentTimestamp(), definition: ProtocolsConfigure2.normalizeDefinition(options.definition) }; const authorization = yield Message.createAuthorization({ descriptor, signer: options.signer, permissionGrantId: options.permissionGrantId }); const message2 = { descriptor, authorization }; Message.validateJsonSchema(message2); ProtocolsConfigure2.validateProtocolDefinition(message2.descriptor.definition); const protocolsConfigure = new ProtocolsConfigure2(message2); return protocolsConfigure; }); } /** * Performs validation on the given protocol definition that are not easy to do using a JSON schema. */ static validateProtocolDefinition(definition) { const { protocol, types: types2 } = definition; validateProtocolUrlNormalized(protocol); for (const typeName in types2) { const schema = types2[typeName].schema; if (schema !== void 0) { validateSchemaUrlNormalized(schema); } } ProtocolsConfigure2.validateStructure(definition); } static validateStructure(definition) { const recordTypes = Object.keys(definition.types); const roles = ProtocolsConfigure2.fetchAllRolePathsRecursively("", definition.structure, []); ProtocolsConfigure2.validateRuleSetRecursively({ ruleSet: definition.structure, ruleSetProtocolPath: "", recordTypes, roles }); } /** * Parses the given rule set hierarchy to get all the role protocol paths. * @throws DwnError if the hierarchy depth goes beyond 10 levels. */ static fetchAllRolePathsRecursively(ruleSetProtocolPath, ruleSet, roles) { if (ruleSetProtocolPath.split("/").length > 10) { throw new DwnError(DwnErrorCode.ProtocolsConfigureRecordNestingDepthExceeded, "Record nesting depth exceeded 10 levels."); } for (const recordType in ruleSet) { if (recordType.startsWith("$")) { continue; } const childRuleSet = ruleSet[recordType]; let childRuleSetProtocolPath; if (ruleSetProtocolPath === "") { childRuleSetProtocolPath = recordType; } else { childRuleSetProtocolPath = `${ruleSetProtocolPath}/${recordType}`; } if (childRuleSet.$role) { roles.push(childRuleSetProtocolPath); } else { ProtocolsConfigure2.fetchAllRolePathsRecursively(childRuleSetProtocolPath, childRuleSet, roles); } } return roles; } /** * Validates the given rule set structure then recursively validates its nested child rule sets. */ static validateRuleSetRecursively(input) { var _a; const { ruleSet, ruleSetProtocolPath, recordTypes, roles } = input; if (ruleSet.$size !== void 0) { const { min = 0, max } = ruleSet.$size; if (max !== void 0 && max < min) { throw new DwnError(DwnErrorCode.ProtocolsConfigureInvalidSize, `Invalid size range found: max limit ${max} less than min limit ${min} at protocol path '${ruleSetProtocolPath}'`); } } if (ruleSet.$tags) { const ajv = new import__.default.default(); const _b = ruleSet.$tags, { $allowUndefinedTags, $requiredTags } = _b, tagProperties = __rest5(_b, ["$allowUndefinedTags", "$requiredTags"]); for (const tag in tagProperties) { const tagSchemaDefinition = tagProperties[tag]; if (!ajv.validateSchema(tagSchemaDefinition)) { const schemaError = ajv.errorsText(ajv.errors, { dataVar: `${ruleSetProtocolPath}/$tags/${tag}` }); throw new DwnError(DwnErrorCode.ProtocolsConfigureInvalidTagSchema, `tags schema validation error: ${schemaError}`); } } } const actionRules = (_a = ruleSet.$actions) !== null && _a !== void 0 ? _a : []; for (let i = 0; i < actionRules.length; i++) { const actionRule = actionRules[i]; if (actionRule.role !== void 0) { if (!roles.includes(actionRule.role)) { throw new DwnError(DwnErrorCode.ProtocolsConfigureRoleDoesNotExistAtGivenPath, `Role in action ${JSON.stringify(actionRule)} for rule set ${ruleSetProtocolPath} does not exist.`); } } if (actionRule.who === "anyone" && actionRule.of) { throw new DwnError(DwnErrorCode.ProtocolsConfigureInvalidActionOfNotAllowed, `'of' is not allowed at rule set protocol path (${ruleSetProtocolPath})`); } if (actionRule.who === ProtocolActor.Recipient && actionRule.of === void 0) { const hasDisallowedAction = actionRule.can.some((action) => ![ProtocolAction.CoUpdate, ProtocolAction.CoDelete, ProtocolAction.CoPrune].includes(action)); if (hasDisallowedAction) { throw new DwnError(DwnErrorCode.ProtocolsConfigureInvalidRecipientOfAction, "Rules for `recipient` without `of` property must have `can` containing only `co-update`, `co-delete`, and `co-prune`."); } } if (actionRule.who === ProtocolActor.Author && !actionRule.of) { throw new DwnError(DwnErrorCode.ProtocolsConfigureInvalidActionMissingOf, `'of' is required when 'author' is specified as 'who'`); } if (actionRule.can !== void 0) { if (actionRule.can.includes(ProtocolAction.Update) && !actionRule.can.includes(ProtocolAction.Create)) { throw new DwnError(DwnErrorCode.ProtocolsConfigureInvalidActionUpdateWithoutCreate, `Action rule ${JSON.stringify(actionRule)} contains 'update' action but missing the required 'create' action.`); } if (actionRule.can.includes(ProtocolAction.Delete) && !actionRule.can.includes(ProtocolAction.Create)) { throw new DwnError(DwnErrorCode.ProtocolsConfigureInvalidActionDeleteWithoutCreate, `Action rule ${JSON.stringify(actionRule)} contains 'delete' action but missing the required 'create' action.`); } } for (let j = i + 1; j < actionRules.length; j++) { const otherActionRule = actionRules[j]; if (actionRule.who !== void 0) { if (actionRule.who === otherActionRule.who && actionRule.of === otherActionRule.of) { throw new DwnError(DwnErrorCode.ProtocolsConfigureDuplicateActorInRuleSet, `More than one action rule per actor ${actionRule.who} of ${actionRule.of} not allowed within a rule set: ${JSON.stringify(actionRule)}`); } } else { if (actionRule.role === otherActionRule.role) { throw new DwnError(DwnErrorCode.ProtocolsConfigureDuplicateRoleInRuleSet, `More than one action rule per role ${actionRule.role} not allowed within a rule set: ${JSON.stringify(actionRule)}`); } } } } for (const recordType in ruleSet) { if (recordType.startsWith("$")) { continue; } if (!recordTypes.includes(recordType)) { throw new DwnError(DwnErrorCode.ProtocolsConfigureInvalidRuleSetRecordType, `Rule set ${recordType} is not declared as an allowed type in the protocol definition.`); } const childRuleSet = ruleSet[recordType]; let childRuleSetProtocolPath; if (ruleSetProtocolPath === "") { childRuleSetProtocolPath = recordType; } else { childRuleSetProtocolPath = `${ruleSetProtocolPath}/${recordType}`; } ProtocolsConfigure2.validateRuleSetRecursively({ ruleSet: childRuleSet, ruleSetProtocolPath: childRuleSetProtocolPath, recordTypes, roles }); } } static normalizeDefinition(definition) { const typesCopy = Object.assign({}, definition.types); for (const typeName in typesCopy) { const schema = typesCopy[typeName].schema; if (schema !== void 0) { typesCopy[typeName].schema = normalizeSchemaUrl(schema); } } return Object.assign(Object.assign({}, definition), { protocol: normalizeProtocolUrl(definition.protocol), types: typesCopy }); } }; // dist/esm/src/handlers/protocols-configure.js var __awaiter33 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __rest6 = function(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var ProtocolsConfigureHandler = class { constructor(didResolver, messageStore, eventLog, eventStream) { this.didResolver = didResolver; this.messageStore = messageStore; this.eventLog = eventLog; this.eventStream = eventStream; } handle({ tenant, message: message2 }) { return __awaiter33(this, void 0, void 0, function* () { let protocolsConfigure; try { protocolsConfigure = yield ProtocolsConfigure2.parse(message2); } catch (e) { return messageReplyFromError(e, 400); } try { yield authenticate(message2.authorization, this.didResolver); yield authorizeOwner(tenant, protocolsConfigure); } catch (e) { return messageReplyFromError(e, 401); } const query = { interface: DwnInterfaceName.Protocols, method: DwnMethodName.Configure, protocol: message2.descriptor.definition.protocol }; const { messages: existingMessages } = yield this.messageStore.query(tenant, [query]); let newestMessage = yield Message.getNewestMessage(existingMessages); let incomingMessageIsNewest = false; if (newestMessage === void 0 || (yield Message.isNewer(message2, newestMessage))) { incomingMessageIsNewest = true; newestMessage = message2; } let messageReply; if (incomingMessageIsNewest) { const indexes = ProtocolsConfigureHandler.constructIndexes(protocolsConfigure); yield this.messageStore.put(tenant, message2, indexes); const messageCid = yield Message.getCid(message2); yield this.eventLog.append(tenant, messageCid, indexes); if (this.eventStream !== void 0) { this.eventStream.emit(tenant, { message: message2 }, indexes); } messageReply = { status: { code: 202, detail: "Accepted" } }; } else { messageReply = { status: { code: 409, detail: "Conflict" } }; } const deletedMessageCids = []; for (const message3 of existingMessages) { if (yield Message.isNewer(newestMessage, message3)) { const messageCid = yield Message.getCid(message3); deletedMessageCids.push(messageCid); yield this.messageStore.delete(tenant, messageCid); } } yield this.eventLog.deleteEventsByCid(tenant, deletedMessageCids); return messageReply; }); } static constructIndexes(protocolsConfigure) { const _a = protocolsConfigure.message.descriptor, { definition } = _a, propertiesToIndex = __rest6(_a, ["definition"]); const { author } = protocolsConfigure; const indexes = Object.assign(Object.assign({}, propertiesToIndex), { author, protocol: definition.protocol, published: definition.published // retain published state from definition }); return indexes; } }; // dist/esm/src/protocols/permissions.js var __awaiter34 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var PermissionsProtocol = class { static parseRequest(base64UrlEncodedRequest) { return Encoder2.base64UrlToObject(base64UrlEncodedRequest); } /** * Convenience method to create a permission request. */ static createRequest(options) { return __awaiter34(this, void 0, void 0, function* () { const scope = PermissionsProtocol.normalizePermissionScope(options.scope); const permissionRequestData = { description: options.description, delegated: options.delegated, scope, conditions: options.conditions }; const permissionRequestBytes = Encoder2.objectToBytes(permissionRequestData); const recordsWrite = yield RecordsWrite2.create({ signer: options.signer, messageTimestamp: options.dateRequested, protocol: PermissionsProtocol.uri, protocolPath: PermissionsProtocol.requestPath, dataFormat: "application/json", data: permissionRequestBytes }); return { recordsWrite, permissionRequestData, permissionRequestBytes }; }); } /** * Convenience method to create a permission grant. */ static createGrant(options) { return __awaiter34(this, void 0, void 0, function* () { const scope = PermissionsProtocol.normalizePermissionScope(options.scope); const permissionGrantData = { dateExpires: options.dateExpires, requestId: options.requestId, description: options.description, delegated: options.delegated, scope, conditions: options.conditions }; const permissionGrantBytes = Encoder2.objectToBytes(permissionGrantData); const recordsWrite = yield RecordsWrite2.create({ signer: options.signer, messageTimestamp: options.dateGranted, dateCreated: options.dateGranted, recipient: options.grantedTo, protocol: PermissionsProtocol.uri, protocolPath: PermissionsProtocol.grantPath, dataFormat: "application/json", data: permissionGrantBytes }); const dataEncodedMessage = Object.assign(Object.assign({}, recordsWrite.message), { encodedData: Encoder2.bytesToBase64Url(permissionGrantBytes) }); return { recordsWrite, permissionGrantData, permissionGrantBytes, dataEncodedMessage }; }); } /** * Convenience method to create a permission revocation. */ static createRevocation(options) { return __awaiter34(this, void 0, void 0, function* () { const permissionRevocationData = { description: options.description }; const permissionRevocationBytes = Encoder2.objectToBytes(permissionRevocationData); const recordsWrite = yield RecordsWrite2.create({ signer: options.signer, parentContextId: options.grantId, protocol: PermissionsProtocol.uri, protocolPath: PermissionsProtocol.revocationPath, dataFormat: "application/json", data: permissionRevocationBytes }); return { recordsWrite, permissionRevocationData, permissionRevocationBytes }; }); } /** * Validates the given Permissions protocol RecordsWrite. It can be a request, grant, or revocation. */ static validateSchema(recordsWriteMessage, dataBytes) { const dataString = Encoder2.bytesToString(dataBytes); const dataObject = JSON.parse(dataString); if (recordsWriteMessage.descriptor.protocolPath === PermissionsProtocol.requestPath) { validateJsonSchema("PermissionRequestData", dataObject); } else if (recordsWriteMessage.descriptor.protocolPath === PermissionsProtocol.grantPath) { validateJsonSchema("PermissionGrantData", dataObject); const permissionGrantData = dataObject; PermissionsProtocol.validateScope(permissionGrantData.scope); Time.validateTimestamp(permissionGrantData.dateExpires); } else if (recordsWriteMessage.descriptor.protocolPath === PermissionsProtocol.revocationPath) { validateJsonSchema("PermissionRevocationData", dataObject); } else { throw new DwnError(DwnErrorCode.PermissionsProtocolValidateSchemaUnexpectedRecord, `Unexpected permission record: ${recordsWriteMessage.descriptor.protocolPath}`); } } /** * Fetches PermissionGrant with the specified `recordID`. * @returns the PermissionGrant matching the `recordId` specified. * @throws {Error} if PermissionGrant does not exist */ static fetchGrant(tenant, messageStore, permissionGrantId) { return __awaiter34(this, void 0, void 0, function* () { const grantQuery = { recordId: permissionGrantId, isLatestBaseState: true }; const { messages } = yield messageStore.query(tenant, [grantQuery]); const possibleGrantMessage = messages[0]; const dwnInterface = possibleGrantMessage === null || possibleGrantMessage === void 0 ? void 0 : possibleGrantMessage.descriptor.interface; const dwnMethod = possibleGrantMessage === null || possibleGrantMessage === void 0 ? void 0 : possibleGrantMessage.descriptor.method; if (dwnInterface !== DwnInterfaceName.Records || dwnMethod !== DwnMethodName.Write || possibleGrantMessage.descriptor.protocolPath !== PermissionsProtocol.grantPath) { throw new DwnError(DwnErrorCode.GrantAuthorizationGrantMissing, `Could not find permission grant with record ID ${permissionGrantId}.`); } const permissionGrantMessage = possibleGrantMessage; const permissionGrant = yield PermissionGrant.parse(permissionGrantMessage); return permissionGrant; }); } /** * Normalizes the given permission scope if needed. * @returns The normalized permission scope. */ static normalizePermissionScope(permissionScope) { const scope = Object.assign({}, permissionScope); if (PermissionsProtocol.isRecordPermissionScope(scope)) { if (scope.protocol !== void 0) { scope.protocol = normalizeProtocolUrl(scope.protocol); } if (scope.schema !== void 0) { scope.schema = normalizeSchemaUrl(scope.schema); } } return scope; } /** * Type guard to determine if the scope is a record permission scope. */ static isRecordPermissionScope(scope) { return scope.interface === "Records"; } /** * Validates scope. */ static validateScope(scope) { if (!this.isRecordPermissionScope(scope)) { return; } if (scope.schema !== void 0) { if (scope.protocol !== void 0 || scope.contextId !== void 0 || scope.protocolPath) { throw new DwnError(DwnErrorCode.PermissionsProtocolValidateScopeSchemaProhibitedProperties, "Permission grants that have `schema` present cannot also have protocol-related properties present"); } } if (scope.protocol !== void 0) { if (scope.contextId !== void 0 && scope.protocolPath !== void 0) { throw new DwnError(DwnErrorCode.PermissionsProtocolValidateScopeContextIdProhibitedProperties, "Permission grants cannot have both `contextId` and `protocolPath` present"); } } } }; PermissionsProtocol.uri = "https://tbd.website/dwn/permissions"; PermissionsProtocol.requestPath = "request"; PermissionsProtocol.grantPath = "grant"; PermissionsProtocol.revocationPath = "grant/revocation"; PermissionsProtocol.definition = { published: true, protocol: PermissionsProtocol.uri, types: { request: { dataFormats: ["application/json"] }, grant: { dataFormats: ["application/json"] }, revocation: { dataFormats: ["application/json"] } }, structure: { request: { $size: { max: 1e4 }, $actions: [ { who: "anyone", can: ["create"] } ] }, grant: { $size: { max: 1e4 }, $actions: [ { who: "recipient", of: "grant", can: ["read", "query"] } ], revocation: { $size: { max: 1e4 }, $actions: [ { who: "anyone", can: ["read"] } ] } } } }; // dist/esm/src/interfaces/protocols-query.js var __awaiter35 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var ProtocolsQuery2 = class extends AbstractMessage { static parse(message2) { return __awaiter35(this, void 0, void 0, function* () { if (message2.authorization !== void 0) { yield Message.validateSignatureStructure(message2.authorization.signature, message2.descriptor); } if (message2.descriptor.filter !== void 0) { validateProtocolUrlNormalized(message2.descriptor.filter.protocol); } Time.validateTimestamp(message2.descriptor.messageTimestamp); return new ProtocolsQuery2(message2); }); } static create(options) { var _a; return __awaiter35(this, void 0, void 0, function* () { const descriptor = { interface: DwnInterfaceName.Protocols, method: DwnMethodName.Query, messageTimestamp: (_a = options.messageTimestamp) !== null && _a !== void 0 ? _a : Time.getCurrentTimestamp(), filter: options.filter ? ProtocolsQuery2.normalizeFilter(options.filter) : void 0 }; removeUndefinedProperties(descriptor); let authorization; if (options.signer !== void 0) { authorization = yield Message.createAuthorization({ descriptor, signer: options.signer, permissionGrantId: options.permissionGrantId }); } const message2 = { descriptor, authorization }; Message.validateJsonSchema(message2); const protocolsQuery = new ProtocolsQuery2(message2); return protocolsQuery; }); } static normalizeFilter(filter2) { return Object.assign(Object.assign({}, filter2), { protocol: normalizeProtocolUrl(filter2.protocol) }); } authorize(tenant, messageStore) { return __awaiter35(this, void 0, void 0, function* () { if (this.author === tenant) { return; } else if (this.author !== void 0 && this.signaturePayload.permissionGrantId) { const permissionGrant = yield PermissionsProtocol.fetchGrant(tenant, messageStore, this.signaturePayload.permissionGrantId); yield GrantAuthorization.performBaseValidation({ incomingMessage: this.message, expectedGrantor: tenant, expectedGrantee: this.author, permissionGrant, messageStore }); } else { throw new DwnError(DwnErrorCode.ProtocolsQueryUnauthorized, "The ProtocolsQuery failed authorization"); } }); } }; // dist/esm/src/handlers/protocols-query.js var __awaiter36 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var ProtocolsQueryHandler = class { constructor(didResolver, messageStore, dataStore) { this.didResolver = didResolver; this.messageStore = messageStore; this.dataStore = dataStore; } handle({ tenant, message: message2 }) { return __awaiter36(this, void 0, void 0, function* () { let protocolsQuery; try { protocolsQuery = yield ProtocolsQuery2.parse(message2); } catch (e) { return messageReplyFromError(e, 400); } try { yield authenticate(message2.authorization, this.didResolver); yield protocolsQuery.authorize(tenant, this.messageStore); } catch (error) { if (error.code === DwnErrorCode.AuthenticateJwsMissing || // unauthenticated error.code === DwnErrorCode.ProtocolsQueryUnauthorized) { const entries = yield this.fetchPublishedProtocolsConfigure(tenant, protocolsQuery); return { status: { code: 200, detail: "OK" }, entries }; } else { return messageReplyFromError(error, 401); } } const query = Object.assign(Object.assign({}, message2.descriptor.filter), { interface: DwnInterfaceName.Protocols, method: DwnMethodName.Configure }); removeUndefinedProperties(query); const { messages } = yield this.messageStore.query(tenant, [query]); return { status: { code: 200, detail: "OK" }, entries: messages }; }); } /** * Fetches only published `ProtocolsConfigure`. */ fetchPublishedProtocolsConfigure(tenant, protocolsQuery) { return __awaiter36(this, void 0, void 0, function* () { const filter2 = Object.assign(Object.assign({}, protocolsQuery.message.descriptor.filter), { interface: DwnInterfaceName.Protocols, method: DwnMethodName.Configure, published: true }); const { messages: publishedProtocolsConfigure } = yield this.messageStore.query(tenant, [filter2]); return publishedProtocolsConfigure; }); } }; // dist/esm/src/core/protocol-authorization.js var import__2 = __toESM(require("ajv/dist/2020.js"), 1); var __awaiter37 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __rest7 = function(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; var ProtocolAuthorization = class { /** * Performs validation on the structure of RecordsWrite messages that use a protocol. * @throws {Error} if validation fails. */ static validateReferentialIntegrity(tenant, incomingMessage, messageStore) { return __awaiter37(this, void 0, void 0, function* () { const protocolDefinition = yield ProtocolAuthorization.fetchProtocolDefinition(tenant, incomingMessage.message.descriptor.protocol, messageStore); ProtocolAuthorization.verifyType(incomingMessage.message, protocolDefinition.types); yield ProtocolAuthorization.verifyProtocolPathAndContextId(tenant, incomingMessage, messageStore); const ruleSet = ProtocolAuthorization.getRuleSet(incomingMessage.message.descriptor.protocolPath, protocolDefinition); yield ProtocolAuthorization.verifyAsRoleRecordIfNeeded(tenant, incomingMessage, ruleSet, messageStore); ProtocolAuthorization.verifySizeLimit(incomingMessage, ruleSet); ProtocolAuthorization.verifyTagsIfNeeded(incomingMessage, ruleSet); }); } /** * Performs protocol-based authorization against the incoming RecordsWrite message. * @throws {Error} if authorization fails. */ static authorizeWrite(tenant, incomingMessage, messageStore) { return __awaiter37(this, void 0, void 0, function* () { const existingInitialWrite = yield ProtocolAuthorization.fetchInitialWrite(tenant, incomingMessage.message.recordId, messageStore); let recordChain; if (existingInitialWrite === void 0) { recordChain = yield ProtocolAuthorization.constructRecordChain(tenant, incomingMessage.message.descriptor.parentId, messageStore); } else { recordChain = yield ProtocolAuthorization.constructRecordChain(tenant, incomingMessage.message.recordId, messageStore); } const protocolDefinition = yield ProtocolAuthorization.fetchProtocolDefinition(tenant, incomingMessage.message.descriptor.protocol, messageStore); const ruleSet = ProtocolAuthorization.getRuleSet(incomingMessage.message.descriptor.protocolPath, protocolDefinition); yield ProtocolAuthorization.verifyInvokedRole(tenant, incomingMessage, incomingMessage.message.descriptor.protocol, incomingMessage.message.contextId, protocolDefinition, messageStore); yield ProtocolAuthorization.authorizeAgainstAllowedActions(tenant, incomingMessage, ruleSet, recordChain, messageStore); }); } /** * Performs protocol-based authorization against the incoming `RecordsRead` message. * @param newestRecordsWrite The latest RecordsWrite associated with the recordId being read. * @throws {Error} if authorization fails. */ static authorizeRead(tenant, incomingMessage, newestRecordsWrite, messageStore) { return __awaiter37(this, void 0, void 0, function* () { const recordChain = yield ProtocolAuthorization.constructRecordChain(tenant, newestRecordsWrite.message.recordId, messageStore); const protocolDefinition = yield ProtocolAuthorization.fetchProtocolDefinition(tenant, newestRecordsWrite.message.descriptor.protocol, messageStore); const ruleSet = ProtocolAuthorization.getRuleSet(newestRecordsWrite.message.descriptor.protocolPath, protocolDefinition); yield ProtocolAuthorization.verifyInvokedRole(tenant, incomingMessage, newestRecordsWrite.message.descriptor.protocol, newestRecordsWrite.message.contextId, protocolDefinition, messageStore); yield ProtocolAuthorization.authorizeAgainstAllowedActions(tenant, incomingMessage, ruleSet, recordChain, messageStore); }); } static authorizeQueryOrSubscribe(tenant, incomingMessage, messageStore) { return __awaiter37(this, void 0, void 0, function* () { const { protocol, protocolPath, contextId } = incomingMessage.message.descriptor.filter; const protocolDefinition = yield ProtocolAuthorization.fetchProtocolDefinition( tenant, protocol, // `authorizeQueryOrSubscribe` is only called if `protocol` is present messageStore ); const ruleSet = ProtocolAuthorization.getRuleSet( protocolPath, // presence of `protocolPath` is verified in `parse()` protocolDefinition ); yield ProtocolAuthorization.verifyInvokedRole(tenant, incomingMessage, protocol, contextId, protocolDefinition, messageStore); yield ProtocolAuthorization.authorizeAgainstAllowedActions( tenant, incomingMessage, ruleSet, [], // record chain is not relevant to queries or subscriptions messageStore ); }); } /** * Performs protocol-based authorization against the incoming `RecordsDelete` message. * @param newestRecordsWrite The latest `RecordsWrite` associated with the recordId being deleted. */ static authorizeDelete(tenant, incomingMessage, newestRecordsWrite, messageStore) { return __awaiter37(this, void 0, void 0, function* () { const recordChain = yield ProtocolAuthorization.constructRecordChain(tenant, incomingMessage.message.descriptor.recordId, messageStore); const protocolDefinition = yield ProtocolAuthorization.fetchProtocolDefinition(tenant, newestRecordsWrite.message.descriptor.protocol, messageStore); const ruleSet = ProtocolAuthorization.getRuleSet(newestRecordsWrite.message.descriptor.protocolPath, protocolDefinition); yield ProtocolAuthorization.verifyInvokedRole(tenant, incomingMessage, newestRecordsWrite.message.descriptor.protocol, newestRecordsWrite.message.contextId, protocolDefinition, messageStore); yield ProtocolAuthorization.authorizeAgainstAllowedActions(tenant, incomingMessage, ruleSet, recordChain, messageStore); }); } /** * Fetches the protocol definition based on the protocol specified in the given message. */ static fetchProtocolDefinition(tenant, protocolUri, messageStore) { return __awaiter37(this, void 0, void 0, function* () { if (protocolUri === PermissionsProtocol.uri) { return PermissionsProtocol.definition; } const query = { interface: DwnInterfaceName.Protocols, method: DwnMethodName.Configure, protocol: protocolUri }; const { messages: protocols } = yield messageStore.query(tenant, [query]); if (protocols.length === 0) { throw new DwnError(DwnErrorCode.ProtocolAuthorizationProtocolNotFound, `unable to find protocol definition for ${protocolUri}`); } const protocolMessage = protocols[0]; return protocolMessage.descriptor.definition; }); } /** * Constructs the chain of EXISTING records in the datastore where the first record is the root initial `RecordsWrite` of the record chain * and last record is the initial `RecordsWrite` of the descendant record specified. * @param descendantRecordId The ID of the descendent record to start constructing the record chain from by repeatedly looking up the parent. * @returns the record chain where each record is represented by its initial `RecordsWrite`; * returns empty array if `descendantRecordId` is `undefined`. * @throws {DwnError} if `descendantRecordId` is defined but any initial `RecordsWrite` is not found in the chain of records. */ static constructRecordChain(tenant, descendantRecordId, messageStore) { return __awaiter37(this, void 0, void 0, function* () { if (descendantRecordId === void 0) { return []; } const recordChain = []; let currentRecordId = descendantRecordId; while (currentRecordId !== void 0) { const initialWrite = yield ProtocolAuthorization.fetchInitialWrite(tenant, currentRecordId, messageStore); if (initialWrite === void 0) { throw new DwnError(DwnErrorCode.ProtocolAuthorizationParentNotFoundConstructingRecordChain, `Unexpected error that should never trigger: no parent found with ID ${currentRecordId} when constructing record chain.`); } recordChain.push(initialWrite); currentRecordId = initialWrite.descriptor.parentId; } return recordChain.reverse(); }); } /** * Fetches the initial RecordsWrite message associated with the given (tenant + recordId). */ static fetchInitialWrite(tenant, recordId, messageStore) { return __awaiter37(this, void 0, void 0, function* () { const query = { interface: DwnInterfaceName.Records, method: DwnMethodName.Write, recordId }; const { messages } = yield messageStore.query(tenant, [query]); if (messages.length === 0) { return void 0; } const initialWrite = yield RecordsWrite2.getInitialWrite(messages); return initialWrite; }); } /** * Gets the rule set corresponding to the given protocolPath. */ static getRuleSet(protocolPath, protocolDefinition) { const ruleSet = ProtocolAuthorization.getRuleSetAtProtocolPath(protocolPath, protocolDefinition); if (ruleSet === void 0) { throw new DwnError(DwnErrorCode.ProtocolAuthorizationMissingRuleSet, `No rule set defined for protocolPath ${protocolPath}`); } return ruleSet; } /** * Verifies the `protocolPath` declared in the given message (if it is a RecordsWrite) matches the path of actual record chain. * @throws {DwnError} if fails verification. */ static verifyProtocolPathAndContextId(tenant, inboundMessage, messageStore) { var _a; return __awaiter37(this, void 0, void 0, function* () { const declaredProtocolPath = inboundMessage.message.descriptor.protocolPath; const declaredTypeName = ProtocolAuthorization.getTypeName(declaredProtocolPath); const parentId = inboundMessage.message.descriptor.parentId; if (parentId === void 0) { if (declaredProtocolPath !== declaredTypeName) { throw new DwnError(DwnErrorCode.ProtocolAuthorizationParentlessIncorrectProtocolPath, `Declared protocol path '${declaredProtocolPath}' is not valid for records with no parent'.`); } return; } const protocol = inboundMessage.message.descriptor.protocol; const query = { isLatestBaseState: true, interface: DwnInterfaceName.Records, method: DwnMethodName.Write, protocol, recordId: parentId }; const { messages: parentMessages } = yield messageStore.query(tenant, [query]); const parentMessage = parentMessages[0]; const parentProtocolPath = (_a = parentMessage === null || parentMessage === void 0 ? void 0 : parentMessage.descriptor) === null || _a === void 0 ? void 0 : _a.protocolPath; const expectedProtocolPath = `${parentProtocolPath}/${declaredTypeName}`; if (expectedProtocolPath !== declaredProtocolPath) { throw new DwnError(DwnErrorCode.ProtocolAuthorizationIncorrectProtocolPath, `Could not find matching parent record to verify declared protocol path '${declaredProtocolPath}'.`); } const expectedContextId = `${parentMessage.contextId}/${inboundMessage.message.recordId}`; const actualContextId = inboundMessage.message.contextId; if (actualContextId !== expectedContextId) { throw new DwnError(DwnErrorCode.ProtocolAuthorizationIncorrectContextId, `Declared contextId '${actualContextId}' is not the same as expected: '${expectedContextId}'.`); } }); } /** * Verifies the `dataFormat` and `schema` declared in the given message (if it is a RecordsWrite) matches dataFormat * and schema of the type in the given protocol. * @throws {DwnError} if fails verification. */ static verifyType(inboundMessage, protocolTypes) { const typeNames = Object.keys(protocolTypes); const declaredProtocolPath = inboundMessage.descriptor.protocolPath; const declaredTypeName = ProtocolAuthorization.getTypeName(declaredProtocolPath); if (!typeNames.includes(declaredTypeName)) { throw new DwnError(DwnErrorCode.ProtocolAuthorizationInvalidType, `record with type ${declaredTypeName} not allowed in protocol`); } const protocolPath = inboundMessage.descriptor.protocolPath; const typeName = ProtocolAuthorization.getTypeName(protocolPath); const protocolType = protocolTypes[typeName]; const { schema } = inboundMessage.descriptor; if (protocolType.schema !== void 0 && protocolType.schema !== schema) { throw new DwnError(DwnErrorCode.ProtocolAuthorizationInvalidSchema, `type '${typeName}' must have schema '${protocolType.schema}', instead has '${schema}'`); } const { dataFormat } = inboundMessage.descriptor; if (protocolType.dataFormats !== void 0 && !protocolType.dataFormats.includes(dataFormat)) { throw new DwnError(DwnErrorCode.ProtocolAuthorizationIncorrectDataFormat, `type '${typeName}' must have data format in (${protocolType.dataFormats}), instead has '${dataFormat}'`); } } /** * Check if the incoming message is invoking a role. If so, validate the invoked role. */ static verifyInvokedRole(tenant, incomingMessage, protocolUri, contextId, protocolDefinition, messageStore) { var _a; return __awaiter37(this, void 0, void 0, function* () { const protocolRole = (_a = incomingMessage.signaturePayload) === null || _a === void 0 ? void 0 : _a.protocolRole; if (protocolRole === void 0) { return; } const roleRuleSet = ProtocolAuthorization.getRuleSetAtProtocolPath(protocolRole, protocolDefinition); if (roleRuleSet === void 0 || !roleRuleSet.$role) { throw new DwnError(DwnErrorCode.ProtocolAuthorizationNotARole, `Protocol path ${protocolRole} does not match role record type.`); } const roleRecordFilter = { interface: DwnInterfaceName.Records, method: DwnMethodName.Write, protocol: protocolUri, protocolPath: protocolRole, recipient: incomingMessage.author, isLatestBaseState: true }; const ancestorSegmentCountOfRolePath = protocolRole.split("/").length - 1; if (contextId === void 0 && ancestorSegmentCountOfRolePath > 0) { throw new DwnError(DwnErrorCode.ProtocolAuthorizationMissingContextId, "Could not verify role because contextId is missing."); } if (ancestorSegmentCountOfRolePath > 0) { const contextIdSegments = contextId.split("/"); const contextIdPrefix = contextIdSegments.slice(0, ancestorSegmentCountOfRolePath).join("/"); const contextIdPrefixFilter = FilterUtility.constructPrefixFilterAsRangeFilter(contextIdPrefix); roleRecordFilter.contextId = contextIdPrefixFilter; } const { messages: matchingMessages } = yield messageStore.query(tenant, [roleRecordFilter]); if (matchingMessages.length === 0) { throw new DwnError(DwnErrorCode.ProtocolAuthorizationMatchingRoleRecordNotFound, `No matching role record found for protocol path ${protocolRole}`); } }); } /** * Returns all the ProtocolActions that would authorized the incoming message * (but we still need to later verify if there is a rule defined that matches one of the actions). * NOTE: the reason why there could be multiple actions is because: * - In case of an initial RecordsWrite, the RecordsWrite can be authorized by an allow `create` or `write` rule. * - In case of a non-initial RecordsWrite by the original record author, the RecordsWrite can be authorized by a `write` or `co-update` rule. * * It is important to recognize that the `write` access that allowed the original record author to create the record maybe revoked * (e.g. by role revocation) by the time a "non-initial" write by the same author is attempted. */ static getActionsSeekingARuleMatch(tenant, incomingMessage, messageStore) { return __awaiter37(this, void 0, void 0, function* () { switch (incomingMessage.message.descriptor.method) { case DwnMethodName.Delete: const recordsDelete = incomingMessage; const recordId = recordsDelete.message.descriptor.recordId; const initialWrite = yield RecordsWrite2.fetchInitialRecordsWrite(messageStore, tenant, recordId); if (initialWrite === void 0) { return []; } const actionsThatWouldAuthorizeDelete = []; const prune = recordsDelete.message.descriptor.prune; if (prune) { actionsThatWouldAuthorizeDelete.push(ProtocolAction.CoPrune); if (incomingMessage.author === initialWrite.author) { actionsThatWouldAuthorizeDelete.push(ProtocolAction.Prune); } } else { actionsThatWouldAuthorizeDelete.push(ProtocolAction.CoDelete); if (incomingMessage.author === initialWrite.author) { actionsThatWouldAuthorizeDelete.push(ProtocolAction.Delete); } } return actionsThatWouldAuthorizeDelete; case DwnMethodName.Query: return [ProtocolAction.Query]; case DwnMethodName.Read: return [ProtocolAction.Read]; case DwnMethodName.Subscribe: return [ProtocolAction.Subscribe]; case DwnMethodName.Write: const incomingRecordsWrite = incomingMessage; if (yield incomingRecordsWrite.isInitialWrite()) { return [ProtocolAction.Create]; } else { const recordId2 = incomingMessage.message.recordId; const initialWrite2 = yield RecordsWrite2.fetchInitialRecordsWrite(messageStore, tenant, recordId2); if (initialWrite2 === void 0) { return []; } if (incomingMessage.author === initialWrite2.author) { return [ProtocolAction.CoUpdate, ProtocolAction.Update]; } else { return [ProtocolAction.CoUpdate]; } } } return []; }); } /** * Verifies the given message is authorized by one of the action rules in the given protocol rule set. * @throws {Error} if action not allowed. */ static authorizeAgainstAllowedActions(tenant, incomingMessage, ruleSet, recordChain, messageStore) { var _a; return __awaiter37(this, void 0, void 0, function* () { const incomingMessageMethod = incomingMessage.message.descriptor.method; const actionsSeekingARuleMatch = yield ProtocolAuthorization.getActionsSeekingARuleMatch(tenant, incomingMessage, messageStore); const author = incomingMessage.author; const actionRules = ruleSet.$actions; if (actionRules === void 0) { throw new DwnError(DwnErrorCode.ProtocolAuthorizationActionRulesNotFound, `no action rule defined for Records${incomingMessageMethod}, ${author} is unauthorized`); } const invokedRole = (_a = incomingMessage.signaturePayload) === null || _a === void 0 ? void 0 : _a.protocolRole; for (const actionRule of actionRules) { const ruleHasAMatchingAllowedAction = actionRule.can.some((allowedAction) => actionsSeekingARuleMatch.includes(allowedAction)); if (!ruleHasAMatchingAllowedAction) { continue; } if (actionRule.who === ProtocolActor.Anyone) { return; } if (author === void 0) { continue; } if (invokedRole !== void 0) { if (actionRule.role === invokedRole) { return; } else { continue; } } if (actionRule.who === ProtocolActor.Recipient && actionRule.of === void 0) { let recordsWriteMessage; if (incomingMessage.message.descriptor.method === DwnMethodName.Write) { recordsWriteMessage = incomingMessage.message; } else { recordsWriteMessage = recordChain[recordChain.length - 1]; } if (recordsWriteMessage.descriptor.recipient === author) { return; } else { continue; } } const ancestorRuleSuccess = yield ProtocolAuthorization.checkActor(author, actionRule, recordChain); if (ancestorRuleSuccess) { return; } } throw new DwnError(DwnErrorCode.ProtocolAuthorizationActionNotAllowed, `Inbound message action Records${incomingMessageMethod} by author ${incomingMessage.author} not allowed.`); }); } /** * Verifies that writes adhere to the $size constraints if provided * @throws {Error} if size is exceeded. */ static verifySizeLimit(incomingMessage, ruleSet) { const { min = 0, max } = ruleSet.$size || {}; const dataSize = incomingMessage.message.descriptor.dataSize; if (dataSize < min) { throw new DwnError(DwnErrorCode.ProtocolAuthorizationMinSizeInvalid, `data size ${dataSize} is less than allowed ${min}`); } if (max === void 0) { return; } if (dataSize > max) { throw new DwnError(DwnErrorCode.ProtocolAuthorizationMaxSizeInvalid, `data size ${dataSize} is more than allowed ${max}`); } } static verifyTagsIfNeeded(incomingMessage, ruleSet) { if (ruleSet.$tags !== void 0) { const { tags = {}, protocol, protocolPath } = incomingMessage.message.descriptor; const _a = ruleSet.$tags, { $allowUndefinedTags, $requiredTags } = _a, properties = __rest7(_a, ["$allowUndefinedTags", "$requiredTags"]); const additionalProperties = $allowUndefinedTags || false; const required = $requiredTags || []; const ajv = new import__2.default.default(); const compiledTags = ajv.compile({ type: "object", properties, required, additionalProperties }); const validSchema = compiledTags(tags); if (!validSchema) { const schemaError = ajv.errorsText(compiledTags.errors, { dataVar: `${protocol}/${protocolPath}/$tags` }); throw new DwnError(DwnErrorCode.ProtocolAuthorizationTagsInvalidSchema, `tags schema validation error: ${schemaError}`); } } } /** * If the given RecordsWrite is not a role record, this method does nothing and succeeds immediately. * * Else it verifies the validity of the given `RecordsWrite` as a role record, including: * 1. The same role has not been assigned to the same entity/recipient. */ static verifyAsRoleRecordIfNeeded(tenant, incomingMessage, ruleSet, messageStore) { return __awaiter37(this, void 0, void 0, function* () { if (!ruleSet.$role) { return; } const incomingRecordsWrite = incomingMessage; const recipient = incomingRecordsWrite.message.descriptor.recipient; if (recipient === void 0) { throw new DwnError(DwnErrorCode.ProtocolAuthorizationRoleMissingRecipient, "Role records must have a recipient"); } const protocolPath = incomingRecordsWrite.message.descriptor.protocolPath; const filter2 = { interface: DwnInterfaceName.Records, method: DwnMethodName.Write, isLatestBaseState: true, protocol: incomingRecordsWrite.message.descriptor.protocol, protocolPath, recipient }; const parentContextId = Records.getParentContextFromOfContextId(incomingRecordsWrite.message.contextId); if (parentContextId !== "") { const prefixFilter = FilterUtility.constructPrefixFilterAsRangeFilter(parentContextId); filter2.contextId = prefixFilter; } const { messages: matchingMessages } = yield messageStore.query(tenant, [filter2]); const matchingRecords = matchingMessages; const matchingRecordsExceptIncomingRecordId = matchingRecords.filter((recordsWriteMessage) => recordsWriteMessage.recordId !== incomingRecordsWrite.message.recordId); if (matchingRecordsExceptIncomingRecordId.length > 0) { throw new DwnError(DwnErrorCode.ProtocolAuthorizationDuplicateRoleRecipient, `DID '${recipient}' is already recipient of a role record at protocol path '${protocolPath} under the parent context ${parentContextId}.`); } }); } static getRuleSetAtProtocolPath(protocolPath, protocolDefinition) { const protocolPathArray = protocolPath.split("/"); let currentRuleSet = protocolDefinition.structure; let i = 0; while (i < protocolPathArray.length) { const currentTypeName = protocolPathArray[i]; const nextRuleSet = currentRuleSet[currentTypeName]; if (nextRuleSet === void 0) { return void 0; } currentRuleSet = nextRuleSet; i++; } return currentRuleSet; } /** * Checks if the `who: 'author' | 'recipient'` action rule has a matching record in the record chain. * @returns `true` if the action rule is satisfied; `false` otherwise. */ static checkActor(author, actionRule, recordChain) { return __awaiter37(this, void 0, void 0, function* () { const ancestorRecordsWrite = recordChain.find((recordsWriteMessage) => recordsWriteMessage.descriptor.protocolPath === actionRule.of); if (ancestorRecordsWrite === void 0) { return false; } if (actionRule.who === ProtocolActor.Recipient) { return author === ancestorRecordsWrite.descriptor.recipient; } else { const ancestorAuthor = (yield RecordsWrite2.parse(ancestorRecordsWrite)).author; return author === ancestorAuthor; } }); } static getTypeName(protocolPath) { return protocolPath.split("/").slice(-1)[0]; } }; // dist/esm/src/interfaces/records-delete.js var __awaiter38 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var RecordsDelete2 = class extends AbstractMessage { static parse(message2) { return __awaiter38(this, void 0, void 0, function* () { let signaturePayload; if (message2.authorization !== void 0) { signaturePayload = yield Message.validateSignatureStructure(message2.authorization.signature, message2.descriptor); } yield Records.validateDelegatedGrantReferentialIntegrity(message2, signaturePayload); Time.validateTimestamp(message2.descriptor.messageTimestamp); const recordsDelete = new RecordsDelete2(message2); return recordsDelete; }); } /** * Creates a RecordsDelete message. * @param options.recordId If `undefined`, will be auto-filled as a originating message as convenience for developer. * @param options.messageTimestamp If `undefined`, it will be auto-filled with current time. */ static create(options) { var _a, _b; return __awaiter38(this, void 0, void 0, function* () { const recordId = options.recordId; const currentTime = Time.getCurrentTimestamp(); const descriptor = { interface: DwnInterfaceName.Records, method: DwnMethodName.Delete, messageTimestamp: (_a = options.messageTimestamp) !== null && _a !== void 0 ? _a : currentTime, recordId, prune: (_b = options.prune) !== null && _b !== void 0 ? _b : false }; const authorization = yield Message.createAuthorization({ descriptor, signer: options.signer, protocolRole: options.protocolRole, delegatedGrant: options.delegatedGrant }); const message2 = { descriptor, authorization }; Message.validateJsonSchema(message2); return new RecordsDelete2(message2); }); } /** * Indexed properties needed for MessageStore indexing. */ constructIndexes(initialWrite) { const message2 = this.message; const descriptor = Object.assign({}, message2.descriptor); const { protocol, protocolPath, recipient, schema, parentId, dateCreated } = initialWrite.descriptor; const indexes = Object.assign({ // isLatestBaseState : "true", // intentionally showing that this index is omitted protocol, protocolPath, recipient, schema, parentId, dateCreated, contextId: initialWrite.contextId, author: this.author }, descriptor); removeUndefinedProperties(indexes); return indexes; } /* * Authorizes the delegate who signed the message. * @param messageStore Used to check if the grant has been revoked. */ authorizeDelegate(recordsWriteToDelete, messageStore) { return __awaiter38(this, void 0, void 0, function* () { const delegatedGrant = yield PermissionGrant.parse(this.message.authorization.authorDelegatedGrant); yield RecordsGrantAuthorization.authorizeDelete({ recordsDeleteMessage: this.message, recordsWriteToDelete, expectedGrantor: this.author, expectedGrantee: this.signer, permissionGrant: delegatedGrant, messageStore }); }); } }; // dist/esm/src/core/dwn-constant.js var DwnConstant = class { }; DwnConstant.maxDataSizeAllowedToBeEncoded = 3e4; // dist/esm/src/store/storage-controller.js var __awaiter39 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var StorageController = class { /** * Deletes the data referenced by the given message if needed. * @param message The message to check if the data it references should be deleted. */ static deleteFromDataStoreIfNeeded(dataStore, tenant, message2, newestMessage) { return __awaiter39(this, void 0, void 0, function* () { if (message2.descriptor.method !== DwnMethodName.Write) { return; } const recordsWriteMessage = message2; if (recordsWriteMessage.descriptor.dataSize <= DwnConstant.maxDataSizeAllowedToBeEncoded) { return; } if (recordsWriteMessage.descriptor.dataCid === newestMessage.descriptor.dataCid) { return; } yield dataStore.delete(tenant, recordsWriteMessage.recordId, recordsWriteMessage.descriptor.dataCid); }); } /** * Purges (permanent hard-delete) all descendant's data of the given `recordId`. */ static purgeRecordDescendants(tenant, recordId, messageStore, dataStore, eventLog) { return __awaiter39(this, void 0, void 0, function* () { const filter2 = { interface: DwnInterfaceName.Records, parentId: recordId }; const { messages: childMessages } = yield messageStore.query(tenant, [filter2]); const recordIdToMessagesMap = /* @__PURE__ */ new Map(); for (const message2 of childMessages) { let recordId2; if (Records.isRecordsWrite(message2)) { recordId2 = message2.recordId; } else { recordId2 = message2.descriptor.recordId; } if (!recordIdToMessagesMap.has(recordId2)) { recordIdToMessagesMap.set(recordId2, []); } recordIdToMessagesMap.get(recordId2).push(message2); } for (const childRecordId of recordIdToMessagesMap.keys()) { yield StorageController.purgeRecordDescendants(tenant, childRecordId, messageStore, dataStore, eventLog); } for (const childRecordId of recordIdToMessagesMap.keys()) { yield StorageController.purgeRecordMessages(tenant, recordIdToMessagesMap.get(childRecordId), messageStore, dataStore, eventLog); } }); } /** * Purges (permanent hard-delete) all messages of the SAME `recordId` given and their associated data and events. * Assumes that the given `recordMessages` are all of the same `recordId`. */ static purgeRecordMessages(tenant, recordMessages, messageStore, dataStore, eventLog) { return __awaiter39(this, void 0, void 0, function* () { const recordsWrites = recordMessages.filter((message2) => message2.descriptor.method === DwnMethodName.Write); const newestRecordsWrite = yield Message.getNewestMessage(recordsWrites); yield dataStore.delete(tenant, newestRecordsWrite.recordId, newestRecordsWrite.descriptor.dataCid); const messageCids = yield Promise.all(recordMessages.map((message2) => Message.getCid(message2))); yield eventLog.deleteEventsByCid(tenant, messageCids); yield Promise.all(messageCids.map((messageCid) => messageStore.delete(tenant, messageCid))); }); } /** * Deletes all messages in `existingMessages` that are older than the `newestMessage` in the given tenant, * but keep the initial write write for future processing by ensuring its `isLatestBaseState` index is "false". */ static deleteAllOlderMessagesButKeepInitialWrite(tenant, existingMessages, newestMessage, messageStore, dataStore, eventLog) { return __awaiter39(this, void 0, void 0, function* () { const deletedMessageCids = []; for (const message2 of existingMessages) { const messageIsOld = yield Message.isOlder(message2, newestMessage); if (messageIsOld) { yield StorageController.deleteFromDataStoreIfNeeded(dataStore, tenant, message2, newestMessage); const messageCid = yield Message.getCid(message2); yield messageStore.delete(tenant, messageCid); const existingMessageIsInitialWrite = yield RecordsWrite2.isInitialWrite(message2); if (existingMessageIsInitialWrite) { const existingRecordsWrite = yield RecordsWrite2.parse(message2); const isLatestBaseState = false; const indexes = yield existingRecordsWrite.constructIndexes(isLatestBaseState); const writeMessage = message2; delete writeMessage.encodedData; yield messageStore.put(tenant, writeMessage, indexes); } else { const messageCid2 = yield Message.getCid(message2); deletedMessageCids.push(messageCid2); } } yield eventLog.deleteEventsByCid(tenant, deletedMessageCids); } }); } }; // dist/esm/src/handlers/records-delete.js var __awaiter40 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var RecordsDeleteHandler = class { constructor(didResolver, messageStore, dataStore, eventLog, eventStream) { this.didResolver = didResolver; this.messageStore = messageStore; this.dataStore = dataStore; this.eventLog = eventLog; this.eventStream = eventStream; } handle({ tenant, message: message2 }) { return __awaiter40(this, void 0, void 0, function* () { let recordsDelete; try { recordsDelete = yield RecordsDelete2.parse(message2); } catch (e) { return messageReplyFromError(e, 400); } try { yield authenticate(message2.authorization, this.didResolver); } catch (e) { return messageReplyFromError(e, 401); } const query = { interface: DwnInterfaceName.Records, recordId: message2.descriptor.recordId }; const { messages: existingMessages } = yield this.messageStore.query(tenant, [query]); const newestExistingMessage = yield Message.getNewestMessage(existingMessages); let incomingMessageIsNewest = false; let newestMessage; if (newestExistingMessage === void 0 || (yield Message.isNewer(message2, newestExistingMessage))) { incomingMessageIsNewest = true; newestMessage = message2; } else { newestMessage = newestExistingMessage; } if (!incomingMessageIsNewest) { return { status: { code: 409, detail: "Conflict" } }; } if (newestExistingMessage === void 0 || newestExistingMessage.descriptor.method === DwnMethodName.Delete) { return { status: { code: 404, detail: "Not Found" } }; } try { yield RecordsDeleteHandler.authorizeRecordsDelete(tenant, recordsDelete, yield RecordsWrite2.parse(newestExistingMessage), this.messageStore); } catch (e) { return messageReplyFromError(e, 401); } const initialWrite = yield RecordsWrite2.getInitialWrite(existingMessages); const indexes = recordsDelete.constructIndexes(initialWrite); const messageCid = yield Message.getCid(message2); yield this.messageStore.put(tenant, message2, indexes); yield this.eventLog.append(tenant, messageCid, indexes); if (this.eventStream !== void 0) { this.eventStream.emit(tenant, { message: message2, initialWrite }, indexes); } if (message2.descriptor.prune) { yield StorageController.purgeRecordDescendants(tenant, message2.descriptor.recordId, this.messageStore, this.dataStore, this.eventLog); } yield StorageController.deleteAllOlderMessagesButKeepInitialWrite(tenant, existingMessages, newestMessage, this.messageStore, this.dataStore, this.eventLog); const messageReply = { status: { code: 202, detail: "Accepted" } }; return messageReply; }); } /** * Authorizes a RecordsDelete message. * * @param newestRecordsWrite Newest RecordsWrite of the record to be deleted. */ static authorizeRecordsDelete(tenant, recordsDelete, newestRecordsWrite, messageStore) { return __awaiter40(this, void 0, void 0, function* () { if (Message.isSignedByAuthorDelegate(recordsDelete.message)) { yield recordsDelete.authorizeDelegate(newestRecordsWrite.message, messageStore); } if (recordsDelete.author === tenant) { return; } else if (newestRecordsWrite.message.descriptor.protocol !== void 0) { yield ProtocolAuthorization.authorizeDelete(tenant, recordsDelete, newestRecordsWrite, messageStore); } else { throw new DwnError(DwnErrorCode.RecordsDeleteAuthorizationFailed, "RecordsDelete message failed authorization"); } }); } }; // dist/esm/src/types/query-types.js var SortDirection; (function(SortDirection2) { SortDirection2[SortDirection2["Descending"] = -1] = "Descending"; SortDirection2[SortDirection2["Ascending"] = 1] = "Ascending"; })(SortDirection || (SortDirection = {})); // dist/esm/src/handlers/records-query.js var __awaiter41 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var RecordsQueryHandler = class { constructor(didResolver, messageStore, dataStore) { this.didResolver = didResolver; this.messageStore = messageStore; this.dataStore = dataStore; } handle({ tenant, message: message2 }) { return __awaiter41(this, void 0, void 0, function* () { let recordsQuery; try { recordsQuery = yield RecordsQuery2.parse(message2); } catch (e) { return messageReplyFromError(e, 400); } let recordsWrites; let cursor; if (Records.filterIncludesPublishedRecords(recordsQuery.message.descriptor.filter) && recordsQuery.author === void 0) { const results = yield this.fetchPublishedRecords(tenant, recordsQuery); recordsWrites = results.messages; cursor = results.cursor; } else { try { yield authenticate(message2.authorization, this.didResolver); yield RecordsQueryHandler.authorizeRecordsQuery(tenant, recordsQuery, this.messageStore); } catch (e) { return messageReplyFromError(e, 401); } if (recordsQuery.author === tenant) { const results = yield this.fetchRecordsAsOwner(tenant, recordsQuery); recordsWrites = results.messages; cursor = results.cursor; } else { const results = yield this.fetchRecordsAsNonOwner(tenant, recordsQuery); recordsWrites = results.messages; cursor = results.cursor; } } for (const recordsWrite of recordsWrites) { if (!(yield RecordsWrite2.isInitialWrite(recordsWrite))) { const initialWriteQueryResult = yield this.messageStore.query(tenant, [{ recordId: recordsWrite.recordId, isLatestBaseState: false, method: DwnMethodName.Write }]); const initialWrite = initialWriteQueryResult.messages[0]; delete initialWrite.encodedData; recordsWrite.initialWrite = initialWrite; } } return { status: { code: 200, detail: "OK" }, entries: recordsWrites, cursor }; }); } /** * Convert an incoming DateSort to a sort type accepted by MessageStore * Defaults to 'dateCreated' in Descending order if no sort is supplied. * * @param dateSort the optional DateSort from the RecordsQuery message descriptor. * @returns {MessageSort} for MessageStore sorting. */ convertDateSort(dateSort) { switch (dateSort) { case DateSort.CreatedAscending: return { dateCreated: SortDirection.Ascending }; case DateSort.CreatedDescending: return { dateCreated: SortDirection.Descending }; case DateSort.PublishedAscending: return { datePublished: SortDirection.Ascending }; case DateSort.PublishedDescending: return { datePublished: SortDirection.Descending }; default: return { dateCreated: SortDirection.Ascending }; } } /** * Fetches the records as the owner of the DWN with no additional filtering. */ fetchRecordsAsOwner(tenant, recordsQuery) { return __awaiter41(this, void 0, void 0, function* () { const { dateSort, filter: filter2, pagination } = recordsQuery.message.descriptor; const queryFilter = Object.assign(Object.assign({}, Records.convertFilter(filter2, dateSort)), { interface: DwnInterfaceName.Records, method: DwnMethodName.Write, isLatestBaseState: true }); const messageSort = this.convertDateSort(dateSort); return this.messageStore.query(tenant, [queryFilter], messageSort, pagination); }); } /** * Fetches the records as a non-owner. * * Filters can support returning both published and unpublished records, * as well as explicitly only published or only unpublished records. * * A) BOTH published and unpublished: * 1. published records; and * 2. unpublished records intended for the query author (where `recipient` is the query author); and * 3. unpublished records authorized by a protocol rule. * * B) PUBLISHED: * 1. only published records; * * C) UNPUBLISHED: * 1. unpublished records intended for the query author (where `recipient` is the query author); and * 2. unpublished records authorized by a protocol rule. * */ fetchRecordsAsNonOwner(tenant, recordsQuery) { return __awaiter41(this, void 0, void 0, function* () { const { dateSort, pagination, filter: filter2 } = recordsQuery.message.descriptor; const filters = []; if (Records.filterIncludesPublishedRecords(filter2)) { filters.push(RecordsQueryHandler.buildPublishedRecordsFilter(recordsQuery)); } if (Records.filterIncludesUnpublishedRecords(filter2)) { filters.push(RecordsQueryHandler.buildUnpublishedRecordsByQueryAuthorFilter(recordsQuery)); const recipientFilter = recordsQuery.message.descriptor.filter.recipient; if (recipientFilter === void 0 || recipientFilter === recordsQuery.author) { filters.push(RecordsQueryHandler.buildUnpublishedRecordsForQueryAuthorFilter(recordsQuery)); } if (Records.shouldProtocolAuthorize(recordsQuery.signaturePayload)) { filters.push(RecordsQueryHandler.buildUnpublishedProtocolAuthorizedRecordsFilter(recordsQuery)); } } const messageSort = this.convertDateSort(dateSort); return this.messageStore.query(tenant, filters, messageSort, pagination); }); } /** * Fetches only published records. */ fetchPublishedRecords(tenant, recordsQuery) { return __awaiter41(this, void 0, void 0, function* () { const { dateSort, pagination } = recordsQuery.message.descriptor; const filter2 = RecordsQueryHandler.buildPublishedRecordsFilter(recordsQuery); const messageSort = this.convertDateSort(dateSort); return this.messageStore.query(tenant, [filter2], messageSort, pagination); }); } static buildPublishedRecordsFilter(recordsQuery) { const { dateSort, filter: filter2 } = recordsQuery.message.descriptor; return Object.assign(Object.assign({}, Records.convertFilter(filter2, dateSort)), { interface: DwnInterfaceName.Records, method: DwnMethodName.Write, published: true, isLatestBaseState: true }); } /** * Creates a filter for unpublished records that are intended for the query author (where `recipient` is the author). */ static buildUnpublishedRecordsForQueryAuthorFilter(recordsQuery) { const { dateSort, filter: filter2 } = recordsQuery.message.descriptor; return Object.assign(Object.assign({}, Records.convertFilter(filter2, dateSort)), { interface: DwnInterfaceName.Records, method: DwnMethodName.Write, recipient: recordsQuery.author, isLatestBaseState: true, published: false }); } /** * Creates a filter for unpublished records that are within the specified protocol. * Validation that `protocol` and other required protocol-related fields occurs before this method. */ static buildUnpublishedProtocolAuthorizedRecordsFilter(recordsQuery) { const { dateSort, filter: filter2 } = recordsQuery.message.descriptor; return Object.assign(Object.assign({}, Records.convertFilter(filter2, dateSort)), { interface: DwnInterfaceName.Records, method: DwnMethodName.Write, isLatestBaseState: true, published: false }); } /** * Creates a filter for only unpublished records where the author is the same as the query author. */ static buildUnpublishedRecordsByQueryAuthorFilter(recordsQuery) { const { dateSort, filter: filter2 } = recordsQuery.message.descriptor; return Object.assign(Object.assign({}, Records.convertFilter(filter2, dateSort)), { author: recordsQuery.author, interface: DwnInterfaceName.Records, method: DwnMethodName.Write, isLatestBaseState: true, published: false }); } /** * @param messageStore Used to check if the grant has been revoked. */ static authorizeRecordsQuery(tenant, recordsQuery, messageStore) { return __awaiter41(this, void 0, void 0, function* () { if (Message.isSignedByAuthorDelegate(recordsQuery.message)) { yield recordsQuery.authorizeDelegate(messageStore); } if (Records.shouldProtocolAuthorize(recordsQuery.signaturePayload)) { yield ProtocolAuthorization.authorizeQueryOrSubscribe(tenant, recordsQuery, messageStore); } }); } }; // dist/esm/src/interfaces/records-read.js var __awaiter42 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var RecordsRead2 = class extends AbstractMessage { static parse(message2) { return __awaiter42(this, void 0, void 0, function* () { let signaturePayload; if (message2.authorization !== void 0) { signaturePayload = yield Message.validateSignatureStructure(message2.authorization.signature, message2.descriptor); } yield Records.validateDelegatedGrantReferentialIntegrity(message2, signaturePayload); Time.validateTimestamp(message2.descriptor.messageTimestamp); const recordsRead = new RecordsRead2(message2); return recordsRead; }); } /** * Creates a RecordsRead message. * @param options.recordId If `undefined`, will be auto-filled as a originating message as convenience for developer. * @param options.date If `undefined`, it will be auto-filled with current time. * * @throws {DwnError} when a combination of required RecordsReadOptions are missing */ static create(options) { var _a; return __awaiter42(this, void 0, void 0, function* () { const { filter: filter2, signer, permissionGrantId, protocolRole } = options; const currentTime = Time.getCurrentTimestamp(); const descriptor = { interface: DwnInterfaceName.Records, method: DwnMethodName.Read, filter: Records.normalizeFilter(filter2), messageTimestamp: (_a = options.messageTimestamp) !== null && _a !== void 0 ? _a : currentTime }; removeUndefinedProperties(descriptor); let authorization = void 0; if (signer !== void 0) { authorization = yield Message.createAuthorization({ descriptor, signer, permissionGrantId, protocolRole, delegatedGrant: options.delegatedGrant }); } const message2 = { descriptor, authorization }; Message.validateJsonSchema(message2); return new RecordsRead2(message2); }); } /** * Authorizes the delegate who signed this message. * @param messageStore Used to check if the grant has been revoked. */ authorizeDelegate(matchedRecordsWrite, messageStore) { return __awaiter42(this, void 0, void 0, function* () { const delegatedGrant = yield PermissionGrant.parse(this.message.authorization.authorDelegatedGrant); yield RecordsGrantAuthorization.authorizeRead({ recordsReadMessage: this.message, recordsWriteMessageToBeRead: matchedRecordsWrite, expectedGrantor: this.author, expectedGrantee: this.signer, permissionGrant: delegatedGrant, messageStore }); }); } }; // dist/esm/src/handlers/records-read.js var __awaiter43 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var RecordsReadHandler = class { constructor(didResolver, messageStore, dataStore) { this.didResolver = didResolver; this.messageStore = messageStore; this.dataStore = dataStore; } handle({ tenant, message: message2 }) { return __awaiter43(this, void 0, void 0, function* () { let recordsRead; try { recordsRead = yield RecordsRead2.parse(message2); } catch (e) { return messageReplyFromError(e, 400); } try { if (recordsRead.author !== void 0) { yield authenticate(message2.authorization, this.didResolver); } } catch (e) { return messageReplyFromError(e, 401); } const query = Object.assign({ interface: DwnInterfaceName.Records, isLatestBaseState: true }, Records.convertFilter(message2.descriptor.filter)); const { messages: existingMessages } = yield this.messageStore.query(tenant, [query]); if (existingMessages.length === 0) { return { status: { code: 404, detail: "Not Found" } }; } else if (existingMessages.length > 1) { return messageReplyFromError(new DwnError(DwnErrorCode.RecordsReadReturnedMultiple, "Multiple records exist for the RecordsRead filter"), 400); } const matchedRecordsWrite = existingMessages[0]; try { yield RecordsReadHandler.authorizeRecordsRead(tenant, recordsRead, yield RecordsWrite2.parse(matchedRecordsWrite), this.messageStore); } catch (error) { return messageReplyFromError(error, 401); } let data; if (matchedRecordsWrite.encodedData !== void 0) { const dataBytes = Encoder2.base64UrlToBytes(matchedRecordsWrite.encodedData); data = DataStream.fromBytes(dataBytes); delete matchedRecordsWrite.encodedData; } else { const result = yield this.dataStore.get(tenant, matchedRecordsWrite.recordId, matchedRecordsWrite.descriptor.dataCid); if ((result === null || result === void 0 ? void 0 : result.dataStream) === void 0) { return { status: { code: 404, detail: "Not Found" } }; } data = result.dataStream; } const record = Object.assign(Object.assign({}, matchedRecordsWrite), { data }); if (!(yield RecordsWrite2.isInitialWrite(record))) { const initialWriteQueryResult = yield this.messageStore.query(tenant, [{ recordId: record.recordId, isLatestBaseState: false, method: DwnMethodName.Write }]); const initialWrite = initialWriteQueryResult.messages[0]; delete initialWrite.encodedData; record.initialWrite = initialWrite; } const messageReply = { status: { code: 200, detail: "OK" }, record }; return messageReply; }); } /** * @param messageStore Used to check if the grant has been revoked. */ static authorizeRecordsRead(tenant, recordsRead, matchedRecordsWrite, messageStore) { return __awaiter43(this, void 0, void 0, function* () { if (Message.isSignedByAuthorDelegate(recordsRead.message)) { yield recordsRead.authorizeDelegate(matchedRecordsWrite.message, messageStore); } const { descriptor } = matchedRecordsWrite.message; if (recordsRead.author === tenant) { return; } else if (descriptor.published === true) { return; } else if (recordsRead.author !== void 0 && recordsRead.author === descriptor.recipient) { return; } else if (recordsRead.author !== void 0 && recordsRead.signaturePayload.permissionGrantId !== void 0) { const permissionGrant = yield PermissionsProtocol.fetchGrant(tenant, messageStore, recordsRead.signaturePayload.permissionGrantId); yield RecordsGrantAuthorization.authorizeRead({ recordsReadMessage: recordsRead.message, recordsWriteMessageToBeRead: matchedRecordsWrite.message, expectedGrantor: tenant, expectedGrantee: recordsRead.author, permissionGrant, messageStore }); } else if (descriptor.protocol !== void 0) { yield ProtocolAuthorization.authorizeRead(tenant, recordsRead, matchedRecordsWrite, messageStore); } else { throw new DwnError(DwnErrorCode.RecordsReadAuthorizationFailed, "message failed authorization"); } }); } }; // dist/esm/src/interfaces/records-subscribe.js var __awaiter44 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var RecordsSubscribe2 = class extends AbstractMessage { static parse(message2) { return __awaiter44(this, void 0, void 0, function* () { let signaturePayload; if (message2.authorization !== void 0) { signaturePayload = yield Message.validateSignatureStructure(message2.authorization.signature, message2.descriptor); } yield Records.validateDelegatedGrantReferentialIntegrity(message2, signaturePayload); if ((signaturePayload === null || signaturePayload === void 0 ? void 0 : signaturePayload.protocolRole) !== void 0) { if (message2.descriptor.filter.protocolPath === void 0) { throw new DwnError(DwnErrorCode.RecordsSubscribeFilterMissingRequiredProperties, "Role-authorized subscriptions must include `protocolPath` in the filter"); } } if (message2.descriptor.filter.protocol !== void 0) { validateProtocolUrlNormalized(message2.descriptor.filter.protocol); } if (message2.descriptor.filter.schema !== void 0) { validateSchemaUrlNormalized(message2.descriptor.filter.schema); } Time.validateTimestamp(message2.descriptor.messageTimestamp); return new RecordsSubscribe2(message2); }); } static create(options) { var _a; return __awaiter44(this, void 0, void 0, function* () { const descriptor = { interface: DwnInterfaceName.Records, method: DwnMethodName.Subscribe, messageTimestamp: (_a = options.messageTimestamp) !== null && _a !== void 0 ? _a : Time.getCurrentTimestamp(), filter: Records.normalizeFilter(options.filter) }; removeUndefinedProperties(descriptor); const signer = options.signer; let authorization; if (signer) { authorization = yield Message.createAuthorization({ descriptor, signer, protocolRole: options.protocolRole, delegatedGrant: options.delegatedGrant }); } const message2 = { descriptor, authorization }; Message.validateJsonSchema(message2); return new RecordsSubscribe2(message2); }); } /** * Authorizes the delegate who signed the message. * @param messageStore Used to check if the grant has been revoked. */ authorizeDelegate(messageStore) { return __awaiter44(this, void 0, void 0, function* () { const delegatedGrant = yield PermissionGrant.parse(this.message.authorization.authorDelegatedGrant); yield RecordsGrantAuthorization.authorizeQueryOrSubscribe({ incomingMessage: this.message, expectedGrantor: this.author, expectedGrantee: this.signer, permissionGrant: delegatedGrant, messageStore }); }); } }; // dist/esm/src/handlers/records-subscribe.js var __awaiter45 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var RecordsSubscribeHandler = class { constructor(didResolver, messageStore, eventStream) { this.didResolver = didResolver; this.messageStore = messageStore; this.eventStream = eventStream; } handle({ tenant, message: message2, subscriptionHandler }) { return __awaiter45(this, void 0, void 0, function* () { if (this.eventStream === void 0) { return messageReplyFromError(new DwnError(DwnErrorCode.RecordsSubscribeEventStreamUnimplemented, "Subscriptions are not supported"), 501); } let recordsSubscribe; try { recordsSubscribe = yield RecordsSubscribe2.parse(message2); } catch (e) { return messageReplyFromError(e, 400); } let filters = []; if (Records.filterIncludesPublishedRecords(recordsSubscribe.message.descriptor.filter) && recordsSubscribe.author === void 0) { filters = [RecordsSubscribeHandler.buildPublishedRecordsFilter(recordsSubscribe)]; delete message2.authorization; } else { try { yield authenticate(message2.authorization, this.didResolver); yield RecordsSubscribeHandler.authorizeRecordsSubscribe(tenant, recordsSubscribe, this.messageStore); } catch (error) { return messageReplyFromError(error, 401); } if (recordsSubscribe.author === tenant) { filters = yield RecordsSubscribeHandler.filterAsOwner(recordsSubscribe); } else { filters = yield RecordsSubscribeHandler.filterAsNonOwner(recordsSubscribe); } } const listener = (eventTenant, event, eventIndexes) => { if (tenant === eventTenant && FilterUtility.matchAnyFilter(eventIndexes, filters)) { subscriptionHandler(event); } }; const messageCid = yield Message.getCid(message2); const subscription = yield this.eventStream.subscribe(tenant, messageCid, listener); return { status: { code: 200, detail: "OK" }, subscription }; }); } /** * Subscribe to records as the owner of the DWN with no additional filtering. */ static filterAsOwner(RecordsSubscribe3) { return __awaiter45(this, void 0, void 0, function* () { const { filter: filter2 } = RecordsSubscribe3.message.descriptor; const subscribeFilter = Object.assign(Object.assign({}, Records.convertFilter(filter2)), { interface: DwnInterfaceName.Records, method: [DwnMethodName.Write, DwnMethodName.Delete] }); return [subscribeFilter]; }); } /** * Creates filters in order to subscribe to records as a non-owner. * * Filters can support emitting messages for both published and unpublished records, * as well as explicitly only published or only unpublished records. * * A) BOTH published and unpublished: * 1. published records; and * 2. unpublished records intended for the subscription author (where `recipient` is the subscription author); and * 3. unpublished records authorized by a protocol rule. * * B) PUBLISHED: * 1. only published records; * * C) UNPUBLISHED: * 1. unpublished records intended for the subscription author (where `recipient` is the subscription author); and * 2. unpublished records authorized by a protocol rule. */ static filterAsNonOwner(recordsSubscribe) { return __awaiter45(this, void 0, void 0, function* () { const filters = []; const { filter: filter2 } = recordsSubscribe.message.descriptor; if (Records.filterIncludesPublishedRecords(filter2)) { filters.push(RecordsSubscribeHandler.buildPublishedRecordsFilter(recordsSubscribe)); } if (Records.filterIncludesUnpublishedRecords(filter2)) { filters.push(RecordsSubscribeHandler.buildUnpublishedRecordsBySubscribeAuthorFilter(recordsSubscribe)); const recipientFilter = recordsSubscribe.message.descriptor.filter.recipient; if (recipientFilter === void 0 || recipientFilter === recordsSubscribe.author) { filters.push(RecordsSubscribeHandler.buildUnpublishedRecordsForSubscribeAuthorFilter(recordsSubscribe)); } if (Records.shouldProtocolAuthorize(recordsSubscribe.signaturePayload)) { filters.push(RecordsSubscribeHandler.buildUnpublishedProtocolAuthorizedRecordsFilter(recordsSubscribe)); } } return filters; }); } /** * Creates a filter for all published records matching the subscribe */ static buildPublishedRecordsFilter(recordsSubscribe) { return Object.assign(Object.assign({}, Records.convertFilter(recordsSubscribe.message.descriptor.filter)), { interface: DwnInterfaceName.Records, method: [DwnMethodName.Write, DwnMethodName.Delete], published: true }); } /** * Creates a filter for unpublished records that are intended for the subscribe author (where `recipient` is the author). */ static buildUnpublishedRecordsForSubscribeAuthorFilter(recordsSubscribe) { return Object.assign(Object.assign({}, Records.convertFilter(recordsSubscribe.message.descriptor.filter)), { interface: DwnInterfaceName.Records, method: [DwnMethodName.Write, DwnMethodName.Delete], recipient: recordsSubscribe.author, published: false }); } /** * Creates a filter for unpublished records that are within the specified protocol. * Validation that `protocol` and other required protocol-related fields occurs before this method. */ static buildUnpublishedProtocolAuthorizedRecordsFilter(recordsSubscribe) { return Object.assign(Object.assign({}, Records.convertFilter(recordsSubscribe.message.descriptor.filter)), { interface: DwnInterfaceName.Records, method: [DwnMethodName.Write, DwnMethodName.Delete], published: false }); } /** * Creates a filter for only unpublished records where the author is the same as the subscribe author. */ static buildUnpublishedRecordsBySubscribeAuthorFilter(recordsSubscribe) { return Object.assign(Object.assign({}, Records.convertFilter(recordsSubscribe.message.descriptor.filter)), { author: recordsSubscribe.author, interface: DwnInterfaceName.Records, method: [DwnMethodName.Write, DwnMethodName.Delete], published: false }); } /** * @param messageStore Used to check if the grant has been revoked. */ static authorizeRecordsSubscribe(tenant, recordsSubscribe, messageStore) { return __awaiter45(this, void 0, void 0, function* () { if (Message.isSignedByAuthorDelegate(recordsSubscribe.message)) { yield recordsSubscribe.authorizeDelegate(messageStore); } if (Records.shouldProtocolAuthorize(recordsSubscribe.signaturePayload)) { yield ProtocolAuthorization.authorizeQueryOrSubscribe(tenant, recordsSubscribe, messageStore); } }); } }; // dist/esm/src/handlers/records-write.js var __awaiter46 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var RecordsWriteHandler = class { constructor(didResolver, messageStore, dataStore, eventLog, eventStream) { this.didResolver = didResolver; this.messageStore = messageStore; this.dataStore = dataStore; this.eventLog = eventLog; this.eventStream = eventStream; } handle({ tenant, message: message2, dataStream }) { return __awaiter46(this, void 0, void 0, function* () { let recordsWrite; try { recordsWrite = yield RecordsWrite2.parse(message2); if (message2.descriptor.protocol !== void 0) { yield ProtocolAuthorization.validateReferentialIntegrity(tenant, recordsWrite, this.messageStore); } } catch (e) { return messageReplyFromError(e, 400); } try { yield authenticate(message2.authorization, this.didResolver); yield RecordsWriteHandler.authorizeRecordsWrite(tenant, recordsWrite, this.messageStore); } catch (e) { return messageReplyFromError(e, 401); } const query = { interface: DwnInterfaceName.Records, recordId: message2.recordId }; const { messages: existingMessages } = yield this.messageStore.query(tenant, [query]); const newMessageIsInitialWrite = yield recordsWrite.isInitialWrite(); let initialWrite; if (!newMessageIsInitialWrite) { try { initialWrite = yield RecordsWrite2.getInitialWrite(existingMessages); RecordsWrite2.verifyEqualityOfImmutableProperties(initialWrite, message2); } catch (e) { return messageReplyFromError(e, 400); } } const newestExistingMessage = yield Message.getNewestMessage(existingMessages); let incomingMessageIsNewest = false; let newestMessage; if (newestExistingMessage === void 0 || (yield Message.isNewer(message2, newestExistingMessage))) { incomingMessageIsNewest = true; newestMessage = message2; } else { newestMessage = newestExistingMessage; } if (!incomingMessageIsNewest) { return { status: { code: 409, detail: "Conflict" } }; } try { let isLatestBaseState = false; let messageWithOptionalEncodedData = message2; if (dataStream !== void 0) { messageWithOptionalEncodedData = yield this.processMessageWithDataStream(tenant, message2, dataStream); isLatestBaseState = true; } else { if ((newestExistingMessage === null || newestExistingMessage === void 0 ? void 0 : newestExistingMessage.descriptor.method) === DwnMethodName.Delete) { throw new DwnError(DwnErrorCode.RecordsWriteMissingDataStream, "No data stream was provided with the previous message being a delete"); } if (!newMessageIsInitialWrite) { const newestExistingWrite = newestExistingMessage; messageWithOptionalEncodedData = yield this.processMessageWithoutDataStream(tenant, message2, newestExistingWrite); isLatestBaseState = true; } } const indexes = yield recordsWrite.constructIndexes(isLatestBaseState); yield this.messageStore.put(tenant, messageWithOptionalEncodedData, indexes); yield this.eventLog.append(tenant, yield Message.getCid(message2), indexes); if (this.eventStream !== void 0 && isLatestBaseState) { this.eventStream.emit(tenant, { message: message2, initialWrite }, indexes); } } catch (error) { const e = error; if (e.code !== void 0) { if (e.code === DwnErrorCode.RecordsWriteMissingEncodedDataInPrevious || e.code === DwnErrorCode.RecordsWriteMissingDataInPrevious || e.code === DwnErrorCode.RecordsWriteMissingDataStream || e.code === DwnErrorCode.RecordsWriteDataCidMismatch || e.code === DwnErrorCode.RecordsWriteDataSizeMismatch || e.code.startsWith("PermissionsProtocolValidate") || e.code.startsWith("SchemaValidator")) { return messageReplyFromError(error, 400); } } throw error; } const messageReply = { status: { code: 202, detail: "Accepted" } }; yield StorageController.deleteAllOlderMessagesButKeepInitialWrite(tenant, existingMessages, newestMessage, this.messageStore, this.dataStore, this.eventLog); yield this.postProcessingForCoreRecordsWrite(tenant, recordsWrite); return messageReply; }); } static validateSchemaForCoreRecordsWrite(recordsWriteMessage, dataBytes) { if (recordsWriteMessage.descriptor.protocol === PermissionsProtocol.uri) { PermissionsProtocol.validateSchema(recordsWriteMessage, dataBytes); } } /** * Performs additional necessary tasks if the RecordsWrite handled is a core DWN RecordsWrite that need additional processing. * For instance: a Permission revocation RecordsWrite. */ postProcessingForCoreRecordsWrite(tenant, recordsWrite) { return __awaiter46(this, void 0, void 0, function* () { if (recordsWrite.message.descriptor.protocol === PermissionsProtocol.uri && recordsWrite.message.descriptor.protocolPath === PermissionsProtocol.revocationPath) { const permissionGrantId = recordsWrite.message.descriptor.parentId; const grantAuthorizedMessagesQuery = { permissionGrantId, dateCreated: { gte: recordsWrite.message.descriptor.messageTimestamp } }; const { messages: grantAuthorizedMessagesAfterRevoke } = yield this.messageStore.query(tenant, [grantAuthorizedMessagesQuery]); const grantAuthorizedMessageCidsAfterRevoke = []; for (const grantAuthorizedMessage of grantAuthorizedMessagesAfterRevoke) { const messageCid = yield Message.getCid(grantAuthorizedMessage); yield this.messageStore.delete(tenant, messageCid); } this.eventLog.deleteEventsByCid(tenant, grantAuthorizedMessageCidsAfterRevoke); } }); } /** * Returns a `RecordsQueryReplyEntry` with a copy of the incoming message and the incoming data encoded to `Base64URL`. */ cloneAndAddEncodedData(message2, dataBytes) { return __awaiter46(this, void 0, void 0, function* () { const recordsWrite = Object.assign({}, message2); recordsWrite.encodedData = Encoder2.bytesToBase64Url(dataBytes); return recordsWrite; }); } processMessageWithDataStream(tenant, message2, dataStream) { return __awaiter46(this, void 0, void 0, function* () { let messageWithOptionalEncodedData = message2; if (message2.descriptor.dataSize <= DwnConstant.maxDataSizeAllowedToBeEncoded) { const dataBytes = yield DataStream.toBytes(dataStream); const dataCid = yield Cid.computeDagPbCidFromBytes(dataBytes); RecordsWriteHandler.validateDataIntegrity(message2.descriptor.dataCid, message2.descriptor.dataSize, dataCid, dataBytes.length); RecordsWriteHandler.validateSchemaForCoreRecordsWrite(message2, dataBytes); messageWithOptionalEncodedData = yield this.cloneAndAddEncodedData(message2, dataBytes); } else { const [dataStreamCopy1, dataStreamCopy2] = DataStream.duplicateDataStream(dataStream, 2); try { const [dataCid, DataStorePutResult] = yield Promise.all([ Cid.computeDagPbCidFromStream(dataStreamCopy1), this.dataStore.put(tenant, message2.recordId, message2.descriptor.dataCid, dataStreamCopy2) ]); RecordsWriteHandler.validateDataIntegrity(message2.descriptor.dataCid, message2.descriptor.dataSize, dataCid, DataStorePutResult.dataSize); } catch (error) { yield this.dataStore.delete(tenant, message2.recordId, message2.descriptor.dataCid); throw error; } } return messageWithOptionalEncodedData; }); } processMessageWithoutDataStream(tenant, message2, newestExistingWrite) { return __awaiter46(this, void 0, void 0, function* () { const messageWithOptionalEncodedData = Object.assign({}, message2); const { dataCid, dataSize } = message2.descriptor; RecordsWriteHandler.validateDataIntegrity(dataCid, dataSize, newestExistingWrite.descriptor.dataCid, newestExistingWrite.descriptor.dataSize); if (dataSize <= DwnConstant.maxDataSizeAllowedToBeEncoded) { if (newestExistingWrite.encodedData !== void 0) { messageWithOptionalEncodedData.encodedData = newestExistingWrite.encodedData; } else { throw new DwnError(DwnErrorCode.RecordsWriteMissingEncodedDataInPrevious, `No dataStream was provided and unable to get data from previous message`); } } else { const DataStoreGetResult = yield this.dataStore.get(tenant, newestExistingWrite.recordId, message2.descriptor.dataCid); if (DataStoreGetResult === void 0) { throw new DwnError(DwnErrorCode.RecordsWriteMissingDataInPrevious, `No dataStream was provided and unable to get data from previous message`); } } return messageWithOptionalEncodedData; }); } /** * Validates the expected `dataCid` and `dataSize` in the descriptor vs the received data. * * @throws {DwnError} with `DwnErrorCode.RecordsWriteDataCidMismatch` * if the data stream resulted in a data CID that mismatches with `dataCid` in the given message * @throws {DwnError} with `DwnErrorCode.RecordsWriteDataSizeMismatch` * if `dataSize` in `descriptor` given mismatches the actual data size */ static validateDataIntegrity(expectedDataCid, expectedDataSize, actualDataCid, actualDataSize) { if (expectedDataCid !== actualDataCid) { throw new DwnError(DwnErrorCode.RecordsWriteDataCidMismatch, `actual data CID ${actualDataCid} does not match dataCid in descriptor: ${expectedDataCid}`); } if (expectedDataSize !== actualDataSize) { throw new DwnError(DwnErrorCode.RecordsWriteDataSizeMismatch, `actual data size ${actualDataSize} bytes does not match dataSize in descriptor: ${expectedDataSize}`); } } static authorizeRecordsWrite(tenant, recordsWrite, messageStore) { return __awaiter46(this, void 0, void 0, function* () { if (recordsWrite.owner !== void 0 && recordsWrite.owner !== tenant) { throw new DwnError(DwnErrorCode.RecordsWriteOwnerAndTenantMismatch, `Owner ${recordsWrite.owner} must be the same as tenant ${tenant} when specified.`); } if (recordsWrite.isSignedByAuthorDelegate) { yield recordsWrite.authorizeAuthorDelegate(messageStore); } if (recordsWrite.isSignedByOwnerDelegate) { yield recordsWrite.authorizeOwnerDelegate(messageStore); } if (recordsWrite.owner !== void 0) { return; } else if (recordsWrite.author === tenant) { return; } else if (recordsWrite.author !== void 0 && recordsWrite.signaturePayload.permissionGrantId !== void 0) { const permissionGrant = yield PermissionsProtocol.fetchGrant(tenant, messageStore, recordsWrite.signaturePayload.permissionGrantId); yield RecordsGrantAuthorization.authorizeWrite({ recordsWriteMessage: recordsWrite.message, expectedGrantor: tenant, expectedGrantee: recordsWrite.author, permissionGrant, messageStore }); } else if (recordsWrite.message.descriptor.protocol !== void 0) { yield ProtocolAuthorization.authorizeWrite(tenant, recordsWrite, messageStore); } else { throw new DwnError(DwnErrorCode.RecordsWriteAuthorizationFailed, "message failed authorization"); } }); } }; // dist/esm/src/dwn.js var import_dids = require("@web5/dids"); var __awaiter47 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var Dwn = class { constructor(config) { this.didResolver = config.didResolver; this.tenantGate = config.tenantGate; this.eventStream = config.eventStream; this.messageStore = config.messageStore; this.dataStore = config.dataStore; this.eventLog = config.eventLog; this.eventStream = config.eventStream; this.methodHandlers = { [DwnInterfaceName.Events + DwnMethodName.Get]: new EventsGetHandler(this.didResolver, this.eventLog), [DwnInterfaceName.Events + DwnMethodName.Query]: new EventsQueryHandler(this.didResolver, this.eventLog), [DwnInterfaceName.Events + DwnMethodName.Subscribe]: new EventsSubscribeHandler(this.didResolver, this.eventStream), [DwnInterfaceName.Messages + DwnMethodName.Get]: new MessagesGetHandler(this.didResolver, this.messageStore, this.dataStore), [DwnInterfaceName.Protocols + DwnMethodName.Configure]: new ProtocolsConfigureHandler(this.didResolver, this.messageStore, this.eventLog, this.eventStream), [DwnInterfaceName.Protocols + DwnMethodName.Query]: new ProtocolsQueryHandler(this.didResolver, this.messageStore, this.dataStore), [DwnInterfaceName.Records + DwnMethodName.Delete]: new RecordsDeleteHandler(this.didResolver, this.messageStore, this.dataStore, this.eventLog, this.eventStream), [DwnInterfaceName.Records + DwnMethodName.Query]: new RecordsQueryHandler(this.didResolver, this.messageStore, this.dataStore), [DwnInterfaceName.Records + DwnMethodName.Read]: new RecordsReadHandler(this.didResolver, this.messageStore, this.dataStore), [DwnInterfaceName.Records + DwnMethodName.Subscribe]: new RecordsSubscribeHandler(this.didResolver, this.messageStore, this.eventStream), [DwnInterfaceName.Records + DwnMethodName.Write]: new RecordsWriteHandler(this.didResolver, this.messageStore, this.dataStore, this.eventLog, this.eventStream) }; } /** * Creates an instance of the DWN. */ static create(config) { var _a, _b; return __awaiter47(this, void 0, void 0, function* () { (_a = config.didResolver) !== null && _a !== void 0 ? _a : config.didResolver = new import_dids.UniversalResolver({ didResolvers: [import_dids.DidDht, import_dids.DidIon, import_dids.DidKey], cache: new import_dids.DidResolverCacheLevel({ location: "RESOLVERCACHE" }) }); (_b = config.tenantGate) !== null && _b !== void 0 ? _b : config.tenantGate = new AllowAllTenantGate(); const dwn = new Dwn(config); yield dwn.open(); return dwn; }); } open() { var _a; return __awaiter47(this, void 0, void 0, function* () { yield this.messageStore.open(); yield this.dataStore.open(); yield this.eventLog.open(); yield (_a = this.eventStream) === null || _a === void 0 ? void 0 : _a.open(); }); } close() { var _a; return __awaiter47(this, void 0, void 0, function* () { yield (_a = this.eventStream) === null || _a === void 0 ? void 0 : _a.close(); yield this.messageStore.close(); yield this.dataStore.close(); yield this.eventLog.close(); }); } processMessage(tenant, rawMessage, options = {}) { var _a; return __awaiter47(this, void 0, void 0, function* () { const errorMessageReply = (_a = yield this.validateTenant(tenant)) !== null && _a !== void 0 ? _a : yield this.validateMessageIntegrity(rawMessage); if (errorMessageReply !== void 0) { return errorMessageReply; } const { dataStream, subscriptionHandler } = options; const handlerKey = rawMessage.descriptor.interface + rawMessage.descriptor.method; const methodHandlerReply = yield this.methodHandlers[handlerKey].handle({ tenant, message: rawMessage, dataStream, subscriptionHandler }); return methodHandlerReply; }); } /** * Checks tenant gate to see if tenant is allowed. * @param tenant The tenant DID to route the given message to. * @returns GenericMessageReply if the message has an integrity error, otherwise undefined. */ validateTenant(tenant) { var _a; return __awaiter47(this, void 0, void 0, function* () { const result = yield this.tenantGate.isActiveTenant(tenant); if (!result.isActiveTenant) { const detail = (_a = result.detail) !== null && _a !== void 0 ? _a : `DID ${tenant} is not an active tenant.`; return { status: { code: 401, detail } }; } }); } /** * Validates structure of DWN message * @param tenant The tenant DID to route the given message to. * @param dwnMessageInterface The interface of DWN message. * @param dwnMessageMethod The interface of DWN message. * @returns GenericMessageReply if the message has an integrity error, otherwise undefined. */ validateMessageIntegrity(rawMessage) { var _a, _b; return __awaiter47(this, void 0, void 0, function* () { const dwnInterface = (_a = rawMessage === null || rawMessage === void 0 ? void 0 : rawMessage.descriptor) === null || _a === void 0 ? void 0 : _a.interface; const dwnMethod = (_b = rawMessage === null || rawMessage === void 0 ? void 0 : rawMessage.descriptor) === null || _b === void 0 ? void 0 : _b.method; if (dwnInterface === void 0 || dwnMethod === void 0) { return { status: { code: 400, detail: `Both interface and method must be present, interface: ${dwnInterface}, method: ${dwnMethod}` } }; } try { Message.validateJsonSchema(rawMessage); } catch (error) { return messageReplyFromError(error, 400); } }); } }; // dist/esm/src/utils/abort.js var __awaiter48 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; function promisifySignal(signal) { return new Promise((resolve5, reject) => { if (signal.aborted) { reject(signal.reason); return; } signal.addEventListener("abort", () => { reject(signal.reason); }); }); } function executeUnlessAborted(promise, signal) { return __awaiter48(this, void 0, void 0, function* () { if (!signal) { return promise; } return Promise.race([ promise, promisifySignal(signal) ]); }); } // dist/esm/src/utils/protocols.js var __awaiter49 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var Protocols = class { /** * Derives public encryptions keys and inject it in the `$encryption` property for each protocol path segment of the given Protocol definition, * then returns the final encryption-enabled protocol definition. * NOTE: The original definition passed in is unmodified. */ static deriveAndInjectPublicEncryptionKeys(protocolDefinition, rootKeyId, privateJwk) { return __awaiter49(this, void 0, void 0, function* () { const encryptionEnabledProtocolDefinition = JSON.parse(JSON.stringify(protocolDefinition)); function addEncryptionProperty(ruleSet, parentKey) { return __awaiter49(this, void 0, void 0, function* () { for (const key in ruleSet) { if (!key.startsWith("$")) { const derivedPrivateKey = yield HdKey.derivePrivateKey(parentKey, [key]); const publicKeyJwk = yield Secp256k1.getPublicJwk(derivedPrivateKey.derivedPrivateKey); ruleSet[key].$encryption = { rootKeyId, publicKeyJwk }; yield addEncryptionProperty(ruleSet[key], derivedPrivateKey); } } }); } const rootKey = { derivationScheme: KeyDerivationScheme.ProtocolPath, derivedPrivateKey: privateJwk, rootKeyId }; const protocolLevelDerivedKey = yield HdKey.derivePrivateKey(rootKey, [KeyDerivationScheme.ProtocolPath, protocolDefinition.protocol]); yield addEncryptionProperty(encryptionEnabledProtocolDefinition.structure, protocolLevelDerivedKey); return encryptionEnabledProtocolDefinition; }); } }; // dist/esm/src/store/level-wrapper.js var import_level = require("level"); var __awaiter50 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __await2 = function(v) { return this instanceof __await2 ? (this.v = v, this) : new __await2(v); }; var __asyncValues3 = function(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i); function verb(n) { i[n] = o[n] && function(v) { return new Promise(function(resolve5, reject) { v = o[n](v), settle(resolve5, reject, v.done, v.value); }); }; } function settle(resolve5, reject, d, v) { Promise.resolve(v).then(function(v2) { resolve5({ value: v2, done: d }); }, reject); } }; var __asyncGenerator2 = function(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i; function verb(n) { if (g[n]) i[n] = function(v) { return new Promise(function(a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await2 ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; function createLevelDatabase(location, options) { return __awaiter50(this, void 0, void 0, function* () { return new import_level.Level(location, Object.assign(Object.assign({}, options), { keyEncoding: "utf8" })); }); } var LevelWrapper = class { /** * @param config.location - must be a directory path (relative or absolute) where `Level`` will * store its files, or in browsers, the name of the {@link https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase `IDBDatabase`} * to be opened. */ constructor(config, db) { this.config = Object.assign({ createLevelDatabase }, config); this.db = db; } open() { return __awaiter50(this, void 0, void 0, function* () { yield this.createLevelDatabase(); switch (this.db.status) { case "open": return; case "opening": return new Promise((resolve5) => { this.db.once("open", resolve5); }); case "closing": return new Promise((resolve5, reject) => { const onClosed = () => { this.db.open().then(resolve5).catch(reject); ; }; this.db.once("closed", onClosed); }); case "closed": return this.db.open(); } }); } close() { return __awaiter50(this, void 0, void 0, function* () { if (!this.db) { return; } switch (this.db.status) { case "open": return this.db.close(); case "opening": return new Promise((resolve5, reject) => { const onOpen = () => { this.db.close().then(resolve5).catch(reject); ; }; this.db.once("open", onOpen); }); case "closing": return new Promise((resolve5) => { this.db.once("closed", resolve5); }); case "closed": return; } }); } partition(name5) { return __awaiter50(this, void 0, void 0, function* () { yield this.createLevelDatabase(); return new LevelWrapper(this.config, this.db.sublevel(name5, { keyEncoding: "utf8", valueEncoding: this.config.valueEncoding })); }); } get(key, options) { var _a; return __awaiter50(this, void 0, void 0, function* () { (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted(); yield executeUnlessAborted(this.createLevelDatabase(), options === null || options === void 0 ? void 0 : options.signal); try { const value = yield executeUnlessAborted(this.db.get(String(key)), options === null || options === void 0 ? void 0 : options.signal); return value; } catch (error) { const e = error; if (e.code === "LEVEL_NOT_FOUND") { return void 0; } else { throw error; } } }); } has(key, options) { return __awaiter50(this, void 0, void 0, function* () { return !!(yield this.get(key, options)); }); } keys(options) { var _a, _b; return __asyncGenerator2(this, arguments, function* keys_1() { var _c, e_1, _d, _e; (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted(); yield __await2(executeUnlessAborted(this.createLevelDatabase(), options === null || options === void 0 ? void 0 : options.signal)); try { for (var _f = true, _g = __asyncValues3(this.db.keys()), _h; _h = yield __await2(_g.next()), _c = _h.done, !_c; _f = true) { _e = _h.value; _f = false; const key = _e; (_b = options === null || options === void 0 ? void 0 : options.signal) === null || _b === void 0 ? void 0 : _b.throwIfAborted(); yield yield __await2(key); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (!_f && !_c && (_d = _g.return)) yield __await2(_d.call(_g)); } finally { if (e_1) throw e_1.error; } } }); } iterator(iteratorOptions, options) { var _a, _b; return __asyncGenerator2(this, arguments, function* iterator_1() { var _c, e_2, _d, _e; (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted(); yield __await2(executeUnlessAborted(this.createLevelDatabase(), options === null || options === void 0 ? void 0 : options.signal)); try { for (var _f = true, _g = __asyncValues3(this.db.iterator(iteratorOptions)), _h; _h = yield __await2(_g.next()), _c = _h.done, !_c; _f = true) { _e = _h.value; _f = false; const entry = _e; (_b = options === null || options === void 0 ? void 0 : options.signal) === null || _b === void 0 ? void 0 : _b.throwIfAborted(); yield yield __await2(entry); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (!_f && !_c && (_d = _g.return)) yield __await2(_d.call(_g)); } finally { if (e_2) throw e_2.error; } } }); } put(key, value, options) { var _a; return __awaiter50(this, void 0, void 0, function* () { (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted(); yield executeUnlessAborted(this.createLevelDatabase(), options === null || options === void 0 ? void 0 : options.signal); return executeUnlessAborted(this.db.put(String(key), value), options === null || options === void 0 ? void 0 : options.signal); }); } delete(key, options) { var _a; return __awaiter50(this, void 0, void 0, function* () { (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted(); yield executeUnlessAborted(this.createLevelDatabase(), options === null || options === void 0 ? void 0 : options.signal); return executeUnlessAborted(this.db.del(String(key)), options === null || options === void 0 ? void 0 : options.signal); }); } isEmpty(options) { var _a, e_3, _b, _c; return __awaiter50(this, void 0, void 0, function* () { try { for (var _d = true, _e = __asyncValues3(this.keys(options)), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) { _c = _f.value; _d = false; const _key = _c; return false; } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (!_d && !_a && (_b = _e.return)) yield _b.call(_e); } finally { if (e_3) throw e_3.error; } } return true; }); } clear() { return __awaiter50(this, void 0, void 0, function* () { yield this.createLevelDatabase(); yield this.db.clear(); yield this.compactUnderlyingStorage(); }); } batch(operations, options) { var _a; return __awaiter50(this, void 0, void 0, function* () { (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted(); yield executeUnlessAborted(this.createLevelDatabase(), options === null || options === void 0 ? void 0 : options.signal); return executeUnlessAborted(this.db.batch(operations), options === null || options === void 0 ? void 0 : options.signal); }); } /** * Wraps the given LevelWrapperBatchOperation as an operation for the specified partition. */ createPartitionOperation(partitionName, operation) { return Object.assign(Object.assign({}, operation), { sublevel: this.db.sublevel(partitionName, { keyEncoding: "utf8", valueEncoding: this.config.valueEncoding }) }); } compactUnderlyingStorage(options) { var _a, _b, _c; return __awaiter50(this, void 0, void 0, function* () { (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted(); yield executeUnlessAborted(this.createLevelDatabase(), options === null || options === void 0 ? void 0 : options.signal); const range = this.sublevelRange; if (!range) { return; } const root = this.root; if (root.db.supports.additionalMethods.compactRange) { return executeUnlessAborted((_c = (_b = root.db).compactRange) === null || _c === void 0 ? void 0 : _c.call(_b, ...range), options === null || options === void 0 ? void 0 : options.signal); } }); } /** * Gets the min and max key value of this partition. */ get sublevelRange() { const prefix = this.db.prefix; if (!prefix) { return void 0; } const maxKey = prefix.slice(0, -1) + String.fromCharCode(prefix.charCodeAt(prefix.length - 1) + 1); const minKey = prefix; return [minKey, maxKey]; } get root() { let db = this.db; for (const parent = db.db; parent && parent !== db; ) { db = parent; } return new LevelWrapper(this.config, db); } createLevelDatabase() { var _a; return __awaiter50(this, void 0, void 0, function* () { (_a = this.db) !== null && _a !== void 0 ? _a : this.db = yield this.config.createLevelDatabase(this.config.location, { keyEncoding: "utf8", valueEncoding: this.config.valueEncoding }); }); } }; // dist/esm/src/store/blockstore-level.js var __awaiter51 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __asyncValues4 = function(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i); function verb(n) { i[n] = o[n] && function(v) { return new Promise(function(resolve5, reject) { v = o[n](v), settle(resolve5, reject, v.done, v.value); }); }; } function settle(resolve5, reject, d, v) { Promise.resolve(v).then(function(v2) { resolve5({ value: v2, done: d }); }, reject); } }; var __await3 = function(v) { return this instanceof __await3 ? (this.v = v, this) : new __await3(v); }; var __asyncGenerator3 = function(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i; function verb(n) { if (g[n]) i[n] = function(v) { return new Promise(function(a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await3 ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var BlockstoreLevel = class { constructor(config, db) { this.config = Object.assign({ createLevelDatabase }, config); this.db = db !== null && db !== void 0 ? db : new LevelWrapper(Object.assign(Object.assign({}, this.config), { valueEncoding: "binary" })); } open() { return __awaiter51(this, void 0, void 0, function* () { return this.db.open(); }); } close() { return __awaiter51(this, void 0, void 0, function* () { return this.db.close(); }); } partition(name5) { return __awaiter51(this, void 0, void 0, function* () { const db = yield this.db.partition(name5); return new BlockstoreLevel(Object.assign(Object.assign({}, this.config), { location: "" }), db); }); } put(key, val, options) { return __awaiter51(this, void 0, void 0, function* () { yield this.db.put(String(key), val, options); return CID.parse(key.toString()); }); } get(key, options) { return __awaiter51(this, void 0, void 0, function* () { const result = yield this.db.get(String(key), options); return result; }); } has(key, options) { return __awaiter51(this, void 0, void 0, function* () { return this.db.has(String(key), options); }); } delete(key, options) { return __awaiter51(this, void 0, void 0, function* () { return this.db.delete(String(key), options); }); } isEmpty(options) { return __awaiter51(this, void 0, void 0, function* () { return this.db.isEmpty(options); }); } putMany(source, options) { return __asyncGenerator3(this, arguments, function* putMany_1() { var _a, e_1, _b, _c; try { for (var _d = true, source_1 = __asyncValues4(source), source_1_1; source_1_1 = yield __await3(source_1.next()), _a = source_1_1.done, !_a; _d = true) { _c = source_1_1.value; _d = false; const entry = _c; yield __await3(this.put(entry.cid, entry.block, options)); yield yield __await3(entry.cid); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (!_d && !_a && (_b = source_1.return)) yield __await3(_b.call(source_1)); } finally { if (e_1) throw e_1.error; } } }); } getMany(source, options) { return __asyncGenerator3(this, arguments, function* getMany_1() { var _a, e_2, _b, _c; try { for (var _d = true, source_2 = __asyncValues4(source), source_2_1; source_2_1 = yield __await3(source_2.next()), _a = source_2_1.done, !_a; _d = true) { _c = source_2_1.value; _d = false; const key = _c; yield yield __await3({ cid: key, block: yield __await3(this.get(key, options)) }); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (!_d && !_a && (_b = source_2.return)) yield __await3(_b.call(source_2)); } finally { if (e_2) throw e_2.error; } } }); } getAll(options) { return __asyncGenerator3(this, arguments, function* getAll_1() { var _a, e_3, _b, _c; const li = this.db.iterator({ keys: true, keyEncoding: "buffer" }, options); try { for (var _d = true, li_1 = __asyncValues4(li), li_1_1; li_1_1 = yield __await3(li_1.next()), _a = li_1_1.done, !_a; _d = true) { _c = li_1_1.value; _d = false; const [key, value] = _c; yield yield __await3({ cid: CID.decode(key), block: value }); } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (!_d && !_a && (_b = li_1.return)) yield __await3(_b.call(li_1)); } finally { if (e_3) throw e_3.error; } } }); } deleteMany(source, options) { return __asyncGenerator3(this, arguments, function* deleteMany_1() { var _a, e_4, _b, _c; try { for (var _d = true, source_3 = __asyncValues4(source), source_3_1; source_3_1 = yield __await3(source_3.next()), _a = source_3_1.done, !_a; _d = true) { _c = source_3_1.value; _d = false; const key = _c; yield __await3(this.delete(key, options)); yield yield __await3(key); } } catch (e_4_1) { e_4 = { error: e_4_1 }; } finally { try { if (!_d && !_a && (_b = source_3.return)) yield __await3(_b.call(source_3)); } finally { if (e_4) throw e_4.error; } } }); } /** * deletes all entries */ clear() { return __awaiter51(this, void 0, void 0, function* () { return this.db.clear(); }); } }; // node_modules/ipfs-unixfs-exporter/dist/src/index.js var import_err_code12 = __toESM(require_err_code(), 1); // node_modules/it-last/dist/src/index.js function isAsyncIterable3(thing) { return thing[Symbol.asyncIterator] != null; } function last(source) { if (isAsyncIterable3(source)) { return (async () => { let res2; for await (const entry of source) { res2 = entry; } return res2; })(); } let res; for (const entry of source) { res = entry; } return res; } var src_default4 = last; // node_modules/ipfs-unixfs-exporter/dist/src/resolvers/index.js var import_err_code11 = __toESM(require_err_code(), 1); // node_modules/ipfs-unixfs-exporter/dist/src/resolvers/dag-cbor.js var import_err_code5 = __toESM(require_err_code(), 1); var resolve = async (cid, name5, path, toResolve, resolve5, depth, blockstore, options) => { const block = await blockstore.get(cid, options); const object = decode12(block); let subObject = object; let subPath = path; while (toResolve.length > 0) { const prop = toResolve[0]; if (prop in subObject) { toResolve.shift(); subPath = `${subPath}/${prop}`; const subObjectCid = CID.asCID(subObject[prop]); if (subObjectCid != null) { return { entry: { type: "object", name: name5, path, cid, node: block, depth, size: BigInt(block.length), content: async function* () { yield object; } }, next: { cid: subObjectCid, name: prop, path: subPath, toResolve } }; } subObject = subObject[prop]; } else { throw (0, import_err_code5.default)(new Error(`No property named ${prop} found in cbor node ${cid}`), "ERR_NO_PROP"); } } return { entry: { type: "object", name: name5, path, cid, node: block, depth, size: BigInt(block.length), content: async function* () { yield object; } } }; }; var dag_cbor_default = resolve; // node_modules/ipfs-unixfs-exporter/dist/src/resolvers/identity.js var import_err_code7 = __toESM(require_err_code(), 1); // node_modules/ipfs-unixfs-exporter/dist/src/utils/extract-data-from-block.js function extractDataFromBlock(block, blockStart, requestedStart, requestedEnd) { const blockLength = BigInt(block.length); const blockEnd = BigInt(blockStart + blockLength); if (requestedStart >= blockEnd || requestedEnd < blockStart) { return new Uint8Array(0); } if (requestedEnd >= blockStart && requestedEnd < blockEnd) { block = block.subarray(0, Number(requestedEnd - blockStart)); } if (requestedStart >= blockStart && requestedStart < blockEnd) { block = block.subarray(Number(requestedStart - blockStart)); } return block; } var extract_data_from_block_default = extractDataFromBlock; // node_modules/ipfs-unixfs-exporter/dist/src/utils/validate-offset-and-length.js var import_err_code6 = __toESM(require_err_code(), 1); var validateOffsetAndLength = (size, offset = 0, length5 = size) => { const fileSize = BigInt(size); const start = BigInt(offset ?? 0); let end = BigInt(length5); if (end !== fileSize) { end = start + end; } if (end > fileSize) { end = fileSize; } if (start < 0n) { throw (0, import_err_code6.default)(new Error("Offset must be greater than or equal to 0"), "ERR_INVALID_PARAMS"); } if (start > fileSize) { throw (0, import_err_code6.default)(new Error("Offset must be less than the file size"), "ERR_INVALID_PARAMS"); } if (end < 0n) { throw (0, import_err_code6.default)(new Error("Length must be greater than or equal to 0"), "ERR_INVALID_PARAMS"); } if (end > fileSize) { throw (0, import_err_code6.default)(new Error("Length must be less than the file size"), "ERR_INVALID_PARAMS"); } return { start, end }; }; var validate_offset_and_length_default = validateOffsetAndLength; // node_modules/ipfs-unixfs-exporter/dist/src/resolvers/identity.js var rawContent = (node) => { async function* contentGenerator(options = {}) { const { start, end } = validate_offset_and_length_default(node.length, options.offset, options.length); const buf2 = extract_data_from_block_default(node, 0n, start, end); options.onProgress?.(new CustomProgressEvent("unixfs:exporter:progress:identity", { bytesRead: BigInt(buf2.byteLength), totalBytes: end - start, fileSize: BigInt(node.byteLength) })); yield buf2; } return contentGenerator; }; var resolve2 = async (cid, name5, path, toResolve, resolve5, depth, blockstore, options) => { if (toResolve.length > 0) { throw (0, import_err_code7.default)(new Error(`No link named ${path} found in raw node ${cid}`), "ERR_NOT_FOUND"); } const buf2 = decode4(cid.multihash.bytes); return { entry: { type: "identity", name: name5, path, cid, content: rawContent(buf2.digest), depth, size: BigInt(buf2.digest.length), node: buf2.digest } }; }; var identity_default = resolve2; // node_modules/ipfs-unixfs-exporter/dist/src/resolvers/raw.js var import_err_code8 = __toESM(require_err_code(), 1); var rawContent2 = (node) => { async function* contentGenerator(options = {}) { const { start, end } = validate_offset_and_length_default(node.length, options.offset, options.length); const buf2 = extract_data_from_block_default(node, 0n, start, end); options.onProgress?.(new CustomProgressEvent("unixfs:exporter:progress:raw", { bytesRead: BigInt(buf2.byteLength), totalBytes: end - start, fileSize: BigInt(node.byteLength) })); yield buf2; } return contentGenerator; }; var resolve3 = async (cid, name5, path, toResolve, resolve5, depth, blockstore, options) => { if (toResolve.length > 0) { throw (0, import_err_code8.default)(new Error(`No link named ${path} found in raw node ${cid}`), "ERR_NOT_FOUND"); } const block = await blockstore.get(cid, options); return { entry: { type: "raw", name: name5, path, cid, content: rawContent2(block), depth, size: BigInt(block.length), node: block } }; }; var raw_default = resolve3; // node_modules/ipfs-unixfs-exporter/dist/src/resolvers/unixfs-v1/index.js var import_err_code10 = __toESM(require_err_code(), 1); // node_modules/ipfs-unixfs-exporter/dist/src/utils/find-cid-in-shard.js var hashFn = async function(buf2) { return (await murmur3128.encode(buf2)).slice(0, 8).reverse(); }; var addLinksToHamtBucket = async (links2, bucket, rootBucket) => { await Promise.all(links2.map(async (link) => { if (link.Name == null) { throw new Error("Unexpected Link without a Name"); } if (link.Name.length === 2) { const pos = parseInt(link.Name, 16); bucket._putObjectAt(pos, new Bucket({ hash: rootBucket._options.hash, bits: rootBucket._options.bits }, bucket, pos)); return; } await rootBucket.put(link.Name.substring(2), true); })); }; var toPrefix = (position) => { return position.toString(16).toUpperCase().padStart(2, "0").substring(0, 2); }; var toBucketPath = (position) => { let bucket = position.bucket; const path = []; while (bucket._parent != null) { path.push(bucket); bucket = bucket._parent; } path.push(bucket); return path.reverse(); }; var findShardCid = async (node, name5, blockstore, context, options) => { if (context == null) { const rootBucket = createHAMT({ hashFn }); context = { rootBucket, hamtDepth: 1, lastBucket: rootBucket }; } await addLinksToHamtBucket(node.Links, context.lastBucket, context.rootBucket); const position = await context.rootBucket._findNewBucketAndPos(name5); let prefix = toPrefix(position.pos); const bucketPath = toBucketPath(position); if (bucketPath.length > context.hamtDepth) { context.lastBucket = bucketPath[context.hamtDepth]; prefix = toPrefix(context.lastBucket._posAtParent); } const link = node.Links.find((link2) => { if (link2.Name == null) { return false; } const entryPrefix = link2.Name.substring(0, 2); const entryName = link2.Name.substring(2); if (entryPrefix !== prefix) { return false; } if (entryName !== "" && entryName !== name5) { return false; } return true; }); if (link == null) { return; } if (link.Name != null && link.Name.substring(2) === name5) { return link.Hash; } context.hamtDepth++; const block = await blockstore.get(link.Hash, options); node = decode17(block); return findShardCid(node, name5, blockstore, context, options); }; var find_cid_in_shard_default = findShardCid; // node_modules/it-peekable/dist/src/index.js function peekable(iterable) { const [iterator, symbol2] = iterable[Symbol.asyncIterator] != null ? [iterable[Symbol.asyncIterator](), Symbol.asyncIterator] : [iterable[Symbol.iterator](), Symbol.iterator]; const queue = []; return { peek: () => { return iterator.next(); }, push: (value) => { queue.push(value); }, next: () => { if (queue.length > 0) { return { done: false, value: queue.shift() }; } return iterator.next(); }, [symbol2]() { return this; } }; } var src_default5 = peekable; // node_modules/it-filter/dist/src/index.js function isAsyncIterable4(thing) { return thing[Symbol.asyncIterator] != null; } function filter(source, fn) { if (isAsyncIterable4(source)) { return async function* () { for await (const entry of source) { if (await fn(entry)) { yield entry; } } }(); } const peekable2 = src_default5(source); const { value, done } = peekable2.next(); if (done === true) { return function* () { }(); } const res = fn(value); if (typeof res.then === "function") { return async function* () { if (await res) { yield value; } for await (const entry of peekable2) { if (await fn(entry)) { yield entry; } } }(); } const func = fn; return function* () { if (res === true) { yield value; } for (const entry of peekable2) { if (func(entry)) { yield entry; } } }(); } var src_default6 = filter; // node_modules/it-map/dist/src/index.js function isAsyncIterable5(thing) { return thing[Symbol.asyncIterator] != null; } function map(source, func) { if (isAsyncIterable5(source)) { return async function* () { for await (const val of source) { yield func(val); } }(); } const peekable2 = src_default5(source); const { value, done } = peekable2.next(); if (done === true) { return function* () { }(); } const res = func(value); if (typeof res.then === "function") { return async function* () { yield await res; for await (const val of peekable2) { yield func(val); } }(); } const fn = func; return function* () { yield res; for (const val of peekable2) { yield fn(val); } }(); } var src_default7 = map; // node_modules/p-defer/index.js function pDefer() { const deferred = {}; deferred.promise = new Promise((resolve5, reject) => { deferred.resolve = resolve5; deferred.reject = reject; }); return deferred; } // node_modules/it-parallel/dist/src/index.js var CustomEvent = globalThis.CustomEvent ?? Event; async function* parallel(source, options = {}) { let concurrency = options.concurrency ?? Infinity; if (concurrency < 1) { concurrency = Infinity; } const ordered = options.ordered == null ? false : options.ordered; const emitter = new EventTarget(); const ops = []; let slotAvailable = pDefer(); let resultAvailable = pDefer(); let sourceFinished = false; let sourceErr; let opErred = false; emitter.addEventListener("task-complete", () => { resultAvailable.resolve(); }); void Promise.resolve().then(async () => { try { for await (const task of source) { if (ops.length === concurrency) { slotAvailable = pDefer(); await slotAvailable.promise; } if (opErred) { break; } const op = { done: false }; ops.push(op); task().then((result) => { op.done = true; op.ok = true; op.value = result; emitter.dispatchEvent(new CustomEvent("task-complete")); }, (err3) => { op.done = true; op.err = err3; emitter.dispatchEvent(new CustomEvent("task-complete")); }); } sourceFinished = true; emitter.dispatchEvent(new CustomEvent("task-complete")); } catch (err3) { sourceErr = err3; emitter.dispatchEvent(new CustomEvent("task-complete")); } }); function valuesAvailable() { if (ordered) { return ops[0]?.done; } return Boolean(ops.find((op) => op.done)); } function* yieldOrderedValues() { while (ops.length > 0 && ops[0].done) { const op = ops[0]; ops.shift(); if (op.ok) { yield op.value; } else { opErred = true; slotAvailable.resolve(); throw op.err; } slotAvailable.resolve(); } } function* yieldUnOrderedValues() { while (valuesAvailable()) { for (let i = 0; i < ops.length; i++) { if (ops[i].done) { const op = ops[i]; ops.splice(i, 1); i--; if (op.ok) { yield op.value; } else { opErred = true; slotAvailable.resolve(); throw op.err; } slotAvailable.resolve(); } } } } while (true) { if (!valuesAvailable()) { resultAvailable = pDefer(); await resultAvailable.promise; } if (sourceErr != null) { throw sourceErr; } if (ordered) { yield* yieldOrderedValues(); } else { yield* yieldUnOrderedValues(); } if (sourceFinished && ops.length === 0) { break; } } } // node_modules/it-pushable/dist/src/fifo.js var FixedFIFO = class { buffer; mask; top; btm; next; constructor(hwm) { if (!(hwm > 0) || (hwm - 1 & hwm) !== 0) { throw new Error("Max size for a FixedFIFO should be a power of two"); } this.buffer = new Array(hwm); this.mask = hwm - 1; this.top = 0; this.btm = 0; this.next = null; } push(data) { if (this.buffer[this.top] !== void 0) { return false; } this.buffer[this.top] = data; this.top = this.top + 1 & this.mask; return true; } shift() { const last2 = this.buffer[this.btm]; if (last2 === void 0) { return void 0; } this.buffer[this.btm] = void 0; this.btm = this.btm + 1 & this.mask; return last2; } isEmpty() { return this.buffer[this.btm] === void 0; } }; var FIFO = class { size; hwm; head; tail; constructor(options = {}) { this.hwm = options.splitLimit ?? 16; this.head = new FixedFIFO(this.hwm); this.tail = this.head; this.size = 0; } calculateSize(obj) { if (obj?.byteLength != null) { return obj.byteLength; } return 1; } push(val) { if (val?.value != null) { this.size += this.calculateSize(val.value); } if (!this.head.push(val)) { const prev = this.head; this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length); this.head.push(val); } } shift() { let val = this.tail.shift(); if (val === void 0 && this.tail.next != null) { const next = this.tail.next; this.tail.next = null; this.tail = next; val = this.tail.shift(); } if (val?.value != null) { this.size -= this.calculateSize(val.value); } return val; } isEmpty() { return this.head.isEmpty(); } }; // node_modules/it-pushable/dist/src/index.js var AbortError = class extends Error { type; code; constructor(message2, code5) { super(message2 ?? "The operation was aborted"); this.type = "aborted"; this.code = code5 ?? "ABORT_ERR"; } }; function pushable(options = {}) { const getNext = (buffer2) => { const next = buffer2.shift(); if (next == null) { return { done: true }; } if (next.error != null) { throw next.error; } return { done: next.done === true, // @ts-expect-error if done is false, value will be present value: next.value }; }; return _pushable(getNext, options); } function _pushable(getNext, options) { options = options ?? {}; let onEnd = options.onEnd; let buffer2 = new FIFO(); let pushable2; let onNext; let ended; let drain = pDefer(); const waitNext = async () => { try { if (!buffer2.isEmpty()) { return getNext(buffer2); } if (ended) { return { done: true }; } return await new Promise((resolve5, reject) => { onNext = (next) => { onNext = null; buffer2.push(next); try { resolve5(getNext(buffer2)); } catch (err3) { reject(err3); } return pushable2; }; }); } finally { if (buffer2.isEmpty()) { queueMicrotask(() => { drain.resolve(); drain = pDefer(); }); } } }; const bufferNext = (next) => { if (onNext != null) { return onNext(next); } buffer2.push(next); return pushable2; }; const bufferError = (err3) => { buffer2 = new FIFO(); if (onNext != null) { return onNext({ error: err3 }); } buffer2.push({ error: err3 }); return pushable2; }; const push = (value) => { if (ended) { return pushable2; } if (options?.objectMode !== true && value?.byteLength == null) { throw new Error("objectMode was not true but tried to push non-Uint8Array value"); } return bufferNext({ done: false, value }); }; const end = (err3) => { if (ended) return pushable2; ended = true; return err3 != null ? bufferError(err3) : bufferNext({ done: true }); }; const _return = () => { buffer2 = new FIFO(); end(); return { done: true }; }; const _throw = (err3) => { end(err3); return { done: true }; }; pushable2 = { [Symbol.asyncIterator]() { return this; }, next: waitNext, return: _return, throw: _throw, push, end, get readableLength() { return buffer2.size; }, onEmpty: async (options2) => { const signal = options2?.signal; signal?.throwIfAborted(); if (buffer2.isEmpty()) { return; } let cancel; let listener; if (signal != null) { cancel = new Promise((resolve5, reject) => { listener = () => { reject(new AbortError()); }; signal.addEventListener("abort", listener); }); } try { await Promise.race([ drain.promise, cancel ]); } finally { if (listener != null && signal != null) { signal?.removeEventListener("abort", listener); } } } }; if (onEnd == null) { return pushable2; } const _pushable2 = pushable2; pushable2 = { [Symbol.asyncIterator]() { return this; }, next() { return _pushable2.next(); }, throw(err3) { _pushable2.throw(err3); if (onEnd != null) { onEnd(err3); onEnd = void 0; } return { done: true }; }, return() { _pushable2.return(); if (onEnd != null) { onEnd(); onEnd = void 0; } return { done: true }; }, push, end(err3) { _pushable2.end(err3); if (onEnd != null) { onEnd(err3); onEnd = void 0; } return pushable2; }, get readableLength() { return _pushable2.readableLength; } }; return pushable2; } // node_modules/it-merge/dist/src/index.js function isAsyncIterable6(thing) { return thing[Symbol.asyncIterator] != null; } function merge(...sources) { const syncSources = []; for (const source of sources) { if (!isAsyncIterable6(source)) { syncSources.push(source); } } if (syncSources.length === sources.length) { return function* () { for (const source of syncSources) { yield* source; } }(); } return async function* () { const output2 = pushable({ objectMode: true }); void Promise.resolve().then(async () => { try { await Promise.all(sources.map(async (source) => { for await (const item of source) { output2.push(item); } })); output2.end(); } catch (err3) { output2.end(err3); } }); yield* output2; }(); } var src_default8 = merge; // node_modules/it-pipe/dist/src/index.js function pipe(first, ...rest) { if (first == null) { throw new Error("Empty pipeline"); } if (isDuplex(first)) { const duplex = first; first = () => duplex.source; } else if (isIterable2(first) || isAsyncIterable7(first)) { const source = first; first = () => source; } const fns = [first, ...rest]; if (fns.length > 1) { if (isDuplex(fns[fns.length - 1])) { fns[fns.length - 1] = fns[fns.length - 1].sink; } } if (fns.length > 2) { for (let i = 1; i < fns.length - 1; i++) { if (isDuplex(fns[i])) { fns[i] = duplexPipelineFn(fns[i]); } } } return rawPipe(...fns); } var rawPipe = (...fns) => { let res; while (fns.length > 0) { res = fns.shift()(res); } return res; }; var isAsyncIterable7 = (obj) => { return obj?.[Symbol.asyncIterator] != null; }; var isIterable2 = (obj) => { return obj?.[Symbol.iterator] != null; }; var isDuplex = (obj) => { if (obj == null) { return false; } return obj.sink != null && obj.source != null; }; var duplexPipelineFn = (duplex) => { return (source) => { const p = duplex.sink(source); if (p?.then != null) { const stream = pushable({ objectMode: true }); p.then(() => { stream.end(); }, (err3) => { stream.end(err3); }); let sourceWrap; const source2 = duplex.source; if (isAsyncIterable7(source2)) { sourceWrap = async function* () { yield* source2; stream.end(); }; } else if (isIterable2(source2)) { sourceWrap = function* () { yield* source2; stream.end(); }; } else { throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable"); } return src_default8(stream, sourceWrap()); } return duplex.source; }; }; // node_modules/ipfs-unixfs-exporter/dist/src/resolvers/unixfs-v1/content/directory.js var directoryContent = (cid, node, unixfs, path, resolve5, depth, blockstore) => { async function* yieldDirectoryContent(options = {}) { const offset = options.offset ?? 0; const length5 = options.length ?? node.Links.length; const links2 = node.Links.slice(offset, length5); options.onProgress?.(new CustomProgressEvent("unixfs:exporter:walk:directory", { cid })); yield* pipe(links2, (source) => src_default7(source, (link) => { return async () => { const linkName = link.Name ?? ""; const linkPath = `${path}/${linkName}`; const result = await resolve5(link.Hash, linkName, linkPath, [], depth + 1, blockstore, options); return result.entry; }; }), (source) => parallel(source, { ordered: true }), (source) => src_default6(source, (entry) => entry != null)); } return yieldDirectoryContent; }; var directory_default = directoryContent; // node_modules/ipfs-unixfs-exporter/dist/src/resolvers/unixfs-v1/content/file.js var import_err_code9 = __toESM(require_err_code(), 1); // node_modules/p-queue/dist/index.js var import_eventemitter3 = __toESM(require_eventemitter3(), 1); // node_modules/p-timeout/index.js var TimeoutError = class extends Error { constructor(message2) { super(message2); this.name = "TimeoutError"; } }; var AbortError2 = class extends Error { constructor(message2) { super(); this.name = "AbortError"; this.message = message2; } }; var getDOMException = (errorMessage) => globalThis.DOMException === void 0 ? new AbortError2(errorMessage) : new DOMException(errorMessage); var getAbortedReason = (signal) => { const reason = signal.reason === void 0 ? getDOMException("This operation was aborted.") : signal.reason; return reason instanceof Error ? reason : getDOMException(reason); }; function pTimeout(promise, milliseconds, fallback, options) { let timer; const cancelablePromise = new Promise((resolve5, reject) => { if (typeof milliseconds !== "number" || Math.sign(milliseconds) !== 1) { throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``); } if (milliseconds === Number.POSITIVE_INFINITY) { resolve5(promise); return; } options = { customTimers: { setTimeout, clearTimeout }, ...options }; if (options.signal) { const { signal } = options; if (signal.aborted) { reject(getAbortedReason(signal)); } signal.addEventListener("abort", () => { reject(getAbortedReason(signal)); }); } timer = options.customTimers.setTimeout.call(void 0, () => { if (typeof fallback === "function") { try { resolve5(fallback()); } catch (error) { reject(error); } return; } const message2 = typeof fallback === "string" ? fallback : `Promise timed out after ${milliseconds} milliseconds`; const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message2); if (typeof promise.cancel === "function") { promise.cancel(); } reject(timeoutError); }, milliseconds); (async () => { try { resolve5(await promise); } catch (error) { reject(error); } finally { options.customTimers.clearTimeout.call(void 0, timer); } })(); }); cancelablePromise.clear = () => { clearTimeout(timer); timer = void 0; }; return cancelablePromise; } // node_modules/p-queue/dist/lower-bound.js function lowerBound(array, value, comparator) { let first = 0; let count = array.length; while (count > 0) { const step = Math.trunc(count / 2); let it = first + step; if (comparator(array[it], value) <= 0) { first = ++it; count -= step + 1; } else { count = step; } } return first; } // node_modules/p-queue/dist/priority-queue.js var __classPrivateFieldGet = function(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; var _PriorityQueue_queue; var PriorityQueue = class { constructor() { _PriorityQueue_queue.set(this, []); } enqueue(run, options) { options = { priority: 0, ...options }; const element = { priority: options.priority, run }; if (this.size && __classPrivateFieldGet(this, _PriorityQueue_queue, "f")[this.size - 1].priority >= options.priority) { __classPrivateFieldGet(this, _PriorityQueue_queue, "f").push(element); return; } const index = lowerBound(__classPrivateFieldGet(this, _PriorityQueue_queue, "f"), element, (a, b) => b.priority - a.priority); __classPrivateFieldGet(this, _PriorityQueue_queue, "f").splice(index, 0, element); } dequeue() { const item = __classPrivateFieldGet(this, _PriorityQueue_queue, "f").shift(); return item === null || item === void 0 ? void 0 : item.run; } filter(options) { return __classPrivateFieldGet(this, _PriorityQueue_queue, "f").filter((element) => element.priority === options.priority).map((element) => element.run); } get size() { return __classPrivateFieldGet(this, _PriorityQueue_queue, "f").length; } }; _PriorityQueue_queue = /* @__PURE__ */ new WeakMap(); // node_modules/p-queue/dist/index.js var __classPrivateFieldSet = function(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; }; var __classPrivateFieldGet2 = function(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; var _PQueue_instances; var _PQueue_carryoverConcurrencyCount; var _PQueue_isIntervalIgnored; var _PQueue_intervalCount; var _PQueue_intervalCap; var _PQueue_interval; var _PQueue_intervalEnd; var _PQueue_intervalId; var _PQueue_timeoutId; var _PQueue_queue; var _PQueue_queueClass; var _PQueue_pending; var _PQueue_concurrency; var _PQueue_isPaused; var _PQueue_throwOnTimeout; var _PQueue_doesIntervalAllowAnother_get; var _PQueue_doesConcurrentAllowAnother_get; var _PQueue_next; var _PQueue_onResumeInterval; var _PQueue_isIntervalPaused_get; var _PQueue_tryToStartAnother; var _PQueue_initializeIntervalIfNeeded; var _PQueue_onInterval; var _PQueue_processQueue; var _PQueue_throwOnAbort; var _PQueue_onEvent; var AbortError3 = class extends Error { }; var PQueue = class extends import_eventemitter3.default { // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()` constructor(options) { var _a, _b, _c, _d; super(); _PQueue_instances.add(this); _PQueue_carryoverConcurrencyCount.set(this, void 0); _PQueue_isIntervalIgnored.set(this, void 0); _PQueue_intervalCount.set(this, 0); _PQueue_intervalCap.set(this, void 0); _PQueue_interval.set(this, void 0); _PQueue_intervalEnd.set(this, 0); _PQueue_intervalId.set(this, void 0); _PQueue_timeoutId.set(this, void 0); _PQueue_queue.set(this, void 0); _PQueue_queueClass.set(this, void 0); _PQueue_pending.set(this, 0); _PQueue_concurrency.set(this, void 0); _PQueue_isPaused.set(this, void 0); _PQueue_throwOnTimeout.set(this, void 0); Object.defineProperty(this, "timeout", { enumerable: true, configurable: true, writable: true, value: void 0 }); options = { carryoverConcurrencyCount: false, intervalCap: Number.POSITIVE_INFINITY, interval: 0, concurrency: Number.POSITIVE_INFINITY, autoStart: true, queueClass: PriorityQueue, ...options }; if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) { throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ""}\` (${typeof options.intervalCap})`); } if (options.interval === void 0 || !(Number.isFinite(options.interval) && options.interval >= 0)) { throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ""}\` (${typeof options.interval})`); } __classPrivateFieldSet(this, _PQueue_carryoverConcurrencyCount, options.carryoverConcurrencyCount, "f"); __classPrivateFieldSet(this, _PQueue_isIntervalIgnored, options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0, "f"); __classPrivateFieldSet(this, _PQueue_intervalCap, options.intervalCap, "f"); __classPrivateFieldSet(this, _PQueue_interval, options.interval, "f"); __classPrivateFieldSet(this, _PQueue_queue, new options.queueClass(), "f"); __classPrivateFieldSet(this, _PQueue_queueClass, options.queueClass, "f"); this.concurrency = options.concurrency; this.timeout = options.timeout; __classPrivateFieldSet(this, _PQueue_throwOnTimeout, options.throwOnTimeout === true, "f"); __classPrivateFieldSet(this, _PQueue_isPaused, options.autoStart === false, "f"); } get concurrency() { return __classPrivateFieldGet2(this, _PQueue_concurrency, "f"); } set concurrency(newConcurrency) { if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) { throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); } __classPrivateFieldSet(this, _PQueue_concurrency, newConcurrency, "f"); __classPrivateFieldGet2(this, _PQueue_instances, "m", _PQueue_processQueue).call(this); } async add(function_, options = {}) { options = { timeout: this.timeout, throwOnTimeout: __classPrivateFieldGet2(this, _PQueue_throwOnTimeout, "f"), ...options }; return new Promise((resolve5, reject) => { __classPrivateFieldGet2(this, _PQueue_queue, "f").enqueue(async () => { var _a; var _b, _c; __classPrivateFieldSet(this, _PQueue_pending, (_b = __classPrivateFieldGet2(this, _PQueue_pending, "f"), _b++, _b), "f"); __classPrivateFieldSet(this, _PQueue_intervalCount, (_c = __classPrivateFieldGet2(this, _PQueue_intervalCount, "f"), _c++, _c), "f"); try { if ((_a = options.signal) === null || _a === void 0 ? void 0 : _a.aborted) { throw new AbortError3("The task was aborted."); } let operation = function_({ signal: options.signal }); if (options.timeout) { operation = pTimeout(Promise.resolve(operation), options.timeout); } if (options.signal) { operation = Promise.race([operation, __classPrivateFieldGet2(this, _PQueue_instances, "m", _PQueue_throwOnAbort).call(this, options.signal)]); } const result = await operation; resolve5(result); this.emit("completed", result); } catch (error) { if (error instanceof TimeoutError && !options.throwOnTimeout) { resolve5(); return; } reject(error); this.emit("error", error); } finally { __classPrivateFieldGet2(this, _PQueue_instances, "m", _PQueue_next).call(this); } }, options); this.emit("add"); __classPrivateFieldGet2(this, _PQueue_instances, "m", _PQueue_tryToStartAnother).call(this); }); } async addAll(functions, options) { return Promise.all(functions.map(async (function_) => this.add(function_, options))); } /** Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) */ start() { if (!__classPrivateFieldGet2(this, _PQueue_isPaused, "f")) { return this; } __classPrivateFieldSet(this, _PQueue_isPaused, false, "f"); __classPrivateFieldGet2(this, _PQueue_instances, "m", _PQueue_processQueue).call(this); return this; } /** Put queue execution on hold. */ pause() { __classPrivateFieldSet(this, _PQueue_isPaused, true, "f"); } /** Clear the queue. */ clear() { __classPrivateFieldSet(this, _PQueue_queue, new (__classPrivateFieldGet2(this, _PQueue_queueClass, "f"))(), "f"); } /** Can be called multiple times. Useful if you for example add additional items at a later time. @returns A promise that settles when the queue becomes empty. */ async onEmpty() { if (__classPrivateFieldGet2(this, _PQueue_queue, "f").size === 0) { return; } await __classPrivateFieldGet2(this, _PQueue_instances, "m", _PQueue_onEvent).call(this, "empty"); } /** @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`. If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item. Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation. */ async onSizeLessThan(limit) { if (__classPrivateFieldGet2(this, _PQueue_queue, "f").size < limit) { return; } await __classPrivateFieldGet2(this, _PQueue_instances, "m", _PQueue_onEvent).call(this, "next", () => __classPrivateFieldGet2(this, _PQueue_queue, "f").size < limit); } /** The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. */ async onIdle() { if (__classPrivateFieldGet2(this, _PQueue_pending, "f") === 0 && __classPrivateFieldGet2(this, _PQueue_queue, "f").size === 0) { return; } await __classPrivateFieldGet2(this, _PQueue_instances, "m", _PQueue_onEvent).call(this, "idle"); } /** Size of the queue, the number of queued items waiting to run. */ get size() { return __classPrivateFieldGet2(this, _PQueue_queue, "f").size; } /** Size of the queue, filtered by the given options. For example, this can be used to find the number of items remaining in the queue with a specific priority level. */ sizeBy(options) { return __classPrivateFieldGet2(this, _PQueue_queue, "f").filter(options).length; } /** Number of running items (no longer in the queue). */ get pending() { return __classPrivateFieldGet2(this, _PQueue_pending, "f"); } /** Whether the queue is currently paused. */ get isPaused() { return __classPrivateFieldGet2(this, _PQueue_isPaused, "f"); } }; _PQueue_carryoverConcurrencyCount = /* @__PURE__ */ new WeakMap(), _PQueue_isIntervalIgnored = /* @__PURE__ */ new WeakMap(), _PQueue_intervalCount = /* @__PURE__ */ new WeakMap(), _PQueue_intervalCap = /* @__PURE__ */ new WeakMap(), _PQueue_interval = /* @__PURE__ */ new WeakMap(), _PQueue_intervalEnd = /* @__PURE__ */ new WeakMap(), _PQueue_intervalId = /* @__PURE__ */ new WeakMap(), _PQueue_timeoutId = /* @__PURE__ */ new WeakMap(), _PQueue_queue = /* @__PURE__ */ new WeakMap(), _PQueue_queueClass = /* @__PURE__ */ new WeakMap(), _PQueue_pending = /* @__PURE__ */ new WeakMap(), _PQueue_concurrency = /* @__PURE__ */ new WeakMap(), _PQueue_isPaused = /* @__PURE__ */ new WeakMap(), _PQueue_throwOnTimeout = /* @__PURE__ */ new WeakMap(), _PQueue_instances = /* @__PURE__ */ new WeakSet(), _PQueue_doesIntervalAllowAnother_get = function _PQueue_doesIntervalAllowAnother_get2() { return __classPrivateFieldGet2(this, _PQueue_isIntervalIgnored, "f") || __classPrivateFieldGet2(this, _PQueue_intervalCount, "f") < __classPrivateFieldGet2(this, _PQueue_intervalCap, "f"); }, _PQueue_doesConcurrentAllowAnother_get = function _PQueue_doesConcurrentAllowAnother_get2() { return __classPrivateFieldGet2(this, _PQueue_pending, "f") < __classPrivateFieldGet2(this, _PQueue_concurrency, "f"); }, _PQueue_next = function _PQueue_next2() { var _a; __classPrivateFieldSet(this, _PQueue_pending, (_a = __classPrivateFieldGet2(this, _PQueue_pending, "f"), _a--, _a), "f"); __classPrivateFieldGet2(this, _PQueue_instances, "m", _PQueue_tryToStartAnother).call(this); this.emit("next"); }, _PQueue_onResumeInterval = function _PQueue_onResumeInterval2() { __classPrivateFieldGet2(this, _PQueue_instances, "m", _PQueue_onInterval).call(this); __classPrivateFieldGet2(this, _PQueue_instances, "m", _PQueue_initializeIntervalIfNeeded).call(this); __classPrivateFieldSet(this, _PQueue_timeoutId, void 0, "f"); }, _PQueue_isIntervalPaused_get = function _PQueue_isIntervalPaused_get2() { const now = Date.now(); if (__classPrivateFieldGet2(this, _PQueue_intervalId, "f") === void 0) { const delay = __classPrivateFieldGet2(this, _PQueue_intervalEnd, "f") - now; if (delay < 0) { __classPrivateFieldSet(this, _PQueue_intervalCount, __classPrivateFieldGet2(this, _PQueue_carryoverConcurrencyCount, "f") ? __classPrivateFieldGet2(this, _PQueue_pending, "f") : 0, "f"); } else { if (__classPrivateFieldGet2(this, _PQueue_timeoutId, "f") === void 0) { __classPrivateFieldSet(this, _PQueue_timeoutId, setTimeout(() => { __classPrivateFieldGet2(this, _PQueue_instances, "m", _PQueue_onResumeInterval).call(this); }, delay), "f"); } return true; } } return false; }, _PQueue_tryToStartAnother = function _PQueue_tryToStartAnother2() { if (__classPrivateFieldGet2(this, _PQueue_queue, "f").size === 0) { if (__classPrivateFieldGet2(this, _PQueue_intervalId, "f")) { clearInterval(__classPrivateFieldGet2(this, _PQueue_intervalId, "f")); } __classPrivateFieldSet(this, _PQueue_intervalId, void 0, "f"); this.emit("empty"); if (__classPrivateFieldGet2(this, _PQueue_pending, "f") === 0) { this.emit("idle"); } return false; } if (!__classPrivateFieldGet2(this, _PQueue_isPaused, "f")) { const canInitializeInterval = !__classPrivateFieldGet2(this, _PQueue_instances, "a", _PQueue_isIntervalPaused_get); if (__classPrivateFieldGet2(this, _PQueue_instances, "a", _PQueue_doesIntervalAllowAnother_get) && __classPrivateFieldGet2(this, _PQueue_instances, "a", _PQueue_doesConcurrentAllowAnother_get)) { const job = __classPrivateFieldGet2(this, _PQueue_queue, "f").dequeue(); if (!job) { return false; } this.emit("active"); job(); if (canInitializeInterval) { __classPrivateFieldGet2(this, _PQueue_instances, "m", _PQueue_initializeIntervalIfNeeded).call(this); } return true; } } return false; }, _PQueue_initializeIntervalIfNeeded = function _PQueue_initializeIntervalIfNeeded2() { if (__classPrivateFieldGet2(this, _PQueue_isIntervalIgnored, "f") || __classPrivateFieldGet2(this, _PQueue_intervalId, "f") !== void 0) { return; } __classPrivateFieldSet(this, _PQueue_intervalId, setInterval(() => { __classPrivateFieldGet2(this, _PQueue_instances, "m", _PQueue_onInterval).call(this); }, __classPrivateFieldGet2(this, _PQueue_interval, "f")), "f"); __classPrivateFieldSet(this, _PQueue_intervalEnd, Date.now() + __classPrivateFieldGet2(this, _PQueue_interval, "f"), "f"); }, _PQueue_onInterval = function _PQueue_onInterval2() { if (__classPrivateFieldGet2(this, _PQueue_intervalCount, "f") === 0 && __classPrivateFieldGet2(this, _PQueue_pending, "f") === 0 && __classPrivateFieldGet2(this, _PQueue_intervalId, "f")) { clearInterval(__classPrivateFieldGet2(this, _PQueue_intervalId, "f")); __classPrivateFieldSet(this, _PQueue_intervalId, void 0, "f"); } __classPrivateFieldSet(this, _PQueue_intervalCount, __classPrivateFieldGet2(this, _PQueue_carryoverConcurrencyCount, "f") ? __classPrivateFieldGet2(this, _PQueue_pending, "f") : 0, "f"); __classPrivateFieldGet2(this, _PQueue_instances, "m", _PQueue_processQueue).call(this); }, _PQueue_processQueue = function _PQueue_processQueue2() { while (__classPrivateFieldGet2(this, _PQueue_instances, "m", _PQueue_tryToStartAnother).call(this)) { } }, _PQueue_throwOnAbort = async function _PQueue_throwOnAbort2(signal) { return new Promise((_resolve, reject) => { signal.addEventListener("abort", () => { reject(new AbortError3("The task was aborted.")); }, { once: true }); }); }, _PQueue_onEvent = async function _PQueue_onEvent2(event, filter2) { return new Promise((resolve5) => { const listener = () => { if (filter2 && !filter2()) { return; } this.off(event, listener); resolve5(); }; this.on(event, listener); }); }; // node_modules/ipfs-unixfs-exporter/dist/src/resolvers/unixfs-v1/content/file.js async function walkDAG(blockstore, node, queue, streamPosition, start, end, options) { if (node instanceof Uint8Array) { const buf2 = extract_data_from_block_default(node, streamPosition, start, end); queue.push(buf2); return; } if (node.Data == null) { throw (0, import_err_code9.default)(new Error("no data in PBNode"), "ERR_NOT_UNIXFS"); } let file; try { file = UnixFS.unmarshal(node.Data); } catch (err3) { throw (0, import_err_code9.default)(err3, "ERR_NOT_UNIXFS"); } if (file.data != null) { const data = file.data; const buf2 = extract_data_from_block_default(data, streamPosition, start, end); queue.push(buf2); streamPosition += BigInt(buf2.byteLength); } const childOps = []; if (node.Links.length !== file.blockSizes.length) { throw (0, import_err_code9.default)(new Error("Inconsistent block sizes and dag links"), "ERR_NOT_UNIXFS"); } for (let i = 0; i < node.Links.length; i++) { const childLink = node.Links[i]; const childStart = streamPosition; const childEnd = childStart + file.blockSizes[i]; if (start >= childStart && start < childEnd || // child has offset byte end >= childStart && end <= childEnd || // child has end byte start < childStart && end > childEnd) { childOps.push({ link: childLink, blockStart: streamPosition }); } streamPosition = childEnd; if (streamPosition > end) { break; } } await pipe(childOps, (source) => src_default7(source, (op) => { return async () => { const block = await blockstore.get(op.link.Hash, options); return { ...op, block }; }; }), (source) => parallel(source, { ordered: true }), async (source) => { for await (const { link, block, blockStart } of source) { let child; switch (link.Hash.code) { case code4: child = decode17(block); break; case code2: child = block; break; default: queue.end((0, import_err_code9.default)(new Error(`Unsupported codec: ${link.Hash.code}`), "ERR_NOT_UNIXFS")); return; } const childQueue = new PQueue({ concurrency: 1 }); childQueue.on("error", (error) => { queue.end(error); }); void childQueue.add(async () => { options.onProgress?.(new CustomProgressEvent("unixfs:exporter:walk:file", { cid: link.Hash })); await walkDAG(blockstore, child, queue, blockStart, start, end, options); }); await childQueue.onIdle(); } }); if (streamPosition >= end) { queue.end(); } } var fileContent = (cid, node, unixfs, path, resolve5, depth, blockstore) => { async function* yieldFileContent(options = {}) { const fileSize = unixfs.fileSize(); if (fileSize === void 0) { throw new Error("File was a directory"); } const { start, end } = validate_offset_and_length_default(fileSize, options.offset, options.length); if (end === 0n) { return; } let read5 = 0n; const wanted = end - start; const queue = pushable(); options.onProgress?.(new CustomProgressEvent("unixfs:exporter:walk:file", { cid })); void walkDAG(blockstore, node, queue, 0n, start, end, options).catch((err3) => { queue.end(err3); }); for await (const buf2 of queue) { if (buf2 == null) { continue; } read5 += BigInt(buf2.byteLength); if (read5 > wanted) { queue.end(); throw (0, import_err_code9.default)(new Error("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect"), "ERR_OVER_READ"); } if (read5 === wanted) { queue.end(); } options.onProgress?.(new CustomProgressEvent("unixfs:exporter:progress:unixfs:file", { bytesRead: read5, totalBytes: wanted, fileSize })); yield buf2; } if (read5 < wanted) { throw (0, import_err_code9.default)(new Error("Traversed entire DAG but did not read enough bytes"), "ERR_UNDER_READ"); } } return yieldFileContent; }; var file_default = fileContent; // node_modules/ipfs-unixfs-exporter/dist/src/resolvers/unixfs-v1/content/hamt-sharded-directory.js var hamtShardedDirectoryContent = (cid, node, unixfs, path, resolve5, depth, blockstore) => { function yieldHamtDirectoryContent(options = {}) { options.onProgress?.(new CustomProgressEvent("unixfs:exporter:walk:hamt-sharded-directory", { cid })); return listDirectory(node, path, resolve5, depth, blockstore, options); } return yieldHamtDirectoryContent; }; async function* listDirectory(node, path, resolve5, depth, blockstore, options) { const links2 = node.Links; const results = pipe(links2, (source) => src_default7(source, (link) => { return async () => { const name5 = link.Name != null ? link.Name.substring(2) : null; if (name5 != null && name5 !== "") { const result = await resolve5(link.Hash, name5, `${path}/${name5}`, [], depth + 1, blockstore, options); return { entries: result.entry == null ? [] : [result.entry] }; } else { const block = await blockstore.get(link.Hash, options); node = decode17(block); options.onProgress?.(new CustomProgressEvent("unixfs:exporter:walk:hamt-sharded-directory", { cid: link.Hash })); return { entries: listDirectory(node, path, resolve5, depth, blockstore, options) }; } }; }), (source) => parallel(source, { ordered: true })); for await (const { entries } of results) { yield* entries; } } var hamt_sharded_directory_default = hamtShardedDirectoryContent; // node_modules/ipfs-unixfs-exporter/dist/src/resolvers/unixfs-v1/index.js var findLinkCid = (node, name5) => { const link = node.Links.find((link2) => link2.Name === name5); return link?.Hash; }; var contentExporters = { raw: file_default, file: file_default, directory: directory_default, "hamt-sharded-directory": hamt_sharded_directory_default, metadata: (cid, node, unixfs, path, resolve5, depth, blockstore) => { return () => []; }, symlink: (cid, node, unixfs, path, resolve5, depth, blockstore) => { return () => []; } }; var unixFsResolver = async (cid, name5, path, toResolve, resolve5, depth, blockstore, options) => { const block = await blockstore.get(cid, options); const node = decode17(block); let unixfs; let next; if (name5 == null) { name5 = cid.toString(); } if (node.Data == null) { throw (0, import_err_code10.default)(new Error("no data in PBNode"), "ERR_NOT_UNIXFS"); } try { unixfs = UnixFS.unmarshal(node.Data); } catch (err3) { throw (0, import_err_code10.default)(err3, "ERR_NOT_UNIXFS"); } if (path == null) { path = name5; } if (toResolve.length > 0) { let linkCid; if (unixfs?.type === "hamt-sharded-directory") { linkCid = await find_cid_in_shard_default(node, toResolve[0], blockstore); } else { linkCid = findLinkCid(node, toResolve[0]); } if (linkCid == null) { throw (0, import_err_code10.default)(new Error("file does not exist"), "ERR_NOT_FOUND"); } const nextName = toResolve.shift(); const nextPath = `${path}/${nextName}`; next = { cid: linkCid, toResolve, name: nextName ?? "", path: nextPath }; } const content = contentExporters[unixfs.type](cid, node, unixfs, path, resolve5, depth, blockstore); if (content == null) { throw (0, import_err_code10.default)(new Error("could not find content exporter"), "ERR_NOT_FOUND"); } if (unixfs.isDirectory()) { return { entry: { type: "directory", name: name5, path, cid, content, unixfs, depth, node, size: unixfs.fileSize() }, next }; } return { entry: { type: "file", name: name5, path, cid, content, unixfs, depth, node, size: unixfs.fileSize() }, next }; }; var unixfs_v1_default = unixFsResolver; // node_modules/ipfs-unixfs-exporter/dist/src/resolvers/index.js var resolvers = { [code4]: unixfs_v1_default, [code2]: raw_default, [code3]: dag_cbor_default, [identity2.code]: identity_default }; var resolve4 = async (cid, name5, path, toResolve, depth, blockstore, options) => { const resolver = resolvers[cid.code]; if (resolver == null) { throw (0, import_err_code11.default)(new Error(`No resolver for code ${cid.code}`), "ERR_NO_RESOLVER"); } return resolver(cid, name5, path, toResolve, resolve4, depth, blockstore, options); }; var resolvers_default = resolve4; // node_modules/ipfs-unixfs-exporter/dist/src/index.js var toPathComponents2 = (path = "") => { return (path.trim().match(/([^\\^/]|\\\/)+/g) ?? []).filter(Boolean); }; var cidAndRest = (path) => { if (path instanceof Uint8Array) { return { cid: CID.decode(path), toResolve: [] }; } const cid = CID.asCID(path); if (cid != null) { return { cid, toResolve: [] }; } if (typeof path === "string") { if (path.indexOf("/ipfs/") === 0) { path = path.substring(6); } const output2 = toPathComponents2(path); return { cid: CID.parse(output2[0]), toResolve: output2.slice(1) }; } throw (0, import_err_code12.default)(new Error(`Unknown path type ${path}`), "ERR_BAD_PATH"); }; async function* walkPath(path, blockstore, options = {}) { let { cid, toResolve } = cidAndRest(path); let name5 = cid.toString(); let entryPath = name5; const startingDepth = toResolve.length; while (true) { const result = await resolvers_default(cid, name5, entryPath, toResolve, startingDepth, blockstore, options); if (result.entry == null && result.next == null) { throw (0, import_err_code12.default)(new Error(`Could not resolve ${path}`), "ERR_NOT_FOUND"); } if (result.entry != null) { yield result.entry; } if (result.next == null) { return; } toResolve = result.next.toResolve; cid = result.next.cid; name5 = result.next.name; entryPath = result.next.path; } } async function exporter(path, blockstore, options = {}) { const result = await src_default4(walkPath(path, blockstore, options)); if (result == null) { throw (0, import_err_code12.default)(new Error(`Could not resolve ${path}`), "ERR_NOT_FOUND"); } return result; } // dist/esm/src/store/data-store-level.js var import_readable_stream3 = require("readable-stream"); var __awaiter52 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __asyncValues5 = function(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i); function verb(n) { i[n] = o[n] && function(v) { return new Promise(function(resolve5, reject) { v = o[n](v), settle(resolve5, reject, v.done, v.value); }); }; } function settle(resolve5, reject, d, v) { Promise.resolve(v).then(function(v2) { resolve5({ value: v2, done: d }); }, reject); } }; var DataStoreLevel = class { constructor(config = {}) { this.config = Object.assign({ blockstoreLocation: "DATASTORE", createLevelDatabase }, config); this.blockstore = new BlockstoreLevel({ location: this.config.blockstoreLocation, createLevelDatabase: this.config.createLevelDatabase }); } open() { return __awaiter52(this, void 0, void 0, function* () { yield this.blockstore.open(); }); } close() { return __awaiter52(this, void 0, void 0, function* () { yield this.blockstore.close(); }); } put(tenant, recordId, dataCid, dataStream) { var _a, e_1, _b, _c; var _d, _e; return __awaiter52(this, void 0, void 0, function* () { const blockstoreForData = yield this.getBlockstoreForStoringData(tenant, recordId, dataCid); const asyncDataBlocks = importer([{ content: dataStream }], blockstoreForData, { cidVersion: 1 }); let dataDagRoot; try { for (var _f = true, asyncDataBlocks_1 = __asyncValues5(asyncDataBlocks), asyncDataBlocks_1_1; asyncDataBlocks_1_1 = yield asyncDataBlocks_1.next(), _a = asyncDataBlocks_1_1.done, !_a; _f = true) { _c = asyncDataBlocks_1_1.value; _f = false; dataDagRoot = _c; ; } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (!_f && !_a && (_b = asyncDataBlocks_1.return)) yield _b.call(asyncDataBlocks_1); } finally { if (e_1) throw e_1.error; } } return { dataSize: Number((_e = (_d = dataDagRoot.unixfs) === null || _d === void 0 ? void 0 : _d.fileSize()) !== null && _e !== void 0 ? _e : dataDagRoot.size) }; }); } get(tenant, recordId, dataCid) { return __awaiter52(this, void 0, void 0, function* () { const blockstoreForData = yield this.getBlockstoreForStoringData(tenant, recordId, dataCid); const exists3 = yield blockstoreForData.has(dataCid); if (!exists3) { return void 0; } const dataDagRoot = yield exporter(dataCid, blockstoreForData); const contentIterator = dataDagRoot.content(); const dataStream = new import_readable_stream3.Readable({ read() { return __awaiter52(this, void 0, void 0, function* () { const result = yield contentIterator.next(); if (result.done) { this.push(null); } else { this.push(result.value); } }); } }); let dataSize = dataDagRoot.size; if (dataDagRoot.type === "file" || dataDagRoot.type === "directory") { dataSize = dataDagRoot.unixfs.fileSize(); } return { dataSize: Number(dataSize), dataStream }; }); } delete(tenant, recordId, dataCid) { return __awaiter52(this, void 0, void 0, function* () { const blockstoreForData = yield this.getBlockstoreForStoringData(tenant, recordId, dataCid); yield blockstoreForData.clear(); }); } /** * Deletes everything in the store. Mainly used in tests. */ clear() { return __awaiter52(this, void 0, void 0, function* () { yield this.blockstore.clear(); }); } /** * Gets the blockstore used for storing data for the given `tenant -> `recordId` -> `dataCid`. */ getBlockstoreForStoringData(tenant, recordId, dataCid) { return __awaiter52(this, void 0, void 0, function* () { const dataPartitionName = "data"; const blockstoreForData = yield this.blockstore.partition(dataPartitionName); const blockstoreOfGivenTenant = yield blockstoreForData.partition(tenant); const blockstoreOfGivenRecordId = yield blockstoreOfGivenTenant.partition(recordId); const blockstoreOfGivenDataCidOfRecordId = yield blockstoreOfGivenRecordId.partition(dataCid); return blockstoreOfGivenDataCidOfRecordId; }); } }; // dist/esm/src/store/index-level.js var __awaiter53 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __asyncValues6 = function(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i); function verb(n) { i[n] = o[n] && function(v) { return new Promise(function(resolve5, reject) { v = o[n](v), settle(resolve5, reject, v.done, v.value); }); }; } function settle(resolve5, reject, d, v) { Promise.resolve(v).then(function(v2) { resolve5({ value: v2, done: d }); }, reject); } }; var __await4 = function(v) { return this instanceof __await4 ? (this.v = v, this) : new __await4(v); }; var __asyncGenerator4 = function(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { return this; }, i; function verb(n) { if (g[n]) i[n] = function(v) { return new Promise(function(a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await4 ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; var INDEX_SUBLEVEL_NAME = "index"; var IndexLevel = class { constructor(config) { this.config = Object.assign({ createLevelDatabase }, config); this.db = new LevelWrapper({ location: this.config.location, createLevelDatabase: this.config.createLevelDatabase, keyEncoding: "utf8" }); } open() { return __awaiter53(this, void 0, void 0, function* () { yield this.db.open(); }); } close() { return __awaiter53(this, void 0, void 0, function* () { yield this.db.close(); }); } /** * deletes everything in the underlying index db. */ clear() { return __awaiter53(this, void 0, void 0, function* () { yield this.db.clear(); }); } /** * Put an item into the index using information that will allow it to be queried for. * * @param tenant * @param messageCid a unique ID that represents the item being indexed, this is also used as the cursor value in a query. * @param indexes - (key-value pairs) to be included as part of indexing this item. Must include at least one indexing property. * @param options IndexLevelOptions that include an AbortSignal. */ put(tenant, messageCid, indexes, options) { return __awaiter53(this, void 0, void 0, function* () { if (isEmptyObject(indexes)) { throw new DwnError(DwnErrorCode.IndexMissingIndexableProperty, "Index must include at least one valid indexable property"); } const item = { messageCid, indexes }; const opCreationPromises = []; for (const indexName in indexes) { const indexValue = indexes[indexName]; if (Array.isArray(indexValue)) { for (const indexValueItem of indexValue) { const partitionOperationPromise2 = this.createPutIndexedItemOperation(tenant, item, indexName, indexValueItem); opCreationPromises.push(partitionOperationPromise2); } } else { const partitionOperationPromise2 = this.createPutIndexedItemOperation(tenant, item, indexName, indexValue); opCreationPromises.push(partitionOperationPromise2); } } const partitionOperationPromise = this.createOperationForIndexesLookupPartition(tenant, { type: "put", key: messageCid, value: JSON.stringify(indexes) }); opCreationPromises.push(partitionOperationPromise); const indexOps = yield Promise.all(opCreationPromises); const tenantPartition = yield this.db.partition(tenant); yield tenantPartition.batch(indexOps, options); }); } /** * Deletes all of the index data associated with the item. */ delete(tenant, messageCid, options) { return __awaiter53(this, void 0, void 0, function* () { const opCreationPromises = []; const indexes = yield this.getIndexes(tenant, messageCid); if (indexes === void 0) { return; } const partitionOperationPromise = this.createOperationForIndexesLookupPartition(tenant, { type: "del", key: messageCid }); opCreationPromises.push(partitionOperationPromise); for (const indexName in indexes) { const indexValue = indexes[indexName]; if (Array.isArray(indexValue)) { for (const indexValueItem of indexValue) { const partitionOperationPromise2 = this.createDeleteIndexedItemOperation(tenant, messageCid, indexName, indexValueItem); opCreationPromises.push(partitionOperationPromise2); } } else { const partitionOperationPromise2 = this.createDeleteIndexedItemOperation(tenant, messageCid, indexName, indexValue); opCreationPromises.push(partitionOperationPromise2); } } const indexOps = yield Promise.all(opCreationPromises); const tenantPartition = yield this.db.partition(tenant); yield tenantPartition.batch(indexOps, options); }); } /** * Creates an IndexLevel `put` operation for indexing an item, creating a partition by `tenant` and by `indexName` */ createPutIndexedItemOperation(tenant, item, indexName, indexValue) { return __awaiter53(this, void 0, void 0, function* () { const { messageCid } = item; const key = IndexLevel.keySegmentJoin(IndexLevel.encodeValue(indexValue), messageCid); return this.createOperationForIndexPartition(tenant, indexName, { type: "put", key, value: JSON.stringify(item) }); }); } /** * Creates an IndexLevel `del` operation for deleting an item, creating a partition by `tenant` and by `indexName` */ createDeleteIndexedItemOperation(tenant, messageCid, indexName, indexValue) { return __awaiter53(this, void 0, void 0, function* () { const key = IndexLevel.keySegmentJoin(IndexLevel.encodeValue(indexValue), messageCid); return this.createOperationForIndexPartition(tenant, indexName, { type: "del", key }); }); } /** * Wraps the given operation as an operation for the specified index partition. */ createOperationForIndexPartition(tenant, indexName, operation) { return __awaiter53(this, void 0, void 0, function* () { const tenantPartition = yield this.db.partition(tenant); const indexPartitionName = IndexLevel.getIndexPartitionName(indexName); const partitionOperation = tenantPartition.createPartitionOperation(indexPartitionName, operation); return partitionOperation; }); } /** * Wraps the given operation as an operation for the messageCid to indexes lookup partition. */ createOperationForIndexesLookupPartition(tenant, operation) { return __awaiter53(this, void 0, void 0, function* () { const tenantPartition = yield this.db.partition(tenant); const partitionOperation = tenantPartition.createPartitionOperation(INDEX_SUBLEVEL_NAME, operation); return partitionOperation; }); } static getIndexPartitionName(indexName) { return `__${indexName}__`; } /** * Gets the index partition of the given indexName. */ getIndexPartition(tenant, indexName) { return __awaiter53(this, void 0, void 0, function* () { const indexPartitionName = IndexLevel.getIndexPartitionName(indexName); return (yield this.db.partition(tenant)).partition(indexPartitionName); }); } /** * Gets the messageCid to indexes lookup partition. */ getIndexesLookupPartition(tenant) { return __awaiter53(this, void 0, void 0, function* () { return (yield this.db.partition(tenant)).partition(INDEX_SUBLEVEL_NAME); }); } /** * Queries the index for items that match the filters. If no filters are provided, all items are returned. * * @param filters Array of filters that are treated as an OR query. * @param queryOptions query options for sort and pagination, requires at least `sortProperty`. The default sort direction is ascending. * @param options IndexLevelOptions that include an AbortSignal. * @returns {IndexedItem[]} an array of `IndexedItem` that match the given filters. */ query(tenant, filters, queryOptions, options) { return __awaiter53(this, void 0, void 0, function* () { if (IndexLevel.shouldQueryWithInMemoryPaging(filters, queryOptions)) { return this.queryWithInMemoryPaging(tenant, filters, queryOptions, options); } return this.queryWithIteratorPaging(tenant, filters, queryOptions, options); }); } /** * Queries the sort property index for items that match the filters. If no filters are provided, all items are returned. * This query is a linear iterator over the sorted index, checking each item for a match. * If a cursor is provided it starts the iteration from the cursor point. */ queryWithIteratorPaging(tenant, filters, queryOptions, options) { var _a, e_1, _b, _c; return __awaiter53(this, void 0, void 0, function* () { const { cursor: queryCursor, limit } = queryOptions; const startKey = queryCursor ? this.createStartingKeyFromCursor(queryCursor) : ""; const matches = []; try { for (var _d = true, _e = __asyncValues6(this.getIndexIterator(tenant, startKey, queryOptions, options)), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) { _c = _f.value; _d = false; const item = _c; if (limit !== void 0 && limit === matches.length) { break; } const { indexes } = item; if (FilterUtility.matchAnyFilter(indexes, filters)) { matches.push(item); } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (!_d && !_a && (_b = _e.return)) yield _b.call(_e); } finally { if (e_1) throw e_1.error; } } return matches; }); } /** * Creates an AsyncGenerator that returns each sorted index item given a specific sortProperty. * If a cursor is passed, the starting value (gt or lt) is derived from that. */ getIndexIterator(tenant, startKey, queryOptions, options) { return __asyncGenerator4(this, arguments, function* getIndexIterator_1() { var _a, e_2, _b, _c; const { sortProperty, sortDirection = SortDirection.Ascending, cursor } = queryOptions; const iteratorOptions = { gt: startKey }; if (sortDirection === SortDirection.Descending) { iteratorOptions.reverse = true; if (cursor !== void 0) { iteratorOptions.lt = startKey; delete iteratorOptions.gt; } } const sortPartition = yield __await4(this.getIndexPartition(tenant, sortProperty)); try { for (var _d = true, _e = __asyncValues6(sortPartition.iterator(iteratorOptions, options)), _f; _f = yield __await4(_e.next()), _a = _f.done, !_a; _d = true) { _c = _f.value; _d = false; const [_, val] = _c; const { indexes, messageCid } = JSON.parse(val); yield yield __await4({ indexes, messageCid }); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (!_d && !_a && (_b = _e.return)) yield __await4(_b.call(_e)); } finally { if (e_2) throw e_2.error; } } }); } /** * Creates the starting point for a LevelDB query given an messageCid as a cursor and the indexed property. * Used as (gt) for ascending queries, or (lt) for descending queries. */ createStartingKeyFromCursor(cursor) { const { messageCid, value } = cursor; return IndexLevel.keySegmentJoin(IndexLevel.encodeValue(value), messageCid); } /** * Returns a PaginationCursor using the last item of a given array of IndexedItems. * If the given array is empty, undefined is returned. * * @throws {DwnError} if the sort property or cursor value is invalid. */ static createCursorFromLastArrayItem(items, sortProperty) { if (items.length > 0) { return this.createCursorFromItem(items.at(-1), sortProperty); } } /** * Creates a PaginationCursor from a given IndexedItem and sortProperty. * * @throws {DwnError} if the sort property or cursor value is invalid. */ static createCursorFromItem(item, sortProperty) { const { messageCid, indexes } = item; const value = indexes[sortProperty]; if (value === void 0) { throw new DwnError(DwnErrorCode.IndexInvalidCursorSortProperty, `the sort property '${sortProperty}' is not defined within the given item.`); } if (typeof value === "boolean" || Array.isArray(value)) { throw new DwnError(DwnErrorCode.IndexInvalidCursorValueType, `only string or number values are supported for cursors, a(n) ${typeof value} was given.`); } return { messageCid, value }; } /** * Queries the provided searchFilters asynchronously, returning results that match the matchFilters. * * @param filters the filters passed to the parent query. * @param searchFilters the modified filters used for the LevelDB query to search for a subset of items to match against. * * @throws {DwnErrorCode.IndexLevelInMemoryInvalidSortProperty} if an invalid sort property is provided. */ queryWithInMemoryPaging(tenant, filters, queryOptions, options) { return __awaiter53(this, void 0, void 0, function* () { const { sortProperty, sortDirection = SortDirection.Ascending, cursor: queryCursor, limit } = queryOptions; const cursorStartingKey = queryCursor ? this.createStartingKeyFromCursor(queryCursor) : void 0; const matches = /* @__PURE__ */ new Map(); if (filters.length === 0) { filters = [{}]; } try { yield Promise.all(filters.map((filter2) => { return this.executeSingleFilterQuery(tenant, filter2, sortProperty, matches, options); })); } catch (error) { if (error.code === DwnErrorCode.IndexInvalidSortPropertyInMemory) { return []; } } const sortedValues = [...matches.values()].sort((a, b) => this.sortItems(a, b, sortProperty, sortDirection)); const start = cursorStartingKey !== void 0 ? this.findCursorStartingIndex(sortedValues, sortDirection, sortProperty, cursorStartingKey) : 0; if (start < 0) { return []; } const end = limit !== void 0 ? start + limit : void 0; return sortedValues.slice(start, end); }); } /** * Execute a filtered query against a single filter and return all results. */ executeSingleFilterQuery(tenant, filter2, sortProperty, matches, levelOptions) { return __awaiter53(this, void 0, void 0, function* () { const filterPromises = []; if (isEmptyObject(filter2)) { const getAllItemsPromise = this.getAllItems(tenant, sortProperty); filterPromises.push(getAllItemsPromise); } const searchFilter = FilterSelector.reduceFilter(filter2); for (const propertyName in searchFilter) { const propertyFilter = searchFilter[propertyName]; if (FilterUtility.isEqualFilter(propertyFilter)) { const exactMatchesPromise = this.filterExactMatches(tenant, propertyName, propertyFilter, levelOptions); filterPromises.push(exactMatchesPromise); } else if (FilterUtility.isOneOfFilter(propertyFilter)) { for (const propertyValue of new Set(propertyFilter)) { const exactMatchesPromise = this.filterExactMatches(tenant, propertyName, propertyValue, levelOptions); filterPromises.push(exactMatchesPromise); } } else if (FilterUtility.isRangeFilter(propertyFilter)) { const rangeMatchesPromise = this.filterRangeMatches(tenant, propertyName, propertyFilter, levelOptions); filterPromises.push(rangeMatchesPromise); } } for (const promise of filterPromises) { const indexItems = yield promise; for (const indexedItem of indexItems) { if (matches.has(indexedItem.messageCid) || !FilterUtility.matchFilter(indexedItem.indexes, filter2)) { continue; } if (indexedItem.indexes[sortProperty] === void 0) { throw new DwnError(DwnErrorCode.IndexInvalidSortPropertyInMemory, `invalid sort property ${sortProperty}`); } matches.set(indexedItem.messageCid, indexedItem); } } }); } getAllItems(tenant, sortProperty) { var _a, e_3, _b, _c; return __awaiter53(this, void 0, void 0, function* () { const filterPartition = yield this.getIndexPartition(tenant, sortProperty); const items = []; try { for (var _d = true, _e = __asyncValues6(filterPartition.iterator()), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) { _c = _f.value; _d = false; const [_key, value] = _c; items.push(JSON.parse(value)); } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (!_d && !_a && (_b = _e.return)) yield _b.call(_e); } finally { if (e_3) throw e_3.error; } } return items; }); } /** * Returns items that match the exact property and value. */ filterExactMatches(tenant, propertyName, propertyValue, options) { var _a, e_4, _b, _c; return __awaiter53(this, void 0, void 0, function* () { const matchPrefix = IndexLevel.keySegmentJoin(IndexLevel.encodeValue(propertyValue)); const iteratorOptions = { gt: matchPrefix }; const filterPartition = yield this.getIndexPartition(tenant, propertyName); const matches = []; try { for (var _d = true, _e = __asyncValues6(filterPartition.iterator(iteratorOptions, options)), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) { _c = _f.value; _d = false; const [key, value] = _c; if (!key.startsWith(matchPrefix)) { break; } matches.push(JSON.parse(value)); } } catch (e_4_1) { e_4 = { error: e_4_1 }; } finally { try { if (!_d && !_a && (_b = _e.return)) yield _b.call(_e); } finally { if (e_4) throw e_4.error; } } return matches; }); } /** * Returns items that match the range filter. */ filterRangeMatches(tenant, propertyName, rangeFilter, options) { var _a, e_5, _b, _c; return __awaiter53(this, void 0, void 0, function* () { const iteratorOptions = {}; for (const comparator in rangeFilter) { const comparatorName = comparator; iteratorOptions[comparatorName] = IndexLevel.encodeValue(rangeFilter[comparatorName]); } if (iteratorOptions.gt === void 0 && iteratorOptions.gte === void 0) { iteratorOptions.reverse = true; } const matches = []; const filterPartition = yield this.getIndexPartition(tenant, propertyName); try { for (var _d = true, _e = __asyncValues6(filterPartition.iterator(iteratorOptions, options)), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) { _c = _f.value; _d = false; const [key, value] = _c; if ("gt" in rangeFilter && this.extractIndexValueFromKey(key) === IndexLevel.encodeValue(rangeFilter.gt)) { continue; } matches.push(JSON.parse(value)); } } catch (e_5_1) { e_5 = { error: e_5_1 }; } finally { try { if (!_d && !_a && (_b = _e.return)) yield _b.call(_e); } finally { if (e_5) throw e_5.error; } } if ("lte" in rangeFilter) { for (const item of yield this.filterExactMatches(tenant, propertyName, rangeFilter.lte, options)) { matches.push(item); } } return matches; }); } /** * Sorts Items lexicographically in ascending or descending order given a specific indexName, using the messageCid as a tie breaker. * We know the indexes include the indexName and they are only of string or number type and not Arrays or booleans. * because they have already been checked within executeSingleFilterQuery. */ sortItems(itemA, itemB, indexName, direction) { const itemAValue = itemA.indexes[indexName]; const itemBValue = itemB.indexes[indexName]; const aCompareValue = IndexLevel.encodeValue(itemAValue) + itemA.messageCid; const bCompareValue = IndexLevel.encodeValue(itemBValue) + itemB.messageCid; return direction === SortDirection.Ascending ? lexicographicalCompare(aCompareValue, bCompareValue) : lexicographicalCompare(bCompareValue, aCompareValue); } /** * Find the starting position for pagination within the IndexedItem array. * Returns the index of the first item found which is either greater than or less than the given cursor, depending on sort order. */ findCursorStartingIndex(items, sortDirection, sortProperty, cursorStartingKey) { const firstItemAfterCursor = (item) => { const { messageCid, indexes } = item; const sortValue = indexes[sortProperty]; const itemCompareValue = IndexLevel.keySegmentJoin(IndexLevel.encodeValue(sortValue), messageCid); return sortDirection === SortDirection.Ascending ? itemCompareValue > cursorStartingKey : itemCompareValue < cursorStartingKey; }; return items.findIndex(firstItemAfterCursor); } /** * Gets the indexes given an messageCid. This is a reverse lookup to construct starting keys, as well as deleting indexed items. */ getIndexes(tenant, messageCid) { return __awaiter53(this, void 0, void 0, function* () { const indexesLookupPartition = yield this.getIndexesLookupPartition(tenant); const serializedIndexes = yield indexesLookupPartition.get(messageCid); if (serializedIndexes === void 0) { return; } return JSON.parse(serializedIndexes); }); } /** * Given a key from an indexed partitioned property key. * ex: * key: '"2023-05-25T11:22:33.000000Z"\u0000bayfreigu....' * returns "2023-05-25T11:22:33.000000Z" */ extractIndexValueFromKey(key) { const [value] = key.split(IndexLevel.delimiter); return value; } static keySegmentJoin(...values) { return values.join(IndexLevel.delimiter); } /** * Encodes a numerical value as a string for lexicographical comparison. * If the number is positive it simply pads it with leading zeros. * ex.: input: 1024 => "0000000000001024" * input: -1024 => "!9007199254739967" * * @param value the number to encode. * @returns a string representation of the number. */ static encodeNumberValue(value) { const NEGATIVE_OFFSET = Number.MAX_SAFE_INTEGER; const NEGATIVE_PREFIX = "!"; const PADDING_LENGTH = String(Number.MAX_SAFE_INTEGER).length; const prefix = value < 0 ? NEGATIVE_PREFIX : ""; const offset = value < 0 ? NEGATIVE_OFFSET : 0; return prefix + String(value + offset).padStart(PADDING_LENGTH, "0"); } /** * Encodes an indexed value to a string * * NOTE: we currently only use this for strings, numbers and booleans. */ static encodeValue(value) { switch (typeof value) { case "number": return this.encodeNumberValue(value); default: return JSON.stringify(value); } } static shouldQueryWithInMemoryPaging(filters, queryOptions) { for (const filter2 of filters) { if (!IndexLevel.isFilterConcise(filter2, queryOptions)) { return false; } } return true; } static isFilterConcise(filter2, queryOptions) { if (filter2.recordId !== void 0) { return true; } if (queryOptions.cursor !== void 0) { return false; } if (filter2.protocolPath !== void 0 || filter2.contextId !== void 0 || filter2.parentId !== void 0 || filter2.schema !== void 0) { return true; } return false; } }; IndexLevel.delimiter = `\0`; // dist/esm/src/event-log/event-log-level.js var import_ulidx = require("ulidx"); var __awaiter54 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var EventLogLevel = class { constructor(config) { this.index = new IndexLevel(Object.assign({ location: "EVENTLOG", createLevelDatabase }, config)); this.ulidFactory = (0, import_ulidx.monotonicFactory)(); } open() { return __awaiter54(this, void 0, void 0, function* () { return this.index.open(); }); } close() { return __awaiter54(this, void 0, void 0, function* () { return this.index.close(); }); } clear() { return __awaiter54(this, void 0, void 0, function* () { return this.index.clear(); }); } append(tenant, messageCid, indexes) { return __awaiter54(this, void 0, void 0, function* () { const watermark = this.ulidFactory(); yield this.index.put(tenant, messageCid, Object.assign(Object.assign({}, indexes), { watermark })); }); } queryEvents(tenant, filters, cursor) { return __awaiter54(this, void 0, void 0, function* () { const results = yield this.index.query(tenant, filters, { sortProperty: "watermark", cursor }); return { events: results.map(({ messageCid }) => messageCid), cursor: IndexLevel.createCursorFromLastArrayItem(results, "watermark") }; }); } getEvents(tenant, cursor) { return __awaiter54(this, void 0, void 0, function* () { return this.queryEvents(tenant, [], cursor); }); } deleteEventsByCid(tenant, messageCids) { return __awaiter54(this, void 0, void 0, function* () { const indexDeletePromises = []; for (const messageCid of messageCids) { indexDeletePromises.push(this.index.delete(tenant, messageCid)); } yield Promise.all(indexDeletePromises); }); } }; // node_modules/multiformats/src/block.js function readonly({ enumerable = true, configurable = false } = {}) { return { enumerable, configurable, writable: false }; } function* linksWithin(path, value) { if (value != null && typeof value === "object") { if (Array.isArray(value)) { for (const [index, element] of value.entries()) { const elementPath = [...path, index]; const cid = CID.asCID(element); if (cid) { yield [elementPath.join("/"), cid]; } else if (typeof element === "object") { yield* links(element, elementPath); } } } else { const cid = CID.asCID(value); if (cid) { yield [path.join("/"), cid]; } else { yield* links(value, path); } } } } function* links(source, base6) { if (source == null || source instanceof Uint8Array) { return; } const cid = CID.asCID(source); if (cid) { yield [base6.join("/"), cid]; } for (const [key, value] of Object.entries(source)) { const path = ( /** @type {[string|number, string]} */ [...base6, key] ); yield* linksWithin(path, value); } } function* treeWithin(path, value) { if (Array.isArray(value)) { for (const [index, element] of value.entries()) { const elementPath = [...path, index]; yield elementPath.join("/"); if (typeof element === "object" && !CID.asCID(element)) { yield* tree(element, elementPath); } } } else { yield* tree(value, path); } } function* tree(source, base6) { if (source == null || typeof source !== "object") { return; } for (const [key, value] of Object.entries(source)) { const path = ( /** @type {[string|number, string]} */ [...base6, key] ); yield path.join("/"); if (value != null && !(value instanceof Uint8Array) && typeof value === "object" && !CID.asCID(value)) { yield* treeWithin(path, value); } } } function get(source, path) { let node = ( /** @type {Record} */ source ); for (const [index, key] of path.entries()) { node = node[key]; if (node == null) { throw new Error(`Object has no property at ${path.slice(0, index + 1).map((part) => `[${JSON.stringify(part)}]`).join("")}`); } const cid = CID.asCID(node); if (cid) { return { value: cid, remaining: path.slice(index + 1).join("/") }; } } return { value: node }; } var Block = class { /** * @param {object} options * @param {CID} options.cid * @param {API.ByteView} options.bytes * @param {T} options.value */ constructor({ cid, bytes: bytes2, value }) { if (!cid || !bytes2 || typeof value === "undefined") { throw new Error("Missing required argument"); } this.cid = cid; this.bytes = bytes2; this.value = value; this.asBlock = this; Object.defineProperties(this, { cid: readonly(), bytes: readonly(), value: readonly(), asBlock: readonly() }); } links() { return links(this.value, []); } tree() { return tree(this.value, []); } /** * * @param {string} [path] * @returns {API.BlockCursorView} */ get(path = "/") { return get(this.value, path.split("/").filter(Boolean)); } }; async function encode15({ value, codec, hasher }) { if (typeof value === "undefined") throw new Error('Missing required argument "value"'); if (!codec || !hasher) throw new Error("Missing required argument: codec or hasher"); const bytes2 = codec.encode(value); const hash2 = await hasher.digest(bytes2); const cid = CID.create( 1, codec.code, hash2 ); return new Block({ value, bytes: bytes2, cid }); } async function decode22({ bytes: bytes2, codec, hasher }) { if (!bytes2) throw new Error('Missing required argument "bytes"'); if (!codec || !hasher) throw new Error("Missing required argument: codec or hasher"); const value = codec.decode(bytes2); const hash2 = await hasher.digest(bytes2); const cid = CID.create(1, codec.code, hash2); return new Block({ value, bytes: bytes2, cid }); } // dist/esm/src/store/message-store-level.js var __awaiter55 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var MessageStoreLevel = class { /** * @param {MessageStoreLevelConfig} config * @param {string} config.blockstoreLocation - must be a directory path (relative or absolute) where * LevelDB will store its files, or in browsers, the name of the * {@link https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase IDBDatabase} to be opened. * @param {string} config.indexLocation - same as config.blockstoreLocation */ constructor(config = {}) { this.config = Object.assign({ blockstoreLocation: "MESSAGESTORE", indexLocation: "INDEX", createLevelDatabase }, config); this.blockstore = new BlockstoreLevel({ location: this.config.blockstoreLocation, createLevelDatabase: this.config.createLevelDatabase }); this.index = new IndexLevel({ location: this.config.indexLocation, createLevelDatabase: this.config.createLevelDatabase }); } open() { return __awaiter55(this, void 0, void 0, function* () { yield this.blockstore.open(); yield this.index.open(); }); } close() { return __awaiter55(this, void 0, void 0, function* () { yield this.blockstore.close(); yield this.index.close(); }); } get(tenant, cidString, options) { var _a; return __awaiter55(this, void 0, void 0, function* () { (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted(); const partition = yield executeUnlessAborted(this.blockstore.partition(tenant), options === null || options === void 0 ? void 0 : options.signal); const cid = CID.parse(cidString); const bytes2 = yield partition.get(cid, options); if (!bytes2) { return void 0; } const decodedBlock = yield executeUnlessAborted(decode22({ bytes: bytes2, codec: src_exports, hasher: sha256 }), options === null || options === void 0 ? void 0 : options.signal); const message2 = decodedBlock.value; return message2; }); } query(tenant, filters, messageSort, pagination, options) { var _a; return __awaiter55(this, void 0, void 0, function* () { (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted(); const queryOptions = MessageStoreLevel.buildQueryOptions(messageSort, pagination); const results = yield this.index.query(tenant, filters, queryOptions, options); let cursor; if ((pagination === null || pagination === void 0 ? void 0 : pagination.limit) !== void 0 && pagination.limit < results.length) { results.splice(-1); cursor = IndexLevel.createCursorFromLastArrayItem(results, queryOptions.sortProperty); } const messages = []; for (let i = 0; i < results.length; i++) { const { messageCid } = results[i]; const message2 = yield this.get(tenant, messageCid, options); if (message2) { messages.push(message2); } } return { messages, cursor }; }); } /** * Builds the IndexLevel QueryOptions object given MessageStore sort and pagination parameters. */ static buildQueryOptions(messageSort = {}, pagination = {}) { let { limit, cursor } = pagination; const { dateCreated, datePublished, messageTimestamp } = messageSort; let sortDirection = SortDirection.Ascending; let sortProperty = "messageTimestamp"; if (dateCreated !== void 0) { sortProperty = "dateCreated"; } else if (datePublished !== void 0) { sortProperty = "datePublished"; } else if (messageTimestamp !== void 0) { sortProperty = "messageTimestamp"; } if (messageSort[sortProperty] !== void 0) { sortDirection = messageSort[sortProperty]; } if (limit !== void 0 && limit > 0) { limit = limit + 1; } return { sortDirection, sortProperty, limit, cursor }; } delete(tenant, cidString, options) { var _a; return __awaiter55(this, void 0, void 0, function* () { (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted(); const partition = yield executeUnlessAborted(this.blockstore.partition(tenant), options === null || options === void 0 ? void 0 : options.signal); const cid = CID.parse(cidString); yield partition.delete(cid, options); yield this.index.delete(tenant, cidString, options); }); } put(tenant, message2, indexes, options) { var _a; return __awaiter55(this, void 0, void 0, function* () { (_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.throwIfAborted(); const partition = yield executeUnlessAborted(this.blockstore.partition(tenant), options === null || options === void 0 ? void 0 : options.signal); const encodedMessageBlock = yield executeUnlessAborted(encode15({ value: message2, codec: src_exports, hasher: sha256 }), options === null || options === void 0 ? void 0 : options.signal); const messageCid = Cid.parseCid(yield Message.getCid(message2)); yield partition.put(messageCid, encodedMessageBlock.bytes, options); const messageCidString = messageCid.toString(); yield this.index.put(tenant, messageCidString, indexes, options); }); } /** * deletes everything in the underlying blockstore and indices. */ clear() { return __awaiter55(this, void 0, void 0, function* () { yield this.blockstore.clear(); yield this.index.clear(); }); } }; // dist/esm/src/event-log/event-emitter-stream.js var import_events4 = require("events"); var __awaiter56 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var EVENTS_LISTENER_CHANNEL = "events"; var EventEmitterStream = class { constructor(config = {}) { this.isOpen = false; this.errorHandler = (error) => { console.error("event emitter error", error); }; this.eventEmitter = new import_events4.EventEmitter({ captureRejections: true }); this.eventEmitter.setMaxListeners(0); if (config.errorHandler) { this.errorHandler = config.errorHandler; } this.eventEmitter.on("error", this.errorHandler); } subscribe(tenant, id, listener) { return __awaiter56(this, void 0, void 0, function* () { this.eventEmitter.on(`${tenant}_${EVENTS_LISTENER_CHANNEL}`, listener); return { id, close: () => __awaiter56(this, void 0, void 0, function* () { this.eventEmitter.off(`${tenant}_${EVENTS_LISTENER_CHANNEL}`, listener); }) }; }); } open() { return __awaiter56(this, void 0, void 0, function* () { this.isOpen = true; }); } close() { return __awaiter56(this, void 0, void 0, function* () { this.isOpen = false; this.eventEmitter.removeAllListeners(); }); } emit(tenant, event, indexes) { if (!this.isOpen) { this.errorHandler(new DwnError(DwnErrorCode.EventEmitterStreamNotOpenError, "a message emitted when EventEmitterStream is closed")); return; } this.eventEmitter.emit(`${tenant}_${EVENTS_LISTENER_CHANNEL}`, tenant, event, indexes); } }; // dist/esm/tests/utils/test-data-generator.js var import_dids2 = require("@web5/dids"); var __awaiter57 = function(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve5) { resolve5(value); }); } return new (P3 || (P3 = Promise))(function(resolve5, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve5(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var TestDataGenerator = class { /** * Generates a persona. */ static generatePersona(input) { var _a, _b; return __awaiter57(this, void 0, void 0, function* () { let did = input === null || input === void 0 ? void 0 : input.did; if (!did) { const didSuffix = TestDataGenerator.randomString(32); did = `did:example:${didSuffix}`; } const keyIdSuffix = TestDataGenerator.randomString(10); const keyId = (_a = input === null || input === void 0 ? void 0 : input.keyId) !== null && _a !== void 0 ? _a : `${did}#${keyIdSuffix}`; const keyPair = (_b = input === null || input === void 0 ? void 0 : input.keyPair) !== null && _b !== void 0 ? _b : yield Secp256k1.generateKeyPair(); const persona = { did, keyId, keyPair, signer: new PrivateKeySigner({ privateJwk: keyPair.privateJwk, algorithm: keyPair.privateJwk.alg, keyId: `${did}#${keyId}` }) }; return persona; }); } /** * Generates a ProtocolsConfigure message for testing. * Optional parameters are generated if not given. * Implementation currently uses `ProtocolsConfigure.create()`. */ static generateProtocolsConfigure(input) { var _a, _b; return __awaiter57(this, void 0, void 0, function* () { const author = (_a = input === null || input === void 0 ? void 0 : input.author) !== null && _a !== void 0 ? _a : yield TestDataGenerator.generatePersona(); let definition = input === null || input === void 0 ? void 0 : input.protocolDefinition; if (!definition) { const generatedLabel = "record" + TestDataGenerator.randomString(10); definition = { protocol: TestDataGenerator.randomString(20), published: (_b = input === null || input === void 0 ? void 0 : input.published) !== null && _b !== void 0 ? _b : false, types: {}, structure: {} }; definition.types[generatedLabel] = { schema: `test-object`, dataFormats: ["text/plain"] }; definition.structure[generatedLabel] = {}; } const signer = Jws.createSigner(author); const options = { messageTimestamp: input === null || input === void 0 ? void 0 : input.messageTimestamp, definition, signer, permissionGrantId: input === null || input === void 0 ? void 0 : input.permissionGrantId }; const protocolsConfigure = yield ProtocolsConfigure2.create(options); return { author, message: protocolsConfigure.message, protocolsConfigure }; }); } /** * Generates a ProtocolsQuery message for testing. */ static generateProtocolsQuery(input) { var _a; return __awaiter57(this, void 0, void 0, function* () { const author = (_a = input === null || input === void 0 ? void 0 : input.author) !== null && _a !== void 0 ? _a : yield TestDataGenerator.generatePersona(); const signer = Jws.createSigner(author); const options = { messageTimestamp: input === null || input === void 0 ? void 0 : input.messageTimestamp, filter: input === null || input === void 0 ? void 0 : input.filter, signer, permissionGrantId: input === null || input === void 0 ? void 0 : input.permissionGrantId }; removeUndefinedProperties(options); const protocolsQuery = yield ProtocolsQuery2.create(options); return { author, message: protocolsQuery.message, protocolsQuery }; }); } /** * Generates a RecordsWrite message for testing. * Implementation currently uses `RecordsWrite.create()`. * @param input.attesters Attesters of the message. Will NOT be generated if not given. * @param input.data Data that belongs to the record. Generated when not given only if `dataCid` and `dataSize` are also not given. * @param input.dataFormat Format of the data. Defaults to 'application/json' if not given. * @param input.signer Signer of the message. Generated if not given. * @param input.schema Schema of the message. Randomly generated if not given. */ static generateRecordsWrite(input) { var _a, _b, _c, _d, _e; return __awaiter57(this, void 0, void 0, function* () { const author = (_a = input === null || input === void 0 ? void 0 : input.author) !== null && _a !== void 0 ? _a : yield TestDataGenerator.generatePersona(); const signer = Jws.createSigner(author); const attestationSigners = Jws.createSigners((_b = input === null || input === void 0 ? void 0 : input.attesters) !== null && _b !== void 0 ? _b : []); const dataCid = input === null || input === void 0 ? void 0 : input.dataCid; const dataSize = input === null || input === void 0 ? void 0 : input.dataSize; let dataBytes; let dataStream; if (dataCid === void 0 && dataSize === void 0) { dataBytes = (_c = input === null || input === void 0 ? void 0 : input.data) !== null && _c !== void 0 ? _c : TestDataGenerator.randomBytes(32); dataStream = DataStream.fromBytes(dataBytes); } const options = { recipient: input === null || input === void 0 ? void 0 : input.recipient, protocol: input === null || input === void 0 ? void 0 : input.protocol, protocolPath: input === null || input === void 0 ? void 0 : input.protocolPath, protocolRole: input === null || input === void 0 ? void 0 : input.protocolRole, schema: (_d = input === null || input === void 0 ? void 0 : input.schema) !== null && _d !== void 0 ? _d : `http://${TestDataGenerator.randomString(20)}`, tags: input === null || input === void 0 ? void 0 : input.tags, recordId: input === null || input === void 0 ? void 0 : input.recordId, parentContextId: input === null || input === void 0 ? void 0 : input.parentContextId, published: input === null || input === void 0 ? void 0 : input.published, dataFormat: (_e = input === null || input === void 0 ? void 0 : input.dataFormat) !== null && _e !== void 0 ? _e : "application/json", dateCreated: input === null || input === void 0 ? void 0 : input.dateCreated, messageTimestamp: input === null || input === void 0 ? void 0 : input.messageTimestamp, datePublished: input === null || input === void 0 ? void 0 : input.datePublished, data: dataBytes, dataCid, dataSize, signer, attestationSigners, encryptionInput: input === null || input === void 0 ? void 0 : input.encryptionInput, permissionGrantId: input === null || input === void 0 ? void 0 : input.permissionGrantId }; const recordsWrite = yield RecordsWrite2.create(options); const message2 = recordsWrite.message; return { author, message: message2, dataCid, dataSize, dataBytes, dataStream, recordsWrite }; }); } /** * Generates a encrypted RecordsWrite message for testing. * * @param input.protocolDefinition Protocol definition used to generate the RecordsWrite. * Must be the RECIPIENT's protocol definition if `encryptSymmetricKeyWithProtocolPathDerivedKey` is true, * because the recipient's public keys will be needed to encrypt the symmetric key. * * @param input.encryptSymmetricKeyWithProtocolPathDerivedKey * Set to `true` to attach the symmetric key encrypted by the protocol path derived public key * * @param input.encryptSymmetricKeyWithProtocolContextDerivedKey * Set to `true` to attach the symmetric key encrypted by the protocol context derived public key */ static generateProtocolEncryptedRecordsWrite(input) { var _a, _b, _c; return __awaiter57(this, void 0, void 0, function* () { const { plaintextBytes, author, recipient, protocolDefinition, protocolPath, protocolParentContextId, protocolContextDerivingRootKeyId, protocolContextDerivedPublicJwk } = input; const plaintextStream = DataStream.fromBytes(plaintextBytes); const dataEncryptionInitializationVector = TestDataGenerator.randomBytes(16); const dataEncryptionKey = TestDataGenerator.randomBytes(32); const encryptedDataStream = yield Encryption.aes256CtrEncrypt(dataEncryptionKey, dataEncryptionInitializationVector, plaintextStream); const encryptedDataBytes = yield DataStream.toBytes(encryptedDataStream); const protocolPathSegments = protocolPath.split("/"); const recordType = protocolPathSegments[protocolPathSegments.length - 1]; const { message: message2, dataStream, recordsWrite } = yield TestDataGenerator.generateRecordsWrite({ author, recipient, protocol: protocolDefinition.protocol, protocolPath, parentContextId: protocolParentContextId, schema: protocolDefinition.types[recordType].schema, dataFormat: (_a = protocolDefinition.types[recordType].dataFormats) === null || _a === void 0 ? void 0 : _a[0], data: encryptedDataBytes }); const encryptionInput = { initializationVector: dataEncryptionInitializationVector, key: dataEncryptionKey, keyEncryptionInputs: [] }; if (input.encryptSymmetricKeyWithProtocolPathDerivedKey) { let protocolRuleSetSegment = protocolDefinition.structure; for (const pathSegment of protocolPathSegments) { protocolRuleSetSegment = protocolRuleSetSegment[pathSegment]; } const protocolPathDerivedPublicJwk = (_b = protocolRuleSetSegment.$encryption) === null || _b === void 0 ? void 0 : _b.publicKeyJwk; const protocolPathDerivationRootKeyId = (_c = protocolRuleSetSegment.$encryption) === null || _c === void 0 ? void 0 : _c.rootKeyId; const protocolPathDerivedKeyEncryptionInput = { publicKeyId: protocolPathDerivationRootKeyId, publicKey: protocolPathDerivedPublicJwk, derivationScheme: KeyDerivationScheme.ProtocolPath }; encryptionInput.keyEncryptionInputs.push(protocolPathDerivedKeyEncryptionInput); } if (input.encryptSymmetricKeyWithProtocolContextDerivedKey) { let protocolContextDerivedKeyEncryptionInput; if (protocolParentContextId === void 0) { const authorRootPrivateKey = { rootKeyId: author.keyId, derivationScheme: KeyDerivationScheme.ProtocolContext, derivedPrivateKey: author.keyPair.privateJwk }; const contextId = yield RecordsWrite2.getEntryId(author.did, message2.descriptor); const contextDerivationPath = Records.constructKeyDerivationPathUsingProtocolContextScheme(contextId); const authorGeneratedProtocolContextDerivedPublicJwk = yield HdKey.derivePublicKey(authorRootPrivateKey, contextDerivationPath); protocolContextDerivedKeyEncryptionInput = { publicKeyId: author.keyId, publicKey: authorGeneratedProtocolContextDerivedPublicJwk, derivationScheme: KeyDerivationScheme.ProtocolContext }; } else { if (protocolContextDerivingRootKeyId === void 0 || protocolContextDerivedPublicJwk === void 0) { throw new Error("`protocolContextDerivingRootKeyId` and `protocolContextDerivedPublicJwk` must both be defined if `protocolContextId` is given"); } protocolContextDerivedKeyEncryptionInput = { publicKeyId: protocolContextDerivingRootKeyId, publicKey: protocolContextDerivedPublicJwk, derivationScheme: KeyDerivationScheme.ProtocolContext }; } encryptionInput.keyEncryptionInputs.push(protocolContextDerivedKeyEncryptionInput); } yield recordsWrite.encryptSymmetricEncryptionKey(encryptionInput); yield recordsWrite.sign({ signer: Jws.createSigner(author) }); return { message: message2, dataStream, recordsWrite, encryptedDataBytes, encryptionInput }; }); } /** * Generates a valid RecordsWrite that modifies the given an existing write. * Any mutable property is not specified will be automatically mutated. * e.g. if `published` is not specified, it will be toggled from the state of the given existing write. */ static generateFromRecordsWrite(input) { var _a, _b, _c; return __awaiter57(this, void 0, void 0, function* () { const existingMessage = input.existingWrite.message; const currentTime = Time.getCurrentTimestamp(); const published = ((_a = input.published) !== null && _a !== void 0 ? _a : existingMessage.descriptor.published) ? false : true; const datePublished = (_b = input.datePublished) !== null && _b !== void 0 ? _b : published ? currentTime : void 0; const dataBytes = (_c = input.data) !== null && _c !== void 0 ? _c : TestDataGenerator.randomBytes(32); const dataStream = DataStream.fromBytes(dataBytes); const options = { recordsWriteMessage: input.existingWrite.message, data: dataBytes, published, datePublished, messageTimestamp: input.messageTimestamp, protocolRole: input.protocolRole, tags: input.tags, signer: Jws.createSigner(input.author) }; const recordsWrite = yield RecordsWrite2.createFrom(options); return { message: recordsWrite.message, recordsWrite, dataBytes, dataStream }; }); } /** * Generates a RecordsQuery message for testing. */ static generateRecordsQuery(input) { var _a, _b; return __awaiter57(this, void 0, void 0, function* () { let author = input === null || input === void 0 ? void 0 : input.author; const anonymous = (_a = input === null || input === void 0 ? void 0 : input.anonymous) !== null && _a !== void 0 ? _a : false; if (anonymous && author) { throw new Error("Cannot have `author` and be anonymous at the same time."); } if (author === void 0 && !anonymous) { author = yield TestDataGenerator.generatePersona(); } let signer = void 0; if (author !== void 0) { signer = Jws.createSigner(author); } const options = { messageTimestamp: input === null || input === void 0 ? void 0 : input.messageTimestamp, signer, filter: (_b = input === null || input === void 0 ? void 0 : input.filter) !== null && _b !== void 0 ? _b : { schema: TestDataGenerator.randomString(10) }, dateSort: input === null || input === void 0 ? void 0 : input.dateSort, pagination: input === null || input === void 0 ? void 0 : input.pagination, protocolRole: input === null || input === void 0 ? void 0 : input.protocolRole }; removeUndefinedProperties(options); const recordsQuery = yield RecordsQuery2.create(options); const message2 = recordsQuery.message; return { author, message: message2 }; }); } /** * Generates a RecordsSubscribe message for testing. */ static generateRecordsSubscribe(input) { var _a, _b; return __awaiter57(this, void 0, void 0, function* () { let author = input === null || input === void 0 ? void 0 : input.author; const anonymous = (_a = input === null || input === void 0 ? void 0 : input.anonymous) !== null && _a !== void 0 ? _a : false; if (anonymous && author) { throw new Error("Cannot have `author` and be anonymous at the same time."); } if (author === void 0 && !anonymous) { author = yield TestDataGenerator.generatePersona(); } let signer = void 0; if (author !== void 0) { signer = Jws.createSigner(author); } const options = { messageTimestamp: input === null || input === void 0 ? void 0 : input.messageTimestamp, signer, filter: (_b = input === null || input === void 0 ? void 0 : input.filter) !== null && _b !== void 0 ? _b : { schema: TestDataGenerator.randomString(10) }, protocolRole: input === null || input === void 0 ? void 0 : input.protocolRole }; removeUndefinedProperties(options); const recordsSubscribe = yield RecordsSubscribe2.create(options); const message2 = recordsSubscribe.message; return { author, message: message2 }; }); } /** * Generates a RecordsDelete for testing. */ static generateRecordsDelete(input) { var _a, _b; return __awaiter57(this, void 0, void 0, function* () { const author = (_a = input === null || input === void 0 ? void 0 : input.author) !== null && _a !== void 0 ? _a : yield TestDataGenerator.generateDidKeyPersona(); const recordsDelete = yield RecordsDelete2.create({ recordId: (_b = input === null || input === void 0 ? void 0 : input.recordId) !== null && _b !== void 0 ? _b : yield TestDataGenerator.randomCborSha256Cid(), protocolRole: input === null || input === void 0 ? void 0 : input.protocolRole, signer: Jws.createSigner(author) }); return { author, recordsDelete, message: recordsDelete.message }; }); } static generateEventsGet(input) { var _a; return __awaiter57(this, void 0, void 0, function* () { const author = (_a = input === null || input === void 0 ? void 0 : input.author) !== null && _a !== void 0 ? _a : yield TestDataGenerator.generatePersona(); const signer = Jws.createSigner(author); const options = { signer }; if (input === null || input === void 0 ? void 0 : input.cursor) { options.cursor = input.cursor; } const eventsGet = yield EventsGet2.create(options); return { author, eventsGet, message: eventsGet.message }; }); } static generateEventsQuery(input) { var _a; return __awaiter57(this, void 0, void 0, function* () { const { filters, cursor } = input; const author = (_a = input.author) !== null && _a !== void 0 ? _a : yield TestDataGenerator.generatePersona(); const signer = Jws.createSigner(author); const options = { signer, filters, cursor }; const eventsQuery = yield EventsQuery2.create(options); return { author, eventsQuery, message: eventsQuery.message }; }); } /** * Generates a EventsSubscribe message for testing. */ static generateEventsSubscribe(input) { var _a; return __awaiter57(this, void 0, void 0, function* () { const author = (_a = input === null || input === void 0 ? void 0 : input.author) !== null && _a !== void 0 ? _a : yield TestDataGenerator.generatePersona(); const signer = Jws.createSigner(author); const options = { filters: input === null || input === void 0 ? void 0 : input.filters, messageTimestamp: input === null || input === void 0 ? void 0 : input.messageTimestamp, signer }; removeUndefinedProperties(options); const eventsSubscribe = yield EventsSubscribe2.create(options); const message2 = eventsSubscribe.message; return { author, eventsSubscribe, message: message2 }; }); } static generateMessagesGet(input) { var _a; return __awaiter57(this, void 0, void 0, function* () { const author = (_a = input === null || input === void 0 ? void 0 : input.author) !== null && _a !== void 0 ? _a : yield TestDataGenerator.generatePersona(); const signer = Jws.createSigner(author); const options = { signer, messageCids: input.messageCids }; const messagesGet = yield MessagesGet2.create(options); return { author, messagesGet, message: messagesGet.message }; }); } /** * Generates a dummy `authorization` property for a DWN message that only conforms to schema validation. */ static generateAuthorization() { return { signature: TestDataGenerator.generateAuthorizationSignature() }; } /** * Generates a dummy `authorization` property for a DWN message that only conforms to schema validation. */ static generateAuthorizationSignature() { return { payload: "anyPayload", signatures: [{ protected: "anyProtectedHeader", signature: "anySignature" }] }; } /** * Generates a random but well-formed signature string in Base64Url format. */ static randomSignatureString() { return __awaiter57(this, void 0, void 0, function* () { const keyPair = yield ed25519.generateKeyPair(); const signatureBytes = yield ed25519.sign(TestDataGenerator.randomBytes(32), keyPair.privateJwk); const signatureString = Encoder2.bytesToBase64Url(signatureBytes); return signatureString; }); } /** * Generates a random alpha-numeric string. */ static randomString(length5) { const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; let randomString = ""; for (let i = 0; i < length5; i++) { randomString += charset.charAt(Math.floor(Math.random() * charset.length)); } return randomString; } /** * Generates a random byte array of given length. */ static randomBytes(length5) { const randomBytes2 = new Uint8Array(length5); for (let i = 0; i < length5; i++) { randomBytes2[i] = Math.floor(Math.random() * 256); } return randomBytes2; } /** * Generates a random CBOR SHA256 CID. */ static randomCborSha256Cid() { return __awaiter57(this, void 0, void 0, function* () { const randomBytes2 = TestDataGenerator.randomBytes(32); const randomMultihash = yield sha256.digest(randomBytes2); const cid = yield CID.createV1(code3, randomMultihash); return cid.toString(); }); } /** * Generates a random within a range (inclusive). * @param min lowest potential value. * @param max greatest potential value. */ static randomInt(min, max) { return Math.floor(Math.random() * (max - min) + min); } /** * Generates a random timestamp. Optionally allows you to set specific non-randomized values for the timestamp. * * @returns random UTC ISO-8601 timestamp */ static randomTimestamp(options) { const { year, month, day, hour, minute, second, millisecond, microsecond } = options || {}; return Time.createTimestamp({ year: year || this.randomInt(2e3, 2022), month: month || this.randomInt(1, 12), day: day || this.randomInt(1, 28), hour: hour || this.randomInt(0, 23), minute: minute || this.randomInt(0, 59), second: second || this.randomInt(0, 59), millisecond: millisecond || this.randomInt(0, 1e3), microsecond: microsecond || this.randomInt(0, 1e3) }); } /** * Creates a mock DID resolution result for testing purposes. */ static createDidResolutionResult(persona) { return { didResolutionMetadata: {}, didDocument: { id: persona.did, verificationMethod: [{ controller: persona.did, id: persona.keyId, type: "JsonWebKey2020", // TODO: #672 - port and use type from @web5/crypto - https://github.com/TBD54566975/dwn-sdk-js/issues/672 publicKeyJwk: persona.keyPair.publicJwk }] }, didDocumentMetadata: {} }; } /** * Generates a did:key persona. */ static generateDidKeyPersona() { return __awaiter57(this, void 0, void 0, function* () { const did = yield import_dids2.DidKey.create(); const signingMethod = yield import_dids2.DidKey.getSigningMethod({ didDocument: did.document }); const keyId = signingMethod.id; const portableDid = yield did.export(); const keyPair = { // TODO: #672 - port and use type from @web5/crypto - https://github.com/TBD54566975/dwn-sdk-js/issues/672 publicJwk: signingMethod.publicKeyJwk, privateJwk: portableDid.privateKeys[0] }; return { did: did.uri, keyId, keyPair, signer: new PrivateKeySigner({ privateJwk: keyPair.privateJwk, algorithm: keyPair.privateJwk.alg, keyId }) }; }); } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { AllowAllTenantGate, Cid, DataStoreLevel, DataStream, DateSort, Dwn, DwnConstant, DwnError, DwnErrorCode, DwnInterfaceName, DwnMethodName, Encoder, Encryption, EncryptionAlgorithm, EventEmitterStream, EventLogLevel, EventsGet, EventsQuery, EventsSubscribe, HdKey, Jws, KeyDerivationScheme, Message, MessageStoreLevel, MessagesGet, PermissionsProtocol, PrivateKeySigner, Protocols, ProtocolsConfigure, ProtocolsQuery, Records, RecordsDelete, RecordsQuery, RecordsRead, RecordsSubscribe, RecordsWrite, Secp256k1, Secp256r1, SortDirection, TestDataGenerator, Time, authenticate, executeUnlessAborted }); /*! Bundled license information: @noble/ed25519/index.js: (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *) @noble/secp256k1/index.js: (*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) *) @noble/hashes/esm/utils.js: (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/abstract/utils.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/abstract/modular.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/abstract/curve.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/abstract/weierstrass.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/_shortw_utils.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/p256.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) */