From 31a0dcd1bf61aa3e890a4b0bfc02c0aa727bb054 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Donny/=EA=B0=95=EB=8F=99=EC=9C=A4?= Date: Sat, 19 Nov 2022 05:34:16 +0900 Subject: [PATCH 01/63] Add tests --- .../server/middleware-build-manifest/input.js | 1 + .../input.js | 1 + .../chunks/1c78a37c-938aa76c30a26578/input.js | 34 + .../chunks/321-84e387e16ad8340e/input.js | 34 + .../framework-b5c497ced4b4c57f/input.js | 496 ++ .../chunks/main-558eb874a0ed3710/input.js | 5575 +++++++++++++++++ .../pages/_app-44371e53a69c3879/input.js | 53 + .../pages/_error-c8b0663085900c58/input.js | 25 + .../pages/index-5f716484c7c1584d/input.js | 47 + .../chunks/webpack-cfb37aae43e748d1/input.js | 189 + .../_buildManifest/input.js | 1 + .../_ssgManifest/input.js | 1 + 12 files changed, 6457 insertions(+) create mode 100644 crates/swc_ecma_minifier/tests/fixture/next/43052/server/middleware-build-manifest/input.js create mode 100644 crates/swc_ecma_minifier/tests/fixture/next/43052/server/middleware-react-loadable-manifest/input.js create mode 100644 crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/1c78a37c-938aa76c30a26578/input.js create mode 100644 crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/321-84e387e16ad8340e/input.js create mode 100644 crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/framework-b5c497ced4b4c57f/input.js create mode 100644 crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/main-558eb874a0ed3710/input.js create mode 100644 crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/pages/_app-44371e53a69c3879/input.js create mode 100644 crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/pages/_error-c8b0663085900c58/input.js create mode 100644 crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/pages/index-5f716484c7c1584d/input.js create mode 100644 crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/webpack-cfb37aae43e748d1/input.js create mode 100644 crates/swc_ecma_minifier/tests/fixture/next/43052/static/n1MT3qCQpVU98YBbM_fvB/_buildManifest/input.js create mode 100644 crates/swc_ecma_minifier/tests/fixture/next/43052/static/n1MT3qCQpVU98YBbM_fvB/_ssgManifest/input.js diff --git a/crates/swc_ecma_minifier/tests/fixture/next/43052/server/middleware-build-manifest/input.js b/crates/swc_ecma_minifier/tests/fixture/next/43052/server/middleware-build-manifest/input.js new file mode 100644 index 000000000000..590e3bedebcb --- /dev/null +++ b/crates/swc_ecma_minifier/tests/fixture/next/43052/server/middleware-build-manifest/input.js @@ -0,0 +1 @@ +self.__BUILD_MANIFEST={"polyfillFiles":["static/chunks/polyfills-c67a75d1b6f99dc8.js"],"devFiles":[],"ampDevFiles":[],"lowPriorityFiles":["static/n1MT3qCQpVU98YBbM_fvB/_buildManifest.js","static/n1MT3qCQpVU98YBbM_fvB/_ssgManifest.js"],"rootMainFiles":[],"pages":{"/":["static/chunks/webpack-cfb37aae43e748d1.js","static/chunks/framework-b5c497ced4b4c57f.js","static/chunks/main-558eb874a0ed3710.js","static/chunks/1c78a37c-938aa76c30a26578.js","static/chunks/321-84e387e16ad8340e.js","static/chunks/pages/index-5f716484c7c1584d.js"],"/_app":["static/chunks/webpack-cfb37aae43e748d1.js","static/chunks/framework-b5c497ced4b4c57f.js","static/chunks/main-558eb874a0ed3710.js","static/css/e642fefc6f19f6c3.css","static/chunks/pages/_app-44371e53a69c3879.js"],"/_error":["static/chunks/webpack-cfb37aae43e748d1.js","static/chunks/framework-b5c497ced4b4c57f.js","static/chunks/main-558eb874a0ed3710.js","static/chunks/pages/_error-c8b0663085900c58.js"]},"ampFirstPages":[]} \ No newline at end of file diff --git a/crates/swc_ecma_minifier/tests/fixture/next/43052/server/middleware-react-loadable-manifest/input.js b/crates/swc_ecma_minifier/tests/fixture/next/43052/server/middleware-react-loadable-manifest/input.js new file mode 100644 index 000000000000..7f1b4e589ecc --- /dev/null +++ b/crates/swc_ecma_minifier/tests/fixture/next/43052/server/middleware-react-loadable-manifest/input.js @@ -0,0 +1 @@ +self.__REACT_LOADABLE_MANIFEST={} \ No newline at end of file diff --git a/crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/1c78a37c-938aa76c30a26578/input.js b/crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/1c78a37c-938aa76c30a26578/input.js new file mode 100644 index 000000000000..3973bb360209 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/1c78a37c-938aa76c30a26578/input.js @@ -0,0 +1,34 @@ +(self["webpackChunk_N_E"] = self["webpackChunk_N_E"] || []).push([[610],{ + +/***/ 1522: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +/** + * react-uploader + * + * Copyright (c) Web3.Storage + * + * This source code is licensed under Apache-2.0 OR MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license Apache-2.0 OR MIT + */ +!function(e,t){ true?t(exports,__webpack_require__(7294),__webpack_require__(1321)):0}(this,(function(exports,React,reactKeyring){"use strict";function _interopDefaultLegacy(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var React__default=_interopDefaultLegacy(React),commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof __webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self?self:{},index_production={exports:{}}; +/** + * uploader-core + * + * Copyright (c) Web3.Storage + * + * This source code is licensed under Apache-2.0 OR MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license Apache-2.0 OR MIT + */ +(function(module,exports){var t;t=function(exports){var _nodeResolve_empty={},nodeCrypto=Object.freeze({__proto__:null,default:_nodeResolve_empty}); +/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */const _0n=BigInt(0),_1n=BigInt(1),_2n=BigInt(2),CU_O=BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),CURVE=Object.freeze({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),P:BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),l:CU_O,n:CU_O,h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960")}),POW_2_256=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000"),SQRT_M1=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt("6853475219497561581579357271197624642482790079785650197046958215289687604742");const SQRT_AD_MINUS_ONE=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),INVSQRT_A_MINUS_D=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),ONE_MINUS_D_SQ=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),D_MINUS_ONE_SQ=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");class ExtendedPoint{constructor(e,t,r,n){this.x=e,this.y=t,this.z=r,this.t=n}static fromAffine(e){if(!(e instanceof Point))throw new TypeError("ExtendedPoint#fromAffine: expected Point");return e.equals(Point.ZERO)?ExtendedPoint.ZERO:new ExtendedPoint(e.x,e.y,_1n,mod(e.x*e.y))}static toAffineBatch(e){const t=invertBatch(e.map((e=>e.z)));return e.map(((e,r)=>e.toAffine(t[r])))}static normalizeZ(e){return this.toAffineBatch(e).map(this.fromAffine)}equals(e){assertExtPoint(e);const{x:t,y:r,z:n}=this,{x:o,y:i,z:s}=e,a=mod(t*s),c=mod(o*n),u=mod(r*s),d=mod(i*n);return a===c&&u===d}negate(){return new ExtendedPoint(mod(-this.x),this.y,this.z,mod(-this.t))}double(){const{x:e,y:t,z:r}=this,{a:n}=CURVE,o=mod(e*e),i=mod(t*t),s=mod(_2n*mod(r*r)),a=mod(n*o),c=e+t,u=mod(mod(c*c)-o-i),d=a+i,l=d-s,f=a-i,h=mod(u*l),p=mod(d*f),y=mod(u*f),m=mod(l*d);return new ExtendedPoint(h,p,m,y)}add(e){assertExtPoint(e);const{x:t,y:r,z:n,t:o}=this,{x:i,y:s,z:a,t:c}=e,u=mod((r-t)*(s+i)),d=mod((r+t)*(s-i)),l=mod(d-u);if(l===_0n)return this.double();const f=mod(n*_2n*c),h=mod(o*_2n*a),p=h+f,y=d+u,m=h-f,g=mod(p*l),w=mod(y*m),b=mod(p*m),v=mod(l*y);return new ExtendedPoint(g,w,v,b)}subtract(e){return this.add(e.negate())}precomputeWindow(e){const t=1+256/e,r=[];let n=this,o=n;for(let i=0;i>=d,s>a&&(s-=u,e+=_1n),0===s){let e=n[r];t%2&&(e=e.negate()),i=i.add(e)}else{let e=n[r+Math.abs(s)-1];s<0&&(e=e.negate()),o=o.add(e)}}return ExtendedPoint.normalizeZ([o,i])[0]}multiply(e,t){return this.wNAF(normalizeScalar(e,CURVE.l),t)}multiplyUnsafe(e){let t=normalizeScalar(e,CURVE.l,!1);const r=ExtendedPoint.BASE,n=ExtendedPoint.ZERO;if(t===_0n)return n;if(this.equals(n)||t===_1n)return this;if(this.equals(r))return this.wNAF(t);let o=n,i=this;for(;t>_0n;)t&_1n&&(o=o.add(i)),i=i.double(),t>>=_1n;return o}isSmallOrder(){return this.multiplyUnsafe(CURVE.h).equals(ExtendedPoint.ZERO)}isTorsionFree(){return this.multiplyUnsafe(CURVE.l).equals(ExtendedPoint.ZERO)}toAffine(e=invert(this.z)){const{x:t,y:r,z:n}=this,o=mod(t*e),i=mod(r*e);if(mod(n*e)!==_1n)throw new Error("invZ was invalid");return new Point(o,i)}fromRistrettoBytes(){legacyRist()}toRistrettoBytes(){legacyRist()}fromRistrettoHash(){legacyRist()}}function assertExtPoint(e){if(!(e instanceof ExtendedPoint))throw new TypeError("ExtendedPoint expected")}function assertRstPoint(e){if(!(e instanceof RistrettoPoint))throw new TypeError("RistrettoPoint expected")}function legacyRist(){throw new Error("Legacy method: switch to RistrettoPoint")}ExtendedPoint.BASE=new ExtendedPoint(CURVE.Gx,CURVE.Gy,_1n,mod(CURVE.Gx*CURVE.Gy)),ExtendedPoint.ZERO=new ExtendedPoint(_0n,_1n,_1n,_0n);class RistrettoPoint{constructor(e){this.ep=e}static calcElligatorRistrettoMap(e){const{d:t}=CURVE,r=mod(SQRT_M1*e*e),n=mod((r+_1n)*ONE_MINUS_D_SQ);let o=BigInt(-1);const i=mod((o-t*r)*mod(r+t));let{isValid:s,value:a}=uvRatio(n,i),c=mod(a*e);edIsNegative(c)||(c=mod(-c)),s||(a=c),s||(o=r);const u=mod(o*(r-_1n)*D_MINUS_ONE_SQ-i),d=a*a,l=mod((a+a)*i),f=mod(u*SQRT_AD_MINUS_ONE),h=mod(_1n-d),p=mod(_1n+d);return new ExtendedPoint(mod(l*p),mod(h*f),mod(f*p),mod(l*h))}static hashToCurve(e){const t=bytes255ToNumberLE((e=ensureBytes(e,64)).slice(0,32)),r=this.calcElligatorRistrettoMap(t),n=bytes255ToNumberLE(e.slice(32,64)),o=this.calcElligatorRistrettoMap(n);return new RistrettoPoint(r.add(o))}static fromHex(e){e=ensureBytes(e,32);const{a:t,d:r}=CURVE,n="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",o=bytes255ToNumberLE(e);if(!equalBytes(numberTo32BytesLE(o),e)||edIsNegative(o))throw new Error(n);const i=mod(o*o),s=mod(_1n+t*i),a=mod(_1n-t*i),c=mod(s*s),u=mod(a*a),d=mod(t*r*c-u),{isValid:l,value:f}=invertSqrt(mod(d*u)),h=mod(f*a),p=mod(f*h*d);let y=mod((o+o)*h);edIsNegative(y)&&(y=mod(-y));const m=mod(s*p),g=mod(y*m);if(!l||edIsNegative(g)||m===_0n)throw new Error(n);return new RistrettoPoint(new ExtendedPoint(y,m,_1n,g))}toRawBytes(){let{x:e,y:t,z:r,t:n}=this.ep;const o=mod(mod(r+t)*mod(r-t)),i=mod(e*t),s=mod(i*i),{value:a}=invertSqrt(mod(o*s)),c=mod(a*o),u=mod(a*i),d=mod(c*u*n);let l;if(edIsNegative(n*d)){let r=mod(t*SQRT_M1),n=mod(e*SQRT_M1);e=r,t=n,l=mod(c*INVSQRT_A_MINUS_D)}else l=u;edIsNegative(e*d)&&(t=mod(-t));let f=mod((r-t)*l);return edIsNegative(f)&&(f=mod(-f)),numberTo32BytesLE(f)}toHex(){return bytesToHex(this.toRawBytes())}toString(){return this.toHex()}equals(e){assertRstPoint(e);const t=this.ep,r=e.ep,n=mod(t.x*r.y)===mod(t.y*r.x),o=mod(t.y*r.y)===mod(t.x*r.x);return n||o}add(e){return assertRstPoint(e),new RistrettoPoint(this.ep.add(e.ep))}subtract(e){return assertRstPoint(e),new RistrettoPoint(this.ep.subtract(e.ep))}multiply(e){return new RistrettoPoint(this.ep.multiply(e))}multiplyUnsafe(e){return new RistrettoPoint(this.ep.multiplyUnsafe(e))}}RistrettoPoint.BASE=new RistrettoPoint(ExtendedPoint.BASE),RistrettoPoint.ZERO=new RistrettoPoint(ExtendedPoint.ZERO);const pointPrecomputes=new WeakMap;class Point{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,pointPrecomputes.delete(this)}static fromHex(e,t=!0){const{d:r,P:n}=CURVE,o=(e=ensureBytes(e,32)).slice();o[31]=-129&e[31];const i=bytesToNumberLE(o);if(t&&i>=n)throw new Error("Expected 0 < hex < P");if(!t&&i>=POW_2_256)throw new Error("Expected 0 < hex < 2**256");const s=mod(i*i),a=mod(s-_1n),c=mod(r*s+_1n);let{isValid:u,value:d}=uvRatio(a,c);if(!u)throw new Error("Point.fromHex: invalid y coordinate");const l=(d&_1n)===_1n;return 0!=(128&e[31])!==l&&(d=mod(-d)),new Point(d,i)}static async fromPrivateKey(e){return(await getExtendedPublicKey(e)).point}toRawBytes(){const e=numberTo32BytesLE(this.y);return e[31]|=this.x&_1n?128:0,e}toHex(){return bytesToHex(this.toRawBytes())}toX25519(){const{y:e}=this;return numberTo32BytesLE(mod((_1n+e)*invert(_1n-e)))}isTorsionFree(){return ExtendedPoint.fromAffine(this).isTorsionFree()}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new Point(mod(-this.x),this.y)}add(e){return ExtendedPoint.fromAffine(this).add(ExtendedPoint.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return ExtendedPoint.fromAffine(this).multiply(e,this).toAffine()}}Point.BASE=new Point(CURVE.Gx,CURVE.Gy),Point.ZERO=new Point(_0n,_1n);class Signature{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromHex(e){const t=ensureBytes(e,64),r=Point.fromHex(t.slice(0,32),!1),n=bytesToNumberLE(t.slice(32,64));return new Signature(r,n)}assertValidity(){const{r:e,s:t}=this;if(!(e instanceof Point))throw new Error("Expected Point instance");return normalizeScalar(t,CURVE.l,!1),this}toRawBytes(){const e=new Uint8Array(64);return e.set(this.r.toRawBytes()),e.set(numberTo32BytesLE(this.s),32),e}toHex(){return bytesToHex(this.toRawBytes())}}function concatBytes(...e){if(!e.every((e=>e instanceof Uint8Array)))throw new Error("Expected Uint8Array list");if(1===e.length)return e[0];const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);for(let t=0,n=0;tt.toString(16).padStart(2,"0")));function bytesToHex(e){if(!(e instanceof Uint8Array))throw new Error("Uint8Array expected");let t="";for(let r=0;r=_0n?r:t+r}function invert(e,t=CURVE.P){if(e===_0n||t<=_0n)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=mod(e,t),n=t,o=_0n,i=_1n;for(;r!==_0n;){const e=n%r,t=o-i*(n/r);n=r,r=e,o=i,i=t}if(n!==_1n)throw new Error("invert: does not exist");return mod(o,t)}function invertBatch(e,t=CURVE.P){const r=new Array(e.length),n=invert(e.reduce(((e,n,o)=>n===_0n?e:(r[o]=e,mod(e*n,t))),_1n),t);return e.reduceRight(((e,n,o)=>n===_0n?e:(r[o]=mod(e*r[o],t),mod(e*n,t))),n),r}function pow2(e,t){const{P:r}=CURVE;let n=e;for(;t-- >_0n;)n*=n,n%=r;return n}function pow_2_252_3(e){const{P:t}=CURVE,r=BigInt(5),n=BigInt(10),o=BigInt(20),i=BigInt(40),s=BigInt(80),a=e*e%t*e%t,c=pow2(a,_2n)*a%t,u=pow2(c,_1n)*e%t,d=pow2(u,r)*u%t,l=pow2(d,n)*d%t,f=pow2(l,o)*l%t,h=pow2(f,i)*f%t,p=pow2(h,s)*h%t,y=pow2(p,s)*h%t,m=pow2(y,n)*d%t;return{pow_p_5_8:pow2(m,_2n)*e%t,b2:a}}function uvRatio(e,t){const r=mod(t*t*t),n=mod(r*r*t);let o=mod(e*r*pow_2_252_3(e*n).pow_p_5_8);const i=mod(t*o*o),s=o,a=mod(o*SQRT_M1),c=i===e,u=i===mod(-e),d=i===mod(-e*SQRT_M1);return c&&(o=s),(u||d)&&(o=a),edIsNegative(o)&&(o=mod(-o)),{isValid:c||u,value:o}}function invertSqrt(e){return uvRatio(_1n,e)}function modlLE(e){return mod(bytesToNumberLE(e),CURVE.l)}function equalBytes(e,t){if(e.length!==t.length)return!1;for(let r=0;r{if((e=ensureBytes(e)).length<40||e.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");return mod(bytesToNumberLE(e),CURVE.l-_1n)+_1n},randomBytes:(e=32)=>{if(crypto$1.web)return crypto$1.web.getRandomValues(new Uint8Array(e));if(crypto$1.node){const{randomBytes:t}=crypto$1.node;return new Uint8Array(t(e).buffer)}throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>utils.randomBytes(32),sha512:async(...e)=>{const t=concatBytes(...e);if(crypto$1.web){const e=await crypto$1.web.subtle.digest("SHA-512",t.buffer);return new Uint8Array(e)}if(crypto$1.node)return Uint8Array.from(crypto$1.node.createHash("sha512").update(t).digest());throw new Error("The environment doesn't have sha512 function")},precompute(e=8,t=Point.BASE){const r=t.equals(Point.BASE)?t:new Point(t.x,t.y);return r._setWindowSize(e),r.multiply(_2n),r},sha512Sync:void 0};Object.defineProperties(utils,{sha512Sync:{configurable:!1,get:()=>_sha512Sync,set(e){_sha512Sync||(_sha512Sync=e)}}});var encode_1$1=encode$i,MSB$2=128,REST$2=127,MSBALL$1=~REST$2,INT$1=Math.pow(2,31);function encode$i(e,t,r){t=t||[];for(var n=r=r||0;e>=INT$1;)t[r++]=255&e|MSB$2,e/=128;for(;e&MSBALL$1;)t[r++]=255&e|MSB$2,e>>>=7;return t[r]=0|e,encode$i.bytes=r-n+1,t}var decode$m=read$1,MSB$1$1=128,REST$1$1=127;function read$1(e,t){var r,n=0,o=0,i=t=t||0,s=e.length;do{if(i>=s)throw read$1.bytes=0,new RangeError("Could not decode varint");r=e[i++],n+=o<28?(r&REST$1$1)<=MSB$1$1);return read$1.bytes=i-t,n}var N1$1=Math.pow(2,7),N2$1=Math.pow(2,14),N3$1=Math.pow(2,21),N4$1=Math.pow(2,28),N5$1=Math.pow(2,35),N6$1=Math.pow(2,42),N7$1=Math.pow(2,49),N8$1=Math.pow(2,56),N9$1=Math.pow(2,63),length$1=function(e){return e[_brrp_varint.decode(e,t),_brrp_varint.decode.bytes],encodeTo=(e,t,r=0)=>(_brrp_varint.encode(e,t,r),t),encodingLength=e=>_brrp_varint.encodingLength(e),equals$1=(e,t)=>{if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},create$7=(e,t)=>{const r=t.byteLength,n=encodingLength(e),o=n+encodingLength(r),i=new Uint8Array(o+r);return encodeTo(e,i,0),encodeTo(r,i,n),i.set(t,o),new Digest(e,r,t,i)},decode$k=e=>{const t=coerce(e),[r,n]=decode$l(t),[o,i]=decode$l(t.subarray(n)),s=t.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new Digest(r,o,s,t)},equals=(e,t)=>e===t||e.code===t.code&&e.size===t.size&&equals$1(e.bytes,t.bytes);class Digest{constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}}function base$2(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,s=new Uint8Array(i);e[t];){var d=r[e.charCodeAt(t)];if(255===d)return;for(var l=0,f=i-1;(0!==d||l>>0,s[f]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");o=l,t++}if(" "!==e[t]){for(var h=i-o;h!==i&&0===s[h];)h++;for(var p=new Uint8Array(n+(i-h)),y=n;h!==i;)p[y++]=s[h++];return p}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,o=0,i=t.length;o!==i&&0===t[o];)o++,r++;for(var s=(i-o)*d+1>>>0,u=new Uint8Array(s);o!==i;){for(var l=t[o],f=0,h=s-1;(0!==l||f>>0,u[h]=l%a>>>0,l=l/a>>>0;if(0!==l)throw new Error("Non-zero carry");n=f,o++}for(var p=s-n;p!==s&&0===u[p];)p++;for(var y=c.repeat(r);pnew ComposedDecoder({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class Codec{constructor(e,t,r,n){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new Encoder(e,t,r),this.decoder=new Decoder(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const from$2=({name:e,prefix:t,encode:r,decode:n})=>new Codec(e,t,r,n),baseX=({prefix:e,name:t,alphabet:r})=>{const{encode:n,decode:o}=_brrp__multiformats_scope_baseX(r,t);return from$2({prefix:e,name:t,encode:n,decode:e=>coerce(o(e))})},decode$j=(e,t,r,n)=>{const o={};for(let e=0;e=8&&(a-=8,s[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s},encode$h=(e,t,r)=>{const n="="===t[t.length-1],o=(1<r;)s-=r,i+=t[o&a>>s];if(s&&(i+=t[o&a<from$2({prefix:t,name:e,encode:e=>encode$h(e,n,r),decode:t=>decode$j(t,n,r,e)}),base58btc=baseX({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});baseX({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});const base32=rfc4648({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5});rfc4648({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),rfc4648({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),rfc4648({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),rfc4648({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),rfc4648({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),rfc4648({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),rfc4648({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),rfc4648({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});class CID{constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=n,this.byteOffset=n.byteOffset,this.byteLength=n.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:hidden,byteLength:hidden,code:readonly,version:readonly,multihash:readonly,bytes:readonly,_baseCache:hidden,asCID:hidden})}toV0(){if(0===this.version)return this;{const{code:e,multihash:t}=this;if(e!==DAG_PB_CODE)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==SHA_256_CODE)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return CID.createV0(t)}}toV1(){switch(this.version){case 0:{const{code:e,digest:t}=this.multihash,r=create$7(e,t);return CID.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&equals(this.multihash,e.multihash)}toString(e){const{bytes:t,version:r,_baseCache:n}=this;return 0===r?toStringV0(t,n,e||base58btc.encoder):toStringV1(t,n,e||base32.encoder)}toJSON(){return{code:this.code,version:this.version,hash:this.multihash.bytes}}get[Symbol.toStringTag](){return"CID"}[Symbol.for("nodejs.util.inspect.custom")](){return"CID("+this.toString()+")"}static isCID(e){return deprecate(/^0\.0/,IS_CID_DEPRECATION),!(!e||!e[cidSymbol]&&e.asCID!==e)}get toBaseEncodedString(){throw new Error("Deprecated, use .toString()")}get codec(){throw new Error('"codec" property is deprecated, use integer "code" property instead')}get buffer(){throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead")}get multibaseName(){throw new Error('"multibaseName" property is deprecated')}get prefix(){throw new Error('"prefix" property is deprecated')}static asCID(e){if(e instanceof CID)return e;if(null!=e&&e.asCID===e){const{version:t,code:r,multihash:n,bytes:o}=e;return new CID(t,r,n,o||encodeCID(t,r,n.bytes))}if(null!=e&&!0===e[cidSymbol]){const{version:t,multihash:r,code:n}=e,o=decode$k(r);return CID.create(t,n,o)}return null}static create(e,t,r){if("number"!=typeof t)throw new Error("String codecs are no longer supported");switch(e){case 0:if(t!==DAG_PB_CODE)throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);return new CID(e,t,r,r.bytes);case 1:{const n=encodeCID(e,t,r.bytes);return new CID(e,t,r,n)}default:throw new Error("Invalid version")}}static createV0(e){return CID.create(0,DAG_PB_CODE,e)}static createV1(e,t){return CID.create(1,e,t)}static decode(e){const[t,r]=CID.decodeFirst(e);if(r.length)throw new Error("Incorrect length");return t}static decodeFirst(e){const t=CID.inspectBytes(e),r=t.size-t.multihashSize,n=coerce(e.subarray(r,r+t.multihashSize));if(n.byteLength!==t.multihashSize)throw new Error("Incorrect length");const o=n.subarray(t.multihashSize-t.digestSize),i=new Digest(t.multihashCode,t.digestSize,o,n);return[0===t.version?CID.createV0(i):CID.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0;const r=()=>{const[r,n]=decode$l(e.subarray(t));return t+=n,r};let n=r(),o=DAG_PB_CODE;if(18===n?(n=0,t=0):1===n&&(o=r()),0!==n&&1!==n)throw new RangeError(`Invalid CID version ${n}`);const i=t,s=r(),a=r(),c=t+a;return{version:n,codec:o,multihashCode:s,digestSize:a,multihashSize:c-i,size:c}}static parse(e,t){const[r,n]=parseCIDtoBytes(e,t),o=CID.decode(n);return o._baseCache.set(r,e),o}}const parseCIDtoBytes=(e,t)=>{switch(e[0]){case"Q":{const r=t||base58btc;return[base58btc.prefix,r.decode(`${base58btc.prefix}${e}`)]}case base58btc.prefix:{const r=t||base58btc;return[base58btc.prefix,r.decode(e)]}case base32.prefix:{const r=t||base32;return[base32.prefix,r.decode(e)]}default:if(null==t)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}},toStringV0=(e,t,r)=>{const{prefix:n}=r;if(n!==base58btc.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const o=t.get(n);if(null==o){const o=r.encode(e).slice(1);return t.set(n,o),o}return o},toStringV1=(e,t,r)=>{const{prefix:n}=r,o=t.get(n);if(null==o){const o=r.encode(e);return t.set(n,o),o}return o},DAG_PB_CODE=112,SHA_256_CODE=18,encodeCID=(e,t,r)=>{const n=encodingLength(e),o=n+encodingLength(t),i=new Uint8Array(o+r.byteLength);return encodeTo(e,i,0),encodeTo(t,i,n),i.set(r,o),i},cidSymbol=Symbol.for("@ipld/js-cid/CID"),readonly={writable:!1,configurable:!1,enumerable:!0},hidden={writable:!1,enumerable:!1,configurable:!1},version="0.0.0-dev",deprecate=(e,t)=>{if(!e.test(version))throw new Error(t);console.warn(t)},IS_CID_DEPRECATION="CID.isCID(v) is deprecated and will be removed in the next major release.\nFollowing code pattern:\n\nif (CID.isCID(value)) {\n doSomethingWithCID(value)\n}\n\nIs replaced with:\n\nconst cid = CID.asCID(value)\nif (cid) {\n // Make sure to use cid instead of value\n doSomethingWithCID(cid)\n}\n",from$1=({name:e,code:t,encode:r})=>new Hasher(e,t,r);class Hasher{constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?create$7(this.code,t):t.then((e=>create$7(this.code,e)))}throw Error("Unknown type, must be binary type")}}const DID_KEY_PREFIX="did:key:",ED25519=237,RSA=4613,P256=4608,algorithm=e=>{const[t]=decode$l(e);switch(t){case ED25519:case RSA:return t;case P256:if(e.length>35)throw new RangeError("Only p256-pub compressed is supported.");return t;default:throw new RangeError(`Unsupported key algorithm with multicode 0x${t.toString(16)}.`)}},parse$4=e=>{if(!e.startsWith(DID_KEY_PREFIX))throw new RangeError(`Invalid DID "${e}", must start with 'did:key:'`);return decode$i(base58btc.decode(e.slice(DID_KEY_PREFIX.length)))},format$3=e=>`${DID_KEY_PREFIX}${base58btc.encode(encode$g(e))}`,decode$i=e=>(algorithm(e),new DID(e.buffer,e.byteOffset,e.byteLength)),encode$g=e=>e,from=e=>e instanceof DID?e:e instanceof Uint8Array?decode$i(e):parse$4(e);class DID extends Uint8Array{did(){return format$3(this)}}const code$8=237,PUBLIC_TAG_SIZE=encodingLength(code$8),SIZE=32+PUBLIC_TAG_SIZE,parse$3=e=>decode$h(parse$4(e)),decode$h=e=>{const[t]=decode$l(e);if(t!==code$8)throw new RangeError(`Unsupported key algorithm with multicode 0x${code$8.toString(16)}`);if(e.byteLength!==SIZE)throw new RangeError(`Expected Uint8Array with byteLength ${SIZE}, instead got Uint8Array with byteLength ${e.byteLength}`);return new Principal(e.buffer,e.byteOffset)},format$2=e=>format$3(e.bytes);class Principal{constructor(e,t=0){this.buffer=e,this.byteOffset=t,this.byteLength=SIZE}get bytes(){const e=new Uint8Array(this.buffer,this.byteOffset,this.byteLength);return Object.defineProperties(this,{bytes:{value:e}}),e}get publicKey(){const e=new Uint8Array(this.buffer,this.byteOffset+PUBLIC_TAG_SIZE);return Object.defineProperties(this,{publicKey:{value:e}}),e}did(){return format$2(this)}verify(e,t){return verify(t,e,this.publicKey)}}const base64$2=rfc4648({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6});rfc4648({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6});const base64url=rfc4648({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6});rfc4648({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});const typeofs=["string","number","bigint","symbol"],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(e){if(null===e)return"null";if(void 0===e)return"undefined";if(!0===e||!1===e)return"boolean";const t=typeof e;return typeofs.includes(t)?t:"function"===t?"Function":Array.isArray(e)?"Array":isBuffer$1(e)?"Buffer":getObjectType(e)||"Object"}function isBuffer$1(e){return e&&e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer.call(null,e)}function getObjectType(e){const t=Object.prototype.toString.call(e).slice(8,-1);if(objectTypeNames.includes(t))return t}class Type{constructor(e,t,r){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=r}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.majore.major?1:0}}Type.uint=new Type(0,"uint",!0),Type.negint=new Type(1,"negint",!0),Type.bytes=new Type(2,"bytes",!0),Type.string=new Type(3,"string",!0),Type.array=new Type(4,"array",!1),Type.map=new Type(5,"map",!1),Type.tag=new Type(6,"tag",!1),Type.float=new Type(7,"float",!0),Type.false=new Type(7,"false",!0),Type.true=new Type(7,"true",!0),Type.null=new Type(7,"null",!0),Type.undefined=new Type(7,"undefined",!0),Type.break=new Type(7,"break",!0);class Token{constructor(e,t,r){this.type=e,this.value=t,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}}const useBuffer=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&"function"==typeof globalThis.Buffer.isBuffer,textDecoder$1=new TextDecoder,textEncoder$2=new TextEncoder;function isBuffer(e){return useBuffer&&globalThis.Buffer.isBuffer(e)}function asU8A(e){return e instanceof Uint8Array?isBuffer(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e:Uint8Array.from(e)}const toString=useBuffer?(e,t,r)=>r-t>64?globalThis.Buffer.from(e.subarray(t,r)).toString("utf8"):utf8Slice(e,t,r):(e,t,r)=>r-t>64?textDecoder$1.decode(e.subarray(t,r)):utf8Slice(e,t,r),fromString=useBuffer?e=>e.length>64?globalThis.Buffer.from(e):utf8ToBytes(e):e=>e.length>64?textEncoder$2.encode(e):utf8ToBytes(e),fromArray=e=>Uint8Array.from(e),slice$1=useBuffer?(e,t,r)=>isBuffer(e)?new Uint8Array(e.subarray(t,r)):e.slice(t,r):(e,t,r)=>e.slice(t,r),concat=useBuffer?(e,t)=>(e=e.map((e=>e instanceof Uint8Array?e:globalThis.Buffer.from(e))),asU8A(globalThis.Buffer.concat(e,t))):(e,t)=>{const r=new Uint8Array(t);let n=0;for(let t of e)n+t.length>r.length&&(t=t.subarray(0,r.length-n)),r.set(t,n),n+=t.length;return r},alloc=useBuffer?e=>globalThis.Buffer.allocUnsafe(e):e=>new Uint8Array(e);function compare(e,t){if(isBuffer(e)&&isBuffer(t))return e.compare(t);for(let r=0;r55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function utf8Slice(e,t,r){const n=[];for(;t239?4:o>223?3:o>191?2:1;if(t+s<=r){let r,n,a,c;switch(s){case 1:o<128&&(i=o);break;case 2:r=e[t+1],128==(192&r)&&(c=(31&o)<<6|63&r,c>127&&(i=c));break;case 3:r=e[t+1],n=e[t+2],128==(192&r)&&128==(192&n)&&(c=(15&o)<<12|(63&r)<<6|63&n,c>2047&&(c<55296||c>57343)&&(i=c));break;case 4:r=e[t+1],n=e[t+2],a=e[t+3],128==(192&r)&&128==(192&n)&&128==(192&a)&&(c=(15&o)<<18|(63&r)<<12|(63&n)<<6|63&a,c>65535&&c<1114112&&(i=c))}}null===i?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|1023&i),n.push(i),t+=s}return decodeCodePointsArray(n)}const MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(e){const t=e.length;if(t<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nr.length/2?(t=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=slice$1(r,0,this.cursor)}else t=concat(this.chunks,this.cursor);return e&&this.reset(),t}}const decodeErrPrefix="CBOR decode error:",encodeErrPrefix="CBOR encode error:";function assertEnoughData(e,t,r){if(e.length-t>>8,255&n])}else if(r>>24&255,n>>>16&255,n>>>8&255,255&n])}else{const n=BigInt(r);if(!(n>BigInt(32)&BigInt(4294967295));r[8]=255&o,o>>=8,r[7]=255&o,o>>=8,r[6]=255&o,o>>=8,r[5]=255&o,r[4]=255&i,i>>=8,r[3]=255&i,i>>=8,r[2]=255&i,i>>=8,r[1]=255&i,e.push(r)}}}function decodeNegint8(e,t,r,n){return new Token(Type.negint,-1-readUint8(e,t+1,n),2)}function decodeNegint16(e,t,r,n){return new Token(Type.negint,-1-readUint16(e,t+1,n),3)}function decodeNegint32(e,t,r,n){return new Token(Type.negint,-1-readUint32(e,t+1,n),5)}encodeUint.encodedSize=function(e){return encodeUintValue.encodedSize(e.value)},encodeUintValue.encodedSize=function(e){return et.value?1:0};const neg1b=BigInt(-1),pos1b=BigInt(1);function decodeNegint64(e,t,r,n){const o=readUint64(e,t+1,n);if("bigint"!=typeof o){const e=-1-o;if(e>=Number.MIN_SAFE_INTEGER)return new Token(Type.negint,e,9)}if(!0!==n.allowBigInt)throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`);return new Token(Type.negint,neg1b-BigInt(o),9)}function encodeNegint(e,t){const r=t.value,n="bigint"==typeof r?r*neg1b-pos1b:-1*r-1;encodeUintValue(e,t.type.majorEncoded,n)}function toToken$3(e,t,r,n){assertEnoughData(e,t,r+n);const o=slice$1(e,t+r,t+r+n);return new Token(Type.bytes,o,r+n)}function decodeBytesCompact(e,t,r,n){return toToken$3(e,t,1,r)}function decodeBytes8(e,t,r,n){return toToken$3(e,t,2,readUint8(e,t+1,n))}function decodeBytes16(e,t,r,n){return toToken$3(e,t,3,readUint16(e,t+1,n))}function decodeBytes32(e,t,r,n){return toToken$3(e,t,5,readUint32(e,t+1,n))}function decodeBytes64(e,t,r,n){const o=readUint64(e,t+1,n);if("bigint"==typeof o)throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`);return toToken$3(e,t,9,o)}function tokenBytes(e){return void 0===e.encodedBytes&&(e.encodedBytes=e.type===Type.string?fromString(e.value):e.value),e.encodedBytes}function encodeBytes(e,t){const r=tokenBytes(t);encodeUintValue(e,t.type.majorEncoded,r.length),e.push(r)}function compareBytes(e,t){return e.lengtht.length?1:compare(e,t)}function toToken$2(e,t,r,n,o){const i=r+n;assertEnoughData(e,t,i);const s=new Token(Type.string,toString(e,t+r,t+i),i);return!0===o.retainStringBytes&&(s.byteValue=slice$1(e,t+r,t+i)),s}function decodeStringCompact(e,t,r,n){return toToken$2(e,t,1,r,n)}function decodeString8(e,t,r,n){return toToken$2(e,t,2,readUint8(e,t+1,n),n)}function decodeString16(e,t,r,n){return toToken$2(e,t,3,readUint16(e,t+1,n),n)}function decodeString32(e,t,r,n){return toToken$2(e,t,5,readUint32(e,t+1,n),n)}function decodeString64(e,t,r,n){const o=readUint64(e,t+1,n);if("bigint"==typeof o)throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`);return toToken$2(e,t,9,o,n)}encodeNegint.encodedSize=function(e){const t=e.value,r="bigint"==typeof t?t*neg1b-pos1b:-1*t-1;return rt.value?-1:0},encodeBytes.encodedSize=function(e){const t=tokenBytes(e);return encodeUintValue.encodedSize(t.length)+t.length},encodeBytes.compareTokens=function(e,t){return compareBytes(tokenBytes(e),tokenBytes(t))};const encodeString=encodeBytes;function toToken$1(e,t,r,n){return new Token(Type.array,n,r)}function decodeArrayCompact(e,t,r,n){return toToken$1(e,t,1,r)}function decodeArray8(e,t,r,n){return toToken$1(e,t,2,readUint8(e,t+1,n))}function decodeArray16(e,t,r,n){return toToken$1(e,t,3,readUint16(e,t+1,n))}function decodeArray32(e,t,r,n){return toToken$1(e,t,5,readUint32(e,t+1,n))}function decodeArray64(e,t,r,n){const o=readUint64(e,t+1,n);if("bigint"==typeof o)throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`);return toToken$1(e,t,9,o)}function decodeArrayIndefinite(e,t,r,n){if(!1===n.allowIndefinite)throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);return toToken$1(e,t,1,1/0)}function encodeArray(e,t){encodeUintValue(e,Type.array.majorEncoded,t.value)}function toToken(e,t,r,n){return new Token(Type.map,n,r)}function decodeMapCompact(e,t,r,n){return toToken(e,t,1,r)}function decodeMap8(e,t,r,n){return toToken(e,t,2,readUint8(e,t+1,n))}function decodeMap16(e,t,r,n){return toToken(e,t,3,readUint16(e,t+1,n))}function decodeMap32(e,t,r,n){return toToken(e,t,5,readUint32(e,t+1,n))}function decodeMap64(e,t,r,n){const o=readUint64(e,t+1,n);if("bigint"==typeof o)throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`);return toToken(e,t,9,o)}function decodeMapIndefinite(e,t,r,n){if(!1===n.allowIndefinite)throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);return toToken(e,t,1,1/0)}function encodeMap(e,t){encodeUintValue(e,Type.map.majorEncoded,t.value)}function decodeTagCompact(e,t,r,n){return new Token(Type.tag,r,1)}function decodeTag8(e,t,r,n){return new Token(Type.tag,readUint8(e,t+1,n),2)}function decodeTag16(e,t,r,n){return new Token(Type.tag,readUint16(e,t+1,n),3)}function decodeTag32(e,t,r,n){return new Token(Type.tag,readUint32(e,t+1,n),5)}function decodeTag64(e,t,r,n){return new Token(Type.tag,readUint64(e,t+1,n),9)}function encodeTag(e,t){encodeUintValue(e,Type.tag.majorEncoded,t.value)}encodeArray.compareTokens=encodeUint.compareTokens,encodeArray.encodedSize=function(e){return encodeUintValue.encodedSize(e.value)},encodeMap.compareTokens=encodeUint.compareTokens,encodeMap.encodedSize=function(e){return encodeUintValue.encodedSize(e.value)},encodeTag.compareTokens=encodeUint.compareTokens,encodeTag.encodedSize=function(e){return encodeUintValue.encodedSize(e.value)};const MINOR_FALSE=20,MINOR_TRUE=21,MINOR_NULL=22,MINOR_UNDEFINED=23;function decodeUndefined(e,t,r,n){if(!1===n.allowUndefined)throw new Error(`${decodeErrPrefix} undefined values are not supported`);return!0===n.coerceUndefinedToNull?new Token(Type.null,null,1):new Token(Type.undefined,void 0,1)}function decodeBreak(e,t,r,n){if(!1===n.allowIndefinite)throw new Error(`${decodeErrPrefix} indefinite length items not allowed`);return new Token(Type.break,void 0,1)}function createToken(e,t,r){if(r){if(!1===r.allowNaN&&Number.isNaN(e))throw new Error(`${decodeErrPrefix} NaN values are not supported`);if(!1===r.allowInfinity&&(e===1/0||e===-1/0))throw new Error(`${decodeErrPrefix} Infinity values are not supported`)}return new Token(Type.float,e,t)}function decodeFloat16(e,t,r,n){return createToken(readFloat16(e,t+1),3,n)}function decodeFloat32(e,t,r,n){return createToken(readFloat32(e,t+1),5,n)}function decodeFloat64(e,t,r,n){return createToken(readFloat64(e,t+1),9,n)}function encodeFloat(e,t,r){const n=t.value;if(!1===n)e.push([Type.float.majorEncoded|MINOR_FALSE]);else if(!0===n)e.push([Type.float.majorEncoded|MINOR_TRUE]);else if(null===n)e.push([Type.float.majorEncoded|MINOR_NULL]);else if(void 0===n)e.push([Type.float.majorEncoded|MINOR_UNDEFINED]);else{let t,o=!1;r&&!0===r.float64||(encodeFloat16(n),t=readFloat16(ui8a,1),n===t||Number.isNaN(n)?(ui8a[0]=249,e.push(ui8a.slice(0,3)),o=!0):(encodeFloat32(n),t=readFloat32(ui8a,1),n===t&&(ui8a[0]=250,e.push(ui8a.slice(0,5)),o=!0))),o||(encodeFloat64(n),t=readFloat64(ui8a,1),ui8a[0]=251,e.push(ui8a.slice(0,9)))}}encodeFloat.encodedSize=function(e,t){const r=e.value;if(!1===r||!0===r||null==r)return 1;if(!t||!0!==t.float64){encodeFloat16(r);let e=readFloat16(ui8a,1);if(r===e||Number.isNaN(r))return 3;if(encodeFloat32(r),e=readFloat32(ui8a,1),r===e)return 5}return 9};const buffer=new ArrayBuffer(9),dataView=new DataView(buffer,1),ui8a=new Uint8Array(buffer,0);function encodeFloat16(e){if(e===1/0)dataView.setUint16(0,31744,!1);else if(e===-1/0)dataView.setUint16(0,64512,!1);else if(Number.isNaN(e))dataView.setUint16(0,32256,!1);else{dataView.setFloat32(0,e);const t=dataView.getUint32(0),r=(2139095040&t)>>23,n=8388607&t;if(255===r)dataView.setUint16(0,31744,!1);else if(0===r)dataView.setUint16(0,(2147483648&e)>>16|n>>13,!1);else{const e=r-127;e<-24?dataView.setUint16(0,0):e<-14?dataView.setUint16(0,(2147483648&t)>>16|1<<24+e,!1):dataView.setUint16(0,(2147483648&t)>>16|e+15<<10|n>>13,!1)}}}function readFloat16(e,t){if(e.length-t<2)throw new Error(`${decodeErrPrefix} not enough data for float16`);const r=(e[t]<<8)+e[t+1];if(31744===r)return 1/0;if(64512===r)return-1/0;if(32256===r)return NaN;const n=r>>10&31,o=1023&r;let i;return i=0===n?o*2**-24:31!==n?(o+1024)*2**(n-25):0===o?1/0:NaN,32768&r?-i:i}function encodeFloat32(e){dataView.setFloat32(0,e,!1)}function readFloat32(e,t){if(e.length-t<4)throw new Error(`${decodeErrPrefix} not enough data for float32`);const r=(e.byteOffset||0)+t;return new DataView(e.buffer,r,4).getFloat32(0,!1)}function encodeFloat64(e){dataView.setFloat64(0,e,!1)}function readFloat64(e,t){if(e.length-t<8)throw new Error(`${decodeErrPrefix} not enough data for float64`);const r=(e.byteOffset||0)+t;return new DataView(e.buffer,r,8).getFloat64(0,!1)}function invalidMinor(e,t,r){throw new Error(`${decodeErrPrefix} encountered invalid minor (${r}) for major ${e[t]>>>5}`)}function errorer(e){return()=>{throw new Error(`${decodeErrPrefix} ${e}`)}}encodeFloat.compareTokens=encodeUint.compareTokens;const jump=[];for(let e=0;e<=23;e++)jump[e]=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 e=32;e<=55;e++)jump[e]=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 e=64;e<=87;e++)jump[e]=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 e=96;e<=119;e++)jump[e]=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 e=128;e<=151;e++)jump[e]=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 e=160;e<=183;e++)jump[e]=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 e=192;e<=215;e++)jump[e]=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 e=224;e<=243;e++)jump[e]=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;const quick=[];for(let e=0;e<24;e++)quick[e]=new Token(Type.uint,e,1);for(let e=-1;e>=-24;e--)quick[31-e]=new Token(Type.negint,e,1);function quickEncodeToken(e){switch(e.type){case Type.false:return fromArray([244]);case Type.true:return fromArray([245]);case Type.null:return fromArray([246]);case Type.bytes:return e.value.length?void 0:fromArray([64]);case Type.string:return""===e.value?fromArray([96]):void 0;case Type.array:return 0===e.value?fromArray([128]):void 0;case Type.map:return 0===e.value?fromArray([160]):void 0;case Type.uint:return e.value<24?fromArray([Number(e.value)]):void 0;case Type.negint:if(e.value>=-24)return fromArray([31-Number(e.value)])}}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,!1,1),quick[245]=new Token(Type.true,!0,1),quick[246]=new Token(Type.null,null,1);const defaultEncodeOptions$2={float64:!1,mapSorter:mapSorter$1,quickEncodeToken:quickEncodeToken};function makeCborEncoders(){const e=[];return e[Type.uint.major]=encodeUint,e[Type.negint.major]=encodeNegint,e[Type.bytes.major]=encodeBytes,e[Type.string.major]=encodeString,e[Type.array.major]=encodeArray,e[Type.map.major]=encodeMap,e[Type.tag.major]=encodeTag,e[Type.float.major]=encodeFloat,e}const cborEncoders$1=makeCborEncoders(),buf=new Bl;class Ref{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do{if(t.obj===e)return!0}while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${encodeErrPrefix} object contains circular references`);return new Ref(t,e)}}const simpleTokens={null:new Token(Type.null,null),undefined:new Token(Type.undefined,void 0),true:new Token(Type.true,!0),false:new Token(Type.false,!1),emptyArray:new Token(Type.array,0),emptyMap:new Token(Type.map,0)},typeEncoders={number:(e,t,r,n)=>Number.isInteger(e)&&Number.isSafeInteger(e)?new Token(e>=0?Type.uint:Type.negint,e):new Token(Type.float,e),bigint:(e,t,r,n)=>e>=BigInt(0)?new Token(Type.uint,e):new Token(Type.negint,e),Uint8Array:(e,t,r,n)=>new Token(Type.bytes,e),string:(e,t,r,n)=>new Token(Type.string,e),boolean:(e,t,r,n)=>e?simpleTokens.true:simpleTokens.false,null:(e,t,r,n)=>simpleTokens.null,undefined:(e,t,r,n)=>simpleTokens.undefined,ArrayBuffer:(e,t,r,n)=>new Token(Type.bytes,new Uint8Array(e)),DataView:(e,t,r,n)=>new Token(Type.bytes,new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),Array(e,t,r,n){if(!e.length)return!0===r.addBreakTokens?[simpleTokens.emptyArray,new Token(Type.break)]:simpleTokens.emptyArray;n=Ref.createCheck(n,e);const o=[];let i=0;for(const t of e)o[i++]=objectToTokens(t,r,n);return r.addBreakTokens?[new Token(Type.array,e.length),o,new Token(Type.break)]:[new Token(Type.array,e.length),o]},Object(e,t,r,n){const o="Object"!==t,i=o?e.keys():Object.keys(e),s=o?e.size:i.length;if(!s)return!0===r.addBreakTokens?[simpleTokens.emptyMap,new Token(Type.break)]:simpleTokens.emptyMap;n=Ref.createCheck(n,e);const a=[];let c=0;for(const t of i)a[c++]=[objectToTokens(t,r,n),objectToTokens(o?e.get(t):e[t],r,n)];return sortMapEntries(a,r),r.addBreakTokens?[new Token(Type.map,s),a,new Token(Type.break)]:[new Token(Type.map,s),a]}};typeEncoders.Map=typeEncoders.Object,typeEncoders.Buffer=typeEncoders.Uint8Array;for(const e of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))typeEncoders[`${e}Array`]=typeEncoders.DataView;function objectToTokens(e,t={},r){const n=is(e),o=t&&t.typeEncoders&&t.typeEncoders[n]||typeEncoders[n];if("function"==typeof o){const i=o(e,n,t,r);if(null!=i)return i}const i=typeEncoders[n];if(!i)throw new Error(`${encodeErrPrefix} unsupported type: ${n}`);return i(e,n,t,r)}function sortMapEntries(e,t){t.mapSorter&&e.sort(t.mapSorter)}function mapSorter$1(e,t){const r=Array.isArray(e[0])?e[0][0]:e[0],n=Array.isArray(t[0])?t[0][0]:t[0];if(r.type!==n.type)return r.type.compare(n.type);const o=r.type.major,i=cborEncoders$1[o].compareTokens(r,n);return 0===i&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function tokensToEncoded(e,t,r,n){if(Array.isArray(t))for(const o of t)tokensToEncoded(e,o,r,n);else r[t.type.major](e,t,n)}function encodeCustom(e,t,r){const n=objectToTokens(e,r);if(!Array.isArray(n)&&r.quickEncodeToken){const e=r.quickEncodeToken(n);if(e)return e;const o=t[n.type.major];if(o.encodedSize){const e=o.encodedSize(n,r),t=new Bl(e);if(o(t,n,r),1!==t.chunks.length)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return asU8A(t.chunks[0])}}return buf.reset(),tokensToEncoded(buf,n,t,r),buf.toBytes(!0)}function encode$f(e,t){return t=Object.assign({},defaultEncodeOptions$2,t),encodeCustom(e,cborEncoders$1,t)}const defaultDecodeOptions={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0};class Tokeniser{constructor(e,t={}){this.pos=0,this.data=e,this.options=t}done(){return this.pos>=this.data.length}next(){const e=this.data[this.pos];let t=quick[e];if(void 0===t){const r=jump[e];if(!r)throw new Error(`${decodeErrPrefix} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);const n=31&e;t=r(this.data,this.pos,n,this.options)}return this.pos+=t.encodedLength,t}}const DONE=Symbol.for("DONE"),BREAK=Symbol.for("BREAK");function tokenToArray(e,t,r){const n=[];for(let o=0;oencode$f(e,encodeOptions$1),decode$f=e=>decode$g(e,decodeOptions$1),sha=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),sha256=from$1({name:"sha2-256",code:18,encode:sha("SHA-256")});from$1({name:"sha2-512",code:19,encode:sha("SHA-512")});const encoder=new TextEncoder,decoder=new TextDecoder,encode$d=e=>encoder.encode(e),decode$e=e=>decoder.decode(e);class JSONEncoder extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){const t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===Type.array&&(t.elements++,1!==t.elements&&e.push([44])),t.type===Type.map&&(t.elements++,1!==t.elements&&(t.elements%2==1?e.push([44]):e.push([58]))))}[Type.uint.major](e,t){this.prefix(e);const r=String(t.value),n=[];for(let e=0;e32?asU8A(r):r)}[Type.array.major](e,t){this.prefix(e),this.inRecursive.push({type:Type.array,elements:0}),e.push([91])}[Type.map.major](e,t){this.prefix(e),this.inRecursive.push({type:Type.map,elements:0}),e.push([123])}[Type.tag.major](e,t){}[Type.float.major](e,t){if("break"===t.type.name){const t=this.inRecursive.pop();if(t){if(t.type===Type.array)e.push([93]);else{if(t.type!==Type.map)throw new Error("Unexpected recursive type; this should not happen!");e.push([125])}return}throw new Error("Unexpected break; this should not happen!")}if(void 0===t.value)throw new Error(`${encodeErrPrefix} unsupported type: undefined`);if(this.prefix(e),"true"===t.type.name)return void e.push([116,114,117,101]);if("false"===t.type.name)return void e.push([102,97,108,115,101]);if("null"===t.type.name)return void e.push([110,117,108,108]);const r=String(t.value),n=[];let o=!1;for(let e=0;en)return 1;throw new Error(`${encodeErrPrefix} unexpected duplicate map keys, this is not supported`)}const defaultEncodeOptions$1={addBreakTokens:!0,mapSorter:mapSorter};function encode$c(e,t){return t=Object.assign({},defaultEncodeOptions$1,t),encodeCustom(e,new JSONEncoder,t)}class Tokenizer{constructor(e,t={}){this.pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}done(){return this.pos>=this.data.length}ch(){return this.data[this.pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;32===e||9===e||13===e||10===e;)e=this.data[++this.pos]}expect(e){if(this.data.length-this.pos{for(;!this.done();){const t=this.ch();if(!e.includes(t))break;this.pos++}};if(45===this.ch()&&(t=!0,this.pos++),48===this.ch()){if(this.pos++,46!==this.ch())return new Token(Type.uint,0,this.pos-e);this.pos++,r=!0}if(n([48,49,50,51,52,53,54,55,56,57]),t&&this.pos===e+1)throw new Error(`${decodeErrPrefix} unexpected token at position ${this.pos}`);if(!this.done()&&46===this.ch()){if(r)throw new Error(`${decodeErrPrefix} unexpected token at position ${this.pos}`);r=!0,this.pos++,n([48,49,50,51,52,53,54,55,56,57])}this.done()||101!==this.ch()&&69!==this.ch()||(r=!0,this.pos++,this.done()||43!==this.ch()&&45!==this.ch()||this.pos++,n([48,49,50,51,52,53,54,55,56,57]));const o=String.fromCharCode.apply(null,this.data.subarray(e,this.pos)),i=parseFloat(o);return r?new Token(Type.float,i,this.pos-e):!0!==this.options.allowBigInt||Number.isSafeInteger(i)?new Token(i>=0?Type.uint:Type.negint,i,this.pos-e):new Token(i>=0?Type.uint:Type.negint,BigInt(o),this.pos-e)}parseString(){if(34!==this.ch())throw new Error(`${decodeErrPrefix} unexpected character at position ${this.pos}; this shouldn't happen`);this.pos++;for(let e=this.pos,t=0;e=128)break;if(34===r){const r=String.fromCharCode.apply(null,this.data.subarray(this.pos,e));return this.pos=e+1,new Token(Type.string,r,t)}}const e=this.pos,t=[],r=()=>{if(this.pos+4>=this.data.length)throw new Error(`${decodeErrPrefix} unexpected end of unicode escape sequence at position ${this.pos}`);let e=0;for(let t=0;t<4;t++){let t=this.ch();if(t>=48&&t<=57)t-=48;else if(t>=97&&t<=102)t=t-97+10;else{if(!(t>=65&&t<=70))throw new Error(`${decodeErrPrefix} unexpected unicode escape character at position ${this.pos}`);t=t-65+10}e=16*e+t,this.pos++}return e},n=()=>{const e=this.ch();let r,n,o,i,s=null,a=e>239?4:e>223?3:e>191?2:1;if(this.pos+a>this.data.length)throw new Error(`${decodeErrPrefix} unexpected unicode sequence at position ${this.pos}`);switch(a){case 1:e<128&&(s=e);break;case 2:r=this.data[this.pos+1],128==(192&r)&&(i=(31&e)<<6|63&r,i>127&&(s=i));break;case 3:r=this.data[this.pos+1],n=this.data[this.pos+2],128==(192&r)&&128==(192&n)&&(i=(15&e)<<12|(63&r)<<6|63&n,i>2047&&(i<55296||i>57343)&&(s=i));break;case 4:r=this.data[this.pos+1],n=this.data[this.pos+2],o=this.data[this.pos+3],128==(192&r)&&128==(192&n)&&128==(192&o)&&(i=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&o,i>65535&&i<1114112&&(s=i))}null===s?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|1023&s),t.push(s),this.pos+=a};for(;!this.done();){const o=this.ch();let i;switch(o){case 92:if(this.pos++,this.done())throw new Error(`${decodeErrPrefix} unexpected string termination at position ${this.pos}`);switch(i=this.ch(),this.pos++,i){case 34:case 39:case 92:case 47:t.push(i);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(r());break;default:throw new Error(`${decodeErrPrefix} unexpected string escape character at position ${this.pos}`)}break;case 34:return this.pos++,new Token(Type.string,decodeCodePointsArray(t),this.pos-e);default:if(o<32)throw new Error(`${decodeErrPrefix} invalid control character at position ${this.pos}`);o<128?(t.push(o),this.pos++):n()}}throw new Error(`${decodeErrPrefix} unexpected end of string at position ${this.pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this.pos++,new Token(Type.map,1/0,1);case 91:return this.modeStack.push("array-start"),this.pos++,new Token(Type.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new Token(Type.null,null,4);case 102:return this.expect([102,97,108,115,101]),new Token(Type.false,!1,5);case 116:return this.expect([116,114,117,101]),new Token(Type.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${decodeErrPrefix} unexpected character at position ${this.pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":if(this.modeStack.pop(),93===this.ch())return this.pos++,this.skipWhitespace(),new Token(Type.break,void 0,1);if(44!==this.ch())throw new Error(`${decodeErrPrefix} unexpected character at position ${this.pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this.pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue();case"array-start":return this.modeStack.pop(),93===this.ch()?(this.pos++,this.skipWhitespace(),new Token(Type.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(125===this.ch())return this.modeStack.pop(),this.pos++,this.skipWhitespace(),new Token(Type.break,void 0,1);if(44!==this.ch())throw new Error(`${decodeErrPrefix} unexpected character at position ${this.pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this.pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),125===this.ch())return this.pos++,this.skipWhitespace(),new Token(Type.break,void 0,1);const e=this.parseString();if(this.skipWhitespace(),58!==this.ch())throw new Error(`${decodeErrPrefix} unexpected character at position ${this.pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this.pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${decodeErrPrefix} unexpected parse state at position ${this.pos}; this shouldn't happen`)}}}function decode$d(e,t){return decode$g(e,t=Object.assign({tokenizer:new Tokenizer(e,t)},t))}function cidEncoder(e){if(e.asCID!==e)return null;const t=CID.asCID(e);if(!t)return null;const r=t.toString();return[new Token(Type.map,1/0,1),new Token(Type.string,"/",1),new Token(Type.string,r,r.length),new Token(Type.break,void 0,1)]}function bytesEncoder(e){const t=base64$2.encode(e).slice(1);return[new Token(Type.map,1/0,1),new Token(Type.string,"/",1),new Token(Type.map,1/0,1),new Token(Type.string,"bytes",5),new Token(Type.string,t,t.length),new Token(Type.break,void 0,1),new Token(Type.break,void 0,1)]}function undefinedEncoder(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function numberEncoder(e){if(Number.isNaN(e))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(e===1/0||e===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}const encodeOptions={typeEncoders:{Object:cidEncoder,Uint8Array:bytesEncoder,Buffer:bytesEncoder,undefined:undefinedEncoder,number:numberEncoder}};class DagJsonTokenizer extends Tokenizer{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return 0===this.tokenBuffer.length&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){const e=this._next();if(e.type===Type.map){const e=this._next();if(e.type===Type.string&&"/"===e.value){const e=this._next();if(e.type===Type.string){if(this._next().type!==Type.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(e),new Token(Type.tag,42,0)}if(e.type===Type.map){const e=this._next();if(e.type===Type.string&&"bytes"===e.value){const e=this._next();if(e.type===Type.string){for(let e=0;e<2;e++)if(this._next().type!==Type.break)throw new Error("Invalid encoded Bytes form");const t=base64$2.decode(`m${e.value}`);return new Token(Type.bytes,t,e.value.length)}this.tokenBuffer.push(e)}this.tokenBuffer.push(e)}this.tokenBuffer.push(e)}this.tokenBuffer.push(e)}return e}}const decodeOptions={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,tags:[]};decodeOptions.tags[42]=CID.parse;const encode$b=e=>encode$c(e,encodeOptions),decode$c=e=>decode$d(e,Object.assign(decodeOptions,{tokenizer:new DagJsonTokenizer(e,decodeOptions)})),code$6=0,name$3="identity",encode$a=coerce,digest=e=>create$7(code$6,encode$a(e)),identity={code:code$6,name:name$3,encode:encode$a,digest:digest},name$2="raw",code$5=85,encode$9=e=>coerce(e),decode$b=e=>coerce(e);var raw=Object.freeze({__proto__:null,name:name$2,code:code$5,encode:encode$9,decode:decode$b});const parse$2=e=>{const t=e.split("."),[r,n,o]=3===t.length?t:ParseError.throw(`Can't parse UCAN: ${e}: Expected JWT format: 3 dot-separated base64url-encoded values.`);return{...parseHeader(r),...parsePayload(n),signature:base64url.baseDecode(o)}},parseHeader=e=>{const{ucv:t,alg:r,typ:n}=decode$c(base64url.baseDecode(e));return parseJWT(n),parseAlgorithm(r),{version:parseVersion(t,"ucv")}},parsePayload=e=>{const t=decode$c(base64url.baseDecode(e));return{issuer:parseDID$2(t.iss,"iss"),audience:parseDID$2(t.aud,"aud"),expiration:parseInt$1(t.exp,"exp"),nonce:parseOptionalString(t.nnc,"nnc"),notBefore:parseOptionalInt(t.nbf,"nbf"),facts:parseOptionalArray(t.fct,parseFact,"fct")||[],proofs:parseProofs(t.prf,"prf"),capabilities:parseCapabilities(t.att,"att")}},parseInt$1=(e,t)=>Number.isInteger(e)?e:ParseError.throw(`Expected integer but instead got '${t}: ${JSON.stringify(e)}'`),parseCapability=(e,t)=>parseStruct(e,asCapability,t),parseCapabilities=(e,t)=>parseArray(e,parseCapability,t),asCapability=e=>{const t={...e,can:parseAbility(e.can),with:parseResource(e.with)},r=t.with;return r.endsWith("*")&&"*"!==t.can&&(r.startsWith("my:")||r.startsWith("as:did:"))?ParseError.throw(`Capability has invalid 'can: ${JSON.stringify(e.can)}', for all 'my:*' or 'as::*' it must be '*'.`):t},parseAbility=e=>"string"!=typeof e?ParseError.throw(`Capability has invalid 'can: ${JSON.stringify(e)}', value must be a string`):e.slice(1,-1).includes("/")?e.toLocaleLowerCase():"*"===e?e:ParseError.throw(`Capability has invalid 'can: "${e}"', value must have at least one path segment`),parseResource=e=>"string"!=typeof e?ParseError.throw(`Capability has invalid 'with: ${JSON.stringify(e)}', value must be a string`):parseURL(e)||ParseError.throw(`Capability has invalid 'with: "${e}"', value must be a valid URI string`),parseURL=e=>{try{return new URL(e),e}catch(e){return null}},parseArray=(e,t,r)=>Array.isArray(e)?e.map(((e,n)=>t(e,`${r}[${n}]`))):ParseError.throw(`${r} must be an array`),parseOptionalArray=(e,t,r)=>void 0===e?e:parseArray(e,t,r),parseStruct=(e,t,r)=>null!=e&&"object"==typeof e?t(e):ParseError.throw(`${r} must be of type object, instead got ${e}`),parseFact=(e,t)=>parseStruct(e,Object,t),parseProofs=(e,t)=>Array.isArray(e)?parseArray(e,parseProof$1,t):[parseProof$1(e,t)],parseProof$1=(e,t)=>{const r="string"==typeof e?e:ParseError.throw(`${t} has invalid value ${JSON.stringify(e)}, must be a string`);try{return CID.parse(r)}catch(e){return CID.create(1,code$5,identity.digest(encode$d(r)))}},parseDID$2=(e,t)=>"string"==typeof e&&e.startsWith("did:")?parse$4(e):ParseError.throw(`DID has invalid representation '${t}: ${JSON.stringify(e)}'`),parseOptionalString=(e,t="Field")=>{switch(typeof e){case"string":case"undefined":return e;default:return ParseError.throw(`${t} has invalid value ${e}`)}},parseOptionalInt=(e,t)=>{switch(typeof e){case"undefined":return;case"number":return parseInt$1(e,t);default:return ParseError.throw(`${t} has invalid value ${JSON.stringify(e)}`)}},parseVersion=(e,t)=>/\d+\.\d+\.\d+/.test(e)?e:ParseError.throw(`Invalid version '${t}: ${JSON.stringify(e)}'`),parseBytes=(e,t)=>e instanceof Uint8Array?e:ParseError.throw(`${t} must be Uint8Array, instead got ${JSON.stringify(e)}`),parseJWT=e=>"JWT"===e?e:ParseError.throw(`Header has invalid type 'typ: "${e}"'`),parseAlgorithm=e=>{switch(e){case"EdDSA":return 237;case"RS256":return 4613;default:return ParseError.throw(`Header has invalid algorithm 'alg: ${JSON.stringify(e)}'`)}};class ParseError extends TypeError{get name(){return"ParseError"}static throw(e){throw new this(e)}}class View$1{constructor(e){this.model=e}get version(){return this.model.version}get issuer(){return from(this.model.issuer)}get audience(){return from(this.model.audience)}get capabilities(){return this.model.capabilities}get expiration(){return this.model.expiration}get notBefore(){return this.model.notBefore}get nonce(){return this.model.nonce}get facts(){return this.model.facts}get proofs(){return this.model.proofs}get signature(){return this.model.signature}}class JWTView extends Uint8Array{constructor(e,{buffer:t,byteOffset:r=0,byteLength:n=t.byteLength}){super(t,r,n),this.model=e}get version(){return this.model.version}get issuer(){return from(this.model.issuer)}get audience(){return from(this.model.audience)}get capabilities(){return this.model.capabilities}get expiration(){return this.model.expiration}get notBefore(){return this.model.notBefore}get nonce(){return this.model.nonce}get facts(){return this.model.facts}get proofs(){return this.model.proofs}get signature(){return this.model.signature}}const cbor=e=>new View$1(e),jwt=(e,t)=>new JWTView(e,t),code$4=code$7,encode$8=e=>{const{facts:t,nonce:r,notBefore:n,...o}=match$2(e);return encode$e({...o,...t.length>0&&{facts:t},...e.nonce&&{nonce:r},...e.notBefore&&{notBefore:e.notBefore},signature:parseBytes(e.signature,"signature")})},decode$a=e=>cbor(match$2(decode$f(e))),match$2=e=>({version:parseVersion(e.version,"version"),issuer:parseDID$1(e.issuer,"issuer"),audience:parseDID$1(e.audience,"audience"),capabilities:parseCapabilities(e.capabilities,"capabilities"),expiration:parseInt$1(e.expiration,"expiration"),proofs:parseOptionalArray(e.proofs,parseProof,"proofs")||[],signature:parseBytes(e.signature,"signature"),nonce:parseOptionalString(e.nonce,"nonce"),facts:parseOptionalArray(e.facts,parseFact,"facts")||[],notBefore:parseOptionalInt(e.notBefore,"notBefore")}),parseProof=(e,t)=>CID.asCID(e)||ParseError.throw(`Expected ${t} to be CID, instead got ${JSON.stringify(e)}`),parseDID$1=(e,t)=>e instanceof Uint8Array?decode$i(e):ParseError.throw(`Expected ${t} to be Uint8Array, instead got ${JSON.stringify(e)}`),code$3=code$5,encode$7=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),format$1=e=>`${formatHeader(e)}.${formatPayload(e)}.${formatSignature(e.signature)}`,formatSignPayload=e=>`${formatHeader(e)}.${formatPayload(e)}`,formatHeader=e=>base64url.baseEncode(encodeHeader(e)),formatPayload=e=>base64url.baseEncode(encodePayload(e)),formatSignature=e=>base64url.baseEncode(e),encodeHeader=e=>encode$b({alg:encodeAgorithm(e),ucv:e.version,typ:"JWT"}),encodePayload=e=>encode$b({iss:format$3(e.issuer),aud:format$3(e.audience),att:e.capabilities,exp:e.expiration,prf:e.proofs.map(encodeProof),...e.facts.length>0&&{fct:e.facts},...e.nonce&&{nnc:e.nonce},...e.notBefore&&{nbf:e.notBefore}}),encodeProof=e=>e.toString(),encodeAgorithm=e=>{switch(algorithm(e.issuer)){case ED25519:return"EdDSA";case RSA:return"RS256";default:throw new RangeError(`Unknown KeyType "${algorithm(e.issuer)}"`)}},VERSION="0.8.1",decode$9=e=>{try{return decode$a(e)}catch(t){const r=decode$e(e);return parse$1(r)}},write$6=async(e,t)=>{const r=t?.hasher||sha256,[n,o]=e instanceof Uint8Array?[code$3,encode$7(e)]:[code$4,encode$8(e)];return{cid:CID.createV1(n,await r.digest(o)),bytes:o,data:e}},parse$1=e=>{const t=parse$2(e);return format$1(t)===e?cbor(t):jwt(t,encode$d(e))},issue=async({issuer:e,audience:t,capabilities:r,lifetimeInSeconds:n=30,expiration:o=Math.floor(Date.now()/1e3)+n,notBefore:i,facts:s=[],proofs:a=[],nonce:c})=>{const u=match$2({version:VERSION,issuer:parseDID(e,"issuer"),audience:parseDID(t,"audience"),capabilities:r,facts:s,expiration:o,notBefore:i,proofs:a,nonce:c,signature:EMPTY$4}),d=encode$d(formatSignPayload(u)),l=await e.sign(d);return cbor({...u,signature:l})},parseDID=(e,t)=>e&&"function"==typeof e.did?parseDID$2(e.did(),`${t}.did()`):ParseError.throw(`The ${t}.did() must be a function that returns DID`),EMPTY$4=new Uint8Array,create$6=(e,t)=>CID.createV1(e,t),isLink=e=>null!=e&&e.asCID===e,asLink$1=CID.asCID;CID.parse,CID.decode;const isDelegation=e=>!isLink(e);class Delegation{constructor(e,t=new Map){this.root=e,this.blocks=t,Object.defineProperties(this,{blocks:{enumerable:!1}})}get version(){return this.data.version}get signature(){return this.data.signature}get cid(){return this.root.cid}get asCID(){return this.cid}get bytes(){return this.root.bytes}get data(){const e=decode$8(this.root);return Object.defineProperties(this,{data:{value:e,enumerable:!1}}),e}export(){return exportDAG(this.root,this.blocks)}get proofs(){return proofs(this)}get issuer(){return this.data.issuer}get audience(){return this.data.audience}get capabilities(){return this.data.capabilities}get expiration(){return this.data.expiration}get notBefore(){return this.data.notBefore}get nonce(){return this.data.nonce}get facts(){return this.data.facts}iterate(){return it(this)}}const it=function*(e){for(const t of e.proofs)isDelegation(t)&&(yield*it(t),yield t)},decodeCache=new WeakMap,decode$8=({bytes:e})=>{const t=decodeCache.get(e);if(!t){const t=decode$9(e);return decodeCache.set(e,t),t}return t},delegate=async({issuer:e,audience:t,proofs:r=[],...n},o)=>{const i=[],s=new Map;for(const e of r)if(isDelegation(e)){i.push(e.cid);for(const t of e.export())s.set(t.cid.toString(),t)}else i.push(e);const a=await issue({...n,issuer:e,audience:t,proofs:i}),{cid:c,bytes:u}=await write$6(a,o);decodeCache.set(c,a);const d=new Delegation({cid:c,bytes:u},s);return Object.defineProperties(d,{proofs:{value:r}}),d},exportDAG=function*(e,t){for(const r of decode$8(e).proofs){const e=t.get(r.toString());e&&(yield*exportDAG(e,t))}yield e},create$5=({root:e,blocks:t})=>new Delegation(e,t),proofs=e=>{const t=[],{root:r,blocks:n}=e;for(const e of decode$8(r).proofs){const r=n.get(e.toString());t.push(r?create$5({root:r,blocks:n}):e)}return Object.defineProperty(e,"proofs",{value:t}),t},invoke=e=>new IssuedInvocation(e);class IssuedInvocation{constructor({issuer:e,audience:t,capability:r,proofs:n=[],expiration:o,lifetimeInSeconds:i,notBefore:s,nonce:a,facts:c=[]}){this.issuer=e,this.audience=t,this.proofs=n,this.capabilities=[r],this.expiration=o,this.lifetimeInSeconds=i,this.notBefore=s,this.nonce=a,this.facts=c}delegate(){return delegate(this)}async execute(e){const[t]=await e.execute(this);return t}}const prepare$1=(e,t)=>{if(t.has(e))throw new TypeError("Can not encode circular structure");if(void 0===e&&0===t.size)return null;if(null===e)return null;if("symbol"==typeof e&&0===t.size)return null;const r=asLink$1(e);if(r)return r;if(ArrayBuffer.isView(e))return e;if(Array.isArray(e)){t.add(e);const r=[];for(const n of e)r.push(void 0===n||"symbol"==typeof n?null:prepare$1(n,t));return r}if("function"==typeof e.toJSON){t.add(e);const r=e.toJSON();return prepare$1(r,t)}if("object"==typeof e){t.add(e);const r={};for(const[n,o]of Object.entries(e))void 0!==o&&"symbol"!=typeof o&&(r[n]=prepare$1(o,t));return r}return e},encode$6=e=>encode$e(prepare$1(e,new Set)),link$2=async(e,{hasher:t=sha256}={})=>create$6(code$7,await t.digest(e)),write$5=async(e,t)=>{const r=encode$6(e);return{cid:await link$2(r,t),bytes:r}};var CBOR$1=Object.freeze({__proto__:null,encode:encode$6,link:link$2,write:write$5,code:code$7,decode:decode$f});const HEADERS$1=Object.freeze({"content-type":"application/cbor"}),codec$1=CBOR$1,encode$5=e=>({headers:HEADERS$1,body:encode$6(e)}),decode$7=async({headers:e,body:t})=>{const r=e["content-type"]||e["Content-Type"];if("application/cbor"!==r)throw TypeError(`Only 'content-type: application/cbor' is supported, intsead got '${r}'`);return decode$f(t)};var CBOR=Object.freeze({__proto__:null,codec:codec$1,encode:encode$5,decode:decode$7}),commonjsGlobal$1="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==commonjsGlobal?commonjsGlobal:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var encode_1=encode$4,MSB$1=128,REST$1=127,MSBALL=~REST$1,INT=Math.pow(2,31);function encode$4(e,t,r){if(Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw encode$4.bytes=0,new RangeError("Could not encode varint");t=t||[];for(var n=r=r||0;e>=INT;)t[r++]=255&e|MSB$1,e/=128;for(;e&MSBALL;)t[r++]=255&e|MSB$1,e>>>=7;return t[r]=0|e,encode$4.bytes=r-n+1,t}var decode$6=read,MSB=128,REST=127;function read(e,t){var r,n=0,o=0,i=t=t||0,s=e.length;do{if(i>=s||o>49)throw read.bytes=0,new RangeError("Could not decode varint");r=e[i++],n+=o<28?(r&REST)<=MSB);return read.bytes=i-t,n}var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63),length=function(e){return e{const{resize:n=!1}=r,{bytes:o,headerSize:i,byteOffset:s,roots:a}=e;e.roots.push(t);const c=headerLength(e);if(c>i){if(!(c-i+s{const r=e.bytes.byteLength+t.byteLength;return varint.encodingLength(r)+r},addBlock=(e,{cid:t,bytes:r})=>{const n=t.bytes.byteLength+r.byteLength,o=varint.encode(n);if(e.byteOffset+o.length+n>e.bytes.byteLength)throw new RangeError("Buffer has no capacity for this block");writeBytes$1(e,o),writeBytes$1(e,t.bytes),writeBytes$1(e,r)},close$6=(e,t={})=>{const{resize:r=!1}=t,{roots:n,bytes:o,byteOffset:i,headerSize:s}=e,a=encode$e({version:1,roots:n}),c=varint.encode(a.length),u=c.length+a.byteLength;if(0==s-u)return writeHeader(e,c,a),o.subarray(0,i);if(r)return resizeHeader(e,u),writeHeader(e,c,a),o.subarray(0,e.byteOffset);throw new RangeError("Header size was overestimated.\nYou can use close({ resize: true }) to resize header")},resizeHeader=(e,t)=>{const{bytes:r,headerSize:n}=e;r.set(r.subarray(n,e.byteOffset),t),e.byteOffset+=t-n,e.headerSize=t},writeBytes$1=(e,t)=>{e.bytes.set(t,e.byteOffset),e.byteOffset+=t.length},writeHeader=({bytes:e},t,r)=>{e.set(t),e.set(r,t.length)},headerPreludeTokens=[new Token(Type.map,2),new Token(Type.string,"version"),new Token(Type.uint,1),new Token(Type.string,"roots")],CID_TAG=new Token(Type.tag,42),calculateHeaderLength=e=>{const t=[...headerPreludeTokens];t.push(new Token(Type.array,e.length));for(const r of e)t.push(CID_TAG),t.push(new Token(Type.bytes,{length:r+1}));const r=tokensToLength(t);return varint.encodingLength(r)+r},headerLength=({roots:e})=>calculateHeaderLength(e.map((e=>e.bytes.byteLength))),createWriter$2=(e,t={})=>{const{roots:r=[],byteOffset:n=0,byteLength:o=e.byteLength,headerSize:i=headerLength({roots:r})}=t,s=new Uint8Array(e,n,o),a=new CarBufferWriter(s,i);for(const e of r)a.addRoot(e);return a},Kinds={Null:e=>null===e,Int:e=>Number.isInteger(e),Float:e=>"number"==typeof e&&Number.isFinite(e),String:e=>"string"==typeof e,Bool:e=>"boolean"==typeof e,Bytes:e=>e instanceof Uint8Array,Link:e=>!Kinds.Null(e)&&"object"==typeof e&&e.asCID===e,List:e=>Array.isArray(e),Map:e=>!Kinds.Null(e)&&"object"==typeof e&&e.asCID!==e&&!Kinds.List(e)&&!Kinds.Bytes(e)},Types={Int:Kinds.Int,"CarHeader > version":e=>Types.Int(e),"CarHeader > roots (anon) > valueType (anon)":Kinds.Link,"CarHeader > roots (anon)":e=>Kinds.List(e)&&Array.prototype.every.call(e,Types["CarHeader > roots (anon) > valueType (anon)"]),"CarHeader > roots":e=>Types["CarHeader > roots (anon)"](e),CarHeader:e=>{const t=e&&Object.keys(e);return Kinds.Map(e)&&["version"].every((e=>t.includes(e)))&&Object.entries(e).every((([e,t])=>Types["CarHeader > "+e]&&Types["CarHeader > "+e](t)))}},CarHeader=Types.CarHeader,CIDV0_BYTES={SHA2_256:18,LENGTH:32,DAG_PB:112},V2_HEADER_LENGTH=40;async function readVarint(e){const t=await e.upTo(8);if(!t.length)throw new Error("Unexpected end of data");const r=varint.decode(t);return e.seek(varint.decode.bytes),r}async function readV2Header(e){const t=await e.exactly(V2_HEADER_LENGTH),r=new DataView(t.buffer,t.byteOffset,t.byteLength);let n=0;const o={version:2,characteristics:[r.getBigUint64(n,!0),r.getBigUint64(n+=8,!0)],dataOffset:Number(r.getBigUint64(n+=8,!0)),dataSize:Number(r.getBigUint64(n+=8,!0)),indexOffset:Number(r.getBigUint64(n+=8,!0))};return e.seek(V2_HEADER_LENGTH),o}async function readHeader(e,t){const r=await readVarint(e);if(0===r)throw new Error("Invalid CAR header (zero length)");const n=await e.exactly(r);e.seek(r);const o=decode$f(n);if(!CarHeader(o))throw new Error("Invalid CAR header format");if(1!==o.version&&2!==o.version||void 0!==t&&o.version!==t)throw new Error(`Invalid CAR version: ${o.version}${void 0!==t?` (expected ${t})`:""}`);const i=Array.isArray(o.roots);if(1===o.version&&!i||2===o.version&&i)throw new Error("Invalid CAR header format");if(1===o.version)return o;const s=await readV2Header(e);e.seek(s.dataOffset-e.pos);const a=await readHeader(e,1);return Object.assign(a,s)}async function readMultihash(e){const t=await e.upTo(8);varint.decode(t);const r=varint.decode.bytes,n=varint.decode(t.subarray(varint.decode.bytes)),o=r+varint.decode.bytes+n,i=await e.exactly(o);return e.seek(o),i}async function readCid(e){const t=await e.exactly(2);if(t[0]===CIDV0_BYTES.SHA2_256&&t[1]===CIDV0_BYTES.LENGTH){const t=await e.exactly(34);e.seek(34);const r=decode$k(t);return CID.create(0,CIDV0_BYTES.DAG_PB,r)}const r=await readVarint(e);if(1!==r)throw new Error(`Unexpected CID version (${r})`);const n=await readVarint(e),o=await readMultihash(e),i=decode$k(o);return CID.create(r,n,i)}async function readBlockHead(e){const t=e.pos;let r=await readVarint(e);if(0===r)throw new Error("Invalid CAR section (zero length)");return r+=e.pos-t,{cid:await readCid(e),length:r,blockLength:r-Number(e.pos-t)}}async function readBlock(e){const{cid:t,blockLength:r}=await readBlockHead(e),n=await e.exactly(r);return e.seek(r),{bytes:n,cid:t}}async function readBlockIndex(e){const t=e.pos,{cid:r,length:n,blockLength:o}=await readBlockHead(e),i={cid:r,length:n,blockLength:o,offset:t,blockOffset:e.pos};return e.seek(i.blockLength),i}function createDecoder(e){const t=(async()=>{const t=await readHeader(e);if(2===t.version){const r=e.pos-t.dataOffset;e=limitReader(e,t.dataSize-r)}return t})();return{header:()=>t,async*blocks(){for(await t;(await e.upTo(8)).length>0;)yield await readBlock(e)},async*blocksIndex(){for(await t;(await e.upTo(8)).length>0;)yield await readBlockIndex(e)}}}function bytesReader(e){let t=0;return{upTo:async r=>e.subarray(t,t+Math.min(r,e.length-t)),async exactly(r){if(r>e.length-t)throw new Error("Unexpected end of data");return e.subarray(t,t+r)},seek(e){t+=e},get pos(){return t}}}function chunkReader(e){let t=0,r=0,n=0,o=new Uint8Array(0);const i=async t=>{r=o.length-n;const i=[o.subarray(n)];for(;rr&&i.push(t.subarray(-r)):i.push(t),r+=t.length}o=new Uint8Array(i.reduce(((e,t)=>e+t.length),0));let s=0;for(const e of i)o.set(e,s),s+=e.length;n=0};return{upTo:async e=>(o.length-nt&&(o=o.subarray(0,t-r)),o},async exactly(n){const o=await e.exactly(n);if(o.length+r>t)throw new Error("Unexpected end of data");return o},seek(t){r+=t,e.seek(t)},get pos(){return e.pos}}}class CarReader{constructor(e,t){this._header=e,this._blocks=t,this._keys=t.map((e=>e.cid.toString()))}get version(){return this._header.version}async getRoots(){return this._header.roots}async has(e){return this._keys.indexOf(e.toString())>-1}async get(e){const t=this._keys.indexOf(e.toString());return t>-1?this._blocks[t]:void 0}async*blocks(){for(const e of this._blocks)yield e}async*cids(){for(const e of this._blocks)yield e.cid}static async fromBytes(e){if(!(e instanceof Uint8Array))throw new TypeError("fromBytes() requires a Uint8Array");return decodeReaderComplete(bytesReader(e))}static async fromIterable(e){if(!e||"function"!=typeof e[Symbol.asyncIterator])throw new TypeError("fromIterable() requires an async iterable");return decodeReaderComplete(asyncIterableReader(e))}}async function decodeReaderComplete(e){const t=createDecoder(e),r=await t.header(),n=[];for await(const e of t.blocks())n.push(e);return new CarReader(r,n)}const code$2=514;class Writer$2{constructor(e=[],t=0){this.written=new Set,this.blocks=e,this.byteLength=t}write(...e){for(const t of e){const e=t.cid.toString(base32);this.written.has(e)||(this.blocks.push(t),this.byteLength+=blockLength(t),this.written.add(e))}return this}flush(...e){const t=[];for(const r of e.reverse()){const e=r.cid.toString(base32);this.written.has(e)||(this.blocks.unshift(r),this.byteLength+=blockLength({cid:r.cid,bytes:r.bytes}),this.written.add(e)),t.push(r.cid)}this.byteLength+=headerLength({roots:t});const r=new ArrayBuffer(this.byteLength),n=createWriter$2(r,{roots:t});for(const e of this.blocks)n.write(e);return n.close()}}const createWriter$1=()=>new Writer$2,encode$3=({roots:e=[],blocks:t})=>{const r=new Writer$2;return t&&r.write(...t.values()),r.flush(...e)},decode$5=async e=>{const t=await CarReader.fromBytes(e),{_header:r,_blocks:n,_keys:o}=t,i=[],s=new Map,a=r.roots.map((e=>o.indexOf(String(e))));for(const[e,t]of n.entries())a.includes(e)?i.push(t):s.set(t.cid.toString(),t);return{roots:i,blocks:s}},link$1=async(e,{hasher:t=sha256}={})=>create$6(code$2,await t.digest(e)),write$4=async(e,t)=>{const r=encode$3(e);return{bytes:r,cid:await link$1(r,t)}};var codec=Object.freeze({__proto__:null,code:code$2,createWriter:createWriter$1,encode:encode$3,decode:decode$5,link:link$1,write:write$4});const HEADERS=Object.freeze({"content-type":"application/car"}),encode$2=async(e,t)=>{const r=[],n=new Map;for(const o of e){const e=await delegate(o,t);r.push(e.root);for(const t of e.export())n.set(t.cid.toString(),t);n.delete(e.root.cid.toString())}const o=encode$3({roots:r,blocks:n});return{headers:HEADERS,body:o}},decode$4=async({headers:e,body:t})=>{const r=e["content-type"]||e["Content-Type"];if("application/car"!==r)throw TypeError(`Only 'content-type: application/car' is supported, instead got '${r}'`);const{roots:n,blocks:o}=await decode$5(t),i=[];for(const e of n)i.push(create$5({root:e,blocks:o}));return i};var CAR=Object.freeze({__proto__:null,codec:codec,encode:encode$2,decode:decode$4});new TextEncoder,new TextDecoder,Object.freeze({"content-type":"application/json"});const open$2=({url:e,method:t="POST",fetch:r})=>{if(!r){if(void 0===globalThis.fetch)throw new TypeError("ucanto HTTP transport got undefined `fetch`. Try passing in a `fetch` implementation explicitly.");r=globalThis.fetch.bind(globalThis)}return new Channel({url:e,method:t,fetch:r})};class Channel{constructor({url:e,fetch:t,method:r}){this.fetch=t,this.method=r,this.url=e}async request({headers:e,body:t}){const r=await this.fetch(this.url.href,{headers:e,body:t,method:this.method}),n=r.ok?await r.arrayBuffer():HTTPError.throw("HTTP Request failed",r);return{headers:Object.fromEntries(r.headers.entries()),body:new Uint8Array(n)}}}class HTTPError extends Error{static throw(e,t){throw new this(e,t)}constructor(e,{url:t,status:r=500,statusText:n="Server error"}){super(e),this.name="HTTPError",this.url=t,this.status=r,this.statusText=n}}const the=e=>e,entries=e=>Object.entries(e),combine=([e,...t])=>{const r=e.map((e=>[e]));for(const e of t){const t=r.splice(0);for(const n of e)for(const e of t)r.push([...e,n])}return r},intersection=(e,t)=>{const[r,n]=e.lengthli(e.message)))].join("\n")}get cause(){if(1!==this.causes.length)return this;{const[e]=this.causes,t="InvalidClaim"===e.name?e.cause:e;return Object.defineProperties(this,{cause:{value:t}}),t}}}class MalformedCapability extends Failure{constructor(e,t){super(),this.name=the("MalformedCapability"),this.capability=e,this.cause=t}describe(){return[`Encountered malformed '${this.capability.can}' capability: ${format(this.capability)}`,li(this.cause.message)].join("\n")}}class UnknownCapability extends Failure{constructor(e){super(),this.name=the("UnknownCapability"),this.capability=e}describe(){return`Encountered unknown capability: ${format(this.capability)}`}}const format=(e,t)=>JSON.stringify(e,((e,t)=>t&&t.asCID===t?t.toString():t),t),indent=(e,t=" ")=>`${t}${e.split("\n").join(`\n${t}`)}`,li=e=>indent(`- ${e}`),capability=e=>new Capability(e),or=(e,t)=>new Or(e,t),and=(...e)=>new And(e),derive=({from:e,to:t,derives:r})=>new Derive(e,t,r);class View{match(e){return new UnknownCapability(e.capability)}select(e){return select(this,e)}derive({derives:e,to:t}){return derive({derives:e,to:t,from:this})}}class Unit extends View{or(e){return or(this,e)}and(e){return and(this,e)}}class Capability extends Unit{constructor(e){super(),this.descriptor={derives:derives$1,...e}}create(e){const{descriptor:t,can:r}=this,n=t.caveats,o=e.caveats||{},i=t.with.decode(e.with);if(i.error)throw Object.assign(new Error(`Invalid 'with' - ${i.message}`),{cause:i});const s={};for(const[e,t]of Object.entries(n||{})){const r=e,n=t.decode(o[r]);if(n?.error)throw Object.assign(new Error(`Invalid 'caveats.${r}' - ${n.message}`),{cause:n});void 0!==n&&(s[e]=n)}return{...s,can:r,with:i.href}}invoke({with:e,caveats:t,...r}){return invoke({...r,capability:this.create({with:e,caveats:t})})}get can(){return this.descriptor.can}match(e){const t=parse(this,e);return t.error?t:new Match(e,t,this.descriptor)}toString(){return JSON.stringify({can:this.descriptor.can})}}class Or extends Unit{constructor(e,t){super(),this.left=e,this.right=t}match(e){const t=this.left.match(e);if(t.error){const r=this.right.match(e);return r.error?"MalformedCapability"===r.name?r:t:r}return t}toString(){return`${this.left.toString()}|${this.right.toString()}`}}class And extends View{constructor(e){super(),this.selectors=e}match(e){const t=[];for(const r of this.selectors){const n=r.match(e);if(n.error)return n;t.push(n)}return new AndMatch(t)}select(e){return selectGroup(this,e)}and(e){return new And([...this.selectors,e])}toString(){return`[${this.selectors.map(String).join(", ")}]`}}class Derive extends Unit{constructor(e,t,r){super(),this.from=e,this.to=t,this.derives=r}create(e){return this.to.create(e)}invoke(e){return this.to.invoke(e)}get can(){return this.to.can}match(e){const t=this.to.match(e);return t.error?t:new DerivedMatch(t,this.from,this.derives)}toString(){return this.to.toString()}}class Match{constructor(e,t,r){this.source=[e],this.value=t,this.descriptor={derives:derives$1,...r}}get can(){return this.value.can}get proofs(){const e=[this.source[0].delegation];return Object.defineProperties(this,{proofs:{value:e}}),e}prune(e){return e.canIssue(this.value,this.source[0].delegation.issuer.did())?null:this}select(e){const t=[],r=[],n=[];for(const o of e){const e=parse(this,o);if(e.error)"UnknownCapability"===e.name?t.push(e.capability):r.push(new DelegationError([e],this));else{const t=this.descriptor.derives(this.value,e);t.error?r.push(new DelegationError([new EscalatedCapability(this.value,e,t)],this)):n.push(new Match(o,e,this.descriptor))}}return{matches:n,unknown:t,errors:r}}toString(){return JSON.stringify({can:this.descriptor.can,with:this.value.uri.href,caveats:Object.keys(this.value.caveats).length>0?this.value.caveats:void 0})}}class DerivedMatch{constructor(e,t,r){this.selected=e,this.from=t,this.derives=r}get can(){return this.value.can}get source(){return this.selected.source}get proofs(){const e=[];for(const{delegation:t}of this.selected.source)e.push(t);return Object.defineProperties(this,{proofs:{value:e}}),e}get value(){return this.selected.value}prune(e){const t=this.selected.prune(e);return t?new DerivedMatch(t,this.from,this.derives):null}select(e){const{derives:t,selected:r,from:n}=this,{value:o}=r,i=r.select(e),s=n.select(e),a=[],c=[];for(const e of s.matches){const r=t(o,e.value);r.error?c.push(new DelegationError([new EscalatedCapability(o,e.value,r)],this)):a.push(e)}return{unknown:intersection(i.unknown,s.unknown),errors:[...c,...i.errors,...s.errors.map((e=>new DelegationError([e],this)))],matches:[...i.matches.map((e=>new DerivedMatch(e,n,t))),...a]}}toString(){return this.selected.toString()}}class AndMatch{constructor(e){this.matches=e}get selectors(){return this.matches}get source(){const e=[];for(const t of this.matches)e.push(...t.source);return Object.defineProperties(this,{source:{value:e}}),e}prune(e){const t=[];for(const r of this.matches){const n=r.prune(e);n&&t.push(n)}return 0===t.length?null:new AndMatch(t)}get proofs(){const e=[];for(const{delegation:t}of this.source)e.push(t);return Object.defineProperties(this,{source:{value:e}}),e}get value(){const e=[];for(const t of this.matches)e.push(t.value);return Object.defineProperties(this,{value:{value:e}}),e}select(e){return selectGroup(this,e)}toString(){return`[${this.matches.map((e=>e.toString())).join(", ")}]`}}const parse=(e,t)=>{const{can:r,with:n,caveats:o}=e.descriptor,{delegation:i,index:s}=t,a=t.capability;if(a.can!==r)return new UnknownCapability(a);const c=n.decode(a.with);if(c.error)return new MalformedCapability(a,c);const u={};if(o)for(const[e,t]of entries(o)){const r=e,n=a[r],o=t.decode(n);if(o?.error)return new MalformedCapability(a,o);null!=o&&(u[r]=o)}return new CapabilityView(r,a.with,c,u,i)};class CapabilityView{constructor(e,t,r,n,o){this.can=e,this.with=t,this.uri=r,this.delegation=o,this.caveats=n}}const select=(e,t)=>{const r=[],n=[],o=[];for(const i of t){const t=e.match(i);t.error?"UnknownCapability"===t.name?r.push(t.capability):o.push(new DelegationError([t],t.capability)):n.push(t)}return{matches:n,errors:o,unknown:r}},selectGroup=(e,t)=>{let r;const n=[],o=[];for(const i of e.selectors){const s=i.select(t);r=r?intersection(r,s.unknown):s.unknown;for(const t of s.errors)o.push(new DelegationError([t],e));n.push(s.matches)}const i=combine(n).map((e=>new AndMatch(e)));return{unknown:r||[],errors:o,matches:i}},derives$1=(e,t)=>{if(t.with.endsWith("*")){if(!e.with.startsWith(t.with.slice(0,-1)))return new Failure(`Resource ${e.with} does not match delegated ${t.with} `)}else if(t.with!==e.with)return new Failure(`Resource ${e.with} does not contain ${t.with}`);for(const[r,n]of entries(t.caveats))if(e.caveats[r]!=n)return new Failure(`${String(r)}: ${e.caveats[r]} violates ${n}`);return!0},decode$3=(e,{protocol:t}={})=>{if("string"!=typeof e&&!(e instanceof URL))return new Failure("Expected URI but got "+typeof e);try{const r=new URL(String(e));return null!=t&&r.protocol!==t?new Failure(`Expected ${t} URI instead got ${r.href}`):r}catch(e){return new Failure("Invalid URI")}},match$1=e=>({decode:t=>decode$3(t,e)}),decode$2=(e,t={})=>{if(null==e)return new Failure(`Expected link but got ${e} instead`);{const r=asLink$1(e);return null==r?new Failure(`Expected link to be a CID instead of ${e}`):null!=t.code&&r.code!==t.code?new Failure(`Expected link to be CID with 0x${t.code.toString(16)} codec`):null!=t.algorithm&&r.multihash.code!==t.algorithm?new Failure(`Expected link to be CID with 0x${t.algorithm.toString(16)} hashing algorithm`):null!=t.version&&r.version!==t.version?new Failure(`Expected link to be CID version ${t.version} instead of ${r.version}`):r}},match=e=>({decode:t=>decode$2(t,e)}),optional=e=>({decode:t=>void 0===t?void 0:decode$2(t,e)});function equalWith(e,t){return e.with===t.with||new Failure(`Can not derive ${e.can} with ${e.with} from ${t.with}`)}function equal(e,t,r){return void 0===t||"*"===t||String(e)===String(t)||new Failure(`Contastraint vilation: ${e} violates imposed ${r} constraint ${t}`)}const derives=(e,t)=>e.uri.href!==t.uri.href?new Failure(`Expected 'with: "${t.uri.href}"' instead got '${e.uri.href}'`):!t.caveats.link||`${t.caveats.link}`==`${e.caveats.link}`||new Failure(`Link ${null==e.caveats.link?"":`${e.caveats.link} `}violates imposed ${t.caveats.link} constraint`);function fail(e){return!0===e?void 0:e}class Never{decode(e){return new Failure("Given input is not valid")}optional(){return new Optional(this)}}class Optional{constructor(e){this.decoder=e}optional(){return this}decode(e){return void 0===e?void 0:this.decoder.decode(e)}}class List extends Never{static of(e){return new this(e)}constructor(e){super(),this.decoder=e}decode(e){if(!Array.isArray(e))return new Failure(`Expected to be an array instead got ${e} `);const t=[];for(const r of e){const e=this.decoder.decode(r);if(e?.error)return new Failure(`Array containts invalid element: ${e.message}`);t.push(e)}return t}}class IntegerDecoder extends Never{constructor({min:e=-1/0,max:t=1/0}={}){super(),this.min=e,this.max=t}static isInteger(e){return Number.isInteger(e)}decode(e){const{min:t,max:r}=this;return IntegerDecoder.isInteger(e)?t>e?new Failure(`Expecting an Integer > ${t} but instead got ${e}`):r{const r=derives(e,t);return r.error?r:null==e.caveats.size||null==t.caveats.size||!(e.caveats.size>t.caveats.size)||new Failure(`Size constraint violation: ${e.caveats.size} > ${t.caveats.size}`)}}),derives:equalWith}),remove$1=base$1.derive({to:capability({can:"store/remove",with:match$1({protocol:"did:"}),caveats:{link:optional()},derives:derives}),derives:equalWith}),list=base$1.derive({to:capability({can:"store/list",with:match$1({protocol:"did:"}),derives:(e,t)=>e.uri.href===t.uri.href||new Failure(`Expected 'with: "${t.uri.href}"' instead got '${e.uri.href}'`)}),derives:equalWith});add$1.or(remove$1).or(list);const upload=any.derive({to:capability({can:"upload/*",with:match$1({protocol:"did:"}),derives:equalWith}),derives:equalWith}),base=any.or(upload),CARLink=match({code:code$2,version:1}),add=base.derive({to:capability({can:"upload/add",with:match$1({protocol:"did:"}),caveats:{root:optional(),shards:List.of(CARLink).optional()},derives:(e,t)=>fail(equalWith(e,t))||fail(equal(e.caveats.root,t.caveats.root,"root"))||fail(equal(e.caveats.shards,t.caveats.shards,"shards"))||!0}),derives:equalWith});base.derive({to:capability({can:"upload/remove",with:match$1({protocol:"did:"}),caveats:{root:optional()},derives:(e,t)=>fail(equalWith(e,t))||fail(equal(e.caveats.root,t.caveats.root,"root"))||!0}),derives:equalWith}),base.derive({to:capability({can:"upload/list",with:match$1({protocol:"did:"})}),derives:equalWith});const connect=e=>new Connection(e);class Connection{constructor(e){this.id=e.id,this.options=e,this.encoder=e.encoder,this.decoder=e.decoder,this.channel=e.channel,this.hasher=e.hasher||sha256}execute(...e){return execute(e,this)}}const execute=async(e,t)=>{const r=await t.encoder.encode(e,t),n=await t.channel.request(r);return await t.decoder.decode(n)},url=new URL("https://access-api.web3.storage");function connection({id:e,url:t=url,fetch:r}){return connect({id:e,encoder:CAR,decoder:CBOR,channel:open$2({url:t,method:"POST",fetch:r})})}parse$3("did:key:z6MkkHafoFWxxWVNpNXocFdU6PL2RVLyTEgS1qTnD3bRP7V9");var retry$2={exports:{}},retry$1={};function RetryOperation(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}var retry_operation=RetryOperation,e,t;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},RetryOperation.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout((function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout((function(){n._operationTimeoutCb(n._attempts)}),n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)}),r),this._options.unref&&this._timer.unref(),!0},RetryOperation.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout((function(){r._operationTimeoutCb()}),r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},RetryOperation.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},RetryOperation.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},RetryOperation.prototype.start=RetryOperation.prototype.try,RetryOperation.prototype.errors=function(){return this._errors},RetryOperation.prototype.attempts=function(){return this._attempts},RetryOperation.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n=r&&(t=o,r=s)}return t},e=retry$1,t=retry_operation,e.operation=function(r){var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o{const n=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=n,e},isNetworkError=e=>networkErrorMsgs.has(e),getDOMException=e=>void 0===globalThis.DOMException?new Error(e):new DOMException(e);async function pRetry(e,t){return new Promise(((r,n)=>{t={onFailedAttempt(){},retries:10,...t};const o=retry.operation(t);o.attempt((async i=>{try{r(await e(i))}catch(e){if(!(e instanceof Error))return void n(new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));if(e instanceof AbortError)o.stop(),n(e.originalError);else if(e instanceof TypeError&&!isNetworkError(e.message))o.stop(),n(e);else{decorateErrorWithCounts(e,i,t);try{await t.onFailedAttempt(e)}catch(e){return void n(e)}o.retry(e)||n(o.mainError())}}})),t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",(()=>{o.stop();const e=void 0===t.signal.reason?getDOMException("The operation was aborted."):t.signal.reason;n(e instanceof Error?e:getDOMException(e))}),{once:!0})}))}function getIterator(e){if("function"==typeof e.next)return e;if("function"==typeof e[Symbol.iterator])return e[Symbol.iterator]();if("function"==typeof e[Symbol.asyncIterator])return e[Symbol.asyncIterator]();throw new TypeError('"values" does not to conform to any of the iterator or iterable protocols')}function defer(){let e,t;return{promise:new Promise(((r,n)=>{t=r,e=n})),reject:e,resolve:t}}function _transform(e,t,r){const n=getIterator(r),o=[],i=[];let s=!1,a=!1,c=0,u=null;function d(){for(;i.length>0&&o.length>0;){const{resolve:e}=i.shift();e({done:!1,value:o.shift()})}for(;i.length>0&&0===c&&s;){const{resolve:e,reject:t}=i.shift();u?(t(u),u=null):e({done:!0,value:void 0})}}async function l(){if(s)d();else if(!(a||c+o.length>=e)){a=!0,c++;try{const{done:e,value:r}=await n.next();e?(s=!0,c--,d()):async function(e){try{const r=await t(e);o.push(r)}catch(e){s=!0,u=e}c--,d(),l()}(r)}catch(e){s=!0,c--,u=e,d()}a=!1,l()}}const f={next:async function(){if(0===o.length){const e=defer();return i.push(e),l(),e.promise}const e=o.shift();return l(),{done:!1,value:e}},[Symbol.asyncIterator]:()=>f};return f}function transform(e,t,r){return void 0===t?(t,r)=>r?transform(e,t,r):transform(e,t):void 0===r?r=>transform(e,t,r):_transform(e,t,r)}var id=0;function _classPrivateFieldLooseKey(e){return"__private_"+id+++"_"+e}function _classPrivateFieldLooseBase(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw new TypeError("attempted to use private field on non-instance");return e}const textDecoder=new TextDecoder;function decodeVarint(e,t){let r=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(t>=e.length)throw new Error("protobuf: unexpected end of data");const o=e[t++];if(r+=n<28?(127&o)<e.length)throw new Error("protobuf: unexpected end of data");return[e.subarray(t,n),n]}function decodeKey(e,t){let r;return[r,t]=decodeVarint(e,t),[7&r,r>>3,t]}function decodeLink(e){const t={},r=e.length;let n=0;for(;nr)throw new Error("protobuf: (PBLink) unexpected end of data");return t}function decodeNode(e){const t=e.length;let r,n,o=0,i=!1;for(;ot)throw new Error("protobuf: (PBNode) unexpected end of data");const s={};return n&&(s.Data=n),s.Links=r||[],s}const textEncoder$1=new TextEncoder,maxInt32=2**32,maxUInt32=2**31;function encodeLink$1(e,t){let r=t.length;if("number"==typeof e.Tsize){if(e.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(e.Tsize))throw new Error("Tsize too large for encoding");r=encodeVarint(t,r,e.Tsize)-1,t[r]=24}if("string"==typeof e.Name){const n=textEncoder$1.encode(e.Name);r-=n.length,t.set(n,r),r=encodeVarint(t,r,n.length)-1,t[r]=18}return e.Hash&&(r-=e.Hash.length,t.set(e.Hash,r),r=encodeVarint(t,r,e.Hash.length)-1,t[r]=10),t.length-r}function encodeNode(e){const t=sizeNode(e),r=new Uint8Array(t);let n=t;if(e.Data&&(n-=e.Data.length,r.set(e.Data,n),n=encodeVarint(r,n,e.Data.length)-1,r[n]=10),e.Links)for(let t=e.Links.length-1;t>=0;t--){const o=encodeLink$1(e.Links[t],r.subarray(0,n));n-=o,n=encodeVarint(r,n,o)-1,r[n]=18}return r}function sizeLink(e){let t=0;if(e.Hash){const r=e.Hash.length;t+=1+r+sov(r)}if("string"==typeof e.Name){const r=textEncoder$1.encode(e.Name).length;t+=1+r+sov(r)}return"number"==typeof e.Tsize&&(t+=1+sov(e.Tsize)),t}function sizeNode(e){let t=0;if(e.Data){const r=e.Data.length;t+=1+r+sov(r)}if(e.Links)for(const r of e.Links){const e=sizeLink(r);t+=1+e+sov(e)}return t}function encodeVarint(e,t,r){const n=t-=sov(r);for(;r>=maxUInt32;)e[t++]=127&r|128,r/=128;for(;r>=128;)e[t++]=127&r|128,r>>>=7;return e[t]=r,n}function sov(e){return e%2==0&&e++,Math.floor((len64(e)+6)/7)}function len64(e){let t=0;return e>=maxInt32&&(e=Math.floor(e/maxInt32),t=32),e>=65536&&(e>>>=16,t+=16),e>=256&&(e>>>=8,t+=8),t+len8tab[e]}const 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],pbNodeProperties=["Data","Links"],pbLinkProperties=["Hash","Name","Tsize"],textEncoder=new TextEncoder;function linkComparator(e,t){if(e===t)return 0;const r=e.Name?textEncoder.encode(e.Name):[],n=t.Name?textEncoder.encode(t.Name):[];let o=r.length,i=n.length;for(let e=0,t=Math.min(o,i);e!t.includes(e)))}function asLink(e){if("object"==typeof e.asCID){const t=CID.asCID(e);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if("object"!=typeof e||Array.isArray(e))throw new TypeError("Invalid DAG-PB form");const t={};if(e.Hash){let r=CID.asCID(e.Hash);try{r||("string"==typeof e.Hash?r=CID.parse(e.Hash):e.Hash instanceof Uint8Array&&(r=CID.decode(e.Hash)))}catch(e){throw new TypeError(`Invalid DAG-PB form: ${e.message}`)}r&&(t.Hash=r)}if(!t.Hash)throw new TypeError("Invalid DAG-PB form");return"string"==typeof e.Name&&(t.Name=e.Name),"number"==typeof e.Tsize&&(t.Tsize=e.Tsize),t}function prepare(e){if((e instanceof Uint8Array||"string"==typeof e)&&(e={Data:e}),"object"!=typeof e||Array.isArray(e))throw new TypeError("Invalid DAG-PB form");const t={};if(void 0!==e.Data)if("string"==typeof e.Data)t.Data=textEncoder.encode(e.Data);else{if(!(e.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form");t.Data=e.Data}if(void 0!==e.Links){if(!Array.isArray(e.Links))throw new TypeError("Invalid DAG-PB form");t.Links=e.Links.map(asLink),t.Links.sort(linkComparator)}else t.Links=[];return t}function validate(e){if(!e||"object"!=typeof e||Array.isArray(e))throw new TypeError("Invalid DAG-PB form");if(!hasOnlyProperties(e,pbNodeProperties))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(void 0!==e.Data&&!(e.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be a Uint8Array)");if(!Array.isArray(e.Links))throw new TypeError("Invalid DAG-PB form (Links must be an array)");for(let t=0;t0&&-1===linkComparator(r,e.Links[t-1]))throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}const code$1=112;function encode$1(e){validate(e);const t={};return e.Links&&(t.Links=e.Links.map((e=>{const t={};return e.Hash&&(t.Hash=e.Hash.bytes),void 0!==e.Name&&(t.Name=e.Name),void 0!==e.Tsize&&(t.Tsize=e.Tsize),t}))),e.Data&&(t.Data=e.Data),encodeNode(t)}function decode$1(e){const t=decodeNode(e),r={};return t.Data&&(r.Data=t.Data),t.Links&&(r.Links=t.Links.map((e=>{const t={};try{t.Hash=CID.decode(e.Hash)}catch(e){}if(!t.Hash)throw new Error("Invalid Hash field found in link, expected CID");return void 0!==e.Name&&(t.Name=e.Name),void 0!==e.Tsize&&(t.Tsize=e.Tsize),t}))),r}var minimal$1={exports:{}},indexMinimal={},minimal={},aspromise=asPromise;function asPromise(e,t){for(var r=new Array(arguments.length-1),n=0,o=2,i=!0;o1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var r=new Array(64),n=new Array(123),o=0;o<64;)n[r[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;t.encode=function(e,t,n){for(var o,i=null,s=[],a=0,c=0;t>2],o=(3&u)<<4,c=1;break;case 1:s[a++]=r[o|u>>4],o=(15&u)<<2,c=2;break;case 2:s[a++]=r[o|u>>6],s[a++]=r[63&u],c=0}a>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,s)),a=0)}return c&&(s[a++]=r[o],s[a++]=61,1===c&&(s[a++]=61)),i?(a&&i.push(String.fromCharCode.apply(String,s.slice(0,a))),i.join("")):String.fromCharCode.apply(String,s.slice(0,a))};var i="invalid encoding";t.decode=function(e,t,r){for(var o,s=r,a=0,c=0;c1)break;if(void 0===(u=n[u]))throw Error(i);switch(a){case 0:o=u,a=1;break;case 1:t[r++]=o<<2|(48&u)>>4,o=u,a=2;break;case 2:t[r++]=(15&o)<<4|(60&u)>>2,o=u,a=3;break;case 3:t[r++]=(3&o)<<6|u,a=0}}if(1===a)throw Error(i);return r-s},t.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}}(base64$1);var eventemitter=EventEmitter;function EventEmitter(){this._listeners={}}EventEmitter.prototype.on=function(e,t,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:r||this}),this},EventEmitter.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var r=this._listeners[e],n=0;n0?0:2147483648,r,n);else if(isNaN(t))e(2143289344,r,n);else if(t>34028234663852886e22)e((o<<31|2139095040)>>>0,r,n);else if(t<11754943508222875e-54)e((o<<31|Math.round(t/1401298464324817e-60))>>>0,r,n);else{var i=Math.floor(Math.log(t)/Math.LN2);e((o<<31|i+127<<23|8388607&Math.round(t*Math.pow(2,-i)*8388608))>>>0,r,n)}}function r(e,t,r){var n=e(t,r),o=2*(n>>31)+1,i=n>>>23&255,s=8388607&n;return 255===i?s?NaN:o*(1/0):0===i?1401298464324817e-60*o*s:o*Math.pow(2,i-150)*(s+8388608)}e.writeFloatLE=t.bind(null,writeUintLE),e.writeFloatBE=t.bind(null,writeUintBE),e.readFloatLE=r.bind(null,readUintLE),e.readFloatBE=r.bind(null,readUintBE)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),n=128===r[7];function o(e,n,o){t[0]=e,n[o]=r[0],n[o+1]=r[1],n[o+2]=r[2],n[o+3]=r[3],n[o+4]=r[4],n[o+5]=r[5],n[o+6]=r[6],n[o+7]=r[7]}function i(e,n,o){t[0]=e,n[o]=r[7],n[o+1]=r[6],n[o+2]=r[5],n[o+3]=r[4],n[o+4]=r[3],n[o+5]=r[2],n[o+6]=r[1],n[o+7]=r[0]}function s(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],r[4]=e[n+4],r[5]=e[n+5],r[6]=e[n+6],r[7]=e[n+7],t[0]}function a(e,n){return r[7]=e[n],r[6]=e[n+1],r[5]=e[n+2],r[4]=e[n+3],r[3]=e[n+4],r[2]=e[n+5],r[1]=e[n+6],r[0]=e[n+7],t[0]}e.writeDoubleLE=n?o:i,e.writeDoubleBE=n?i:o,e.readDoubleLE=n?s:a,e.readDoubleBE=n?a:s}():function(){function t(e,t,r,n,o,i){var s=n<0?1:0;if(s&&(n=-n),0===n)e(0,o,i+t),e(1/n>0?0:2147483648,o,i+r);else if(isNaN(n))e(0,o,i+t),e(2146959360,o,i+r);else if(n>17976931348623157e292)e(0,o,i+t),e((s<<31|2146435072)>>>0,o,i+r);else{var a;if(n<22250738585072014e-324)e((a=n/5e-324)>>>0,o,i+t),e((s<<31|a/4294967296)>>>0,o,i+r);else{var c=Math.floor(Math.log(n)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=n*Math.pow(2,-c))>>>0,o,i+t),e((s<<31|c+1023<<20|1048576*a&1048575)>>>0,o,i+r)}}}function r(e,t,r,n,o){var i=e(n,o+t),s=e(n,o+r),a=2*(s>>31)+1,c=s>>>20&2047,u=4294967296*(1048575&s)+i;return 2047===c?u?NaN:a*(1/0):0===c?5e-324*a*u:a*Math.pow(2,c-1075)*(u+4503599627370496)}e.writeDoubleLE=t.bind(null,writeUintLE,0,4),e.writeDoubleBE=t.bind(null,writeUintBE,4,0),e.readDoubleLE=r.bind(null,readUintLE,0,4),e.readDoubleBE=r.bind(null,readUintBE,4,0)}(),e}function writeUintLE(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function writeUintBE(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function readUintLE(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function readUintBE(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}var inquire_1=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}var utf8$2={};!function(e){var t=e;t.length=function(e){for(var t=0,r=0,n=0;n191&&n<224?i[s++]=(31&n)<<6|63&e[t++]:n>239&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,i[s++]=55296+(n>>10),i[s++]=56320+(1023&n)):i[s++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],s>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,i)),s=0);return o?(s&&o.push(String.fromCharCode.apply(String,i.slice(0,s))),o.join("")):String.fromCharCode.apply(String,i.slice(0,s))},t.write=function(e,t,r){for(var n,o,i=r,s=0;s>6|192,t[r++]=63&n|128):55296==(64512&n)&&56320==(64512&(o=e.charCodeAt(s+1)))?(n=65536+((1023&n)<<10)+(1023&o),++s,t[r++]=n>>18|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128,t[r++]=63&n|128):(t[r++]=n>>12|224,t[r++]=n>>6&63|128,t[r++]=63&n|128);return r-i}}(utf8$2);var pool_1=pool,longbits,hasRequiredLongbits,hasRequiredMinimal;function pool(e,t,r){var n=r||8192,o=n>>>1,i=null,s=n;return function(r){if(r<1||r>o)return e(r);s+r>n&&(i=e(n),s=0);var a=t.call(i,s,s+=r);return 7&s&&(s=1+(7|s)),a}}function requireLongbits(){if(hasRequiredLongbits)return longbits;hasRequiredLongbits=1,longbits=t;var e=requireMinimal();function t(e,t){this.lo=e>>>0,this.hi=t>>>0}var r=t.zero=new t(0,0);r.toNumber=function(){return 0},r.zzEncode=r.zzDecode=function(){return this},r.length=function(){return 1};var n=t.zeroHash="\0\0\0\0\0\0\0\0";t.fromNumber=function(e){if(0===e)return r;var n=e<0;n&&(e=-e);var o=e>>>0,i=(e-o)/4294967296>>>0;return n&&(i=~i>>>0,o=~o>>>0,++o>4294967295&&(o=0,++i>4294967295&&(i=0))),new t(o,i)},t.from=function(n){if("number"==typeof n)return t.fromNumber(n);if(e.isString(n)){if(!e.Long)return t.fromNumber(parseInt(n,10));n=e.Long.fromString(n)}return n.low||n.high?new t(n.low>>>0,n.high>>>0):r},t.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},t.prototype.toLong=function(t){return e.Long?new e.Long(0|this.lo,0|this.hi,Boolean(t)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var o=String.prototype.charCodeAt;return t.fromHash=function(e){return e===n?r:new t((o.call(e,0)|o.call(e,1)<<8|o.call(e,2)<<16|o.call(e,3)<<24)>>>0,(o.call(e,4)|o.call(e,5)<<8|o.call(e,6)<<16|o.call(e,7)<<24)>>>0)},t.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},t.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},t.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},t.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10},longbits}function requireMinimal(){return hasRequiredMinimal||(hasRequiredMinimal=1,function(e){var t=e;function r(e,t,r){for(var n=Object.keys(t),o=0;o0)},t.Buffer=function(){try{var e=t.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),t._Buffer_from=null,t._Buffer_allocUnsafe=null,t.newBuffer=function(e){return"number"==typeof e?t.Buffer?t._Buffer_allocUnsafe(e):new t.Array(e):t.Buffer?t._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},t.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,t.Long=t.global.dcodeIO&&t.global.dcodeIO.Long||t.global.Long||t.inquire("long"),t.key2Re=/^true|false|0|1$/,t.key32Re=/^-?(?:0|[1-9][0-9]*)$/,t.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,t.longToHash=function(e){return e?t.LongBits.from(e).toHash():t.LongBits.zeroHash},t.longFromHash=function(e,r){var n=t.LongBits.fromHash(e);return t.Long?t.Long.fromBits(n.lo,n.hi,r):n.toNumber(Boolean(r))},t.merge=r,t.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},t.newError=n,t.ProtocolError=n("ProtocolError"),t.oneOfGetter=function(e){for(var t={},r=0;r-1;--r)if(1===t[e[r]]&&void 0!==this[e[r]]&&null!==this[e[r]])return e[r]}},t.oneOfSetter=function(e){return function(t){for(var r=0;r127;)t[r++]=127&e|128,e>>>=7;t[r]=e}function VarintOp(e,t){this.len=e,this.next=void 0,this.val=t}function writeVarint64(e,t,r){for(;e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function writeFixed32(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}Writer$1.create=create$4(),Writer$1.alloc=function(e){return new util$4.Array(e)},util$4.Array!==Array&&(Writer$1.alloc=util$4.pool(Writer$1.alloc,util$4.Array.prototype.subarray)),Writer$1.prototype._push=function(e,t,r){return this.tail=this.tail.next=new Op(e,t,r),this.len+=t,this},VarintOp.prototype=Object.create(Op.prototype),VarintOp.prototype.fn=writeVarint32,Writer$1.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new VarintOp((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},Writer$1.prototype.int32=function(e){return e<0?this._push(writeVarint64,10,LongBits$1.fromNumber(e)):this.uint32(e)},Writer$1.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},Writer$1.prototype.uint64=function(e){var t=LongBits$1.from(e);return this._push(writeVarint64,t.length(),t)},Writer$1.prototype.int64=Writer$1.prototype.uint64,Writer$1.prototype.sint64=function(e){var t=LongBits$1.from(e).zzEncode();return this._push(writeVarint64,t.length(),t)},Writer$1.prototype.bool=function(e){return this._push(writeByte,1,e?1:0)},Writer$1.prototype.fixed32=function(e){return this._push(writeFixed32,4,e>>>0)},Writer$1.prototype.sfixed32=Writer$1.prototype.fixed32,Writer$1.prototype.fixed64=function(e){var t=LongBits$1.from(e);return this._push(writeFixed32,4,t.lo)._push(writeFixed32,4,t.hi)},Writer$1.prototype.sfixed64=Writer$1.prototype.fixed64,Writer$1.prototype.float=function(e){return this._push(util$4.float.writeFloatLE,4,e)},Writer$1.prototype.double=function(e){return this._push(util$4.float.writeDoubleLE,8,e)};var writeBytes=util$4.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n>>0;if(!t)return this._push(writeByte,1,0);if(util$4.isString(e)){var r=Writer$1.alloc(t=base64.length(e));base64.decode(e,r,0),e=r}return this.uint32(t)._push(writeBytes,t,e)},Writer$1.prototype.string=function(e){var t=utf8$1.length(e);return t?this.uint32(t)._push(utf8$1.write,t,e):this._push(writeByte,1,0)},Writer$1.prototype.fork=function(){return this.states=new State(this),this.head=this.tail=new Op(noop$1,0,0),this.len=0,this},Writer$1.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Op(noop$1,0,0),this.len=0),this},Writer$1.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},Writer$1.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},Writer$1._configure=function(e){BufferWriter$1=e,Writer$1.create=create$4(),BufferWriter$1._configure()};var writer_buffer=BufferWriter,Writer=writer;(BufferWriter.prototype=Object.create(Writer.prototype)).constructor=BufferWriter;var util$3=requireMinimal();function BufferWriter(){Writer.call(this)}function writeStringBuffer(e,t,r){e.length<40?util$3.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}BufferWriter._configure=function(){BufferWriter.alloc=util$3._Buffer_allocUnsafe,BufferWriter.writeBytesBuffer=util$3.Buffer&&util$3.Buffer.prototype instanceof Uint8Array&&"set"===util$3.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var n=0;n>>0;return this.uint32(t),t&&this._push(BufferWriter.writeBytesBuffer,t,e),this},BufferWriter.prototype.string=function(e){var t=util$3.Buffer.byteLength(e);return this.uint32(t),t&&this._push(writeStringBuffer,t,e),this},BufferWriter._configure();var reader=Reader$1,util$2=requireMinimal(),BufferReader$1,LongBits=util$2.LongBits,utf8=util$2.utf8;function indexOutOfRange(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function Reader$1(e){this.buf=e,this.pos=0,this.len=e.length}var create_array="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new Reader$1(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new Reader$1(e);throw Error("illegal buffer")},create$3=function(){return util$2.Buffer?function(e){return(Reader$1.create=function(e){return util$2.Buffer.isBuffer(e)?new BufferReader$1(e):create_array(e)})(e)}:create_array},value;function readLongVarint(){var e=new LongBits(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw indexOutOfRange(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw indexOutOfRange(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function readFixed32_end(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>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$1.create=create$3(),Reader$1.prototype._slice=util$2.Array.prototype.subarray||util$2.Array.prototype.slice,Reader$1.prototype.uint32=(value=4294967295,function(){if(value=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return value;if(value=(value|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return value;if(value=(value|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return value;if(value=(value|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return value;if(value=(value|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return value;if((this.pos+=5)>this.len)throw this.pos=this.len,indexOutOfRange(this,10);return value}),Reader$1.prototype.int32=function(){return 0|this.uint32()},Reader$1.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)|0},Reader$1.prototype.bool=function(){return 0!==this.uint32()},Reader$1.prototype.fixed32=function(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)},Reader$1.prototype.sfixed32=function(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return 0|readFixed32_end(this.buf,this.pos+=4)},Reader$1.prototype.float=function(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);var e=util$2.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},Reader$1.prototype.double=function(){if(this.pos+8>this.len)throw indexOutOfRange(this,4);var e=util$2.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},Reader$1.prototype.bytes=function(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw indexOutOfRange(this,e);return this.pos+=e,Array.isArray(this.buf)?this.buf.slice(t,r):t===r?new this.buf.constructor(0):this._slice.call(this.buf,t,r)},Reader$1.prototype.string=function(){var e=this.bytes();return utf8.read(e,0,e.length)},Reader$1.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw indexOutOfRange(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw indexOutOfRange(this)}while(128&this.buf[this.pos++]);return this},Reader$1.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},Reader$1._configure=function(e){BufferReader$1=e,Reader$1.create=create$3(),BufferReader$1._configure();var t=util$2.Long?"toLong":"toNumber";util$2.merge(Reader$1.prototype,{int64:function(){return readLongVarint.call(this)[t](!1)},uint64:function(){return readLongVarint.call(this)[t](!0)},sint64:function(){return readLongVarint.call(this).zzDecode()[t](!1)},fixed64:function(){return readFixed64.call(this)[t](!0)},sfixed64:function(){return readFixed64.call(this)[t](!1)}})};var reader_buffer=BufferReader,Reader=reader;(BufferReader.prototype=Object.create(Reader.prototype)).constructor=BufferReader;var util$1=requireMinimal();function BufferReader(e){Reader.call(this,e)}BufferReader._configure=function(){util$1.Buffer&&(BufferReader.prototype._slice=util$1.Buffer.prototype.slice)},BufferReader.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},BufferReader._configure();var rpc={},service=Service,util=requireMinimal();function Service(e,t,r){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");util.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(r)}(Service.prototype=Object.create(util.EventEmitter.prototype)).constructor=Service,Service.prototype.rpcCall=function e(t,r,n,o,i){if(!o)throw TypeError("request must be specified");var s=this;if(!i)return util.asPromise(e,s,t,r,n,o);if(s.rpcImpl)try{return s.rpcImpl(t,r[s.requestDelimited?"encodeDelimited":"encode"](o).finish(),(function(e,r){if(e)return s.emit("error",e,t),i(e);if(null!==r){if(!(r instanceof n))try{r=n[s.responseDelimited?"decodeDelimited":"decode"](r)}catch(e){return s.emit("error",e,t),i(e)}return s.emit("data",r,t),i(null,r)}s.end(!0)}))}catch(e){return s.emit("error",e,t),void setTimeout((function(){i(e)}),0)}else setTimeout((function(){i(Error("already ended"))}),0)},Service.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this},function(e){e.Service=service}(rpc);var roots={};!function(e){var t=e;function r(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}t.build="minimal",t.Writer=writer,t.BufferWriter=writer_buffer,t.Reader=reader,t.BufferReader=reader_buffer,t.util=requireMinimal(),t.rpc=rpc,t.roots=roots,t.configure=r,r()}(indexMinimal),function(e){e.exports=indexMinimal}(minimal$1);var $protobuf=getDefaultExportFromCjs(minimal$1.exports);const $Reader=$protobuf.Reader,$Writer=$protobuf.Writer,$util=$protobuf.util,$root=$protobuf.roots.unixfs||($protobuf.roots.unixfs={}),Data=$root.Data=(()=>{function e(e){if(this.blocksizes=[],e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.Type=e.int32();break;case 2:n.Data=e.bytes();break;case 3:n.filesize=e.uint64();break;case 4:if(n.blocksizes&&n.blocksizes.length||(n.blocksizes=[]),2==(7&o))for(var i=e.uint32()+e.pos;e.pos>>0,e.filesize.high>>>0).toNumber(!0))),e.blocksizes){if(!Array.isArray(e.blocksizes))throw TypeError(".Data.blocksizes: array expected");t.blocksizes=[];for(var r=0;r>>0,e.blocksizes[r].high>>>0).toNumber(!0))}if(null!=e.hashType&&($util.Long?(t.hashType=$util.Long.fromValue(e.hashType)).unsigned=!0:"string"==typeof e.hashType?t.hashType=parseInt(e.hashType,10):"number"==typeof e.hashType?t.hashType=e.hashType:"object"==typeof e.hashType&&(t.hashType=new $util.LongBits(e.hashType.low>>>0,e.hashType.high>>>0).toNumber(!0))),null!=e.fanout&&($util.Long?(t.fanout=$util.Long.fromValue(e.fanout)).unsigned=!0:"string"==typeof e.fanout?t.fanout=parseInt(e.fanout,10):"number"==typeof e.fanout?t.fanout=e.fanout:"object"==typeof e.fanout&&(t.fanout=new $util.LongBits(e.fanout.low>>>0,e.fanout.high>>>0).toNumber(!0))),null!=e.mode&&(t.mode=e.mode>>>0),null!=e.mtime){if("object"!=typeof e.mtime)throw TypeError(".Data.mtime: object expected");t.mtime=$root.UnixTime.fromObject(e.mtime)}return t},e.toObject=function(e,t){t||(t={});var r={};if((t.arrays||t.defaults)&&(r.blocksizes=[]),t.defaults){if(r.Type=t.enums===String?"Raw":0,t.bytes===String?r.Data="":(r.Data=[],t.bytes!==Array&&(r.Data=$util.newBuffer(r.Data))),$util.Long){var n=new $util.Long(0,0,!0);r.filesize=t.longs===String?n.toString():t.longs===Number?n.toNumber():n}else r.filesize=t.longs===String?"0":0;$util.Long?(n=new $util.Long(0,0,!0),r.hashType=t.longs===String?n.toString():t.longs===Number?n.toNumber():n):r.hashType=t.longs===String?"0":0,$util.Long?(n=new $util.Long(0,0,!0),r.fanout=t.longs===String?n.toString():t.longs===Number?n.toNumber():n):r.fanout=t.longs===String?"0":0,r.mode=0,r.mtime=null}if(null!=e.Type&&e.hasOwnProperty("Type")&&(r.Type=t.enums===String?$root.Data.DataType[e.Type]:e.Type),null!=e.Data&&e.hasOwnProperty("Data")&&(r.Data=t.bytes===String?$util.base64.encode(e.Data,0,e.Data.length):t.bytes===Array?Array.prototype.slice.call(e.Data):e.Data),null!=e.filesize&&e.hasOwnProperty("filesize")&&("number"==typeof e.filesize?r.filesize=t.longs===String?String(e.filesize):e.filesize:r.filesize=t.longs===String?$util.Long.prototype.toString.call(e.filesize):t.longs===Number?new $util.LongBits(e.filesize.low>>>0,e.filesize.high>>>0).toNumber(!0):e.filesize),e.blocksizes&&e.blocksizes.length){r.blocksizes=[];for(var o=0;o>>0,e.blocksizes[o].high>>>0).toNumber(!0):e.blocksizes[o]}return null!=e.hashType&&e.hasOwnProperty("hashType")&&("number"==typeof e.hashType?r.hashType=t.longs===String?String(e.hashType):e.hashType:r.hashType=t.longs===String?$util.Long.prototype.toString.call(e.hashType):t.longs===Number?new $util.LongBits(e.hashType.low>>>0,e.hashType.high>>>0).toNumber(!0):e.hashType),null!=e.fanout&&e.hasOwnProperty("fanout")&&("number"==typeof e.fanout?r.fanout=t.longs===String?String(e.fanout):e.fanout:r.fanout=t.longs===String?$util.Long.prototype.toString.call(e.fanout):t.longs===Number?new $util.LongBits(e.fanout.low>>>0,e.fanout.high>>>0).toNumber(!0):e.fanout),null!=e.mode&&e.hasOwnProperty("mode")&&(r.mode=e.mode),null!=e.mtime&&e.hasOwnProperty("mtime")&&(r.mtime=$root.UnixTime.toObject(e.mtime,t)),r},e.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},e.DataType=function(){const e={},t=Object.create(e);return t[e[0]="Raw"]=0,t[e[1]="Directory"]=1,t[e[2]="File"]=2,t[e[3]="Metadata"]=3,t[e[4]="Symlink"]=4,t[e[5]="HAMTShard"]=5,t}(),e})();$root.UnixTime=(()=>{function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3){case 1:n.Seconds=e.int64();break;case 2:n.FractionalNanoseconds=e.fixed32();break;default:e.skipType(7&o)}}if(!n.hasOwnProperty("Seconds"))throw $util.ProtocolError("missing required 'Seconds'",{instance:n});return n},e.fromObject=function(e){if(e instanceof $root.UnixTime)return e;var t=new $root.UnixTime;return null!=e.Seconds&&($util.Long?(t.Seconds=$util.Long.fromValue(e.Seconds)).unsigned=!1:"string"==typeof e.Seconds?t.Seconds=parseInt(e.Seconds,10):"number"==typeof e.Seconds?t.Seconds=e.Seconds:"object"==typeof e.Seconds&&(t.Seconds=new $util.LongBits(e.Seconds.low>>>0,e.Seconds.high>>>0).toNumber())),null!=e.FractionalNanoseconds&&(t.FractionalNanoseconds=e.FractionalNanoseconds>>>0),t},e.toObject=function(e,t){t||(t={});var r={};if(t.defaults){if($util.Long){var n=new $util.Long(0,0,!1);r.Seconds=t.longs===String?n.toString():t.longs===Number?n.toNumber():n}else r.Seconds=t.longs===String?"0":0;r.FractionalNanoseconds=0}return null!=e.Seconds&&e.hasOwnProperty("Seconds")&&("number"==typeof e.Seconds?r.Seconds=t.longs===String?String(e.Seconds):e.Seconds:r.Seconds=t.longs===String?$util.Long.prototype.toString.call(e.Seconds):t.longs===Number?new $util.LongBits(e.Seconds.low>>>0,e.Seconds.high>>>0).toNumber():e.Seconds),null!=e.FractionalNanoseconds&&e.hasOwnProperty("FractionalNanoseconds")&&(r.FractionalNanoseconds=e.FractionalNanoseconds),r},e.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},e})(),$root.Metadata=(()=>{function e(e){if(e)for(var t=Object.keys(e),r=0;r>>3==1?n.MimeType=e.string():e.skipType(7&o)}return n},e.fromObject=function(e){if(e instanceof $root.Metadata)return e;var t=new $root.Metadata;return null!=e.MimeType&&(t.MimeType=String(e.MimeType)),t},e.toObject=function(e,t){t||(t={});var r={};return t.defaults&&(r.MimeType=""),null!=e.MimeType&&e.hasOwnProperty("MimeType")&&(r.MimeType=e.MimeType),r},e.prototype.toJSON=function(){return this.constructor.toObject(this,$protobuf.util.toJSONOptions)},e})();const NodeType=Data.DataType,EMPTY$3=Object.freeze([]),EMPTY_BUFFER$1=new Uint8Array(0),BLANK$2=Object.freeze({}),DEFAULT_FILE_MODE=parseInt("0644",8),DEFAULT_DIRECTORY_MODE=parseInt("0755",8),code=code$1,name$1="UnixFS",encodePB=(e,t)=>(Object(globalThis).debug&&console.log({data:e,links:t}),encode$1(prepare({Data:Data.encode(e).finish(),Links:t}))),createRaw=e=>({type:NodeType.Raw,content:e}),createEmptyFile=e=>createSimpleFile(EMPTY_BUFFER$1,e),createSimpleFile=(e,t)=>({type:NodeType.File,layout:"simple",content:e,metadata:decodeMetadata(t)}),createFileChunk=e=>({type:NodeType.File,layout:"simple",content:e}),createAdvancedFile=(e,t)=>({type:NodeType.File,layout:"advanced",parts:e,metadata:decodeMetadata(t)}),createFileShard=e=>({type:NodeType.File,layout:"advanced",parts:e}),createComplexFile=(e,t,r)=>({type:NodeType.File,layout:"complex",content:e,parts:t,metadata:decodeMetadata(r)}),createFlatDirectory=(e,t)=>({type:NodeType.Directory,metadata:decodeMetadata(t),entries:e}),createShardedDirectory=(e,t,r,n,o=BLANK$2)=>({type:NodeType.HAMTShard,bitfield:t,fanout:readFanout(r),hashType:readInt(n),entries:e,metadata:decodeMetadata(o)}),createDirectoryShard=(e,t,r,n)=>({type:NodeType.HAMTShard,bitfield:t,fanout:readFanout(r),hashType:readInt(n),entries:e}),encodeRaw=e=>encodePB({Type:NodeType.Raw,Data:e.byteLength>0?e:void 0,filesize:e.byteLength,blocksizes:EMPTY$3},[]),encodeFile$1=(e,t=!1)=>{const r=t?BLANK$2:Object(e).metadata;switch(e.layout){case"simple":return encodeSimpleFile(e.content,r);case"advanced":return encodeAdvancedFile(e.parts,r);case"complex":return encodeComplexFile(e.content,e.parts,r);default:throw new TypeError(`File with unknown layout "${Object(e).layout}" was passed`)}},encodeFileChunk=e=>encodeSimpleFile(e,BLANK$2),encodeFileShard=e=>encodePB({Type:NodeType.File,blocksizes:e.map(contentByteLength),filesize:cumulativeContentByteLength(e)},e.map(encodeLink)),encodeAdvancedFile=(e,t=BLANK$2)=>encodePB({Type:NodeType.File,blocksizes:e.map(contentByteLength),filesize:cumulativeContentByteLength(e),...encodeMetadata(t)},e.map(encodeLink)),encodeLink=e=>({Name:"",Tsize:e.dagByteLength,Hash:e.cid}),encodeSimpleFile=(e,t=BLANK$2)=>encodePB({Type:NodeType.File,Data:e.byteLength>0?e:void 0,filesize:e.byteLength,blocksizes:[],...encodeMetadata(t)},[]),encodeComplexFile=(e,t,r=BLANK$2)=>encodePB({Type:NodeType.File,Data:e,filesize:e.byteLength+cumulativeContentByteLength(t),blocksizes:t.map(contentByteLength)},t.map(encodeLink)),encodeDirectory$1=e=>encodePB({Type:e.type,...encodeDirectoryMetadata(e.metadata||BLANK$2)},e.entries.map(encodeNamedLink)),encodeHAMTShard=({bitfield:e,fanout:t,hashType:r,entries:n,metadata:o=BLANK$2})=>encodePB({Type:NodeType.HAMTShard,Data:e.byteLength>0?e:void 0,fanout:readFanout(t),hashType:readInt(r),...encodeDirectoryMetadata(o)},n.map(encodeNamedLink)),readFanout=e=>{if(Math.log2(e)%1==0)return e;throw new TypeError(`Expected hamt size to be a power of two instead got ${e}`)},readInt=e=>{if(Number.isInteger(e))return e;throw new TypeError(`Expected an integer value instead got ${e}`)},createSymlink=(e,t=BLANK$2)=>({type:NodeType.Symlink,content:e,metadata:decodeMetadata(t)}),encodeSymlink=(e,t=!1)=>{const r=t?BLANK$2:Object(e).metadata;return encodePB({Type:NodeType.Symlink,Data:e.content,...encodeMetadata(r||BLANK$2)},[])},encode=(e,t=!0)=>{switch(e.type){case NodeType.Raw:return encodeRaw(e.content);case NodeType.File:return encodeFile$1(e);case NodeType.Directory:return encodeDirectory$1(e);case NodeType.HAMTShard:return encodeHAMTShard(e);case NodeType.Symlink:return encodeSymlink(e);default:throw new Error(`Unknown node type ${Object(e).type}`)}},decode=e=>{const t=decode$1(e),r=Data.decode(t.Data),{Type:n,Data:o,mtime:i,mode:s,blocksizes:a,...c}=Data.toObject(r,{defaults:!1,arrays:!0,longs:Number,objects:!1}),u={...s&&{mode:s},...decodeMtime(i)},d=t.Links;switch(r.Type){case NodeType.Raw:return createRaw(o);case NodeType.File:return 0===d.length?new SimpleFileView(o,u):0===o.byteLength?new AdvancedFileView(decodeFileLinks(c.blocksizes,d),u):new ComplexFileView(o,decodeFileLinks(c.blocksizes,d),u);case NodeType.Directory:return createFlatDirectory(decodeDirectoryLinks(d),u);case NodeType.HAMTShard:return createShardedDirectory(decodeDirectoryLinks(t.Links),o||EMPTY_BUFFER$1,c.fanout,c.hashType,u);case NodeType.Symlink:return createSymlink(o,u);default:throw new TypeError(`Unsupported node type ${r.Type}`)}},decodeMtime=e=>null==e?void 0:{mtime:{secs:e.Seconds,nsecs:e.FractionalNanoseconds||0}},decodeFileLinks=(e,t)=>{const r=[],n=e.length;for(;0e.map((e=>({cid:e.Hash,name:e.Name||"",dagByteLength:e.Tsize||0}))),cumulativeContentByteLength=e=>e.reduce(((e,t)=>e+t.contentByteLength),0),cumulativeDagByteLength=(e,t)=>t.reduce(((e,t)=>e+t.dagByteLength),e.byteLength),contentByteLength=e=>e.contentByteLength,encodeNamedLink=({name:e,dagByteLength:t,cid:r})=>({Name:e,Tsize:t,Hash:r}),encodeDirectoryMetadata=e=>encodeMetadata(e,DEFAULT_DIRECTORY_MODE),encodeMetadata=({mode:e,mtime:t},r=DEFAULT_FILE_MODE)=>({mode:null!=e?encodeMode(e,r):void 0,mtime:null!=t?encodeMTime(t):void 0}),decodeMetadata=e=>null==e?BLANK$2:{...null==e.mode?void 0:{mode:decodeMode(e.mode)},...null==e.mtime?void 0:{mtime:e.mtime}},encodeMTime=e=>null==e?void 0:0!==e.nsecs?{Seconds:e.secs,FractionalNanoseconds:e.nsecs}:{Seconds:e.secs},encodeMode=(e,t)=>{const r=null==e?void 0:decodeMode(e);return r===t||null==r?void 0:r},decodeMode=e=>4095&e|4294963200&e,matchFile=({content:e=EMPTY_BUFFER$1,parts:t=EMPTY$3,metadata:r=BLANK$2,...n})=>0===t.length?new SimpleFileView(e,r):0===e.byteLength?new AdvancedFileView(t,r):new ComplexFileView(e,t,r);class SimpleFileView{constructor(e,t){this.content=e,this.metadata=t,this.layout="simple",this.type=NodeType.File}get filesize(){return this.content.byteLength}encode(){return encodeSimpleFile(this.content,this.metadata)}}class AdvancedFileView{constructor(e,t){this.parts=e,this.metadata=t}get layout(){return"advanced"}get type(){return NodeType.File}get fileSize(){return cumulativeContentByteLength(this.parts)}get blockSizes(){return this.parts.map(contentByteLength)}encode(){return encodeAdvancedFile(this.parts,this.metadata)}}class ComplexFileView{constructor(e,t,r){this.content=e,this.parts=t,this.metadata=r}get layout(){return"complex"}get type(){return NodeType.File}get fileSize(){return this.content.byteLength+cumulativeContentByteLength(this.parts)}get blockSizes(){return this.parts.map(contentByteLength)}encode(){return encodeComplexFile(this.content,this.parts,this.metadata)}}const filesize=e=>{switch(e.type){case NodeType.Raw:case NodeType.Symlink:return e.content.byteLength;case NodeType.File:switch(e.layout){case"simple":return e.content.byteLength;case"advanced":return cumulativeContentByteLength(e.parts);case"complex":return e.content.byteLength+cumulativeContentByteLength(e.parts)}default:return 0}};var UnixFS=Object.freeze({__proto__:null,DEFAULT_FILE_MODE:DEFAULT_FILE_MODE,DEFAULT_DIRECTORY_MODE:DEFAULT_DIRECTORY_MODE,code:code,name:name$1,createRaw:createRaw,createEmptyFile:createEmptyFile,createSimpleFile:createSimpleFile,createFileChunk:createFileChunk,createAdvancedFile:createAdvancedFile,createFileShard:createFileShard,createComplexFile:createComplexFile,createFlatDirectory:createFlatDirectory,createShardedDirectory:createShardedDirectory,createDirectoryShard:createDirectoryShard,encodeRaw:encodeRaw,encodeFile:encodeFile$1,encodeFileChunk:encodeFileChunk,encodeFileShard:encodeFileShard,encodeAdvancedFile:encodeAdvancedFile,encodeLink:encodeLink,encodeSimpleFile:encodeSimpleFile,encodeComplexFile:encodeComplexFile,encodeDirectory:encodeDirectory$1,encodeHAMTShard:encodeHAMTShard,createSymlink:createSymlink,encodeSymlink:encodeSymlink,encode:encode,decode:decode,cumulativeContentByteLength:cumulativeContentByteLength,cumulativeDagByteLength:cumulativeDagByteLength,encodeDirectoryMetadata:encodeDirectoryMetadata,encodeMetadata:encodeMetadata,decodeMetadata:decodeMetadata,encodeMode:encodeMode,matchFile:matchFile,filesize:filesize,NodeType:NodeType});const effect=function*(e){const t=yield*e;yield*send(t)};function*current(){return yield CURRENT}const suspend=function*(){yield SUSPEND},wait=function*(e){const t=yield*current();if(isAsync(e)){let r,n=!1;if(e.then((e=>{n=!1,r=e,enqueue(t)}),(e=>{n=!0,r=e,enqueue(t)})),yield*suspend(),n)throw r;return r}return main(wake(t)),yield*suspend(),e};function*wake(e){enqueue(e)}const isAsync=e=>null!=e&&"function"==typeof e.then,send=function*(e){yield e},listen=function*(e){const t=[];for(const r of Object.entries(e)){const[e,n]=r;n!==NONE&&t.push(yield*fork$1(tag(n,e)))}yield*group(t)},effects=e=>e.length>0?batch(e.map(effect)):NONE;function*batch(e){const t=[];for(const r of e)t.push(yield*fork$1(r));yield*group(t)}const tag=(e,t)=>e===NONE?NONE:e instanceof Tagger?new Tagger([...e.tags,t],e.source):new Tagger([t],e);class Tagger{constructor(e,t){this.tags=e,this.source=t,this.controller}[Symbol.iterator](){return this.controller||(this.controller=this.source[Symbol.iterator]()),this}box(e){if(e.done)return e;switch(e.value){case SUSPEND:case CURRENT:return e;default:{const t=e;let{value:r}=t;for(const e of this.tags)r=withTag(e,r);return t.value=r,t}}}next(e){return this.box(this.controller.next(e))}throw(e){return this.box(this.controller.throw(e))}return(e){return this.box(this.controller.return(e))}get[Symbol.toStringTag](){return"TaggedEffect"}}const none=()=>NONE,withTag=(e,t)=>({type:e,[e]:t}),CURRENT=Symbol("current"),SUSPEND=Symbol("suspend");class Group{static of(e){return e.group||MAIN}static enqueue(e,t){e.group=t,t.stack.active.push(e)}constructor(e,t=[],r=new Set,n=new Stack(t,r)){this.driver=e,this.parent=Group.of(e),this.stack=n,this.id=++ID}}class Main{constructor(){this.status=IDLE,this.stack=new Stack,this.id=0}}class Stack{constructor(e=[],t=new Set){this.active=e,this.idle=t}static size({active:e,idle:t}){return e.length+t.size}}const main=e=>enqueue(e[Symbol.iterator]()),enqueue=e=>{let t=Group.of(e);for(t.stack.active.push(e),t.stack.idle.delete(e);t.parent;){const{idle:e,active:r}=t.parent.stack;if(!e.has(t.driver))break;e.delete(t.driver),r.push(t.driver),t=t.parent}if(MAIN.status===IDLE)for(MAIN.status=ACTIVE;;)try{for(const e of step(MAIN));MAIN.status=IDLE;break}catch(e){MAIN.stack.active.shift()}},resume=e=>enqueue(e),step=function*(e){const{active:t}=e.stack;let r=t[0];for(e.stack.idle.delete(r);r;){let n=INIT;e:for(;!n.done&&r===t[0];){const t=n.value;switch(t){case SUSPEND:e.stack.idle.add(r);break e;case CURRENT:n=r.next(r);break;default:n=r.next(yield t)}}t.shift(),r=t[0],e.stack.idle.delete(r)}},fork$1=(e,t)=>new Fork(e,t),exit=(e,t)=>conclude(e,{ok:!0,value:t}),abort=(e,t)=>conclude(e,{ok:!1,error:t});function*conclude(e,t){try{const r=e,n=t.ok?r.return(t.value):r.throw(t.error);if(!n.done)if(n.value===SUSPEND){const{idle:e}=Group.of(r).stack;e.add(r)}else enqueue(r)}catch(e){}}function*group(e){if(0===e.length)return;const t=yield*current(),r=new Group(t);let n=null;for(const t of e){const{result:e}=t;e?e.ok||n||(n=e):move(t,r)}try{if(n)throw n.error;for(;yield*step(r),Stack.size(r.stack)>0;)yield*suspend()}catch(e){for(const t of r.stack.active)yield*abort(t,e);for(const t of r.stack.idle)yield*abort(t,e),enqueue(t);throw e}}const move=(e,t)=>{const r=Group.of(e);if(r!==t){const{active:n,idle:o}=r.stack,i=t.stack;if(e.group=t,o.has(e))o.delete(e),i.idle.add(e);else{const t=n.indexOf(e);t>=0&&(n.splice(t,1),i.active.push(e))}}};function*join(e){e.status===IDLE&&(yield*e),e.result||(yield*group([e]));const t=e.result;if(t.ok)return t.value;throw t.error}class Future{constructor(e){this.handler=e,this.result}get promise(){const{result:e}=this,t=null==e?new Promise(((e,t)=>{this.handler.onsuccess=e,this.handler.onfailure=t})):e.ok?Promise.resolve(e.value):Promise.reject(e.error);return Object.defineProperty(this,"promise",{value:t}),t}then(e,t){return this.activate().promise.then(e,t)}catch(e){return this.activate().promise.catch(e)}finally(e){return this.activate().promise.finally(e)}activate(){return this}}class Fork extends Future{constructor(e,t=BLANK$1,r={},n=INIT){super(r),this.id=++ID,this.name=t.name||"",this.task=e,this.state=n,this.status=IDLE,this.result,this.handler=r,this.controller}*resume(){resume(this)}join(){return join(this)}abort(e){return abort(this,e)}exit(e){return exit(this,e)}get[Symbol.toStringTag](){return"Fork"}*[Symbol.iterator](){return this.activate()}activate(){return this.controller=this.task[Symbol.iterator](),this.status=ACTIVE,enqueue(this),this}panic(e){this.result={ok:!1,error:e},this.status=FINISHED;const{handler:t}=this;throw t.onfailure&&t.onfailure(e),e}step(e){if(this.state=e,e.done){this.result={ok:!0,value:e.value},this.status=FINISHED;const{handler:t}=this;t.onsuccess&&t.onsuccess(e.value)}return e}next(e){try{return this.step(this.controller.next(e))}catch(e){return this.panic(e)}}return(e){try{return this.step(this.controller.return(e))}catch(e){return this.panic(e)}}throw(e){try{return this.step(this.controller.throw(e))}catch(e){return this.panic(e)}}}const loop=function*(e,t){const r=yield*current(),n=new Group(r);for(Group.enqueue(e[Symbol.iterator](),n);;){for(const e of step(n))Group.enqueue(t(e)[Symbol.iterator](),n);if(!(Stack.size(n.stack)>0))break;yield*suspend()}};let ID=0;const IDLE="idle",ACTIVE="active",FINISHED="finished",INIT={done:!1,value:CURRENT},BLANK$1={},NONE=function*(){}(),MAIN=new Main;function Indexed(){}Object.defineProperties(Indexed,{prototype:{value:new Proxy(Object.prototype,{get:(e,t,r)=>"symbol"==typeof t?Reflect.get(e,t,r):r.get(t)})}});const empty=()=>new BufferView,slice=(e,t=0,r=e.byteLength)=>{const n=[],o=t<0?e.byteLength-t:t,i=r<0?e.byteLength-r:r;if(0===o&&i>=e.byteLength)return e;if(o>i||o>e.byteLength||i<=0)return empty();let s=0,a=0;for(const t of e.segments){const e=a+t.byteLength;if(0===s){if(i<=e){const e=t.subarray(o-a,i-a);n.push(e),s=e.byteLength;break}if(ot.byteLength>0?(e.segments.push(t),new BufferView(e.segments,e.byteOffset,e.byteLength+t.byteLength)):e,get=(e,t)=>{if(t{let n=r;for(const r of e.segments)t.set(r,n),n+=r.byteLength;return t};function*iterate(e){for(const t of e.segments)yield*t}class BufferView extends Indexed{constructor(e=[],t=0,r=0){super(),this.segments=e,this.byteLength=r,this.length=r,this.byteOffset=t}[Symbol.iterator](){return iterate(this)}slice(e,t){return slice(this,e,t)}subarray(e,t){return slice(this,e,t)}push(e){return push(this,e)}get(e){return get(this,e)}copyTo(e,t){return copyTo(this,e,t)}}const panic=e=>{throw new Error(e)},unreachable=(e,t,...r)=>panic(String.raw(e,JSON.stringify(t),...r)),EMPTY_BUFFER=new Uint8Array(0),EMPTY$2=[],open$1=e=>({config:e,buffer:empty()}),write$3=(e,t)=>t.byteLength>0?split(e.config,e.buffer.push(t),!1):{...e,chunks:EMPTY$2},close$5=e=>split(e.config,e.buffer,!0),split=(e,t,r)=>{const n=e.chunker,o=[];let i=0;for(const e of n.cut(n.context,t,r))if(e>0){const r=t.subarray(i,i+e);o.push(r),i+=e}return{config:e,chunks:o,buffer:t.subarray(i)}},mutable=()=>({mutable:!0,needs:{},nodes:{},links:{},linked:EMPTY$1}),addNodes=(e,t)=>{let r=patch(t,{});for(const t of e){const{ready:e,has:n,wants:o}=collect$1(t.children,r.links);r=0===o.length?patch(r,{links:assign(void 0,n),linked:[{id:t.id,links:e}]}):patch(r,{needs:assign(t.id,o),nodes:{[t.id]:{children:t.children,count:o.length}}})}return r},addLink=(e,t,r)=>{const n=r.needs[e],o=r.nodes[n];if(null!=o){if(1===o.count){const{ready:i,has:s}=collect$1(o.children,{...r.links,[e]:t});return patch(r,{needs:{[e]:void 0},links:assign(void 0,s),nodes:{[n]:void 0},linked:[{id:n,links:i}]})}return patch(r,{needs:{[e]:void 0},links:{[e]:t},nodes:{[n]:{...o,count:o.count-1}}})}return patch(r,{links:{[e]:t}})},patch=(e,{needs:t,nodes:r,links:n,linked:o})=>{const i=e.mutable?e:{...e},s=e.mutable?BLANK:void 0;return t&&(i.needs=patchDict(e.needs,t,s)),r&&(i.nodes=patchDict(e.nodes,r,s)),n&&(i.links=patchDict(e.links,n,s)),i.linked=o?append(e.linked||EMPTY$1,o,EMPTY$1):e.linked||[],i},assign=(e,t)=>{const r={};for(const n of t)r[n]=e;return r},patchDict=(e,t,r=e)=>{const n=e===r?{...e}:e;for(const e of Object.entries(t)){const[t,r]=e;null==r?delete n[t]:n[t]=r}return n},append=(e,t,r=e)=>{if(e===r)return[...e,...t];for(const r of t)e.push(r);return e},collect$1=(e,t)=>{const r=[],n=[],o=[];for(const i of e){const e=t[i];e?(r.push(i),o.push(e)):n.push(i)}return{has:r,wants:n,ready:o}},EMPTY$1=Object.freeze([]),BLANK=Object.freeze({}),update=(e,t)=>{switch(e.type){case"write":return write$2(t,e.bytes);case"link":return link(t,e.link);case"block":case"end":return{state:t,effect:none()};case"close":return close$4(t);default:return unreachable`File Writer got unknown message ${e}`}},init=(e,t,r)=>({status:"open",metadata:t,config:r,writer:e,chunker:open$1({chunker:r.chunker}),layout:r.fileLayout.open(),nodeQueue:mutable()}),write$2=(e,t)=>{if("open"===e.status){const{chunks:r,...n}=write$3(e.chunker,t),{nodes:o,leaves:i,layout:s}=e.config.fileLayout.write(e.layout,r),{linked:a,...c}=addNodes(o,e.nodeQueue),u=[...encodeLeaves(i,e.config),...encodeBranches(a,e.config)];return{state:{...e,chunker:n,layout:s,nodeQueue:c},effect:listen({link:effects(u)})}}return panic("Unable to perform write on closed file")},link=(e,{id:t,link:r,block:n})=>{let{linked:o,...i}=addLink(t,r,e.nodeQueue);const s=encodeBranches(o,e.config),a="closed"===e.status&&t===e.rootID?{...e,status:"linked",link:r,nodeQueue:i}:{...e,nodeQueue:i},c="closed"===e.status&&t===e.rootID&&e.end?e.end.resume():none();return{state:a,effect:listen({link:effects(s),block:writeBlock(e.writer,n),end:c})}},close$4=e=>{if("open"===e.status){const{chunks:t}=close$5(e.chunker),{layout:r,...n}=e.config.fileLayout.write(e.layout,t),{root:o,...i}=e.config.fileLayout.close(r,e.metadata),[s,a]=isLeafNode(o)?[[...n.nodes,...i.nodes],[...n.leaves,...i.leaves,o]]:[[...n.nodes,...i.nodes,o],[...n.leaves,...i.leaves]],{linked:c,...u}=addNodes(s,e.nodeQueue),d=[...encodeLeaves(a,e.config),...encodeBranches(c,e.config)],l=fork$1(suspend());return{state:{...e,chunker:null,layout:null,rootID:o.id,status:"closed",end:l,nodeQueue:u},effect:listen({link:effects(d),end:join(l)})}}return{state:e,effect:none()}},encodeLeaves=(e,t)=>e.map((e=>encodeLeaf(t,e,t.fileChunkEncoder))),encodeLeaf=function*({hasher:e,linker:t},{id:r,content:n},o){const i=o.encode(n?asUint8Array(n):EMPTY_BUFFER),s=yield*wait(e.digest(i)),a=t.createLink(o.code,s);return{id:r,block:{cid:a,bytes:i},link:{cid:a,contentByteLength:n?n.byteLength:0,dagByteLength:i.byteLength}}},encodeBranches=(e,t)=>e.map((e=>encodeBranch(t,e))),encodeBranch=function*(e,{id:t,links:r},n){const o=e.fileEncoder.encode({type:NodeType.File,layout:"advanced",parts:r,metadata:n}),i=yield*wait(Promise.resolve(e.hasher.digest(o))),s=e.linker.createLink(e.fileEncoder.code,i);return{id:t,block:{bytes:o,cid:s},link:{cid:s,contentByteLength:cumulativeContentByteLength(r),dagByteLength:cumulativeDagByteLength(o,r)}}},writeBlock=function*(e,t){(e.desiredSize||0)<=0&&(yield*wait(e.ready)),e.write(t)},asUint8Array=e=>e instanceof Uint8Array?e:e.copyTo(new Uint8Array(e.byteLength),0),isLeafNode=e=>null==e.children,name="fixed",context={maxChunkSize:262144},type="Stateless",withMaxChunkSize=e=>({type:"Stateless",context:{maxChunkSize:e},name:name,cut:cut}),cut=({maxChunkSize:e},{byteLength:t},r)=>{const n=t/e|0,o=new Array(n).fill(e),i=r?t-n*e:0;return i>0&&o.push(i),o};var FixedSize=Object.freeze({__proto__:null,name:name,context:context,type:type,withMaxChunkSize:withMaxChunkSize,cut:cut});class Node{constructor(e,t,r){this.id=e,this.children=t,this.metadata=r}}const withWidth=e=>({open:()=>open({width:e}),write:write$1,close:close$3}),defaults$2={width:174},open=({width:e}=defaults$2)=>({width:e,head:null,leafIndex:[],nodeIndex:[],lastID:0}),write$1=(e,t)=>{if(0===t.length)return{layout:e,nodes:EMPTY,leaves:EMPTY};{let{lastID:r}=e;const[n,o]=e.head?[null,(t.unshift(e.head),t)]:1===t.length&&0===e.leafIndex.length?[t[0],EMPTY]:[null,t];if(0===o.length)return{layout:{...e,head:n},nodes:EMPTY,leaves:EMPTY};{const t=[...e.leafIndex],i=[];for(const e of o){const n={id:++r,content:e};i.push(n),t.push(n.id)}return t.length>=e.width?flush({...e,leafIndex:t,head:n,lastID:r},i):{layout:{...e,head:n,leafIndex:t,lastID:r},leaves:i,nodes:EMPTY}}}},flush=(e,t=EMPTY,r=[],n=!1)=>{let{lastID:o}=e;const i=e.nodeIndex.map((e=>[...e])),s=[...e.leafIndex],{width:a}=e;for(;s.length>=a||s.length>0&&n;){grow(i,1);const e=new Node(++o,s.splice(0,a));i[0].push(e.id),r.push(e)}let c=0;for(;c=a||e.length>0&&n&&c{const r=e;if(e.head)return{root:{id:1,content:e.head,metadata:t},leaves:EMPTY,nodes:EMPTY};if(0===e.leafIndex.length)return{root:{id:1,metadata:t},leaves:EMPTY,nodes:EMPTY};{const{nodes:e,layout:n}=flush(r,EMPTY,[],!0),{nodeIndex:o}=n,i=o[o.length-1];if(1===i.length){const t=e[e.length-1];return e.length=e.length-1,{root:t,nodes:e,leaves:EMPTY}}return{root:new Node(n.lastID+1,i,t),nodes:e,leaves:EMPTY}}},grow=(e,t)=>{for(;e.length({chunker:FixedSize,fileChunkEncoder:UnixFSLeaf,smallFileEncoder:UnixFSLeaf,fileEncoder:UnixFS,fileLayout:withWidth(174),hasher:sha256,linker:{createLink:CID.createV1}}),configure=e=>({...defaults$1(),...e}),UnixFSLeaf={code:code,name:name$1,encode:encodeFileChunk},create$2=({writer:e,metadata:t={},settings:r=defaults$1()})=>new FileWriterView(init(e,t,configure(r))),write=async(e,t)=>(await perform(e,send({type:"write",bytes:t})),e),close$2=async(e,{releaseLock:t=!1,closeWriter:r=!1}={})=>{await perform(e,send({type:"close"}));const{state:n}=e;if("linked"===n.status)return r?await e.state.writer.close():t&&e.state.writer.releaseLock(),n.link;panic(`Expected writer to be in 'linked' state after close, but it is in "${n.status}" instead`)},perform=(e,t)=>fork$1(loop(t,(t=>{const{state:r,effect:n}=update(t,e.state);return e.state=r,n})));class FileWriterView{constructor(e){this.state=e}get writer(){return this.state.writer}get settings(){return this.state.config}write(e){return write(this,e)}close(e){return close$2(this,e)}}const defaults=defaults$1,create$1=({writer:e,settings:t=defaults(),metadata:r={}})=>new DirectoryWriter({writer:e,metadata:r,settings:t,entries:new Map,closed:!1}),set=(e,t,r,{overwrite:n=!1}={})=>{const o=asWritable(e.state);if(t.includes("/"))throw new Error(`Directory entry name "${t}" contains forbidden "/" character`);if(!n&&o.entries.has(t))throw new Error(`Directory already contains entry with name "${t}"`);return o.entries.set(t,r),e},remove=(e,t)=>(asWritable(e.state).entries.delete(t),e),asWritable=e=>{if(e.closed)throw new Error("Can not change written directory, but you can .fork() and make changes to it");return e},close$1=async(e,{closeWriter:t=!1,releaseLock:r=!1}={})=>{const{writer:n,settings:o,metadata:i}=asWritable(e.state);e.state.closed=!0;const s=[...links(e)],a=createFlatDirectory(s,i),c=encodeDirectory$1(a),u=await o.hasher.digest(c),d=o.linker.createLink(code,u);return(n.desiredSize||0)<=0&&await n.ready,n.write({cid:d,bytes:c}),t?await n.close():r&&n.releaseLock(),{cid:d,dagByteLength:cumulativeDagByteLength(c,s)}},links=function*({state:e}){for(const[t,{dagByteLength:r,cid:n}]of e.entries)yield{name:t,dagByteLength:r,cid:n}},fork=({state:e},{writer:t=e.writer,metadata:r=e.metadata,settings:n=e.settings}={})=>new DirectoryWriter({writer:t,metadata:r,settings:n,entries:new Map(e.entries.entries()),closed:!1});class DirectoryWriter{constructor(e){this.state=e}get writer(){return this.state.writer}get settings(){return this.state.settings}links(){return links(this)}set(e,t,r){return set(this,e,t,r)}remove(e){return remove(this,e)}fork(e){return fork(this,e)}close(e){return close$1(this,e)}entries(){return this.state.entries.entries()}has(e){return this.state.entries.has(e)}get size(){return this.state.entries.size}}const createWriter=({writable:e,settings:t=defaults$1()})=>new FileSystemWriter({writer:e.getWriter(),settings:t}),close=async(e,{releaseLock:t=!0,closeWriter:r=!0}={})=>(r?await e.writer.close():t&&e.writer.releaseLock(),e);class FileSystemWriter{constructor({writer:e,settings:t}){this.writer=e,this.settings=configure(t)}createFileWriter({settings:e=this.settings,metadata:t}={}){return create$2({writer:this.writer,settings:e,metadata:t})}createDirectoryWriter({settings:e=this.settings,metadata:t}={}){return create$1({writer:this.writer,settings:e,metadata:t})}close(e){return close(this,e)}}const BLOCK_SIZE_LIMIT=1048576,defaultCapacity=100*BLOCK_SIZE_LIMIT,withCapacity=(e=defaultCapacity)=>({highWaterMark:e,size:e=>e.bytes.length});function toIterable(e){if(null!=e[Symbol.asyncIterator])return e;if("getReader"in e)return async function*(){const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)return;yield r}}finally{t.releaseLock()}}();throw new Error("unknown stream")}const queuingStrategy=withCapacity(183500800),settings=configure({fileChunkEncoder:raw,smallFileEncoder:raw});function encodeFile(e){const{readable:t,writable:r}=new TransformStream({},queuingStrategy),n=createWriter({writable:r,settings:settings}),o=new UnixFsFileBuilder(e);return{cid:(async()=>{const{cid:e}=await o.finalize(n);return await n.close(),e})(),blocks:t}}var _file=_classPrivateFieldLooseKey("file");class UnixFsFileBuilder{constructor(e){Object.defineProperty(this,_file,{writable:!0,value:void 0}),_classPrivateFieldLooseBase(this,_file)[_file]=e}async finalize(e){const t=create$2(e),r=toIterable(_classPrivateFieldLooseBase(this,_file)[_file].stream());for await(const e of r)await t.write(e);return await t.close()}}class UnixFSDirectoryBuilder{constructor(){this.entries=new Map}async finalize(e){const t=create$1(e);for(const[r,n]of this.entries){const o=await n.finalize(e);t.set(r,o)}return await t.close()}}function encodeDirectory(e){const t=new UnixFSDirectoryBuilder;for(const r of e){const e=r.name.split("/");""!==e[0]&&"."!==e[0]||e.shift();let n=t;for(const[t,o]of e.entries()){if(t===e.length-1){n.entries.set(o,new UnixFsFileBuilder(r));break}let i=n.entries.get(o);if(null==i&&(i=new UnixFSDirectoryBuilder,n.entries.set(o,i)),!(i instanceof UnixFSDirectoryBuilder))throw new Error(`"${o}" cannot be a file and a directory`);n=i}}const{readable:r,writable:n}=new TransformStream({},queuingStrategy),o=createWriter({writable:n,settings:settings});return{cid:(async()=>{const{cid:e}=await t.finalize(o);return await o.close(),e})(),blocks:r}}function createHeader(e){const t=encode$e({version:1,roots:e}),r=varint.encode(t.length),n=new Uint8Array(r.length+t.length);return n.set(r,0),n.set(t,r.length),n}function createEncoder(e){return{async setRoots(t){const r=createHeader(t);await e.write(r)},async writeBlock(t){const{cid:r,bytes:n}=t;await e.write(new Uint8Array(varint.encode(r.bytes.length+n.length))),await e.write(r.bytes),n.length&&await e.write(n)},async close(){await e.end()}}}function noop(){}function create(){const e=[];let t=null,r=noop,n=!1,o=null,i=noop;const s=()=>(t||(t=new Promise((e=>{r=()=>{t=null,r=noop,e()}}))),t),a={write(t){e.push(t);const r=s();return i(),r},async end(){n=!0;const e=s();i(),await e}},c={async next(){const t=e.shift();return t?(0===e.length&&r(),{done:!1,value:t}):n?(r(),{done:!0,value:void 0}):(o||(o=new Promise((e=>{i=()=>(o=null,i=noop,e(c.next()))}))),o)}};return{writer:a,iterator:c}}class CarWriter{constructor(e,t){this._encoder=t,this._mutex=t.setRoots(e),this._ended=!1}async put(e){if(!(e.bytes instanceof Uint8Array&&e.cid))throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");const t=CID.asCID(e.cid);if(!t)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then((()=>this._encoder.writeBlock({cid:t,bytes:e.bytes}))),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}static create(e){e=toRoots(e);const{encoder:t,iterator:r}=encodeWriter();return{writer:new CarWriter(e,t),out:new CarWriterOut(r)}}static createAppender(){const{encoder:e,iterator:t}=encodeWriter();return e.setRoots=()=>Promise.resolve(),{writer:new CarWriter([],e),out:new CarWriterOut(t)}}static async updateRootsInBytes(e,t){const r=bytesReader(e);await readHeader(r);const n=createHeader(t);if(Number(r.pos)!==n.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${r.pos} bytes, new header is ${n.length} bytes)`);return e.set(n,0),e}}class CarWriterOut{constructor(e){this._iterator=e}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}}function encodeWriter(){const e=create(),{writer:t,iterator:r}=e;return{encoder:createEncoder(t),iterator:r}}function toRoots(e){if(void 0===e)return[];if(!Array.isArray(e)){const t=CID.asCID(e);if(!t)throw new TypeError("roots must be a single CID or an array of CIDs");return[t]}const t=[];for(const r of e){const e=CID.asCID(r);if(!e)throw new TypeError("roots must be a single CID or an array of CIDs");t.push(e)}return t}const CHUNK_SIZE=31457280;async function*chunkBlocks(e,t={}){const r=toIterable(e),n=t.chunkSize??CHUNK_SIZE;let o=[],i=null,s=0;for await(const e of r)null!=i&&(yield encodeCar(i),i=null),s+e.bytes.length>n&&(i=o,o=[],s=0),o.push(e),s+=e.bytes.length;null!=i&&(yield encodeCar(i)),o.length>0&&(yield encodeCar(o,[o[o.length-1].cid]))}function encodeCar(e,t){const{writer:r,out:n}=CarWriter.create(t);return(async()=>{for(const t of e)await r.put(t);await r.close()})(),n}const serviceUrl=new URL("https://8609r1772a.execute-api.us-east-1.amazonaws.com"),serviceDid=parse$3("did:key:z6MkrZ1r5XBFZjBU34qyD8fueMbMRkKw17BZaq2ivKFjnz2z"),RETRIES=3,CONCURRENT_UPLOADS=3;async function uploadCarChunks(e,t,r={}){const n=r.onChunkUploaded??(()=>{}),o=transform(CONCURRENT_UPLOADS,(async t=>{const o=await collect(t),i=new Uint8Array(await new Blob(o).arrayBuffer()),s=await uploadCarBytes(e,i,r);return n({meta:{cid:s,size:i.length}}),s}),t);return await collect(o)}async function createUpload(e,t,r){const n=connection({id:serviceDid,url:serviceUrl}),o=await add.invoke({issuer:e,audience:serviceDid,with:e.did(),caveats:{root:t,shards:r}}).execute(n);if(!0===(null==o?void 0:o.error))throw o}async function uploadCarBytes(e,t,r={}){const n=await link$1(t),o=connection({id:serviceDid,url:serviceUrl}),i=await pRetry((async()=>await add$1.invoke({issuer:e,audience:serviceDid,with:e.did(),caveats:{link:n}}).execute(o)),{onFailedAttempt:console.warn,retries:r.retries??RETRIES});if("done"===i.status)return n;if(null!=i.error)throw new Error("failed store/add invocation",{cause:i.error});if(!(await pRetry((async()=>{const e=await fetch(i.url,{method:"PUT",mode:"cors",body:t,headers:i.headers});if(e.status>=400&&e.status<500)throw new AbortError(`upload failed: ${e.status}`);return e}),{onFailedAttempt:console.warn,retries:r.retries??RETRIES})).ok)throw new Error("upload failed");return n}async function collect(e){const t=[];for await(const r of e)t.push(r);return t}exports.chunkBlocks=chunkBlocks,exports.createUpload=createUpload,exports.encodeDirectory=encodeDirectory,exports.encodeFile=encodeFile,exports.uploadCarBytes=uploadCarBytes,exports.uploadCarChunks=uploadCarChunks,Object.defineProperty(exports,"__esModule",{value:!0})},t(exports)})(index_production,index_production.exports);const UploaderContext=React.createContext([{uploadedCarChunks:[]},{uploadFile:async()=>{throw new Error("missing uploader context provider")},uploadDirectory:async()=>{throw new Error("missing uploader context provider")},uploadCarChunks:async()=>{throw new Error("missing uploader context provider")}}]);function UploaderProvider({children:e}){const{identity:t}=reactKeyring.useAuth(),[r,n]=React.useState([]),o={uploadedCarChunks:r},i={async uploadFile(e){if(null==t)throw new Error("missing identity");const{cid:r,blocks:n}=index_production.exports.encodeFile(e),o=await i.uploadCarChunks(index_production.exports.chunkBlocks(n)),s=await r;return await index_production.exports.createUpload(t.signingPrincipal,s,o),s},async uploadDirectory(e){if(null==t)throw new Error("missing identity");const{cid:r,blocks:n}=index_production.exports.encodeDirectory(e),o=await i.uploadCarChunks(index_production.exports.chunkBlocks(n)),s=await r;return await index_production.exports.createUpload(t.signingPrincipal,s,o),s},async uploadCarChunks(e){if(null==t)throw new Error("missing identity");const r=[];return n(r),await index_production.exports.uploadCarChunks(t.signingPrincipal,e,{onChunkUploaded:e=>{r.push(e.meta),n([...r])}})}};return React__default.default.createElement(UploaderContext.Provider,{value:[o,i]},e)}function useUploader(){return React.useContext(UploaderContext)}exports.UploaderProvider=UploaderProvider,exports.chunkBlocks=index_production.exports.chunkBlocks,exports.encodeDirectory=index_production.exports.encodeDirectory,exports.encodeFile=index_production.exports.encodeFile,exports.useUploader=useUploader,Object.defineProperty(exports,"__esModule",{value:!0})})); +//# sourceMappingURL=index.production.js.map + + +/***/ }) + +}]); \ No newline at end of file diff --git a/crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/321-84e387e16ad8340e/input.js b/crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/321-84e387e16ad8340e/input.js new file mode 100644 index 000000000000..9972fc663df8 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/321-84e387e16ad8340e/input.js @@ -0,0 +1,34 @@ +(self["webpackChunk_N_E"] = self["webpackChunk_N_E"] || []).push([[321],{ + +/***/ 1321: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +/** + * react-keyring + * + * Copyright (c) Web3.Storage + * + * This source code is licensed under Apache-2.0 OR MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license Apache-2.0 OR MIT + */ +!function(e,t){ true?t(exports,__webpack_require__(7294)):0}(this,(function(e,t){"use strict";function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=r(t),o=("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof __webpack_require__.g?__webpack_require__.g:"undefined"!=typeof self&&self,{exports:{}}); +/** + * keyring-core + * + * Copyright (c) Web3.Storage + * + * This source code is licensed under Apache-2.0 OR MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license Apache-2.0 OR MIT + */ +!function(e,t){!function(e){var t=Object.freeze({__proto__:null,default:{}}); +/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */const r=BigInt(0),n=BigInt(1),o=BigInt(2),i=BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),s=Object.freeze({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),P:BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),l:i,n:i,h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960")}),a=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000"),c=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt("6853475219497561581579357271197624642482790079785650197046958215289687604742");const u=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),h=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),f=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),d=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");class l{constructor(e,t,r,n){this.x=e,this.y=t,this.z=r,this.t=n}static fromAffine(e){if(!(e instanceof m))throw new TypeError("ExtendedPoint#fromAffine: expected Point");return e.equals(m.ZERO)?l.ZERO:new l(e.x,e.y,n,$(e.x*e.y))}static toAffineBatch(e){const t=function(e,t=s.P){const o=new Array(e.length),i=T(e.reduce(((e,n,i)=>n===r?e:(o[i]=e,$(e*n,t))),n),t);return e.reduceRight(((e,n,i)=>n===r?e:(o[i]=$(e*o[i],t),$(e*n,t))),i),o}(e.map((e=>e.z)));return e.map(((e,r)=>e.toAffine(t[r])))}static normalizeZ(e){return this.toAffineBatch(e).map(this.fromAffine)}equals(e){p(e);const{x:t,y:r,z:n}=this,{x:o,y:i,z:s}=e,a=$(t*s),c=$(o*n),u=$(r*s),h=$(i*n);return a===c&&u===h}negate(){return new l($(-this.x),this.y,this.z,$(-this.t))}double(){const{x:e,y:t,z:r}=this,{a:n}=s,i=$(e*e),a=$(t*t),c=$(o*$(r*r)),u=$(n*i),h=e+t,f=$($(h*h)-i-a),d=u+a,p=d-c,w=u-a,y=$(f*p),g=$(d*w),b=$(f*w),m=$(p*d);return new l(y,g,m,b)}add(e){p(e);const{x:t,y:n,z:i,t:s}=this,{x:a,y:c,z:u,t:h}=e,f=$((n-t)*(c+a)),d=$((n+t)*(c-a)),w=$(d-f);if(w===r)return this.double();const y=$(i*o*h),g=$(s*o*u),b=g+y,m=d+f,v=g-y,x=$(b*w),E=$(m*v),k=$(b*v),S=$(w*m);return new l(x,E,S,k)}subtract(e){return this.add(e.negate())}precomputeWindow(e){const t=1+256/e,r=[];let n=this,o=n;for(let i=0;i>=f,a>c&&(a-=h,e+=n),0===a){let e=o[r];t%2&&(e=e.negate()),s=s.add(e)}else{let e=o[r+Math.abs(a)-1];a<0&&(e=e.negate()),i=i.add(e)}}return l.normalizeZ([i,s])[0]}multiply(e,t){return this.wNAF(D(e,s.l),t)}multiplyUnsafe(e){let t=D(e,s.l,!1);const o=l.BASE,i=l.ZERO;if(t===r)return i;if(this.equals(i)||t===n)return this;if(this.equals(o))return this.wNAF(t);let a=i,c=this;for(;t>r;)t&n&&(a=a.add(c)),c=c.double(),t>>=n;return a}isSmallOrder(){return this.multiplyUnsafe(s.h).equals(l.ZERO)}isTorsionFree(){return this.multiplyUnsafe(s.l).equals(l.ZERO)}toAffine(e=T(this.z)){const{x:t,y:r,z:o}=this,i=$(t*e),s=$(r*e);if($(o*e)!==n)throw new Error("invZ was invalid");return new m(i,s)}fromRistrettoBytes(){y()}toRistrettoBytes(){y()}fromRistrettoHash(){y()}}function p(e){if(!(e instanceof l))throw new TypeError("ExtendedPoint expected")}function w(e){if(!(e instanceof g))throw new TypeError("RistrettoPoint expected")}function y(){throw new Error("Legacy method: switch to RistrettoPoint")}l.BASE=new l(s.Gx,s.Gy,n,$(s.Gx*s.Gy)),l.ZERO=new l(r,n,n,r);class g{constructor(e){this.ep=e}static calcElligatorRistrettoMap(e){const{d:t}=s,r=$(c*e*e),o=$((r+n)*f);let i=BigInt(-1);const a=$((i-t*r)*$(r+t));let{isValid:h,value:p}=_(o,a),w=$(p*e);I(w)||(w=$(-w)),h||(p=w),h||(i=r);const y=$(i*(r-n)*d-a),g=p*p,b=$((p+p)*a),m=$(y*u),v=$(n-g),x=$(n+g);return new l($(b*x),$(v*m),$(m*x),$(b*v))}static hashToCurve(e){const t=R((e=z(e,64)).slice(0,32)),r=this.calcElligatorRistrettoMap(t),n=R(e.slice(32,64)),o=this.calcElligatorRistrettoMap(n);return new g(r.add(o))}static fromHex(e){e=z(e,32);const{a:t,d:o}=s,i="RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint",a=R(e);if(!function(e,t){if(e.length!==t.length)return!1;for(let r=0;r=o)throw new Error("Expected 0 < hex < P");if(!t&&c>=a)throw new Error("Expected 0 < hex < 2**256");const u=$(c*c),h=$(u-n),f=$(r*u+n);let{isValid:d,value:l}=_(h,f);if(!d)throw new Error("Point.fromHex: invalid y coordinate");const p=(l&n)===n;return 0!=(128&e[31])!==p&&(l=$(-l)),new m(l,c)}static async fromPrivateKey(e){return(await L(e)).point}toRawBytes(){const e=A(this.y);return e[31]|=this.x&n?128:0,e}toHex(){return k(this.toRawBytes())}toX25519(){const{y:e}=this;return A($((n+e)*T(n-e)))}isTorsionFree(){return l.fromAffine(this).isTorsionFree()}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new m($(-this.x),this.y)}add(e){return l.fromAffine(this).add(l.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return l.fromAffine(this).multiply(e,this).toAffine()}}m.BASE=new m(s.Gx,s.Gy),m.ZERO=new m(r,n);class v{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromHex(e){const t=z(e,64),r=m.fromHex(t.slice(0,32),!1),n=C(t.slice(32,64));return new v(r,n)}assertValidity(){const{r:e,s:t}=this;if(!(e instanceof m))throw new Error("Expected Point instance");return D(t,s.l,!1),this}toRawBytes(){const e=new Uint8Array(64);return e.set(this.r.toRawBytes()),e.set(A(this.s),32),e}toHex(){return k(this.toRawBytes())}}function x(...e){if(!e.every((e=>e instanceof Uint8Array)))throw new Error("Expected Uint8Array list");if(1===e.length)return e[0];const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);for(let t=0,n=0;tt.toString(16).padStart(2,"0")));function k(e){if(!(e instanceof Uint8Array))throw new Error("Uint8Array expected");let t="";for(let r=0;r=r?n:t+n}function T(e,t=s.P){if(e===r||t<=r)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let o=$(e,t),i=t,a=r,c=n;for(;o!==r;){const e=i%o,t=a-c*(i/o);i=o,o=e,a=c,c=t}if(i!==n)throw new Error("invert: does not exist");return $(a,t)}function U(e,t){const{P:n}=s;let o=e;for(;t-- >r;)o*=o,o%=n;return o}function _(e,t){const r=$(t*t*t),i=function(e){const{P:t}=s,r=BigInt(5),i=BigInt(10),a=BigInt(20),c=BigInt(40),u=BigInt(80),h=e*e%t*e%t,f=U(h,o)*h%t,d=U(f,n)*e%t,l=U(d,r)*d%t,p=U(l,i)*l%t,w=U(p,a)*p%t,y=U(w,c)*w%t,g=U(y,u)*y%t,b=U(g,u)*y%t,m=U(b,i)*l%t;return{pow_p_5_8:U(m,o)*e%t,b2:h}}(e*$(r*r*t)).pow_p_5_8;let a=$(e*r*i);const u=$(t*a*a),h=a,f=$(a*c),d=u===e,l=u===$(-e),p=u===$(-e*c);return d&&(a=h),(l||p)&&(a=f),I(a)&&(a=$(-a)),{isValid:d||l,value:a}}function N(e){return _(n,e)}function j(e){return $(C(e),s.l)}function z(e,t){const r=e instanceof Uint8Array?Uint8Array.from(e):S(e);if("number"==typeof t&&r.length!==t)throw new Error(`Expected ${t} bytes`);return r}function D(e,t,n=!0){if(!t)throw new TypeError("Specify max value");if("number"==typeof e&&Number.isSafeInteger(e)&&(e=BigInt(e)),"bigint"==typeof e&&e{if((e=z(e)).length<40||e.length>1024)throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");return $(C(e),s.l-n)+n},randomBytes:(e=32)=>{if(V.web)return V.web.getRandomValues(new Uint8Array(e));if(V.node){const{randomBytes:t}=V.node;return new Uint8Array(t(e).buffer)}throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>W.randomBytes(32),sha512:async(...e)=>{const t=x(...e);if(V.web){const e=await V.web.subtle.digest("SHA-512",t.buffer);return new Uint8Array(e)}if(V.node)return Uint8Array.from(V.node.createHash("sha512").update(t).digest());throw new Error("The environment doesn't have sha512 function")},precompute(e=8,t=m.BASE){const r=t.equals(m.BASE)?t:new m(t.x,t.y);return r._setWindowSize(e),r.multiply(o),r},sha512Sync:void 0};Object.defineProperties(W,{sha512Sync:{configurable:!1,get:()=>P,set(e){P||(P=e)}}});var F=function e(t,r,n){r=r||[];for(var o=n=n||0;t>=H;)r[n++]=255&t|128,t/=128;for(;-128&t;)r[n++]=255&t|128,t>>>=7;return r[n]=0|t,e.bytes=n-o+1,r},H=Math.pow(2,31),q=function e(t,r){var n,o=0,i=0,s=r=r||0,a=t.length;do{if(s>=a)throw e.bytes=0,new RangeError("Could not decode varint");n=t[s++],o+=i<28?(127&n)<=128);return e.bytes=s-r,o},J=Math.pow(2,7),G=Math.pow(2,14),Z=Math.pow(2,21),K=Math.pow(2,28),X=Math.pow(2,35),Q=Math.pow(2,42),Y=Math.pow(2,49),ee=Math.pow(2,56),te=Math.pow(2,63),re={encode:F,decode:q,encodingLength:function(e){return e[re.decode(e,t),re.decode.bytes],oe=(e,t,r=0)=>(re.encode(e,t,r),t),ie=e=>re.encodingLength(e),se=e=>{if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")},ae=(e,t)=>{const r=t.byteLength,n=ie(e),o=n+ie(r),i=new Uint8Array(o+r);return oe(e,i,0),oe(r,i,n),i.set(t,o),new ue(e,r,t,i)},ce=e=>{const t=se(e),[r,n]=ne(t),[o,i]=ne(t.subarray(n)),s=t.subarray(n+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new ue(r,o,s,t)};class ue{constructor(e,t,r,n){this.code=e,this.size=t,this.digest=r,this.bytes=n}}var he=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,s=new Uint8Array(i);e[t];){var h=r[e.charCodeAt(t)];if(255===h)return;for(var f=0,d=i-1;(0!==h||f>>0,s[d]=h%256>>>0,h=h/256>>>0;if(0!==h)throw new Error("Non-zero carry");o=f,t++}if(" "!==e[t]){for(var l=i-o;l!==i&&0===s[l];)l++;for(var p=new Uint8Array(n+(i-l)),w=n;l!==i;)p[w++]=s[l++];return p}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,o=0,i=t.length;o!==i&&0===t[o];)o++,r++;for(var s=(i-o)*h+1>>>0,u=new Uint8Array(s);o!==i;){for(var f=t[o],d=0,l=s-1;(0!==f||d>>0,u[l]=f%a>>>0,f=f/a>>>0;if(0!==f)throw new Error("Non-zero carry");n=d,o++}for(var p=s-n;p!==s&&0===u[p];)p++;for(var w=c.repeat(r);pnew pe({...e.decoders||{[e.prefix]:e},...t.decoders||{[t.prefix]:t}});class ye{constructor(e,t,r,n){this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=n,this.encoder=new de(e,t,r),this.decoder=new le(e,t,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ge=({name:e,prefix:t,encode:r,decode:n})=>new ye(e,t,r,n),be=({prefix:e,name:t,alphabet:r})=>{const{encode:n,decode:o}=fe(r,t);return ge({prefix:e,name:t,encode:n,decode:e=>se(o(e))})},me=({name:e,prefix:t,bitsPerChar:r,alphabet:n})=>ge({prefix:t,name:e,encode:e=>((e,t,r)=>{const n="="===t[t.length-1],o=(1<r;)s-=r,i+=t[o&a>>s];if(s&&(i+=t[o&a<((e,t,r,n)=>{const o={};for(let e=0;e=8&&(a-=8,s[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return s})(t,n,r,e)}),ve=be({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"});be({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});const xe=me({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5});me({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),me({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),me({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),me({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),me({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),me({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),me({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),me({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});class Ee{constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=n,this.byteOffset=n.byteOffset,this.byteLength=n.byteLength,this.asCID=this,this._baseCache=new Map,Object.defineProperties(this,{byteOffset:$e,byteLength:$e,code:Re,version:Re,multihash:Re,bytes:Re,_baseCache:$e,asCID:$e})}toV0(){if(0===this.version)return this;{const{code:e,multihash:t}=this;if(e!==Ae)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ie)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return Ee.createV0(t)}}toV1(){switch(this.version){case 0:{const{code:e,digest:t}=this.multihash,r=ae(e,t);return Ee.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}equals(e){return e&&this.code===e.code&&this.version===e.version&&((t=this.multihash)===(r=e.multihash)||t.code===r.code&&t.size===r.size&&((e,t)=>{if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r{const[r,n]=ne(e.subarray(t));return t+=n,r};let n=r(),o=Ae;if(18===n?(n=0,t=0):1===n&&(o=r()),0!==n&&1!==n)throw new RangeError(`Invalid CID version ${n}`);const i=t,s=r(),a=r(),c=t+a;return{version:n,codec:o,multihashCode:s,digestSize:a,multihashSize:c-i,size:c}}static parse(e,t){const[r,n]=ke(e,t),o=Ee.decode(n);return o._baseCache.set(r,e),o}}const ke=(e,t)=>{switch(e[0]){case"Q":{const r=t||ve;return[ve.prefix,r.decode(`${ve.prefix}${e}`)]}case ve.prefix:{const r=t||ve;return[ve.prefix,r.decode(e)]}case xe.prefix:{const r=t||xe;return[xe.prefix,r.decode(e)]}default:if(null==t)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}},Se=(e,t,r)=>{const{prefix:n}=r;if(n!==ve.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const o=t.get(n);if(null==o){const o=r.encode(e).slice(1);return t.set(n,o),o}return o},Be=(e,t,r)=>{const{prefix:n}=r,o=t.get(n);if(null==o){const o=r.encode(e);return t.set(n,o),o}return o},Ae=112,Ie=18,Ce=(e,t,r)=>{const n=ie(e),o=n+ie(t),i=new Uint8Array(o+r.byteLength);return oe(e,i,0),oe(t,i,n),i.set(r,o),i},Oe=Symbol.for("@ipld/js-cid/CID"),Re={writable:!1,configurable:!1,enumerable:!0},$e={writable:!1,enumerable:!1,configurable:!1},Te=(e,t)=>{if(!e.test("0.0.0-dev"))throw new Error(t);console.warn(t)},Ue="CID.isCID(v) is deprecated and will be removed in the next major release.\nFollowing code pattern:\n\nif (CID.isCID(value)) {\n doSomethingWithCID(value)\n}\n\nIs replaced with:\n\nconst cid = CID.asCID(value)\nif (cid) {\n // Make sure to use cid instead of value\n doSomethingWithCID(cid)\n}\n",_e=({name:e,code:t,encode:r})=>new Ne(e,t,r);class Ne{constructor(e,t,r){this.name=e,this.code=t,this.encode=r}digest(e){if(e instanceof Uint8Array){const t=this.encode(e);return t instanceof Uint8Array?ae(this.code,t):t.then((e=>ae(this.code,e)))}throw Error("Unknown type, must be binary type")}}const je="did:key:",ze=e=>{const[t]=ne(e);switch(t){case 237:case 4613:return t;case 4608:if(e.length>35)throw new RangeError("Only p256-pub compressed is supported.");return t;default:throw new RangeError(`Unsupported key algorithm with multicode 0x${t.toString(16)}.`)}},De=e=>{if(!e.startsWith(je))throw new RangeError(`Invalid DID "${e}", must start with 'did:key:'`);return Le(ve.decode(e.slice(je.length)))},Pe=e=>`did:key:${ve.encode(Me(e))}`,Le=e=>(ze(e),new We(e.buffer,e.byteOffset,e.byteLength)),Me=e=>e,Ve=e=>e instanceof We?e:e instanceof Uint8Array?Le(e):De(e);class We extends Uint8Array{did(){return Pe(this)}}const Fe=237,He=ie(Fe),qe=32+He,Je=e=>Ge(De(e)),Ge=e=>{const[t]=ne(e);if(t!==Fe)throw new RangeError(`Unsupported key algorithm with multicode 0x${Fe.toString(16)}`);if(e.byteLength!==qe)throw new RangeError(`Expected Uint8Array with byteLength ${qe}, instead got Uint8Array with byteLength ${e.byteLength}`);return new Ze(e.buffer,e.byteOffset)};class Ze{constructor(e,t=0){this.buffer=e,this.byteOffset=t,this.byteLength=qe}get bytes(){const e=new Uint8Array(this.buffer,this.byteOffset,this.byteLength);return Object.defineProperties(this,{bytes:{value:e}}),e}get publicKey(){const e=new Uint8Array(this.buffer,this.byteOffset+He);return Object.defineProperties(this,{publicKey:{value:e}}),e}did(){return Pe(this.bytes)}verify(e,t){return M(t,e,this.publicKey)}}const Ke=me({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Xe=me({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Qe=me({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6});me({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});const Ye=4864,et=ie(Ye),tt=ie(Fe),rt=32,nt=et+rt+tt+rt,ot=async e=>{if(e.byteLength!==rt)throw new Error(`Expected Uint8Array with byteLength of 32 instead not ${e.byteLength}`);const t=await async function(e){return(await L(e)).pointBytes}(e),r=new Uint8Array(nt);return oe(Ye,r,0),r.set(e,et),oe(Fe,r,et+rt),r.set(t,et+rt+tt),new it(r)};class it{constructor(e){this.buffer=e.buffer,this.byteOffset=e.byteOffset,this.byteLength=nt,this.bytes=e}get principal(){const e=new Uint8Array(this.buffer,et+rt),t=Ge(e);return Object.defineProperties(this,{principal:{value:t}}),t}get secret(){const e=new Uint8Array(this.buffer,et,rt);return Object.defineProperties(this,{secret:{value:e}}),e}did(){return(({principal:e})=>e.did())(this)}sign(e){return async function(e,t){e=z(e);const{prefix:r,scalar:n,pointBytes:o}=await L(t),i=j(await W.sha512(r,e)),a=m.BASE.multiply(i),c=$(i+j(await W.sha512(a.toRawBytes(),o,e))*n,s.l);return new v(a,c).toRawBytes()}(e,this.secret)}verify(e,t){return this.principal.verify(e,t)}}const st=["string","number","bigint","symbol"],at=["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 ct(e){if(null===e)return"null";if(void 0===e)return"undefined";if(!0===e||!1===e)return"boolean";const t=typeof e;if(st.includes(t))return t;if("function"===t)return"Function";if(Array.isArray(e))return"Array";if(function(e){return e&&e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer.call(null,e)}(e))return"Buffer";const r=function(e){const t=Object.prototype.toString.call(e).slice(8,-1);if(at.includes(t))return t}(e);return r||"Object"}class ut{constructor(e,t,r){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=r}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.majore.major?1:0}}ut.uint=new ut(0,"uint",!0),ut.negint=new ut(1,"negint",!0),ut.bytes=new ut(2,"bytes",!0),ut.string=new ut(3,"string",!0),ut.array=new ut(4,"array",!1),ut.map=new ut(5,"map",!1),ut.tag=new ut(6,"tag",!1),ut.float=new ut(7,"float",!0),ut.false=new ut(7,"false",!0),ut.true=new ut(7,"true",!0),ut.null=new ut(7,"null",!0),ut.undefined=new ut(7,"undefined",!0),ut.break=new ut(7,"break",!0);class ht{constructor(e,t,r){this.type=e,this.value=t,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}}const ft=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&"function"==typeof globalThis.Buffer.isBuffer,dt=new TextDecoder,lt=new TextEncoder;function pt(e){return ft&&globalThis.Buffer.isBuffer(e)}function wt(e){return e instanceof Uint8Array?pt(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e:Uint8Array.from(e)}const yt=ft?(e,t,r)=>r-t>64?globalThis.Buffer.from(e.subarray(t,r)).toString("utf8"):kt(e,t,r):(e,t,r)=>r-t>64?dt.decode(e.subarray(t,r)):kt(e,t,r),gt=ft?e=>e.length>64?globalThis.Buffer.from(e):Et(e):e=>e.length>64?lt.encode(e):Et(e),bt=e=>Uint8Array.from(e),mt=ft?(e,t,r)=>pt(e)?new Uint8Array(e.subarray(t,r)):e.slice(t,r):(e,t,r)=>e.slice(t,r),vt=ft?(e,t)=>(e=e.map((e=>e instanceof Uint8Array?e:globalThis.Buffer.from(e))),wt(globalThis.Buffer.concat(e,t))):(e,t)=>{const r=new Uint8Array(t);let n=0;for(let t of e)n+t.length>r.length&&(t=t.subarray(0,r.length-n)),r.set(t,n),n+=t.length;return r},xt=ft?e=>globalThis.Buffer.allocUnsafe(e):e=>new Uint8Array(e);function Et(e,t=1/0){let r;const n=e.length;let o=null;const i=[];for(let s=0;s55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function kt(e,t,r){const n=[];for(;t239?4:o>223?3:o>191?2:1;if(t+s<=r){let r,n,a,c;switch(s){case 1:o<128&&(i=o);break;case 2:r=e[t+1],128==(192&r)&&(c=(31&o)<<6|63&r,c>127&&(i=c));break;case 3:r=e[t+1],n=e[t+2],128==(192&r)&&128==(192&n)&&(c=(15&o)<<12|(63&r)<<6|63&n,c>2047&&(c<55296||c>57343)&&(i=c));break;case 4:r=e[t+1],n=e[t+2],a=e[t+3],128==(192&r)&&128==(192&n)&&128==(192&a)&&(c=(15&o)<<18|(63&r)<<12|(63&n)<<6|63&a,c>65535&&c<1114112&&(i=c))}}null===i?(i=65533,s=1):i>65535&&(i-=65536,n.push(i>>>10&1023|55296),i=56320|1023&i),n.push(i),t+=s}return St(n)}function St(e){const t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nr.length/2?(t=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=mt(r,0,this.cursor)}else t=vt(this.chunks,this.cursor);return e&&this.reset(),t}}function At(e,t,r){if(e.length-t>>8,255&n])}else if(r>>24&255,n>>>16&255,n>>>8&255,255&n])}else{const n=BigInt(r);if(!(n>BigInt(32)&BigInt(4294967295));r[8]=255&o,o>>=8,r[7]=255&o,o>>=8,r[6]=255&o,o>>=8,r[5]=255&o,r[4]=255&i,i>>=8,r[3]=255&i,i>>=8,r[2]=255&i,i>>=8,r[1]=255&i,e.push(r)}}}Tt.encodedSize=function(e){return Ut.encodedSize(e.value)},Ut.encodedSize=function(e){return et.value?1:0};const _t=BigInt(-1),Nt=BigInt(1);function jt(e,t){const r=t.value,n="bigint"==typeof r?r*_t-Nt:-1*r-1;Ut(e,t.type.majorEncoded,n)}function zt(e,t,r,n){At(e,t,r+n);const o=mt(e,t+r,t+r+n);return new ht(ut.bytes,o,r+n)}function Dt(e,t,r,n){return zt(e,t,1,r)}function Pt(e){return void 0===e.encodedBytes&&(e.encodedBytes=e.type===ut.string?gt(e.value):e.value),e.encodedBytes}function Lt(e,t){const r=Pt(t);Ut(e,t.type.majorEncoded,r.length),e.push(r)}function Mt(e,t,r,n,o){const i=r+n;At(e,t,i);const s=new ht(ut.string,yt(e,t+r,t+i),i);return!0===o.retainStringBytes&&(s.byteValue=mt(e,t+r,t+i)),s}function Vt(e,t,r,n){return Mt(e,t,1,r,n)}jt.encodedSize=function(e){const t=e.value,r="bigint"==typeof t?t*_t-Nt:-1*t-1;return rt.value?-1:0},Lt.encodedSize=function(e){const t=Pt(e);return Ut.encodedSize(t.length)+t.length},Lt.compareTokens=function(e,t){return r=Pt(e),n=Pt(t),r.lengthn.length?1:function(e,t){if(pt(e)&&pt(t))return e.compare(t);for(let r=0;r>23,n=8388607&t;if(255===r)tr.setUint16(0,31744,!1);else if(0===r)tr.setUint16(0,(2147483648&e)>>16|n>>13,!1);else{const e=r-127;e<-24?tr.setUint16(0,0):e<-14?tr.setUint16(0,(2147483648&t)>>16|1<<24+e,!1):tr.setUint16(0,(2147483648&t)>>16|e+15<<10|n>>13,!1)}}}function or(e,t){if(e.length-t<2)throw new Error("CBOR decode error: not enough data for float16");const r=(e[t]<<8)+e[t+1];if(31744===r)return 1/0;if(64512===r)return-1/0;if(32256===r)return NaN;const n=r>>10&31,o=1023&r;let i;return i=0===n?o*2**-24:31!==n?(o+1024)*2**(n-25):0===o?1/0:NaN,32768&r?-i:i}function ir(e){tr.setFloat32(0,e,!1)}function sr(e,t){if(e.length-t<4)throw new Error("CBOR decode error: not enough data for float32");const r=(e.byteOffset||0)+t;return new DataView(e.buffer,r,4).getFloat32(0,!1)}function ar(e,t){if(e.length-t<8)throw new Error("CBOR decode error: not enough data for float64");const r=(e.byteOffset||0)+t;return new DataView(e.buffer,r,8).getFloat64(0,!1)}function cr(e,t,r){throw new Error(`CBOR decode error: encountered invalid minor (${r}) for major ${e[t]>>>5}`)}function ur(e){return()=>{throw new Error(`CBOR decode error: ${e}`)}}Yt.compareTokens=Tt.compareTokens;const hr=[];for(let e=0;e<=23;e++)hr[e]=cr;hr[24]=function(e,t,r,n){return new ht(ut.uint,Ct(e,t+1,n),2)},hr[25]=function(e,t,r,n){return new ht(ut.uint,Ot(e,t+1,n),3)},hr[26]=function(e,t,r,n){return new ht(ut.uint,Rt(e,t+1,n),5)},hr[27]=function(e,t,r,n){return new ht(ut.uint,$t(e,t+1,n),9)},hr[28]=cr,hr[29]=cr,hr[30]=cr,hr[31]=cr;for(let e=32;e<=55;e++)hr[e]=cr;hr[56]=function(e,t,r,n){return new ht(ut.negint,-1-Ct(e,t+1,n),2)},hr[57]=function(e,t,r,n){return new ht(ut.negint,-1-Ot(e,t+1,n),3)},hr[58]=function(e,t,r,n){return new ht(ut.negint,-1-Rt(e,t+1,n),5)},hr[59]=function(e,t,r,n){const o=$t(e,t+1,n);if("bigint"!=typeof o){const e=-1-o;if(e>=Number.MIN_SAFE_INTEGER)return new ht(ut.negint,e,9)}if(!0!==n.allowBigInt)throw new Error("CBOR decode error: integers outside of the safe integer range are not supported");return new ht(ut.negint,_t-BigInt(o),9)},hr[60]=cr,hr[61]=cr,hr[62]=cr,hr[63]=cr;for(let e=64;e<=87;e++)hr[e]=Dt;hr[88]=function(e,t,r,n){return zt(e,t,2,Ct(e,t+1,n))},hr[89]=function(e,t,r,n){return zt(e,t,3,Ot(e,t+1,n))},hr[90]=function(e,t,r,n){return zt(e,t,5,Rt(e,t+1,n))},hr[91]=function(e,t,r,n){const o=$t(e,t+1,n);if("bigint"==typeof o)throw new Error("CBOR decode error: 64-bit integer bytes lengths not supported");return zt(e,t,9,o)},hr[92]=cr,hr[93]=cr,hr[94]=cr,hr[95]=ur("indefinite length bytes/strings are not supported");for(let e=96;e<=119;e++)hr[e]=Vt;hr[120]=function(e,t,r,n){return Mt(e,t,2,Ct(e,t+1,n),n)},hr[121]=function(e,t,r,n){return Mt(e,t,3,Ot(e,t+1,n),n)},hr[122]=function(e,t,r,n){return Mt(e,t,5,Rt(e,t+1,n),n)},hr[123]=function(e,t,r,n){const o=$t(e,t+1,n);if("bigint"==typeof o)throw new Error("CBOR decode error: 64-bit integer string lengths not supported");return Mt(e,t,9,o,n)},hr[124]=cr,hr[125]=cr,hr[126]=cr,hr[127]=ur("indefinite length bytes/strings are not supported");for(let e=128;e<=151;e++)hr[e]=Ht;hr[152]=function(e,t,r,n){return Ft(0,0,2,Ct(e,t+1,n))},hr[153]=function(e,t,r,n){return Ft(0,0,3,Ot(e,t+1,n))},hr[154]=function(e,t,r,n){return Ft(0,0,5,Rt(e,t+1,n))},hr[155]=function(e,t,r,n){const o=$t(e,t+1,n);if("bigint"==typeof o)throw new Error("CBOR decode error: 64-bit integer array lengths not supported");return Ft(0,0,9,o)},hr[156]=cr,hr[157]=cr,hr[158]=cr,hr[159]=function(e,t,r,n){if(!1===n.allowIndefinite)throw new Error("CBOR decode error: indefinite length items not allowed");return Ft(0,0,1,1/0)};for(let e=160;e<=183;e++)hr[e]=Gt;hr[184]=function(e,t,r,n){return Jt(0,0,2,Ct(e,t+1,n))},hr[185]=function(e,t,r,n){return Jt(0,0,3,Ot(e,t+1,n))},hr[186]=function(e,t,r,n){return Jt(0,0,5,Rt(e,t+1,n))},hr[187]=function(e,t,r,n){const o=$t(e,t+1,n);if("bigint"==typeof o)throw new Error("CBOR decode error: 64-bit integer map lengths not supported");return Jt(0,0,9,o)},hr[188]=cr,hr[189]=cr,hr[190]=cr,hr[191]=function(e,t,r,n){if(!1===n.allowIndefinite)throw new Error("CBOR decode error: indefinite length items not allowed");return Jt(0,0,1,1/0)};for(let e=192;e<=215;e++)hr[e]=Kt;hr[216]=function(e,t,r,n){return new ht(ut.tag,Ct(e,t+1,n),2)},hr[217]=function(e,t,r,n){return new ht(ut.tag,Ot(e,t+1,n),3)},hr[218]=function(e,t,r,n){return new ht(ut.tag,Rt(e,t+1,n),5)},hr[219]=function(e,t,r,n){return new ht(ut.tag,$t(e,t+1,n),9)},hr[220]=cr,hr[221]=cr,hr[222]=cr,hr[223]=cr;for(let e=224;e<=243;e++)hr[e]=ur("simple values are not supported");hr[244]=cr,hr[245]=cr,hr[246]=cr,hr[247]=function(e,t,r,n){if(!1===n.allowUndefined)throw new Error("CBOR decode error: undefined values are not supported");return!0===n.coerceUndefinedToNull?new ht(ut.null,null,1):new ht(ut.undefined,void 0,1)},hr[248]=ur("simple values are not supported"),hr[249]=function(e,t,r,n){return Qt(or(e,t+1),3,n)},hr[250]=function(e,t,r,n){return Qt(sr(e,t+1),5,n)},hr[251]=function(e,t,r,n){return Qt(ar(e,t+1),9,n)},hr[252]=cr,hr[253]=cr,hr[254]=cr,hr[255]=function(e,t,r,n){if(!1===n.allowIndefinite)throw new Error("CBOR decode error: indefinite length items not allowed");return new ht(ut.break,void 0,1)};const fr=[];for(let e=0;e<24;e++)fr[e]=new ht(ut.uint,e,1);for(let e=-1;e>=-24;e--)fr[31-e]=new ht(ut.negint,e,1);function dr(e){switch(e.type){case ut.false:return bt([244]);case ut.true:return bt([245]);case ut.null:return bt([246]);case ut.bytes:return e.value.length?void 0:bt([64]);case ut.string:return""===e.value?bt([96]):void 0;case ut.array:return 0===e.value?bt([128]):void 0;case ut.map:return 0===e.value?bt([160]):void 0;case ut.uint:return e.value<24?bt([Number(e.value)]):void 0;case ut.negint:if(e.value>=-24)return bt([31-Number(e.value)])}}fr[64]=new ht(ut.bytes,new Uint8Array(0),1),fr[96]=new ht(ut.string,"",1),fr[128]=new ht(ut.array,0,1),fr[160]=new ht(ut.map,0,1),fr[244]=new ht(ut.false,!1,1),fr[245]=new ht(ut.true,!0,1),fr[246]=new ht(ut.null,null,1);const lr={float64:!1,mapSorter:function(e,t){const r=Array.isArray(e[0])?e[0][0]:e[0],n=Array.isArray(t[0])?t[0][0]:t[0];if(r.type!==n.type)return r.type.compare(n.type);const o=r.type.major,i=wr[o].compareTokens(r,n);return 0===i&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i},quickEncodeToken:dr};function pr(){const e=[];return e[ut.uint.major]=Tt,e[ut.negint.major]=jt,e[ut.bytes.major]=Lt,e[ut.string.major]=Wt,e[ut.array.major]=qt,e[ut.map.major]=Zt,e[ut.tag.major]=Xt,e[ut.float.major]=Yt,e}const wr=pr(),yr=new Bt;class gr{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do{if(t.obj===e)return!0}while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error("CBOR encode error: object contains circular references");return new gr(t,e)}}const br={null:new ht(ut.null,null),undefined:new ht(ut.undefined,void 0),true:new ht(ut.true,!0),false:new ht(ut.false,!1),emptyArray:new ht(ut.array,0),emptyMap:new ht(ut.map,0)},mr={number:(e,t,r,n)=>Number.isInteger(e)&&Number.isSafeInteger(e)?new ht(e>=0?ut.uint:ut.negint,e):new ht(ut.float,e),bigint:(e,t,r,n)=>e>=BigInt(0)?new ht(ut.uint,e):new ht(ut.negint,e),Uint8Array:(e,t,r,n)=>new ht(ut.bytes,e),string:(e,t,r,n)=>new ht(ut.string,e),boolean:(e,t,r,n)=>e?br.true:br.false,null:(e,t,r,n)=>br.null,undefined:(e,t,r,n)=>br.undefined,ArrayBuffer:(e,t,r,n)=>new ht(ut.bytes,new Uint8Array(e)),DataView:(e,t,r,n)=>new ht(ut.bytes,new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),Array(e,t,r,n){if(!e.length)return!0===r.addBreakTokens?[br.emptyArray,new ht(ut.break)]:br.emptyArray;n=gr.createCheck(n,e);const o=[];let i=0;for(const t of e)o[i++]=vr(t,r,n);return r.addBreakTokens?[new ht(ut.array,e.length),o,new ht(ut.break)]:[new ht(ut.array,e.length),o]},Object(e,t,r,n){const o="Object"!==t,i=o?e.keys():Object.keys(e),s=o?e.size:i.length;if(!s)return!0===r.addBreakTokens?[br.emptyMap,new ht(ut.break)]:br.emptyMap;n=gr.createCheck(n,e);const a=[];let c=0;for(const t of i)a[c++]=[vr(t,r,n),vr(o?e.get(t):e[t],r,n)];return function(e,t){t.mapSorter&&e.sort(t.mapSorter)}(a,r),r.addBreakTokens?[new ht(ut.map,s),a,new ht(ut.break)]:[new ht(ut.map,s),a]}};mr.Map=mr.Object,mr.Buffer=mr.Uint8Array;for(const e of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))mr[`${e}Array`]=mr.DataView;function vr(e,t={},r){const n=ct(e),o=t&&t.typeEncoders&&t.typeEncoders[n]||mr[n];if("function"==typeof o){const i=o(e,n,t,r);if(null!=i)return i}const i=mr[n];if(!i)throw new Error(`CBOR encode error: unsupported type: ${n}`);return i(e,n,t,r)}function xr(e,t,r,n){if(Array.isArray(t))for(const o of t)xr(e,o,r,n);else r[t.type.major](e,t,n)}function Er(e,t,r){const n=vr(e,r);if(!Array.isArray(n)&&r.quickEncodeToken){const e=r.quickEncodeToken(n);if(e)return e;const o=t[n.type.major];if(o.encodedSize){const e=o.encodedSize(n,r),t=new Bt(e);if(o(t,n,r),1!==t.chunks.length)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return wt(t.chunks[0])}}return yr.reset(),xr(yr,n,t,r),yr.toBytes(!0)}const kr={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0};class Sr{constructor(e,t={}){this.pos=0,this.data=e,this.options=t}done(){return this.pos>=this.data.length}next(){const e=this.data[this.pos];let t=fr[e];if(void 0===t){const r=hr[e];if(!r)throw new Error(`CBOR decode error: no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);const n=31&e;t=r(this.data,this.pos,n,this.options)}return this.pos+=t.encodedLength,t}}const Br=Symbol.for("DONE"),Ar=Symbol.for("BREAK");function Ir(e,t){if(e.done())return Br;const r=e.next();if(r.type===ut.break)return Ar;if(r.type.terminal)return r.value;if(r.type===ut.array)return function(e,t,r){const n=[];for(let o=0;o{return t=e,r=Or,r=Object.assign({},lr,r),Er(t,wr,r);var t,r},Tr=e=>Cr(e,Rr),Ur=new TextEncoder,_r=new TextDecoder,Nr=e=>Ur.encode(e);class jr extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){const t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===ut.array&&(t.elements++,1!==t.elements&&e.push([44])),t.type===ut.map&&(t.elements++,1!==t.elements&&(t.elements%2==1?e.push([44]):e.push([58]))))}[ut.uint.major](e,t){this.prefix(e);const r=String(t.value),n=[];for(let e=0;e32?wt(r):r)}[ut.array.major](e,t){this.prefix(e),this.inRecursive.push({type:ut.array,elements:0}),e.push([91])}[ut.map.major](e,t){this.prefix(e),this.inRecursive.push({type:ut.map,elements:0}),e.push([123])}[ut.tag.major](e,t){}[ut.float.major](e,t){if("break"===t.type.name){const t=this.inRecursive.pop();if(t){if(t.type===ut.array)e.push([93]);else{if(t.type!==ut.map)throw new Error("Unexpected recursive type; this should not happen!");e.push([125])}return}throw new Error("Unexpected break; this should not happen!")}if(void 0===t.value)throw new Error("CBOR encode error: unsupported type: undefined");if(this.prefix(e),"true"===t.type.name)return void e.push([116,114,117,101]);if("false"===t.type.name)return void e.push([102,97,108,115,101]);if("null"===t.type.name)return void e.push([110,117,108,108]);const r=String(t.value),n=[];let o=!1;for(let e=0;en)return 1;throw new Error("CBOR encode error: unexpected duplicate map keys, this is not supported")}};class Dr{constructor(e,t={}){this.pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}done(){return this.pos>=this.data.length}ch(){return this.data[this.pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;32===e||9===e||13===e||10===e;)e=this.data[++this.pos]}expect(e){if(this.data.length-this.pos{for(;!this.done();){const t=this.ch();if(!e.includes(t))break;this.pos++}};if(45===this.ch()&&(t=!0,this.pos++),48===this.ch()){if(this.pos++,46!==this.ch())return new ht(ut.uint,0,this.pos-e);this.pos++,r=!0}if(n([48,49,50,51,52,53,54,55,56,57]),t&&this.pos===e+1)throw new Error(`CBOR decode error: unexpected token at position ${this.pos}`);if(!this.done()&&46===this.ch()){if(r)throw new Error(`CBOR decode error: unexpected token at position ${this.pos}`);r=!0,this.pos++,n([48,49,50,51,52,53,54,55,56,57])}this.done()||101!==this.ch()&&69!==this.ch()||(r=!0,this.pos++,this.done()||43!==this.ch()&&45!==this.ch()||this.pos++,n([48,49,50,51,52,53,54,55,56,57]));const o=String.fromCharCode.apply(null,this.data.subarray(e,this.pos)),i=parseFloat(o);return r?new ht(ut.float,i,this.pos-e):!0!==this.options.allowBigInt||Number.isSafeInteger(i)?new ht(i>=0?ut.uint:ut.negint,i,this.pos-e):new ht(i>=0?ut.uint:ut.negint,BigInt(o),this.pos-e)}parseString(){if(34!==this.ch())throw new Error(`CBOR decode error: unexpected character at position ${this.pos}; this shouldn't happen`);this.pos++;for(let e=this.pos,t=0;e=128)break;if(34===r){const r=String.fromCharCode.apply(null,this.data.subarray(this.pos,e));return this.pos=e+1,new ht(ut.string,r,t)}}const e=this.pos,t=[],r=()=>{if(this.pos+4>=this.data.length)throw new Error(`CBOR decode error: unexpected end of unicode escape sequence at position ${this.pos}`);let e=0;for(let t=0;t<4;t++){let t=this.ch();if(t>=48&&t<=57)t-=48;else if(t>=97&&t<=102)t=t-97+10;else{if(!(t>=65&&t<=70))throw new Error(`CBOR decode error: unexpected unicode escape character at position ${this.pos}`);t=t-65+10}e=16*e+t,this.pos++}return e},n=()=>{const e=this.ch();let r,n,o,i,s=null,a=e>239?4:e>223?3:e>191?2:1;if(this.pos+a>this.data.length)throw new Error(`CBOR decode error: unexpected unicode sequence at position ${this.pos}`);switch(a){case 1:e<128&&(s=e);break;case 2:r=this.data[this.pos+1],128==(192&r)&&(i=(31&e)<<6|63&r,i>127&&(s=i));break;case 3:r=this.data[this.pos+1],n=this.data[this.pos+2],128==(192&r)&&128==(192&n)&&(i=(15&e)<<12|(63&r)<<6|63&n,i>2047&&(i<55296||i>57343)&&(s=i));break;case 4:r=this.data[this.pos+1],n=this.data[this.pos+2],o=this.data[this.pos+3],128==(192&r)&&128==(192&n)&&128==(192&o)&&(i=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&o,i>65535&&i<1114112&&(s=i))}null===s?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|1023&s),t.push(s),this.pos+=a};for(;!this.done();){const o=this.ch();let i;switch(o){case 92:if(this.pos++,this.done())throw new Error(`CBOR decode error: unexpected string termination at position ${this.pos}`);switch(i=this.ch(),this.pos++,i){case 34:case 39:case 92:case 47:t.push(i);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(r());break;default:throw new Error(`CBOR decode error: unexpected string escape character at position ${this.pos}`)}break;case 34:return this.pos++,new ht(ut.string,St(t),this.pos-e);default:if(o<32)throw new Error(`CBOR decode error: invalid control character at position ${this.pos}`);o<128?(t.push(o),this.pos++):n()}}throw new Error(`CBOR decode error: unexpected end of string at position ${this.pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this.pos++,new ht(ut.map,1/0,1);case 91:return this.modeStack.push("array-start"),this.pos++,new ht(ut.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new ht(ut.null,null,4);case 102:return this.expect([102,97,108,115,101]),new ht(ut.false,!1,5);case 116:return this.expect([116,114,117,101]),new ht(ut.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`CBOR decode error: unexpected character at position ${this.pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":if(this.modeStack.pop(),93===this.ch())return this.pos++,this.skipWhitespace(),new ht(ut.break,void 0,1);if(44!==this.ch())throw new Error(`CBOR decode error: unexpected character at position ${this.pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this.pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue();case"array-start":return this.modeStack.pop(),93===this.ch()?(this.pos++,this.skipWhitespace(),new ht(ut.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(125===this.ch())return this.modeStack.pop(),this.pos++,this.skipWhitespace(),new ht(ut.break,void 0,1);if(44!==this.ch())throw new Error(`CBOR decode error: unexpected character at position ${this.pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this.pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),125===this.ch())return this.pos++,this.skipWhitespace(),new ht(ut.break,void 0,1);const e=this.parseString();if(this.skipWhitespace(),58!==this.ch())throw new Error(`CBOR decode error: unexpected character at position ${this.pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this.pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`CBOR decode error: unexpected parse state at position ${this.pos}; this shouldn't happen`)}}}function Pr(e){const t=Ke.encode(e).slice(1);return[new ht(ut.map,1/0,1),new ht(ut.string,"/",1),new ht(ut.map,1/0,1),new ht(ut.string,"bytes",5),new ht(ut.string,t,t.length),new ht(ut.break,void 0,1),new ht(ut.break,void 0,1)]}const Lr={typeEncoders:{Object:function(e){if(e.asCID!==e)return null;const t=Ee.asCID(e);if(!t)return null;const r=t.toString();return[new ht(ut.map,1/0,1),new ht(ut.string,"/",1),new ht(ut.string,r,r.length),new ht(ut.break,void 0,1)]},Uint8Array:Pr,Buffer:Pr,undefined:function(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")},number:function(e){if(Number.isNaN(e))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(e===1/0||e===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}}};class Mr extends Dr{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return 0===this.tokenBuffer.length&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){const e=this._next();if(e.type===ut.map){const e=this._next();if(e.type===ut.string&&"/"===e.value){const e=this._next();if(e.type===ut.string){if(this._next().type!==ut.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(e),new ht(ut.tag,42,0)}if(e.type===ut.map){const e=this._next();if(e.type===ut.string&&"bytes"===e.value){const e=this._next();if(e.type===ut.string){for(let e=0;e<2;e++)if(this._next().type!==ut.break)throw new Error("Invalid encoded Bytes form");const t=Ke.decode(`m${e.value}`);return new ht(ut.bytes,t,e.value.length)}this.tokenBuffer.push(e)}this.tokenBuffer.push(e)}this.tokenBuffer.push(e)}this.tokenBuffer.push(e)}return e}}const Vr={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,tags:[]};Vr.tags[42]=Ee.parse;const Wr=e=>{return t=e,r=Lr,r=Object.assign({},zr,r),Er(t,new jr,r);var t,r},Fr=e=>function(e,t){return Cr(e,t=Object.assign({tokenizer:new Dr(e,t)},t))}(e,Object.assign(Vr,{tokenizer:new Mr(e,Vr)})),Hr=se,qr=e=>ae(0,Hr(e)),Jr=e=>{const{ucv:t,alg:r,typ:n}=Fr(Qe.baseDecode(e));return pn(n),wn(r),{version:dn(t,"ucv")}},Gr=e=>{const t=Fr(Qe.baseDecode(e));return{issuer:un(t.iss,"iss"),audience:un(t.aud,"aud"),expiration:Zr(t.exp,"exp"),nonce:hn(t.nnc,"nnc"),notBefore:fn(t.nbf,"nbf"),facts:nn(t.fct,sn,"fct")||[],proofs:an(t.prf,"prf"),capabilities:Xr(t.att,"att")}},Zr=(e,t)=>Number.isInteger(e)?e:yn.throw(`Expected integer but instead got '${t}: ${JSON.stringify(e)}'`),Kr=(e,t)=>on(e,Qr,t),Xr=(e,t)=>rn(e,Kr,t),Qr=e=>{const t={...e,can:Yr(e.can),with:en(e.with)},r=t.with;return r.endsWith("*")&&"*"!==t.can&&(r.startsWith("my:")||r.startsWith("as:did:"))?yn.throw(`Capability has invalid 'can: ${JSON.stringify(e.can)}', for all 'my:*' or 'as::*' it must be '*'.`):t},Yr=e=>"string"!=typeof e?yn.throw(`Capability has invalid 'can: ${JSON.stringify(e)}', value must be a string`):e.slice(1,-1).includes("/")?e.toLocaleLowerCase():"*"===e?e:yn.throw(`Capability has invalid 'can: "${e}"', value must have at least one path segment`),en=e=>"string"!=typeof e?yn.throw(`Capability has invalid 'with: ${JSON.stringify(e)}', value must be a string`):tn(e)||yn.throw(`Capability has invalid 'with: "${e}"', value must be a valid URI string`),tn=e=>{try{return new URL(e),e}catch(e){return null}},rn=(e,t,r)=>Array.isArray(e)?e.map(((e,n)=>t(e,`${r}[${n}]`))):yn.throw(`${r} must be an array`),nn=(e,t,r)=>void 0===e?e:rn(e,t,r),on=(e,t,r)=>null!=e&&"object"==typeof e?t(e):yn.throw(`${r} must be of type object, instead got ${e}`),sn=(e,t)=>on(e,Object,t),an=(e,t)=>Array.isArray(e)?rn(e,cn,t):[cn(e,t)],cn=(e,t)=>{const r="string"==typeof e?e:yn.throw(`${t} has invalid value ${JSON.stringify(e)}, must be a string`);try{return Ee.parse(r)}catch(e){return Ee.create(1,85,qr(Nr(r)))}},un=(e,t)=>"string"==typeof e&&e.startsWith("did:")?De(e):yn.throw(`DID has invalid representation '${t}: ${JSON.stringify(e)}'`),hn=(e,t="Field")=>{switch(typeof e){case"string":case"undefined":return e;default:return yn.throw(`${t} has invalid value ${e}`)}},fn=(e,t)=>{switch(typeof e){case"undefined":return;case"number":return Zr(e,t);default:return yn.throw(`${t} has invalid value ${JSON.stringify(e)}`)}},dn=(e,t)=>/\d+\.\d+\.\d+/.test(e)?e:yn.throw(`Invalid version '${t}: ${JSON.stringify(e)}'`),ln=(e,t)=>e instanceof Uint8Array?e:yn.throw(`${t} must be Uint8Array, instead got ${JSON.stringify(e)}`),pn=e=>"JWT"===e?e:yn.throw(`Header has invalid type 'typ: "${e}"'`),wn=e=>{switch(e){case"EdDSA":return 237;case"RS256":return 4613;default:return yn.throw(`Header has invalid algorithm 'alg: ${JSON.stringify(e)}'`)}};class yn extends TypeError{get name(){return"ParseError"}static throw(e){throw new this(e)}}class gn{constructor(e){this.model=e}get version(){return this.model.version}get issuer(){return Ve(this.model.issuer)}get audience(){return Ve(this.model.audience)}get capabilities(){return this.model.capabilities}get expiration(){return this.model.expiration}get notBefore(){return this.model.notBefore}get nonce(){return this.model.nonce}get facts(){return this.model.facts}get proofs(){return this.model.proofs}get signature(){return this.model.signature}}class bn extends Uint8Array{constructor(e,{buffer:t,byteOffset:r=0,byteLength:n=t.byteLength}){super(t,r,n),this.model=e}get version(){return this.model.version}get issuer(){return Ve(this.model.issuer)}get audience(){return Ve(this.model.audience)}get capabilities(){return this.model.capabilities}get expiration(){return this.model.expiration}get notBefore(){return this.model.notBefore}get nonce(){return this.model.nonce}get facts(){return this.model.facts}get proofs(){return this.model.proofs}get signature(){return this.model.signature}}const mn=e=>new gn(e),vn=e=>{const{facts:t,nonce:r,notBefore:n,...o}=xn(e);return $r({...o,...t.length>0&&{facts:t},...e.nonce&&{nonce:r},...e.notBefore&&{notBefore:e.notBefore},signature:ln(e.signature,"signature")})},xn=e=>({version:dn(e.version,"version"),issuer:kn(e.issuer,"issuer"),audience:kn(e.audience,"audience"),capabilities:Xr(e.capabilities,"capabilities"),expiration:Zr(e.expiration,"expiration"),proofs:nn(e.proofs,En,"proofs")||[],signature:ln(e.signature,"signature"),nonce:hn(e.nonce,"nonce"),facts:nn(e.facts,sn,"facts")||[],notBefore:fn(e.notBefore,"notBefore")}),En=(e,t)=>Ee.asCID(e)||yn.throw(`Expected ${t} to be CID, instead got ${JSON.stringify(e)}`),kn=(e,t)=>e instanceof Uint8Array?Le(e):yn.throw(`Expected ${t} to be Uint8Array, instead got ${JSON.stringify(e)}`),Sn=e=>Qe.baseEncode(In(e)),Bn=e=>Qe.baseEncode(Cn(e)),An=e=>Qe.baseEncode(e),In=e=>Wr({alg:Rn(e),ucv:e.version,typ:"JWT"}),Cn=e=>Wr({iss:Pe(e.issuer),aud:Pe(e.audience),att:e.capabilities,exp:e.expiration,prf:e.proofs.map(On),...e.facts.length>0&&{fct:e.facts},...e.nonce&&{nnc:e.nonce},...e.notBefore&&{nbf:e.notBefore}}),On=e=>e.toString(),Rn=e=>{switch(ze(e.issuer)){case 237:return"EdDSA";case 4613:return"RS256";default:throw new RangeError(`Unknown KeyType "${ze(e.issuer)}"`)}},$n=e=>async t=>new Uint8Array(await crypto.subtle.digest(e,t)),Tn=_e({name:"sha2-256",code:18,encode:$n("SHA-256")});_e({name:"sha2-512",code:19,encode:$n("SHA-512")});const Un=e=>{try{return(e=>mn(xn(Tr(e))))(e)}catch(t){const r=(e=>_r.decode(e))(e);return Nn(r)}},_n=async(e,t)=>{const r=t?.hasher||Tn,[n,o]=e instanceof Uint8Array?[85,(i=e,new Uint8Array(i.buffer,i.byteOffset,i.byteLength))]:[113,vn(e)];var i;return{cid:Ee.createV1(n,await r.digest(o)),bytes:o,data:e}},Nn=e=>{const t=(e=>{const t=e.split("."),[r,n,o]=3===t.length?t:yn.throw(`Can't parse UCAN: ${e}: Expected JWT format: 3 dot-separated base64url-encoded values.`);return{...Jr(r),...Gr(n),signature:Qe.baseDecode(o)}})(e);return(e=>`${Sn(e)}.${Bn(e)}.${An(e.signature)}`)(t)===e?mn(t):((e,t)=>new bn(e,t))(t,Nr(e))},jn=async({issuer:e,audience:t,capabilities:r,lifetimeInSeconds:n=30,expiration:o=Math.floor(Date.now()/1e3)+n,notBefore:i,facts:s=[],proofs:a=[],nonce:c})=>{const u=xn({version:"0.8.1",issuer:zn(e,"issuer"),audience:zn(t,"audience"),capabilities:r,facts:s,expiration:o,notBefore:i,proofs:a,nonce:c,signature:Dn}),h=Nr(`${Sn(f=u)}.${Bn(f)}`);var f;const d=await e.sign(h);return mn({...u,signature:d})},zn=(e,t)=>e&&"function"==typeof e.did?un(e.did(),`${t}.did()`):yn.throw(`The ${t}.did() must be a function that returns DID`),Dn=new Uint8Array;var Pn=globalThis.fetch;function Ln(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Mn={exports:{}},Vn={};function Wn(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}var Fn=Wn;Wn.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},Wn.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},Wn.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout((function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout((function(){n._operationTimeoutCb(n._attempts)}),n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)}),r),this._options.unref&&this._timer.unref(),!0},Wn.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout((function(){r._operationTimeoutCb()}),r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},Wn.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},Wn.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},Wn.prototype.start=Wn.prototype.try,Wn.prototype.errors=function(){return this._errors},Wn.prototype.attempts=function(){return this._attempts},Wn.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n=r&&(t=o,r=s)}return t},function(e){var t=Fn;e.operation=function(r){var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;ovoid 0===globalThis.DOMException?new Error(e):new DOMException(e);async function Zn(e,t){return new Promise(((r,n)=>{t={onFailedAttempt(){},retries:10,...t};const o=Hn.operation(t);o.attempt((async i=>{try{r(await e(i))}catch(e){if(!(e instanceof Error))return void n(new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));if(e instanceof Jn)o.stop(),n(e.originalError);else if(e instanceof TypeError&&(s=e.message,!qn.has(s)))o.stop(),n(e);else{((e,t,r)=>{const n=r.retries-(t-1);e.attemptNumber=t,e.retriesLeft=n})(e,i,t);try{await t.onFailedAttempt(e)}catch(e){return void n(e)}o.retry(e)||n(o.mainError())}}var s})),t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",(()=>{o.stop();const e=void 0===t.signal.reason?Gn("The operation was aborted."):t.signal.reason;n(e instanceof Error?e:Gn(e))}),{once:!0})}))}const Kn=(e,t)=>Ee.createV1(e,t),Xn=Ee.asCID;Ee.parse,Ee.decode;const Qn=e=>{return!(null!=(t=e)&&t.asCID===t);var t};class Yn{constructor(e,t=new Map){this.root=e,this.blocks=t,Object.defineProperties(this,{blocks:{enumerable:!1}})}get version(){return this.data.version}get signature(){return this.data.signature}get cid(){return this.root.cid}get asCID(){return this.cid}get bytes(){return this.root.bytes}get data(){const e=ro(this.root);return Object.defineProperties(this,{data:{value:e,enumerable:!1}}),e}export(){return oo(this.root,this.blocks)}get proofs(){return so(this)}get issuer(){return this.data.issuer}get audience(){return this.data.audience}get capabilities(){return this.data.capabilities}get expiration(){return this.data.expiration}get notBefore(){return this.data.notBefore}get nonce(){return this.data.nonce}get facts(){return this.data.facts}iterate(){return eo(this)}}const eo=function*(e){for(const t of e.proofs)Qn(t)&&(yield*eo(t),yield t)},to=new WeakMap,ro=({bytes:e})=>{const t=to.get(e);if(!t){const t=Un(e);return to.set(e,t),t}return t},no=async({issuer:e,audience:t,proofs:r=[],...n},o)=>{const i=[],s=new Map;for(const e of r)if(Qn(e)){i.push(e.cid);for(const t of e.export())s.set(t.cid.toString(),t)}else i.push(e);const a=await jn({...n,issuer:e,audience:t,proofs:i}),{cid:c,bytes:u}=await _n(a,o);to.set(c,a);const h=new Yn({cid:c,bytes:u},s);return Object.defineProperties(h,{proofs:{value:r}}),h},oo=function*(e,t){for(const r of ro(e).proofs){const e=t.get(r.toString());e&&(yield*oo(e,t))}yield e},io=({root:e,blocks:t})=>new Yn(e,t),so=e=>{const t=[],{root:r,blocks:n}=e;for(const e of ro(r).proofs){const r=n.get(e.toString());t.push(r?io({root:r,blocks:n}):e)}return Object.defineProperty(e,"proofs",{value:t}),t};class ao{constructor({issuer:e,audience:t,capability:r,proofs:n=[],expiration:o,lifetimeInSeconds:i,notBefore:s,nonce:a,facts:c=[]}){this.issuer=e,this.audience=t,this.proofs=n,this.capabilities=[r],this.expiration=o,this.lifetimeInSeconds=i,this.notBefore=s,this.nonce=a,this.facts=c}delegate(){return no(this)}async execute(e){const[t]=await e.execute(this);return t}}const co=e=>Object.entries(e),uo=(e,t)=>{const[r,n]=e.lengthgo(e.message)))].join("\n")}get cause(){if(1!==this.causes.length)return this;{const[e]=this.causes,t="InvalidClaim"===e.name?e.cause:e;return Object.defineProperties(this,{cause:{value:t}}),t}}}class po extends ho{constructor(e,t){super(),this.name="MalformedCapability",this.capability=e,this.cause=t}describe(){return[`Encountered malformed '${this.capability.can}' capability: ${yo(this.capability)}`,go(this.cause.message)].join("\n")}}class wo extends ho{constructor(e){super(),this.name="UnknownCapability",this.capability=e}describe(){return`Encountered unknown capability: ${yo(this.capability)}`}}const yo=(e,t)=>JSON.stringify(e,((e,t)=>t&&t.asCID===t?t.toString():t),t),go=e=>((e,t=" ")=>`${t}${e.split("\n").join(`\n${t}`)}`)(`- ${e}`),bo=e=>new xo(e);class mo{match(e){return new wo(e.capability)}select(e){return Ro(this,e)}derive({derives:e,to:t}){return(({from:e,to:t,derives:r})=>new So(e,t,r))({derives:e,to:t,from:this})}}class vo extends mo{or(e){return new Eo(this,e)}and(e){return((...e)=>new ko(e))(this,e)}}class xo extends vo{constructor(e){super(),this.descriptor={derives:To,...e}}create(e){const{descriptor:t,can:r}=this,n=t.caveats,o=e.caveats||{},i=t.with.decode(e.with);if(i.error)throw Object.assign(new Error(`Invalid 'with' - ${i.message}`),{cause:i});const s={};for(const[e,t]of Object.entries(n||{})){const r=e,n=t.decode(o[r]);if(n?.error)throw Object.assign(new Error(`Invalid 'caveats.${r}' - ${n.message}`),{cause:n});void 0!==n&&(s[e]=n)}return{...s,can:r,with:i.href}}invoke({with:e,caveats:t,...r}){return(e=>new ao(e))({...r,capability:this.create({with:e,caveats:t})})}get can(){return this.descriptor.can}match(e){const t=Co(this,e);return t.error?t:new Bo(e,t,this.descriptor)}toString(){return JSON.stringify({can:this.descriptor.can})}}class Eo extends vo{constructor(e,t){super(),this.left=e,this.right=t}match(e){const t=this.left.match(e);if(t.error){const r=this.right.match(e);return r.error?"MalformedCapability"===r.name?r:t:r}return t}toString(){return`${this.left.toString()}|${this.right.toString()}`}}class ko extends mo{constructor(e){super(),this.selectors=e}match(e){const t=[];for(const r of this.selectors){const n=r.match(e);if(n.error)return n;t.push(n)}return new Io(t)}select(e){return $o(this,e)}and(e){return new ko([...this.selectors,e])}toString(){return`[${this.selectors.map(String).join(", ")}]`}}class So extends vo{constructor(e,t,r){super(),this.from=e,this.to=t,this.derives=r}create(e){return this.to.create(e)}invoke(e){return this.to.invoke(e)}get can(){return this.to.can}match(e){const t=this.to.match(e);return t.error?t:new Ao(t,this.from,this.derives)}toString(){return this.to.toString()}}class Bo{constructor(e,t,r){this.source=[e],this.value=t,this.descriptor={derives:To,...r}}get can(){return this.value.can}get proofs(){const e=[this.source[0].delegation];return Object.defineProperties(this,{proofs:{value:e}}),e}prune(e){return e.canIssue(this.value,this.source[0].delegation.issuer.did())?null:this}select(e){const t=[],r=[],n=[];for(const o of e){const e=Co(this,o);if(e.error)"UnknownCapability"===e.name?t.push(e.capability):r.push(new lo([e],this));else{const t=this.descriptor.derives(this.value,e);t.error?r.push(new lo([new fo(this.value,e,t)],this)):n.push(new Bo(o,e,this.descriptor))}}return{matches:n,unknown:t,errors:r}}toString(){return JSON.stringify({can:this.descriptor.can,with:this.value.uri.href,caveats:Object.keys(this.value.caveats).length>0?this.value.caveats:void 0})}}class Ao{constructor(e,t,r){this.selected=e,this.from=t,this.derives=r}get can(){return this.value.can}get source(){return this.selected.source}get proofs(){const e=[];for(const{delegation:t}of this.selected.source)e.push(t);return Object.defineProperties(this,{proofs:{value:e}}),e}get value(){return this.selected.value}prune(e){const t=this.selected.prune(e);return t?new Ao(t,this.from,this.derives):null}select(e){const{derives:t,selected:r,from:n}=this,{value:o}=r,i=r.select(e),s=n.select(e),a=[],c=[];for(const e of s.matches){const r=t(o,e.value);r.error?c.push(new lo([new fo(o,e.value,r)],this)):a.push(e)}return{unknown:uo(i.unknown,s.unknown),errors:[...c,...i.errors,...s.errors.map((e=>new lo([e],this)))],matches:[...i.matches.map((e=>new Ao(e,n,t))),...a]}}toString(){return this.selected.toString()}}class Io{constructor(e){this.matches=e}get selectors(){return this.matches}get source(){const e=[];for(const t of this.matches)e.push(...t.source);return Object.defineProperties(this,{source:{value:e}}),e}prune(e){const t=[];for(const r of this.matches){const n=r.prune(e);n&&t.push(n)}return 0===t.length?null:new Io(t)}get proofs(){const e=[];for(const{delegation:t}of this.source)e.push(t);return Object.defineProperties(this,{source:{value:e}}),e}get value(){const e=[];for(const t of this.matches)e.push(t.value);return Object.defineProperties(this,{value:{value:e}}),e}select(e){return $o(this,e)}toString(){return`[${this.matches.map((e=>e.toString())).join(", ")}]`}}const Co=(e,t)=>{const{can:r,with:n,caveats:o}=e.descriptor,{delegation:i,index:s}=t,a=t.capability;if(a.can!==r)return new wo(a);const c=n.decode(a.with);if(c.error)return new po(a,c);const u={};if(o)for(const[e,t]of co(o)){const r=e,n=a[r],o=t.decode(n);if(o?.error)return new po(a,o);null!=o&&(u[r]=o)}return new Oo(r,a.with,c,u,i)};class Oo{constructor(e,t,r,n,o){this.can=e,this.with=t,this.uri=r,this.delegation=o,this.caveats=n}}const Ro=(e,t)=>{const r=[],n=[],o=[];for(const i of t){const t=e.match(i);t.error?"UnknownCapability"===t.name?r.push(t.capability):o.push(new lo([t],t.capability)):n.push(t)}return{matches:n,errors:o,unknown:r}},$o=(e,t)=>{let r;const n=[],o=[];for(const i of e.selectors){const s=i.select(t);r=r?uo(r,s.unknown):s.unknown;for(const t of s.errors)o.push(new lo([t],e));n.push(s.matches)}return{unknown:r||[],errors:o,matches:(([e,...t])=>{const r=e.map((e=>[e]));for(const e of t){const t=r.splice(0);for(const n of e)for(const e of t)r.push([...e,n])}return r})(n).map((e=>new Io(e)))}},To=(e,t)=>{if(t.with.endsWith("*")){if(!e.with.startsWith(t.with.slice(0,-1)))return new ho(`Resource ${e.with} does not match delegated ${t.with} `)}else if(t.with!==e.with)return new ho(`Resource ${e.with} does not contain ${t.with}`);for(const[r,n]of co(t.caveats))if(e.caveats[r]!=n)return new ho(`${String(r)}: ${e.caveats[r]} violates ${n}`);return!0},Uo=(e,{protocol:t}={})=>{if("string"!=typeof e&&!(e instanceof URL))return new ho("Expected URI but got "+typeof e);try{const r=new URL(String(e));return null!=t&&r.protocol!==t?new ho(`Expected ${t} URI instead got ${r.href}`):r}catch(e){return new ho("Invalid URI")}},_o=e=>({decode:t=>Uo(t,e)}),No=e=>({decode:t=>{const r=Uo(t,e);return r.error?r:r.href}}),jo=e=>({decode:t=>void 0===t?void 0:((e,t={})=>{if(null==e)return new ho(`Expected link but got ${e} instead`);{const r=Xn(e);return null==r?new ho(`Expected link to be a CID instead of ${e}`):null!=t.code&&r.code!==t.code?new ho(`Expected link to be CID with 0x${t.code.toString(16)} codec`):null!=t.algorithm&&r.multihash.code!==t.algorithm?new ho(`Expected link to be CID with 0x${t.algorithm.toString(16)} hashing algorithm`):null!=t.version&&r.version!==t.version?new ho(`Expected link to be CID version ${t.version} instead of ${r.version}`):r}})(t,e)});function zo(e,t){return t.endsWith("*")?!!e.startsWith(t.slice(0,-1))||new ho(`${e} does not match ${t}`):e===t||new ho(`${e} is different from ${t}`)}function Do(e,t){return e.with===t.with||new ho(`Can not derive ${e.can} with ${e.with} from ${t.with}`)}const Po=(e,t)=>e.uri.href!==t.uri.href?new ho(`Expected 'with: "${t.uri.href}"' instead got '${e.uri.href}'`):!t.caveats.link||`${t.caveats.link}`==`${e.caveats.link}`||new ho(`Link ${null==e.caveats.link?"":`${e.caveats.link} `}violates imposed ${t.caveats.link} constraint`);class Lo{constructor(e){this.decoder=e}optional(){return this}decode(e){return void 0===e?void 0:this.decoder.decode(e)}}class Mo extends class{decode(e){return new ho("Given input is not valid")}optional(){return new Lo(this)}}{constructor({min:e=-1/0,max:t=1/0}={}){super(),this.min=e,this.max=t}static isInteger(e){return Number.isInteger(e)}decode(e){const{min:t,max:r}=this;return Mo.isInteger(e)?t>e?new ho(`Expecting an Integer > ${t} but instead got ${e}`):r{const r=Po(e,t);return r.error?r:null==e.caveats.size||null==t.caveats.size||!(e.caveats.size>t.caveats.size)||new ho(`Size constraint violation: ${e.caveats.size} > ${t.caveats.size}`)}}),derives:Do}),Jo=Ho.derive({to:bo({can:"store/remove",with:_o({protocol:"did:"}),caveats:{link:jo()},derives:Po}),derives:Do}),Go=Ho.derive({to:bo({can:"store/list",with:_o({protocol:"did:"}),derives:(e,t)=>e.uri.href===t.uri.href||new ho(`Expected 'with: "${t.uri.href}"' instead got '${e.uri.href}'`)}),derives:Do}),Zo=qo.or(Jo).or(Go),Ko=bo({can:"identity/validate",with:_o({protocol:"did:"}),caveats:{as:No({protocol:"mailto:"})},derives:(e,t)=>zo(e.caveats.as,t.caveats.as)&&Do(e,t)}),Xo=bo({can:"identity/register",with:_o({protocol:"mailto:"}),caveats:{as:No({protocol:"did:"})},derives:(e,t)=>zo(e.caveats.as,t.caveats.as)&&zo(e.with,t.with)}),Qo=Zo.derive({to:bo({can:"identity/identify",with:_o({protocol:"did:"}),derives:Do}),derives:Do});Xo.or(Ko).or(Qo);class Yo{constructor(e){this.id=e.id,this.options=e,this.encoder=e.encoder,this.decoder=e.decoder,this.channel=e.channel,this.hasher=e.hasher||Tn}execute(...e){return ei(e,this)}}const ei=async(e,t)=>{const r=await t.encoder.encode(e,t),n=await t.channel.request(r);return await t.decoder.decode(n)};var ti=function e(t,r,n){if(Number.MAX_SAFE_INTEGER&&t>Number.MAX_SAFE_INTEGER)throw e.bytes=0,new RangeError("Could not encode varint");r=r||[];for(var o=n=n||0;t>=ri;)r[n++]=255&t|128,t/=128;for(;-128&t;)r[n++]=255&t|128,t>>>=7;return r[n]=0|t,e.bytes=n-o+1,r},ri=Math.pow(2,31),ni=function e(t,r){var n,o=0,i=0,s=r=r||0,a=t.length;do{if(s>=a||i>49)throw e.bytes=0,new RangeError("Could not decode varint");n=t[s++],o+=i<28?(127&n)<=128);return e.bytes=s-r,o},oi=Math.pow(2,7),ii=Math.pow(2,14),si=Math.pow(2,21),ai=Math.pow(2,28),ci=Math.pow(2,35),ui=Math.pow(2,42),hi=Math.pow(2,49),fi=Math.pow(2,56),di=Math.pow(2,63),li={encode:ti,decode:ni,encodingLength:function(e){return e{const{resize:n=!1}=r,{bytes:o,headerSize:i,byteOffset:s,roots:a}=e;e.roots.push(t);const c=Ci(e);if(c>i){if(!(c-i+s{const r=e.bytes.byteLength+t.byteLength;return li.encodingLength(r)+r},vi=(e,{cid:t,bytes:r})=>{const n=t.bytes.byteLength+r.byteLength,o=li.encode(n);if(e.byteOffset+o.length+n>e.bytes.byteLength)throw new RangeError("Buffer has no capacity for this block");ki(e,o),ki(e,t.bytes),ki(e,r)},xi=(e,t={})=>{const{resize:r=!1}=t,{roots:n,bytes:o,byteOffset:i,headerSize:s}=e,a=$r({version:1,roots:n}),c=li.encode(a.length),u=c.length+a.byteLength;if(0==s-u)return Si(e,c,a),o.subarray(0,i);if(r)return Ei(e,u),Si(e,c,a),o.subarray(0,e.byteOffset);throw new RangeError("Header size was overestimated.\nYou can use close({ resize: true }) to resize header")},Ei=(e,t)=>{const{bytes:r,headerSize:n}=e;r.set(r.subarray(n,e.byteOffset),t),e.byteOffset+=t-n,e.headerSize=t},ki=(e,t)=>{e.bytes.set(t,e.byteOffset),e.byteOffset+=t.length},Si=({bytes:e},t,r)=>{e.set(t),e.set(r,t.length)},Bi=[new ht(ut.map,2),new ht(ut.string,"version"),new ht(ut.uint,1),new ht(ut.string,"roots")],Ai=new ht(ut.tag,42),Ii=e=>{const t=[...Bi];t.push(new ht(ut.array,e.length));for(const r of e)t.push(Ai),t.push(new ht(ut.bytes,{length:r+1}));const r=yi(t);return li.encodingLength(r)+r},Ci=({roots:e})=>Ii(e.map((e=>e.bytes.byteLength))),Oi={Null:e=>null===e,Int:e=>Number.isInteger(e),Float:e=>"number"==typeof e&&Number.isFinite(e),String:e=>"string"==typeof e,Bool:e=>"boolean"==typeof e,Bytes:e=>e instanceof Uint8Array,Link:e=>!Oi.Null(e)&&"object"==typeof e&&e.asCID===e,List:e=>Array.isArray(e),Map:e=>!Oi.Null(e)&&"object"==typeof e&&e.asCID!==e&&!Oi.List(e)&&!Oi.Bytes(e)},Ri={Int:Oi.Int,"CarHeader > version":e=>Ri.Int(e),"CarHeader > roots (anon) > valueType (anon)":Oi.Link,"CarHeader > roots (anon)":e=>Oi.List(e)&&Array.prototype.every.call(e,Ri["CarHeader > roots (anon) > valueType (anon)"]),"CarHeader > roots":e=>Ri["CarHeader > roots (anon)"](e),CarHeader:e=>{const t=e&&Object.keys(e);return Oi.Map(e)&&["version"].every((e=>t.includes(e)))&&Object.entries(e).every((([e,t])=>Ri["CarHeader > "+e]&&Ri["CarHeader > "+e](t)))}},$i=Ri.CarHeader,Ti=18,Ui=32,_i=112;async function Ni(e){const t=await e.upTo(8);if(!t.length)throw new Error("Unexpected end of data");const r=li.decode(t);return e.seek(li.decode.bytes),r}async function ji(e,t){const r=await Ni(e);if(0===r)throw new Error("Invalid CAR header (zero length)");const n=await e.exactly(r);e.seek(r);const o=Tr(n);if(!$i(o))throw new Error("Invalid CAR header format");if(1!==o.version&&2!==o.version||void 0!==t&&o.version!==t)throw new Error(`Invalid CAR version: ${o.version}${void 0!==t?` (expected ${t})`:""}`);const i=Array.isArray(o.roots);if(1===o.version&&!i||2===o.version&&i)throw new Error("Invalid CAR header format");if(1===o.version)return o;const s=await async function(e){const t=await e.exactly(40),r=new DataView(t.buffer,t.byteOffset,t.byteLength);let n=0;const o={version:2,characteristics:[r.getBigUint64(n,!0),r.getBigUint64(n+=8,!0)],dataOffset:Number(r.getBigUint64(n+=8,!0)),dataSize:Number(r.getBigUint64(n+=8,!0)),indexOffset:Number(r.getBigUint64(n+=8,!0))};return e.seek(40),o}(e);e.seek(s.dataOffset-e.pos);const a=await ji(e,1);return Object.assign(a,s)}async function zi(e){const t=await e.exactly(2);if(t[0]===Ti&&t[1]===Ui){const t=await e.exactly(34);e.seek(34);const r=ce(t);return Ee.create(0,_i,r)}const r=await Ni(e);if(1!==r)throw new Error(`Unexpected CID version (${r})`);const n=await Ni(e),o=await async function(e){const t=await e.upTo(8);li.decode(t);const r=li.decode.bytes,n=li.decode(t.subarray(li.decode.bytes)),o=r+li.decode.bytes+n,i=await e.exactly(o);return e.seek(o),i}(e),i=ce(o);return Ee.create(r,n,i)}async function Di(e){const t=e.pos;let r=await Ni(e);if(0===r)throw new Error("Invalid CAR section (zero length)");return r+=e.pos-t,{cid:await zi(e),length:r,blockLength:r-Number(e.pos-t)}}async function Pi(e){const{cid:t,blockLength:r}=await Di(e),n=await e.exactly(r);return e.seek(r),{bytes:n,cid:t}}async function Li(e){const t=e.pos,{cid:r,length:n,blockLength:o}=await Di(e),i={cid:r,length:n,blockLength:o,offset:t,blockOffset:e.pos};return e.seek(i.blockLength),i}function Mi(e){const t=(async()=>{const t=await ji(e);if(2===t.version){const r=e.pos-t.dataOffset;e=function(e,t){let r=0;return{async upTo(n){let o=await e.upTo(n);return o.length+r>t&&(o=o.subarray(0,t-r)),o},async exactly(n){const o=await e.exactly(n);if(o.length+r>t)throw new Error("Unexpected end of data");return o},seek(t){r+=t,e.seek(t)},get pos(){return e.pos}}}(e,t.dataSize-r)}return t})();return{header:()=>t,async*blocks(){for(await t;(await e.upTo(8)).length>0;)yield await Pi(e)},async*blocksIndex(){for(await t;(await e.upTo(8)).length>0;)yield await Li(e)}}}function Vi(e){const t=e[Symbol.asyncIterator]();return function(e){let t=0,r=0,n=0,o=new Uint8Array(0);const i=async t=>{r=o.length-n;const i=[o.subarray(n)];for(;rr&&i.push(t.subarray(-r)):i.push(t),r+=t.length}o=new Uint8Array(i.reduce(((e,t)=>e+t.length),0));let s=0;for(const e of i)o.set(e,s),s+=e.length;n=0};return{upTo:async e=>(o.length-ne.cid.toString()))}get version(){return this._header.version}async getRoots(){return this._header.roots}async has(e){return this._keys.indexOf(e.toString())>-1}async get(e){const t=this._keys.indexOf(e.toString());return t>-1?this._blocks[t]:void 0}async*blocks(){for(const e of this._blocks)yield e}async*cids(){for(const e of this._blocks)yield e.cid}static async fromBytes(e){if(!(e instanceof Uint8Array))throw new TypeError("fromBytes() requires a Uint8Array");return Fi(function(e){let t=0;return{upTo:async r=>e.subarray(t,t+Math.min(r,e.length-t)),async exactly(r){if(r>e.length-t)throw new Error("Unexpected end of data");return e.subarray(t,t+r)},seek(e){t+=e},get pos(){return t}}}(e))}static async fromIterable(e){if(!e||"function"!=typeof e[Symbol.asyncIterator])throw new TypeError("fromIterable() requires an async iterable");return Fi(Vi(e))}}async function Fi(e){const t=Mi(e),r=await t.header(),n=[];for await(const e of t.blocks())n.push(e);return new Wi(r,n)}class Hi{constructor(e=[],t=0){this.written=new Set,this.blocks=e,this.byteLength=t}write(...e){for(const t of e){const e=t.cid.toString(xe);this.written.has(e)||(this.blocks.push(t),this.byteLength+=mi(t),this.written.add(e))}return this}flush(...e){const t=[];for(const r of e.reverse()){const e=r.cid.toString(xe);this.written.has(e)||(this.blocks.unshift(r),this.byteLength+=mi({cid:r.cid,bytes:r.bytes}),this.written.add(e)),t.push(r.cid)}this.byteLength+=Ci({roots:t});const r=((e,t={})=>{const{roots:r=[],byteOffset:n=0,byteLength:o=e.byteLength,headerSize:i=Ci({roots:r})}=t,s=new Uint8Array(e,n,o),a=new gi(s,i);for(const e of r)a.addRoot(e);return a})(new ArrayBuffer(this.byteLength),{roots:t});for(const e of this.blocks)r.write(e);return r.close()}}const qi=({roots:e=[],blocks:t})=>{const r=new Hi;return t&&r.write(...t.values()),r.flush(...e)},Ji=async e=>{const t=await Wi.fromBytes(e),{_header:r,_blocks:n,_keys:o}=t,i=[],s=new Map,a=r.roots.map((e=>o.indexOf(String(e))));for(const[e,t]of n.entries())a.includes(e)?i.push(t):s.set(t.cid.toString(),t);return{roots:i,blocks:s}},Gi=async(e,{hasher:t=Tn}={})=>Kn(514,await t.digest(e));var Zi=Object.freeze({__proto__:null,code:514,createWriter:()=>new Hi,encode:qi,decode:Ji,link:Gi,write:async(e,t)=>{const r=qi(e);return{bytes:r,cid:await Gi(r,t)}}});const Ki=Object.freeze({"content-type":"application/car"});var Xi=Object.freeze({__proto__:null,codec:Zi,encode:async(e,t)=>{const r=[],n=new Map;for(const o of e){const e=await no(o,t);r.push(e.root);for(const t of e.export())n.set(t.cid.toString(),t);n.delete(e.root.cid.toString())}const o=qi({roots:r,blocks:n});return{headers:Ki,body:o}},decode:async({headers:e,body:t})=>{const r=e["content-type"]||e["Content-Type"];if("application/car"!==r)throw TypeError(`Only 'content-type: application/car' is supported, instead got '${r}'`);const{roots:n,blocks:o}=await Ji(t),i=[];for(const e of n)i.push(io({root:e,blocks:o}));return i}});const Qi=(e,t)=>{if(t.has(e))throw new TypeError("Can not encode circular structure");if(void 0===e&&0===t.size)return null;if(null===e)return null;if("symbol"==typeof e&&0===t.size)return null;const r=Xn(e);if(r)return r;if(ArrayBuffer.isView(e))return e;if(Array.isArray(e)){t.add(e);const r=[];for(const n of e)r.push(void 0===n||"symbol"==typeof n?null:Qi(n,t));return r}if("function"==typeof e.toJSON){t.add(e);const r=e.toJSON();return Qi(r,t)}if("object"==typeof e){t.add(e);const r={};for(const[n,o]of Object.entries(e))void 0!==o&&"symbol"!=typeof o&&(r[n]=Qi(o,t));return r}return e},Yi=e=>$r(Qi(e,new Set)),es=async(e,{hasher:t=Tn}={})=>Kn(113,await t.digest(e));var ts=Object.freeze({__proto__:null,encode:Yi,link:es,write:async(e,t)=>{const r=Yi(e);return{cid:await es(r,t),bytes:r}},code:113,decode:Tr});const rs=Object.freeze({"content-type":"application/cbor"}),ns=ts;var os=Object.freeze({__proto__:null,codec:ns,encode:e=>({headers:rs,body:Yi(e)}),decode:async({headers:e,body:t})=>{const r=e["content-type"]||e["Content-Type"];if("application/cbor"!==r)throw TypeError(`Only 'content-type: application/cbor' is supported, intsead got '${r}'`);return Tr(t)}});const is=({url:e,method:t="POST",fetch:r})=>{if(!r){if(void 0===globalThis.fetch)throw new TypeError("ucanto HTTP transport got undefined `fetch`. Try passing in a `fetch` implementation explicitly.");r=globalThis.fetch.bind(globalThis)}return new ss({url:e,method:t,fetch:r})};class ss{constructor({url:e,fetch:t,method:r}){this.fetch=t,this.method=r,this.url=e}async request({headers:e,body:t}){const r=await this.fetch(this.url.href,{headers:e,body:t,method:this.method}),n=r.ok?await r.arrayBuffer():as.throw("HTTP Request failed",r);return{headers:Object.fromEntries(r.headers.entries()),body:new Uint8Array(n)}}}class as extends Error{static throw(e,t){throw new this(e,t)}constructor(e,{url:t,status:r=500,statusText:n="Server error"}){super(e),this.name="HTTPError",this.url=t,this.status=r,this.statusText=n}}const cs=new URL("https://access-api.web3.storage"),us=Je("did:key:z6MkkHafoFWxxWVNpNXocFdU6PL2RVLyTEgS1qTnD3bRP7V9");function hs({id:e,url:t=cs,fetch:r}){return n={id:e,encoder:Xi,decoder:os,channel:is({url:t,method:"POST",fetch:r})},new Yo(n);var n}async function fs(e){const t=hs({id:e.issuer,url:e.url||cs}),r=Ko.invoke({audience:e.audience||us,issuer:e.issuer,with:e.issuer.did(),caveats:{...e.caveats}}),n=await r.execute(t);if(n?.error)throw n}async function ds(e){const t=hs({id:e.issuer,url:e.url||cs}),r=Xo.invoke({audience:e.audience||us,issuer:e.issuer,with:e.proof.capabilities[0].with,caveats:{as:e.proof.capabilities[0].as},proofs:[e.proof]}),n=await r.execute(t);if(n?.error)throw n}async function ls(e){const t=e.url||cs,r=await Zn(((e,t,r)=>async()=>{const n=await Pn(`${t}validate?did=${e}`,{signal:r});if(!n.ok)throw new Error(n.statusText);return n.text()})(e.issuer.did(),t.toString(),e.signal),{retries:100,signal:e.signal}),n=Nn(r),o=await _n(n);return io({root:o})}const ps=new URL("https://access-api.web3.storage"),ws=Je("did:key:z6MkkHafoFWxxWVNpNXocFdU6PL2RVLyTEgS1qTnD3bRP7V9");var ys;async function gs({email:e}){const t=localStorage.getItem(`__w3ui_id.v0.mailto:${e}`);if(null!=t)try{const{email:e,verified:r,signingPrincipalBytes:n}=JSON.parse(t),o=(e=>{if(e.byteLength!==nt)throw new Error(`Expected Uint8Array with byteLength of ${nt} instead not ${e.byteLength}`);{const[t]=ne(e);if(t!==Ye)throw new Error("Given bytes must be a multiformat with 4864 tag")}{const[t]=ne(e.subarray(et+rt));if(t!==Fe)throw new Error("Given bytes must contain public key in multiformats with 237 tag")}return new it(e)})(Xe.decode(n));return{email:e,verified:r,signingPrincipal:o}}catch(e){console.warn("failed to load identity",e)}}e.AuthStatus=void 0,(ys=e.AuthStatus||(e.AuthStatus={}))[ys.SignedIn=0]="SignedIn",ys[ys.SignedOut=1]="SignedOut",ys[ys.EmailVerification=2]="EmailVerification",e.createIdentity=async function({email:e}){if(null==e||""===e)throw new Error("missing email address");return{email:e,verified:!1,signingPrincipal:await ot(W.randomPrivateKey())}},e.loadDefaultIdentity=async function(){const e=localStorage.getItem("__w3ui_id.v0.default.email");if(null!=e)return await gs({email:e})},e.loadIdentity=gs,e.registerIdentity=async function(e,t){if(!e.verified)throw new Error("identity must be verified");await ds({audience:ws,url:ps,issuer:e.signingPrincipal,proof:t})},e.removeIdentity=async function(e){localStorage.removeItem(`__w3ui_id.v0.mailto:${e.email}`);const t=localStorage.getItem("__w3ui_id.v0.default.email");e.email===t&&localStorage.removeItem("__w3ui_id.v0.default.email")},e.sendVerificationEmail=async function(e){if(e.verified)throw new Error("already verified");await fs({audience:ws,url:ps,issuer:e.signingPrincipal,caveats:{as:`mailto:${e.email}`}})},e.storeIdentity=async function(e){const{email:t,verified:r,signingPrincipal:n}=e,o=Xe.encode(n.bytes);localStorage.setItem(`__w3ui_id.v0.mailto:${t}`,JSON.stringify({email:t,verified:r,signingPrincipalBytes:o})),localStorage.setItem("__w3ui_id.v0.default.email",t)},e.waitIdentityVerification=async function(e,t={}){if(e.verified)throw new Error("already verified");const r=await ls({issuer:e.signingPrincipal,url:ps,signal:t.signal});return{identity:{email:e.email,verified:!0,signingPrincipal:e.signingPrincipal},proof:r}},Object.defineProperty(e,"__esModule",{value:!0})}(t)}(0,o.exports);const i=t.createContext({identity:void 0,loadDefaultIdentity:async()=>{},unloadIdentity:async()=>{},unloadAndRemoveIdentity:async()=>{},registerAndStoreIdentity:async()=>{},cancelRegisterAndStoreIdentity:()=>{},authStatus:o.exports.AuthStatus.SignedOut});e.AuthContext=i,e.AuthProvider=function({children:e}){const[r,s]=t.useState(o.exports.AuthStatus.SignedOut),[a,c]=t.useState(),[u,h]=t.useState(),f=async e=>{const t=new AbortController;h(t);try{s(o.exports.AuthStatus.EmailVerification);const{identity:r,proof:n}=await o.exports.waitIdentityVerification(e,{signal:t.signal});await o.exports.registerIdentity(r,n),await o.exports.storeIdentity(r),c(r),s(o.exports.AuthStatus.SignedIn)}catch(e){if(s(o.exports.AuthStatus.SignedOut),!t.signal.aborted)throw e}},d=async()=>{s(o.exports.AuthStatus.SignedOut),c(void 0)},l={authStatus:r,identity:a,loadDefaultIdentity:async()=>{const e=await o.exports.loadDefaultIdentity();if(null!=e){if(c(e),e.verified)return void s(o.exports.AuthStatus.SignedIn);await f(e)}},unloadIdentity:d,unloadAndRemoveIdentity:async()=>{if(null==a)throw new Error("missing current identity");await Promise.all([o.exports.removeIdentity(a),d()])},registerAndStoreIdentity:async e=>{let t;if(null!=a){if(a.email!==e)throw new Error("unload current identity before registering a new one");t=a}else t=await o.exports.loadIdentity({email:e}),null==t&&(t=await o.exports.createIdentity({email:e}),await o.exports.storeIdentity(t));if(c(t),t.verified)return void s(o.exports.AuthStatus.SignedIn);const r=t;await o.exports.sendVerificationEmail(r),await f(r)},cancelRegisterAndStoreIdentity:()=>{null!=u&&u.abort()}};return n.default.createElement(i.Provider,{value:l},e)},e.AuthStatus=o.exports.AuthStatus,e.Identity=o.exports.Identity,e.useAuth=function(){return t.useContext(i)},Object.defineProperty(e,"__esModule",{value:!0})})); +//# sourceMappingURL=index.production.js.map + + +/***/ }) + +}]); \ No newline at end of file diff --git a/crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/framework-b5c497ced4b4c57f/input.js b/crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/framework-b5c497ced4b4c57f/input.js new file mode 100644 index 000000000000..05105c3a3b3a --- /dev/null +++ b/crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/framework-b5c497ced4b4c57f/input.js @@ -0,0 +1,496 @@ +"use strict"; +(self["webpackChunk_N_E"] = self["webpackChunk_N_E"] || []).push([[774],{ + +/***/ 4448: +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/* + Modernizr 3.0.0pre (Custom Build) | MIT +*/ +var aa=__webpack_require__(7294),ca=__webpack_require__(3840);function p(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;cb}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={}; +"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)}); +["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)}); +["checked","multiple","muted","selected"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});["capture","download"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});["cols","rows","size","span"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});["rowSpan","start"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()} +"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(ra, +sa);z[b]=new v(b,1,!1,a,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)}); +z.xlinkHref=new v("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)}); +function ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k="\n"+e[g].replace(" at new "," at ");a.displayName&&k.includes("")&&(k=k.replace("",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:"")?Ma(a):""} +function Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma("Lazy");case 13:return Ma("Suspense");case 19:return Ma("SuspenseList");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return""}} +function Qa(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case ya:return"Fragment";case wa:return"Portal";case Aa:return"Profiler";case za:return"StrictMode";case Ea:return"Suspense";case Fa:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||"Context")+".Consumer";case Ba:return(a._context.displayName||"Context")+".Provider";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName|| +b.name||"",a=""!==a?"ForwardRef("+a+")":"ForwardRef");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||"Memo";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null} +function Ra(a){var b=a.type;switch(a.tag){case 24:return"Cache";case 9:return(b.displayName||"Context")+".Consumer";case 10:return(b._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return a=b.render,a=a.displayName||a.name||"",b.displayName||(""!==a?"ForwardRef("+a+")":"ForwardRef");case 7:return"Fragment";case 5:return b;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Qa(b);case 8:return b===za?"StrictMode":"Mode";case 22:return"Offscreen"; +case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"===typeof b)return b.displayName||b.name||null;if("string"===typeof b)return b}return null}function Sa(a){switch(typeof a){case "boolean":case "number":case "string":case "undefined":return a;case "object":return a;default:return""}} +function Ta(a){var b=a.type;return(a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===b)} +function Ua(a){var b=Ta(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=""+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=""+a},stopTracking:function(){a._valueTracker= +null;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d="";a&&(d=Ta(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}} +function Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,"checked",b,!1)} +function bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if("number"===d){if(0===c&&""===a.value||a.value!=c)a.value=""+c}else a.value!==""+c&&(a.value=""+c);else if("submit"===d||"reset"===d){a.removeAttribute("value");return}b.hasOwnProperty("value")?cb(a,b.type,c):b.hasOwnProperty("defaultValue")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)} +function db(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;""!==c&&(a.name="");a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c)} +function cb(a,b,c){if("number"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c)}var eb=Array.isArray; +function fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e"+b.valueOf().toString()+"";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}}); +function ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b} +var pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0, +zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=["Webkit","ms","Moz","O"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(""+b).trim():b+"px"} +function sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=rb(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0}); +function ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if("object"!==typeof b.dangerouslySetInnerHTML||!("__html"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&"object"!==typeof b.style)throw Error(p(62));}} +function vb(a,b){if(-1===a.indexOf("-"))return"string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null; +function Bb(a){if(a=Cb(a)){if("function"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304; +function tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824; +default:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b} +function Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be),ee=String.fromCharCode(32),fe=!1; +function ge(a,b){switch(a){case "keyup":return-1!==$d.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "focusout":return!0;default:return!1}}function he(a){a=a.detail;return"object"===typeof a&&"data"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case "compositionend":return he(b);case "keypress":if(32!==b.which)return null;fe=!0;return ee;case "textInput":return a=b.data,a===ee&&fe?null:a;default:return null}} +function ke(a,b){if(ie)return"compositionend"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1} +function Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)} +function Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),"selectionStart"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c, +d);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});"function"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe=null,Re=null,Se=null,Te=!1; +function Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,"selectionStart"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,"onSelect"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e} +function Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||"Unknown",e));return A({},c,d)} +function cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)} +function jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e, +m),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){"object"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if("object"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k= +f.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||"object"===typeof k&&null!==k&&k.$$typeof===Ha&&uh(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=sh(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Ah(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=yh(f.type,f.key,f.props,null,a.mode,h),h.ref=sh(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!== +d;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=zh(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);th(a,f)}return"string"===typeof f&&""!==f||"number"===typeof f?(f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d): +(c(a,d),d=xh(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Bh=vh(!0),Ch=vh(!1),Dh={},Eh=Uf(Dh),Fh=Uf(Dh),Gh=Uf(Dh);function Hh(a){if(a===Dh)throw Error(p(174));return a}function Ih(a,b){G(Gh,b);G(Fh,a);G(Eh,Dh);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:lb(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=lb(b,a)}E(Eh);G(Eh,b)}function Jh(){E(Eh);E(Fh);E(Gh)} +function Kh(a){Hh(Gh.current);var b=Hh(Eh.current);var c=lb(b,a.type);b!==c&&(G(Fh,a),G(Eh,c))}function Lh(a){Fh.current===a&&(E(Eh),E(Fh))}var M=Uf(0); +function Mh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||"$?"===c.data||"$!"===c.data))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.flags&128))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}var Nh=[]; +function Oh(){for(var a=0;ac?c:4;a(!0);var d=Qh.transition;Qh.transition={};try{a(!1),b()}finally{C=c,Qh.transition=d}}function Fi(){return di().memoizedState} +function Gi(a,b,c){var d=lh(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,c);else if(c=Yg(a,b,c,d),null!==c){var e=L();mh(c,a,d,e);Ji(c,b,d)}} +function ri(a,b,c){var d=lh(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,Xg(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=Yg(a,b,e,d);null!==c&&(e=L(),mh(c,a,d,e),Ji(c,b,d))}} +function Hi(a){var b=a.alternate;return a===N||null!==b&&b===N}function Ii(a,b){Th=Sh=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Ji(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}} +var ai={readContext:Vg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useInsertionEffect:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useDeferredValue:Q,useTransition:Q,useMutableSource:Q,useSyncExternalStore:Q,useId:Q,unstable_isNewReconciler:!1},Yh={readContext:Vg,useCallback:function(a,b){ci().memoizedState=[a,void 0===b?null:b];return a},useContext:Vg,useEffect:vi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ti(4194308, +4,yi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ti(4194308,4,a,b)},useInsertionEffect:function(a,b){return ti(4,2,a,b)},useMemo:function(a,b){var c=ci();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=ci();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=Gi.bind(null,N,a);return[d.memoizedState,a]},useRef:function(a){var b= +ci();a={current:a};return b.memoizedState=a},useState:qi,useDebugValue:Ai,useDeferredValue:function(a){return ci().memoizedState=a},useTransition:function(){var a=qi(!1),b=a[0];a=Ei.bind(null,a[1]);ci().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=N,e=ci();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===R)throw Error(p(349));0!==(Rh&30)||ni(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;vi(ki.bind(null,d, +f,a),[a]);d.flags|=2048;li(9,mi.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=ci(),b=R.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=":"+b+"R"+c;c=Uh++;0\x3c/script>",a=a.removeChild(a.firstChild)): +"string"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),"select"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;Aj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case "dialog":D("cancel",a);D("close",a);e=d;break;case "iframe":case "object":case "embed":D("load",a);e=d;break;case "video":case "audio":for(e=0;eHj&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304)}else{if(!d)if(a=Mh(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Ej(f,!0),null===f.tail&&"hidden"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Hj&&1073741824!==c&&(b.flags|=128,d=!0,Ej(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering= +b,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=M.current,G(M,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Ij(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(gj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));} +function Jj(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return Jh(),E(Wf),E(H),Oh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Lh(b),null;case 13:E(M);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(M),null;case 4:return Jh(),null;case 10:return Rg(b.type._context),null;case 22:case 23:return Ij(), +null;case 24:return null;default:return null}}var Kj=!1,U=!1,Lj="function"===typeof WeakSet?WeakSet:Set,V=null;function Mj(a,b){var c=a.ref;if(null!==c)if("function"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Nj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Oj=!1; +function Pj(a,b){Cf=dd;a=Me();if(Ne(a)){if("selectionStart"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+= +q.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break; +case 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Lg(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent="":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Oj;Oj=!1;return n} +function Qj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Nj(b,c,f)}e=e.next}while(e!==d)}}function Rj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Sj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}"function"===typeof b?b(a):b.current=a}} +function Tj(a){var b=a.alternate;null!==b&&(a.alternate=null,Tj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Uj(a){return 5===a.tag||3===a.tag||4===a.tag} +function Vj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Uj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}} +function Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling} +function Xj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Xj(a,b,c),a=a.sibling;null!==a;)Xj(a,b,c),a=a.sibling}var X=null,Yj=!1;function Zj(a,b,c){for(c=c.child;null!==c;)ak(a,b,c),c=c.sibling} +function ak(a,b,c){if(lc&&"function"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Mj(c,b);case 6:var d=X,e=Yj;X=null;Zj(a,b,c);X=d;Yj=e;null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Yj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Yj;X=c.stateNode.containerInfo;Yj=!0; +Zj(a,b,c);X=d;Yj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Nj(c,b,g):0!==(f&4)&&Nj(c,b,g));e=e.next}while(e!==d)}Zj(a,b,c);break;case 1:if(!U&&(Mj(c,b),d=c.stateNode,"function"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Zj(a,b,c);break;case 21:Zj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!== +c.memoizedState,Zj(a,b,c),U=d):Zj(a,b,c);break;default:Zj(a,b,c)}}function bk(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Lj);b.forEach(function(b){var d=ck.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}} +function dk(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*mk(d/1960))-d;if(10a?16:a;if(null===xk)var d=!1;else{a=xk;xk=null;yk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-gk?Lk(a,0):sk|=c);Ek(a,b)}function Zk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=L();a=Zg(a,b);null!==a&&(Ac(a,b,c),Ek(a,c))}function vj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Zk(a,c)} +function ck(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Zk(a,c)}var Wk; +Wk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)Ug=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return Ug=!1,zj(a,b,c);Ug=0!==(a.flags&131072)?!0:!1}else Ug=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;jj(a,b);a=b.pendingProps;var e=Yf(b,H.current);Tg(b,c);e=Xh(null,b,d,a,e,c);var f=bi();b.flags|=1;"object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue= +null,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,ah(b),e.updater=nh,b.stateNode=e,e._reactInternals=b,rh(b,d,a,c),b=kj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Yi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{jj(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=$k(d);a=Lg(d,a);switch(e){case 0:b=dj(null,b,d,a,c);break a;case 1:b=ij(null,b,d,a,c);break a;case 11:b=Zi(null,b,d,a,c);break a;case 14:b=aj(null,b,d,Lg(d.type,a),c);break a}throw Error(p(306, +d,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),dj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),ij(a,b,d,e,c);case 3:a:{lj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;bh(a,b);gh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState= +f,b.memoizedState=f,b.flags&256){e=Ki(Error(p(423)),b);b=mj(a,b,d,c,e);break a}else if(d!==e){e=Ki(Error(p(424)),b);b=mj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Ch(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=$i(a,b,c);break a}Yi(a,b,d,c)}b=b.child}return b;case 5:return Kh(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32), +hj(a,b),Yi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return pj(a,b,c);case 4:return Ih(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Bh(b,null,d,c):Yi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),Zi(a,b,d,e,c);case 7:return Yi(a,b,b.pendingProps,c),b.child;case 8:return Yi(a,b,b.pendingProps.children,c),b.child;case 12:return Yi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps; +g=e.value;G(Mg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=$i(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=ch(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);Sg(f.return, +c,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);Sg(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Yi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,Tg(b,c),e=Vg(e),d=d(e),b.flags|=1,Yi(a,b,d,c), +b.child;case 14:return d=b.type,e=Lg(d,b.pendingProps),e=Lg(d.type,e),aj(a,b,d,e,c);case 15:return cj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Lg(d,e),jj(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,Tg(b,c),ph(b,d,e),rh(b,d,e,c),kj(null,b,d,!0,a,c);case 19:return yj(a,b,c);case 22:return ej(a,b,c)}throw Error(p(156,b.tag));};function Gk(a,b){return ac(a,b)} +function al(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new al(a,b,c,d)}function bj(a){a=a.prototype;return!(!a||!a.isReactComponent)} +function $k(a){if("function"===typeof a)return bj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2} +function wh(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext}; +c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c} +function yh(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)bj(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case ya:return Ah(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return qj(c,e,f,b);default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11; +break a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,""));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Ah(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function qj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function xh(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a} +function zh(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b} +function bl(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData= +null}function cl(a,b,c,d,e,f,g,h,k){a=new bl(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};ah(f);return a}function dl(a,b,c){var d=3>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b} +function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D="function"===typeof setTimeout?setTimeout:null,E="function"===typeof clearTimeout?clearTimeout:null,F="undefined"!==typeof setImmediate?setImmediate:null; +"undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}} +function J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if("function"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1; +function M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a}; +exports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}}; + + +/***/ }), + +/***/ 3840: +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + + + +if (true) { + module.exports = __webpack_require__(53); +} else {} + + +/***/ }) + +}]); \ No newline at end of file diff --git a/crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/main-558eb874a0ed3710/input.js b/crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/main-558eb874a0ed3710/input.js new file mode 100644 index 000000000000..469a821df7d3 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/fixture/next/43052/static/chunks/main-558eb874a0ed3710/input.js @@ -0,0 +1,5575 @@ +(self["webpackChunk_N_E"] = self["webpackChunk_N_E"] || []).push([[179],{ + +/***/ 932: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +var __webpack_unused_export__; + +__webpack_unused_export__ = ({ + value: true +}); +exports.Z = _asyncToGenerator; +function _asyncToGenerator(fn) { + return function() { + var self = this, args = arguments; + return new Promise(function(resolve, reject) { + var gen = fn.apply(self, args); + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); + } + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); + } + _next(undefined); + }); + }; +} +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } +} + + +/***/ }), + +/***/ 6495: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +var __webpack_unused_export__; + +__webpack_unused_export__ = ({ + value: true +}); +exports.Z = _extends; +function _extends() { + return extends_.apply(this, arguments); +} +function extends_() { + extends_ = Object.assign || function(target) { + for(var i = 1; i < arguments.length; i++){ + var source = arguments[i]; + for(var key in source){ + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + return target; + }; + return extends_.apply(this, arguments); +} + + +/***/ }), + +/***/ 2648: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +var __webpack_unused_export__; + +__webpack_unused_export__ = ({ + value: true +}); +exports.Z = _interopRequireDefault; +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; +} + + +/***/ }), + +/***/ 1598: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +var __webpack_unused_export__; + +__webpack_unused_export__ = ({ + value: true +}); +exports.Z = _interopRequireWildcard; +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for(var key in obj){ + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +function _getRequireWildcardCache(nodeInterop1) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function(nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop1); +} + + +/***/ }), + +/***/ 7273: +/***/ (function(__unused_webpack_module, exports) { + +"use strict"; +var __webpack_unused_export__; + +__webpack_unused_export__ = ({ + value: true +}); +exports.Z = _objectWithoutPropertiesLoose; +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + for(i = 0; i < sourceKeys.length; i++){ + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + return target; +} + + +/***/ }), + +/***/ 37: +/***/ (function() { + +"trimStart"in String.prototype||(String.prototype.trimStart=String.prototype.trimLeft),"trimEnd"in String.prototype||(String.prototype.trimEnd=String.prototype.trimRight),"description"in Symbol.prototype||Object.defineProperty(Symbol.prototype,"description",{configurable:!0,get:function(){var t=/\((.*)\)/.exec(this.toString());return t?t[1]:void 0}}),Array.prototype.flat||(Array.prototype.flat=function(t,r){return r=this.concat.apply([],this),t>1&&r.some(Array.isArray)?r.flat(t-1):r},Array.prototype.flatMap=function(t,r){return this.map(t,r).flat()}),Promise.prototype.finally||(Promise.prototype.finally=function(t){if("function"!=typeof t)return this.then(t,t);var r=this.constructor||Promise;return this.then(function(o){return r.resolve(t()).then(function(){return o})},function(o){return r.resolve(t()).then(function(){throw o})})}),Object.fromEntries||(Object.fromEntries=function(t){return Array.from(t).reduce(function(t,r){return t[r[0]]=r[1],t},{})}); + + +/***/ }), + +/***/ 3468: +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.addBasePath = addBasePath; +var _addPathPrefix = __webpack_require__(4135); +var _normalizeTrailingSlash = __webpack_require__(2700); +const basePath = false || ""; +function addBasePath(path, required) { + if (false) {} + return (0, _normalizeTrailingSlash).normalizePathTrailingSlash((0, _addPathPrefix).addPathPrefix(path, basePath)); +} +if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { + Object.defineProperty(exports.default, "__esModule", { + value: true + }); + Object.assign(exports.default, exports); + module.exports = exports.default; +} //# sourceMappingURL=add-base-path.js.map + + +/***/ }), + +/***/ 4465: +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.addLocale = void 0; +var _normalizeTrailingSlash = __webpack_require__(2700); +const addLocale = function(path) { + for(var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){ + args[_key - 1] = arguments[_key]; + } + if (false) {} + return path; +}; +exports.addLocale = addLocale; +if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { + Object.defineProperty(exports.default, "__esModule", { + value: true + }); + Object.assign(exports.default, exports); + module.exports = exports.default; +} //# sourceMappingURL=add-locale.js.map + + +/***/ }), + +/***/ 4643: +/***/ (function(module, exports) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.detectDomainLocale = void 0; +const detectDomainLocale = function() { + for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){ + args[_key] = arguments[_key]; + } + if (false) {} +}; +exports.detectDomainLocale = detectDomainLocale; +if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { + Object.defineProperty(exports.default, "__esModule", { + value: true + }); + Object.assign(exports.default, exports); + module.exports = exports.default; +} //# sourceMappingURL=detect-domain-locale.js.map + + +/***/ }), + +/***/ 928: +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.hasBasePath = hasBasePath; +var _pathHasPrefix = __webpack_require__(3210); +const basePath = false || ""; +function hasBasePath(path) { + return (0, _pathHasPrefix).pathHasPrefix(path, basePath); +} +if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { + Object.defineProperty(exports.default, "__esModule", { + value: true + }); + Object.assign(exports.default, exports); + module.exports = exports.default; +} //# sourceMappingURL=has-base-path.js.map + + +/***/ }), + +/***/ 1831: +/***/ (function(module, exports) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = initHeadManager; +exports.isEqualNode = isEqualNode; +exports.DOMAttributeNames = void 0; +function initHeadManager() { + return { + mountedInstances: new Set(), + updateHead: (head)=>{ + const tags = {}; + head.forEach((h)=>{ + if (// it won't be inlined. In this case revert to the original behavior + h.type === "link" && h.props["data-optimized-fonts"]) { + if (document.querySelector('style[data-href="'.concat(h.props["data-href"], '"]'))) { + return; + } else { + h.props.href = h.props["data-href"]; + h.props["data-href"] = undefined; + } + } + const components = tags[h.type] || []; + components.push(h); + tags[h.type] = components; + }); + const titleComponent = tags.title ? tags.title[0] : null; + let title = ""; + if (titleComponent) { + const { children } = titleComponent.props; + title = typeof children === "string" ? children : Array.isArray(children) ? children.join("") : ""; + } + if (title !== document.title) document.title = title; + [ + "meta", + "base", + "link", + "style", + "script" + ].forEach((type)=>{ + updateElements(type, tags[type] || []); + }); + } + }; +} +const DOMAttributeNames = { + acceptCharset: "accept-charset", + className: "class", + htmlFor: "for", + httpEquiv: "http-equiv", + noModule: "noModule" +}; +exports.DOMAttributeNames = DOMAttributeNames; +function reactElementToDOM(param) { + let { type , props } = param; + const el = document.createElement(type); + for(const p in props){ + if (!props.hasOwnProperty(p)) continue; + if (p === "children" || p === "dangerouslySetInnerHTML") continue; + // we don't render undefined props to the DOM + if (props[p] === undefined) continue; + const attr = DOMAttributeNames[p] || p.toLowerCase(); + if (type === "script" && (attr === "async" || attr === "defer" || attr === "noModule")) { + el[attr] = !!props[p]; + } else { + el.setAttribute(attr, props[p]); + } + } + const { children , dangerouslySetInnerHTML } = props; + if (dangerouslySetInnerHTML) { + el.innerHTML = dangerouslySetInnerHTML.__html || ""; + } else if (children) { + el.textContent = typeof children === "string" ? children : Array.isArray(children) ? children.join("") : ""; + } + return el; +} +function isEqualNode(oldTag, newTag) { + if (oldTag instanceof HTMLElement && newTag instanceof HTMLElement) { + const nonce = newTag.getAttribute("nonce"); + // Only strip the nonce if `oldTag` has had it stripped. An element's nonce attribute will not + // be stripped if there is no content security policy response header that includes a nonce. + if (nonce && !oldTag.getAttribute("nonce")) { + const cloneTag = newTag.cloneNode(true); + cloneTag.setAttribute("nonce", ""); + cloneTag.nonce = nonce; + return nonce === oldTag.nonce && oldTag.isEqualNode(cloneTag); + } + } + return oldTag.isEqualNode(newTag); +} +function updateElements(type, components) { + const headEl = document.getElementsByTagName("head")[0]; + const headCountEl = headEl.querySelector("meta[name=next-head-count]"); + if (false) {} + const headCount = Number(headCountEl.content); + const oldTags = []; + for(let i = 0, j = headCountEl.previousElementSibling; i < headCount; i++, j = (j == null ? void 0 : j.previousElementSibling) || null){ + var ref; + if ((j == null ? void 0 : (ref = j.tagName) == null ? void 0 : ref.toLowerCase()) === type) { + oldTags.push(j); + } + } + const newTags = components.map(reactElementToDOM).filter((newTag)=>{ + for(let k = 0, len = oldTags.length; k < len; k++){ + const oldTag = oldTags[k]; + if (isEqualNode(oldTag, newTag)) { + oldTags.splice(k, 1); + return false; + } + } + return true; + }); + oldTags.forEach((t)=>{ + var ref; + return (ref = t.parentNode) == null ? void 0 : ref.removeChild(t); + }); + newTags.forEach((t)=>headEl.insertBefore(t, headCountEl)); + headCountEl.content = (headCount - oldTags.length + newTags.length).toString(); +} +if ((typeof exports.default === "function" || typeof exports.default === "object" && exports.default !== null) && typeof exports.default.__esModule === "undefined") { + Object.defineProperty(exports.default, "__esModule", { + value: true + }); + Object.assign(exports.default, exports); + module.exports = exports.default; +} //# sourceMappingURL=head-manager.js.map + + +/***/ }), + +/***/ 4534: +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +const _interopRequireWildcard = (__webpack_require__(1598)/* ["default"] */ .Z); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.initialize = initialize; +exports.hydrate = hydrate; +exports.emitter = exports.router = exports.version = void 0; +var _async_to_generator = (__webpack_require__(932)/* ["default"] */ .Z); +var _extends = (__webpack_require__(6495)/* ["default"] */ .Z); +var _interop_require_default = (__webpack_require__(2648)/* ["default"] */ .Z); +var _interop_require_wildcard = (__webpack_require__(1598)/* ["default"] */ .Z); +__webpack_require__(37); +var _react = _interop_require_default(__webpack_require__(7294)); +var _client = _interop_require_default(__webpack_require__(745)); +var _headManagerContext = __webpack_require__(4664); +var _mitt = _interop_require_default(__webpack_require__(8550)); +var _routerContext = __webpack_require__(2692); +var _isDynamic = __webpack_require__(6238); +var _querystring = __webpack_require__(4919); +var _runtimeConfig = __webpack_require__(6949); +var _utils = __webpack_require__(670); +var _portal = __webpack_require__(7345); +var _headManager = _interop_require_default(__webpack_require__(1831)); +var _pageLoader = _interop_require_default(__webpack_require__(976)); +var _performanceRelayer = _interop_require_default(__webpack_require__(659)); +var _routeAnnouncer = __webpack_require__(8483); +var _router = __webpack_require__(880); +var _isError = __webpack_require__(676); +var _imageConfigContext = __webpack_require__(8730); +var _removeBasePath = __webpack_require__(2813); +var _hasBasePath = __webpack_require__(928); +var _appRouterContext = __webpack_require__(8245); +var _adapters = __webpack_require__(401); +var _hooksClientContext = __webpack_require__(8914); +const version = "13.0.3"; +exports.version = version; +let router; +exports.router = router; +const emitter = (0, _mitt).default(); +exports.emitter = emitter; +const looseToArray = (input)=>[].slice.call(input); +let initialData; +let defaultLocale = undefined; +let asPath; +let pageLoader; +let appElement; +let headManager; +let initialMatchesMiddleware = false; +let lastAppProps; +let lastRenderReject; +let webpackHMR; +let CachedApp, onPerfEntry; +let CachedComponent; +self.__next_require__ = __webpack_require__; +class Container extends _react.default.Component { + componentDidCatch(componentErr, info) { + this.props.fn(componentErr, info); + } + componentDidMount() { + this.scrollToHash(); + // We need to replace the router state if: + // - the page was (auto) exported and has a query string or search (hash) + // - it was auto exported and is a dynamic route (to provide params) + // - if it is a client-side skeleton (fallback render) + // - if middleware matches the current page (may have rewrite params) + // - if rewrites in next.config.js match (may have rewrite params) + if (router.isSsr && // We don't update for 404 requests as this can modify + // the asPath unexpectedly e.g. adding basePath when + // it wasn't originally present + initialData.page !== "/404" && initialData.page !== "/_error" && (initialData.isFallback || initialData.nextExport && ((0, _isDynamic).isDynamicRoute(router.pathname) || location.search || false || initialMatchesMiddleware) || initialData.props && initialData.props.__N_SSG && (location.search || false || initialMatchesMiddleware))) { + // update query on mount for exported pages + router.replace(router.pathname + "?" + String((0, _querystring).assign((0, _querystring).urlQueryToSearchParams(router.query), new URLSearchParams(location.search))), asPath, { + // @ts-ignore + // WARNING: `_h` is an internal option for handing Next.js + // client-side hydration. Your app should _never_ use this property. + // It may change at any time without notice. + _h: 1, + // Fallback pages must trigger the data fetch, so the transition is + // not shallow. + // Other pages (strictly updating query) happens shallowly, as data + // requirements would already be present. + shallow: !initialData.isFallback && !initialMatchesMiddleware + }).catch((err)=>{ + if (!err.cancelled) throw err; + }); + } + } + componentDidUpdate() { + this.scrollToHash(); + } + scrollToHash() { + let { hash } = location; + hash = hash && hash.substring(1); + if (!hash) return; + const el = document.getElementById(hash); + if (!el) return; + // If we call scrollIntoView() in here without a setTimeout + // it won't scroll properly. + setTimeout(()=>el.scrollIntoView(), 0); + } + render() { + if (true) { + return this.props.children; + } else {} + } +} +function initialize() { + return _initialize.apply(this, arguments); +} +function _initialize() { + _initialize = _async_to_generator(function*() { + let opts = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}; + // This makes sure this specific lines are removed in production + if (false) {} + initialData = JSON.parse(document.getElementById("__NEXT_DATA__").textContent); + window.__NEXT_DATA__ = initialData; + defaultLocale = initialData.defaultLocale; + const prefix = initialData.assetPrefix || ""; + // With dynamic assetPrefix it's no longer possible to set assetPrefix at the build time + // So, this is how we do it in the client side at runtime + __webpack_require__.p = "".concat(prefix, "/_next/") //eslint-disable-line + ; + // Initialize next/config with the environment configuration + (0, _runtimeConfig).setConfig({ + serverRuntimeConfig: {}, + publicRuntimeConfig: initialData.runtimeConfig || {} + }); + asPath = (0, _utils).getURL(); + // make sure not to attempt stripping basePath for 404s + if ((0, _hasBasePath).hasBasePath(asPath)) { + asPath = (0, _removeBasePath).removeBasePath(asPath); + } + if (false) {} + if (initialData.scriptLoader) { + const { initScriptLoader } = __webpack_require__(3573); + initScriptLoader(initialData.scriptLoader); + } + pageLoader = new _pageLoader.default(initialData.buildId, prefix); + const register = (param)=>{ + let [r, f] = param; + return pageLoader.routeLoader.onEntrypoint(r, f); + }; + if (window.__NEXT_P) { + // Defer page registration for another tick. This will increase the overall + // latency in hydrating the page, but reduce the total blocking time. + window.__NEXT_P.map((p)=>setTimeout(()=>register(p), 0)); + } + window.__NEXT_P = []; + window.__NEXT_P.push = register; + headManager = (0, _headManager).default(); + headManager.getIsSsr = ()=>{ + return router.isSsr; + }; + appElement = document.getElementById("__next"); + return { + assetPrefix: prefix + }; + }); + return _initialize.apply(this, arguments); +} +function renderApp(App, appProps) { + return /*#__PURE__*/ _react.default.createElement(App, Object.assign({}, appProps)); +} +function AppContainer(param) { + let { children } = param; + var _autoExport; + return /*#__PURE__*/ _react.default.createElement(Container, { + fn: (error)=>// eslint-disable-next-line @typescript-eslint/no-use-before-define + renderError({ + App: CachedApp, + err: error + }).catch((err)=>console.error("Error rendering page: ", err)) + }, /*#__PURE__*/ _react.default.createElement(_appRouterContext.AppRouterContext.Provider, { + value: (0, _adapters).adaptForAppRouterInstance(router) + }, /*#__PURE__*/ _react.default.createElement(_hooksClientContext.SearchParamsContext.Provider, { + value: (0, _adapters).adaptForSearchParams(router) + }, /*#__PURE__*/ _react.default.createElement(_adapters.PathnameContextProviderAdapter, { + router: router, + isAutoExport: (_autoExport = self.__NEXT_DATA__.autoExport) != null ? _autoExport : false + }, /*#__PURE__*/ _react.default.createElement(_routerContext.RouterContext.Provider, { + value: (0, _router).makePublicRouterInstance(router) + }, /*#__PURE__*/ _react.default.createElement(_headManagerContext.HeadManagerContext.Provider, { + value: headManager + }, /*#__PURE__*/ _react.default.createElement(_imageConfigContext.ImageConfigContext.Provider, { + value: {"deviceSizes":[640,750,828,1080,1200,1920,2048,3840],"imageSizes":[16,32,48,64,96,128,256,384],"path":"/_next/image","loader":"default","dangerouslyAllowSVG":false,"unoptimized":false} + }, children))))))); +} +const wrapApp = (App)=>(wrappedAppProps)=>{ + const appProps = _extends({}, wrappedAppProps, { + Component: CachedComponent, + err: initialData.err, + router + }); + return /*#__PURE__*/ _react.default.createElement(AppContainer, null, renderApp(App, appProps)); + }; +// This method handles all runtime and debug errors. +// 404 and 500 errors are special kind of errors +// and they are still handle via the main render method. +function renderError(renderErrorProps) { + let { App , err } = renderErrorProps; + // In development runtime errors are caught by our overlay + // In production we catch runtime errors using componentDidCatch which will trigger renderError + if (false) {} + // Make sure we log the error to the console, otherwise users can't track down issues. + console.error(err); + console.error("A client-side exception has occurred, see here for more info: https://nextjs.org/docs/messages/client-side-exception-occurred"); + return pageLoader.loadPage("/_error").then((param)=>{ + let { page: ErrorComponent , styleSheets } = param; + return (lastAppProps == null ? void 0 : lastAppProps.Component) === ErrorComponent ? Promise.resolve().then(()=>/*#__PURE__*/ _interopRequireWildcard(__webpack_require__(67))).then((errorModule)=>{ + return Promise.resolve().then(()=>/*#__PURE__*/ _interopRequireWildcard(__webpack_require__(4297))).then((appModule)=>{ + App = appModule.default; + renderErrorProps.App = App; + return errorModule; + }); + }).then((m)=>({ + ErrorComponent: m.default, + styleSheets: [] + })) : { + ErrorComponent, + styleSheets + }; + }).then((param)=>{ + let { ErrorComponent , styleSheets } = param; + var ref; + // In production we do a normal render with the `ErrorComponent` as component. + // If we've gotten here upon initial render, we can use the props from the server. + // Otherwise, we need to call `getInitialProps` on `App` before mounting. + const AppTree = wrapApp(App); + const appCtx = { + Component: ErrorComponent, + AppTree, + router, + ctx: { + err, + pathname: initialData.page, + query: initialData.query, + asPath, + AppTree + } + }; + return Promise.resolve(((ref = renderErrorProps.props) == null ? void 0 : ref.err) ? renderErrorProps.props : (0, _utils).loadGetInitialProps(App, appCtx)).then((initProps)=>// eslint-disable-next-line @typescript-eslint/no-use-before-define + doRender(_extends({}, renderErrorProps, { + err, + Component: ErrorComponent, + styleSheets, + props: initProps + }))); + }); +} +// Dummy component that we render as a child of Root so that we can +// toggle the correct styles before the page is rendered. +function Head(param) { + let { callback } = param; + // We use `useLayoutEffect` to guarantee the callback is executed + // as soon as React flushes the update. + _react.default.useLayoutEffect(()=>callback(), [ + callback + ]); + return null; +} +let reactRoot = null; +// On initial render a hydrate should always happen +let shouldHydrate = true; +function clearMarks() { + [ + "beforeRender", + "afterHydrate", + "afterRender", + "routeChange" + ].forEach((mark)=>performance.clearMarks(mark)); +} +function markHydrateComplete() { + if (!_utils.ST) return; + performance.mark("afterHydrate") // mark end of hydration + ; + performance.measure("Next.js-before-hydration", "navigationStart", "beforeRender"); + performance.measure("Next.js-hydration", "beforeRender", "afterHydrate"); + if (onPerfEntry) { + performance.getEntriesByName("Next.js-hydration").forEach(onPerfEntry); + } + clearMarks(); +} +function markRenderComplete() { + if (!_utils.ST) return; + performance.mark("afterRender") // mark end of render + ; + const navStartEntries = performance.getEntriesByName("routeChange", "mark"); + if (!navStartEntries.length) return; + performance.measure("Next.js-route-change-to-render", navStartEntries[0].name, "beforeRender"); + performance.measure("Next.js-render", "beforeRender", "afterRender"); + if (onPerfEntry) { + performance.getEntriesByName("Next.js-render").forEach(onPerfEntry); + performance.getEntriesByName("Next.js-route-change-to-render").forEach(onPerfEntry); + } + clearMarks(); + [ + "Next.js-route-change-to-render", + "Next.js-render" + ].forEach((measure)=>performance.clearMeasures(measure)); +} +function renderReactElement(domEl, fn) { + // mark start of hydrate/render + if (_utils.ST) { + performance.mark("beforeRender"); + } + const reactEl = fn(shouldHydrate ? markHydrateComplete : markRenderComplete); + if (!reactRoot) { + // Unlike with createRoot, you don't need a separate root.render() call here + reactRoot = _client.default.hydrateRoot(domEl, reactEl); + // TODO: Remove shouldHydrate variable when React 18 is stable as it can depend on `reactRoot` existing + shouldHydrate = false; + } else { + const startTransition = _react.default.startTransition; + startTransition(()=>{ + reactRoot.render(reactEl); + }); + } +} +function Root(param) { + let { callbacks , children } = param; + // We use `useLayoutEffect` to guarantee the callbacks are executed + // as soon as React flushes the update + _react.default.useLayoutEffect(()=>callbacks.forEach((callback)=>callback()), [ + callbacks + ]); + // We should ask to measure the Web Vitals after rendering completes so we + // don't cause any hydration delay: + _react.default.useEffect(()=>{ + (0, _performanceRelayer).default(onPerfEntry); + }, []); + if (false) {} + return children; +} +function doRender(input) { + let { App , Component , props , err } = input; + let styleSheets = "initial" in input ? undefined : input.styleSheets; + Component = Component || lastAppProps.Component; + props = props || lastAppProps.props; + const appProps = _extends({}, props, { + Component, + err, + router + }); + // lastAppProps has to be set before ReactDom.render to account for ReactDom throwing an error. + lastAppProps = appProps; + let canceled = false; + let resolvePromise; + const renderPromise = new Promise((resolve, reject)=>{ + if (lastRenderReject) { + lastRenderReject(); + } + resolvePromise = ()=>{ + lastRenderReject = null; + resolve(); + }; + lastRenderReject = ()=>{ + canceled = true; + lastRenderReject = null; + const error = new Error("Cancel rendering route"); + error.cancelled = true; + reject(error); + }; + }); + // This function has a return type to ensure it doesn't start returning a + // Promise. It should remain synchronous. + function onStart() { + if (!styleSheets || // We use `style-loader` in development, so we don't need to do anything + // unless we're in production: + "production" !== "production") { + return false; + } + const currentStyleTags = looseToArray(document.querySelectorAll("style[data-n-href]")); + const currentHrefs = new Set(currentStyleTags.map((tag)=>tag.getAttribute("data-n-href"))); + const noscript = document.querySelector("noscript[data-n-css]"); + const nonce = noscript == null ? void 0 : noscript.getAttribute("data-n-css"); + styleSheets.forEach((param)=>{ + let { href , text } = param; + if (!currentHrefs.has(href)) { + const styleTag = document.createElement("style"); + styleTag.setAttribute("data-n-href", href); + styleTag.setAttribute("media", "x"); + if (nonce) { + styleTag.setAttribute("nonce", nonce); + } + document.head.appendChild(styleTag); + styleTag.appendChild(document.createTextNode(text)); + } + }); + return true; + } + function onHeadCommit() { + if (// unless we're in production: + true && // We can skip this during hydration. Running it wont cause any harm, but + // we may as well save the CPU cycles: + styleSheets && // Ensure this render was not canceled + !canceled) { + const desiredHrefs = new Set(styleSheets.map((s)=>s.href)); + const currentStyleTags = looseToArray(document.querySelectorAll("style[data-n-href]")); + const currentHrefs = currentStyleTags.map((tag)=>tag.getAttribute("data-n-href")); + // Toggle `