@snaha/swarm-id 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +431 -0
- package/dist/chunk/bmt.d.ts +17 -0
- package/dist/chunk/bmt.d.ts.map +1 -0
- package/dist/chunk/cac.d.ts +18 -0
- package/dist/chunk/cac.d.ts.map +1 -0
- package/dist/chunk/constants.d.ts +10 -0
- package/dist/chunk/constants.d.ts.map +1 -0
- package/dist/chunk/encrypted-cac.d.ts +48 -0
- package/dist/chunk/encrypted-cac.d.ts.map +1 -0
- package/dist/chunk/encryption.d.ts +86 -0
- package/dist/chunk/encryption.d.ts.map +1 -0
- package/dist/chunk/index.d.ts +6 -0
- package/dist/chunk/index.d.ts.map +1 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/proxy/act/act.d.ts +78 -0
- package/dist/proxy/act/act.d.ts.map +1 -0
- package/dist/proxy/act/crypto.d.ts +44 -0
- package/dist/proxy/act/crypto.d.ts.map +1 -0
- package/dist/proxy/act/grantee-list.d.ts +82 -0
- package/dist/proxy/act/grantee-list.d.ts.map +1 -0
- package/dist/proxy/act/history.d.ts +183 -0
- package/dist/proxy/act/history.d.ts.map +1 -0
- package/dist/proxy/act/index.d.ts +104 -0
- package/dist/proxy/act/index.d.ts.map +1 -0
- package/dist/proxy/chunking-encrypted.d.ts +14 -0
- package/dist/proxy/chunking-encrypted.d.ts.map +1 -0
- package/dist/proxy/chunking.d.ts +15 -0
- package/dist/proxy/chunking.d.ts.map +1 -0
- package/dist/proxy/download-data.d.ts +16 -0
- package/dist/proxy/download-data.d.ts.map +1 -0
- package/dist/proxy/feed-manifest.d.ts +62 -0
- package/dist/proxy/feed-manifest.d.ts.map +1 -0
- package/dist/proxy/feeds/epochs/async-finder.d.ts +77 -0
- package/dist/proxy/feeds/epochs/async-finder.d.ts.map +1 -0
- package/dist/proxy/feeds/epochs/epoch.d.ts +88 -0
- package/dist/proxy/feeds/epochs/epoch.d.ts.map +1 -0
- package/dist/proxy/feeds/epochs/finder.d.ts +67 -0
- package/dist/proxy/feeds/epochs/finder.d.ts.map +1 -0
- package/dist/proxy/feeds/epochs/index.d.ts +35 -0
- package/dist/proxy/feeds/epochs/index.d.ts.map +1 -0
- package/dist/proxy/feeds/epochs/test-utils.d.ts +93 -0
- package/dist/proxy/feeds/epochs/test-utils.d.ts.map +1 -0
- package/dist/proxy/feeds/epochs/types.d.ts +109 -0
- package/dist/proxy/feeds/epochs/types.d.ts.map +1 -0
- package/dist/proxy/feeds/epochs/updater.d.ts +68 -0
- package/dist/proxy/feeds/epochs/updater.d.ts.map +1 -0
- package/dist/proxy/feeds/epochs/utils.d.ts +22 -0
- package/dist/proxy/feeds/epochs/utils.d.ts.map +1 -0
- package/dist/proxy/feeds/index.d.ts +5 -0
- package/dist/proxy/feeds/index.d.ts.map +1 -0
- package/dist/proxy/feeds/sequence/async-finder.d.ts +14 -0
- package/dist/proxy/feeds/sequence/async-finder.d.ts.map +1 -0
- package/dist/proxy/feeds/sequence/finder.d.ts +17 -0
- package/dist/proxy/feeds/sequence/finder.d.ts.map +1 -0
- package/dist/proxy/feeds/sequence/index.d.ts +23 -0
- package/dist/proxy/feeds/sequence/index.d.ts.map +1 -0
- package/dist/proxy/feeds/sequence/types.d.ts +80 -0
- package/dist/proxy/feeds/sequence/types.d.ts.map +1 -0
- package/dist/proxy/feeds/sequence/updater.d.ts +26 -0
- package/dist/proxy/feeds/sequence/updater.d.ts.map +1 -0
- package/dist/proxy/index.d.ts +6 -0
- package/dist/proxy/index.d.ts.map +1 -0
- package/dist/proxy/manifest-builder.d.ts +183 -0
- package/dist/proxy/manifest-builder.d.ts.map +1 -0
- package/dist/proxy/mantaray-encrypted.d.ts +27 -0
- package/dist/proxy/mantaray-encrypted.d.ts.map +1 -0
- package/dist/proxy/mantaray.d.ts +26 -0
- package/dist/proxy/mantaray.d.ts.map +1 -0
- package/dist/proxy/types.d.ts +29 -0
- package/dist/proxy/types.d.ts.map +1 -0
- package/dist/proxy/upload-data.d.ts +17 -0
- package/dist/proxy/upload-data.d.ts.map +1 -0
- package/dist/proxy/upload-encrypted-data.d.ts +103 -0
- package/dist/proxy/upload-encrypted-data.d.ts.map +1 -0
- package/dist/schemas.d.ts +240 -0
- package/dist/schemas.d.ts.map +1 -0
- package/dist/storage/debounced-uploader.d.ts +62 -0
- package/dist/storage/debounced-uploader.d.ts.map +1 -0
- package/dist/storage/utilization-store.d.ts +108 -0
- package/dist/storage/utilization-store.d.ts.map +1 -0
- package/dist/swarm-id-auth.d.ts +74 -0
- package/dist/swarm-id-auth.d.ts.map +1 -0
- package/dist/swarm-id-auth.js +2 -0
- package/dist/swarm-id-auth.js.map +1 -0
- package/dist/swarm-id-client.d.ts +878 -0
- package/dist/swarm-id-client.d.ts.map +1 -0
- package/dist/swarm-id-client.js +2 -0
- package/dist/swarm-id-client.js.map +1 -0
- package/dist/swarm-id-proxy.d.ts +236 -0
- package/dist/swarm-id-proxy.d.ts.map +1 -0
- package/dist/swarm-id-proxy.js +2 -0
- package/dist/swarm-id-proxy.js.map +1 -0
- package/dist/swarm-id.esm.js +2 -0
- package/dist/swarm-id.esm.js.map +1 -0
- package/dist/swarm-id.umd.js +2 -0
- package/dist/swarm-id.umd.js.map +1 -0
- package/dist/sync/index.d.ts +9 -0
- package/dist/sync/index.d.ts.map +1 -0
- package/dist/sync/key-derivation.d.ts +25 -0
- package/dist/sync/key-derivation.d.ts.map +1 -0
- package/dist/sync/restore-account.d.ts +28 -0
- package/dist/sync/restore-account.d.ts.map +1 -0
- package/dist/sync/serialization.d.ts +16 -0
- package/dist/sync/serialization.d.ts.map +1 -0
- package/dist/sync/store-interfaces.d.ts +53 -0
- package/dist/sync/store-interfaces.d.ts.map +1 -0
- package/dist/sync/sync-account.d.ts +44 -0
- package/dist/sync/sync-account.d.ts.map +1 -0
- package/dist/sync/types.d.ts +13 -0
- package/dist/sync/types.d.ts.map +1 -0
- package/dist/test-fixtures.d.ts +17 -0
- package/dist/test-fixtures.d.ts.map +1 -0
- package/dist/types-BD_VkNn0.js +2 -0
- package/dist/types-BD_VkNn0.js.map +1 -0
- package/dist/types-lJCaT-50.js +2 -0
- package/dist/types-lJCaT-50.js.map +1 -0
- package/dist/types.d.ts +2157 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/utils/account-payload.d.ts +94 -0
- package/dist/utils/account-payload.d.ts.map +1 -0
- package/dist/utils/account-state-snapshot.d.ts +38 -0
- package/dist/utils/account-state-snapshot.d.ts.map +1 -0
- package/dist/utils/backup-encryption.d.ts +127 -0
- package/dist/utils/backup-encryption.d.ts.map +1 -0
- package/dist/utils/batch-utilization.d.ts +432 -0
- package/dist/utils/batch-utilization.d.ts.map +1 -0
- package/dist/utils/constants.d.ts +11 -0
- package/dist/utils/constants.d.ts.map +1 -0
- package/dist/utils/hex.d.ts +17 -0
- package/dist/utils/hex.d.ts.map +1 -0
- package/dist/utils/key-derivation.d.ts +92 -0
- package/dist/utils/key-derivation.d.ts.map +1 -0
- package/dist/utils/storage-managers.d.ts +65 -0
- package/dist/utils/storage-managers.d.ts.map +1 -0
- package/dist/utils/swarm-id-export.d.ts +24 -0
- package/dist/utils/swarm-id-export.d.ts.map +1 -0
- package/dist/utils/ttl.d.ts +49 -0
- package/dist/utils/ttl.d.ts.map +1 -0
- package/dist/utils/url.d.ts +41 -0
- package/dist/utils/url.d.ts.map +1 -0
- package/dist/utils/versioned-storage.d.ts +131 -0
- package/dist/utils/versioned-storage.d.ts.map +1 -0
- package/package.json +78 -0
- package/src/chunk/bmt.test.ts +217 -0
- package/src/chunk/bmt.ts +57 -0
- package/src/chunk/cac.test.ts +214 -0
- package/src/chunk/cac.ts +65 -0
- package/src/chunk/constants.ts +18 -0
- package/src/chunk/encrypted-cac.test.ts +385 -0
- package/src/chunk/encrypted-cac.ts +131 -0
- package/src/chunk/encryption.test.ts +352 -0
- package/src/chunk/encryption.ts +300 -0
- package/src/chunk/index.ts +47 -0
- package/src/index.ts +430 -0
- package/src/proxy/act/act.test.ts +278 -0
- package/src/proxy/act/act.ts +158 -0
- package/src/proxy/act/bee-compat.test.ts +948 -0
- package/src/proxy/act/crypto.test.ts +436 -0
- package/src/proxy/act/crypto.ts +376 -0
- package/src/proxy/act/grantee-list.test.ts +393 -0
- package/src/proxy/act/grantee-list.ts +239 -0
- package/src/proxy/act/history.test.ts +360 -0
- package/src/proxy/act/history.ts +413 -0
- package/src/proxy/act/index.test.ts +748 -0
- package/src/proxy/act/index.ts +853 -0
- package/src/proxy/chunking-encrypted.ts +95 -0
- package/src/proxy/chunking.ts +65 -0
- package/src/proxy/download-data.ts +448 -0
- package/src/proxy/feed-manifest.ts +174 -0
- package/src/proxy/feeds/epochs/async-finder.ts +372 -0
- package/src/proxy/feeds/epochs/epoch.test.ts +249 -0
- package/src/proxy/feeds/epochs/epoch.ts +181 -0
- package/src/proxy/feeds/epochs/finder.ts +282 -0
- package/src/proxy/feeds/epochs/index.ts +73 -0
- package/src/proxy/feeds/epochs/integration.test.ts +1336 -0
- package/src/proxy/feeds/epochs/test-utils.ts +274 -0
- package/src/proxy/feeds/epochs/types.ts +128 -0
- package/src/proxy/feeds/epochs/updater.ts +192 -0
- package/src/proxy/feeds/epochs/utils.ts +62 -0
- package/src/proxy/feeds/index.ts +5 -0
- package/src/proxy/feeds/sequence/async-finder.ts +31 -0
- package/src/proxy/feeds/sequence/finder.ts +73 -0
- package/src/proxy/feeds/sequence/index.ts +54 -0
- package/src/proxy/feeds/sequence/integration.test.ts +966 -0
- package/src/proxy/feeds/sequence/types.ts +103 -0
- package/src/proxy/feeds/sequence/updater.ts +71 -0
- package/src/proxy/index.ts +5 -0
- package/src/proxy/manifest-builder.test.ts +427 -0
- package/src/proxy/manifest-builder.ts +679 -0
- package/src/proxy/mantaray-encrypted.ts +78 -0
- package/src/proxy/mantaray.ts +104 -0
- package/src/proxy/types.ts +32 -0
- package/src/proxy/upload-data.ts +189 -0
- package/src/proxy/upload-encrypted-data.ts +658 -0
- package/src/schemas.ts +299 -0
- package/src/storage/debounced-uploader.ts +192 -0
- package/src/storage/utilization-store.ts +397 -0
- package/src/swarm-id-client.test.ts +99 -0
- package/src/swarm-id-client.ts +3095 -0
- package/src/swarm-id-proxy.ts +3891 -0
- package/src/sync/index.ts +28 -0
- package/src/sync/restore-account.ts +90 -0
- package/src/sync/serialization.ts +39 -0
- package/src/sync/store-interfaces.ts +62 -0
- package/src/sync/sync-account.test.ts +302 -0
- package/src/sync/sync-account.ts +396 -0
- package/src/sync/types.ts +11 -0
- package/src/test-fixtures.ts +109 -0
- package/src/types.ts +1651 -0
- package/src/utils/account-state-snapshot.test.ts +595 -0
- package/src/utils/account-state-snapshot.ts +94 -0
- package/src/utils/backup-encryption.test.ts +442 -0
- package/src/utils/backup-encryption.ts +352 -0
- package/src/utils/batch-utilization.ts +1309 -0
- package/src/utils/constants.ts +20 -0
- package/src/utils/hex.ts +27 -0
- package/src/utils/key-derivation.ts +197 -0
- package/src/utils/storage-managers.ts +365 -0
- package/src/utils/ttl.ts +129 -0
- package/src/utils/url.test.ts +136 -0
- package/src/utils/url.ts +71 -0
- package/src/utils/versioned-storage.ts +323 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:a,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const i=a.prototype,o=Object.keys(i);for(let e=0;e<o.length;e++){const t=o[e];t in n||(n[t]=i[t].bind(n))}}const i=n?.Parent??Object;class o extends i{}function a(e){var t;const i=n?.Parent?new o:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const e of i._zod.deferred)e();return i}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}class t extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class n extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}const r={};function i(e){return r}function o(e,t){return"bigint"==typeof t?t.toString():t}function a(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function s(e){return null==e}function c(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const u=Symbol("evaluating");function l(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==u)return void 0===r&&(r=u,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function d(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function h(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function f(e){return JSON.stringify(e)}const p="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function m(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const g=a(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function y(e){if(!1===m(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==m(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function w(e){return y(e)?{...e}:Array.isArray(e)?[...e]:e}const b=new Set(["string","number","symbol"]);function v(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function x(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function E(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}const A={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function R(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function S(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function I(e){return"string"==typeof e?e:e?.message}function k(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const i=I(e.inst?._zod.def?.error?.(e))??I(t?.error?.(e))??I(n.customError?.(e))??I(n.localeError?.(e))??"Invalid input";r.message=i}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function T(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function B(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const O=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,o,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},D=e("$ZodError",O),C=e("$ZodError",O,{Parent:Error});const $=e=>(n,r,o,a)=>{const s=o?Object.assign(o,{async:!1}):{async:!1},c=n._zod.run({value:r,issues:[]},s);if(c instanceof Promise)throw new t;if(c.issues.length){const t=new(a?.Err??e)(c.issues.map(e=>k(e,s,i())));throw p(t,a?.callee),t}return c.value},z=e=>async(t,n,r,o)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},a);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new(o?.Err??e)(s.issues.map(e=>k(e,a,i())));throw p(t,o?.callee),t}return s.value},F=e=>(n,r,o)=>{const a=o?{...o,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},a);if(s instanceof Promise)throw new t;return s.issues.length?{success:!1,error:new(e??D)(s.issues.map(e=>k(e,a,i())))}:{success:!0,data:s.value}},P=F(C),U=e=>async(t,n,r)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let a=t._zod.run({value:n,issues:[]},o);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>k(e,o,i())))}:{success:!0,data:a.value}},q=U(C),N=e=>(t,n,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return $(e)(t,n,i)},M=e=>(t,n,r)=>$(e)(t,n,r),_=e=>async(t,n,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return z(e)(t,n,i)},V=e=>async(t,n,r)=>z(e)(t,n,r),L=e=>(t,n,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return F(e)(t,n,i)},j=e=>(t,n,r)=>F(e)(t,n,r),G=e=>async(t,n,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return U(e)(t,n,i)},K=e=>async(t,n,r)=>U(e)(t,n,r),H=/^[cC][^\s-]{8,}$/,W=/^[0-9a-z]+$/,Z=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,J=/^[0-9a-vA-V]{20}$/,X=/^[A-Za-z0-9]{27}$/,Y=/^[a-zA-Z0-9_-]{21}$/,Q=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ee=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,te=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ne=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;const re=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ie=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,oe=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ae=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,se=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ce=/^[A-Za-z0-9_-]*$/,ue=/^\+(?:[0-9]){6,14}[0-9]$/,le="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",de=new RegExp(`^${le}$`);function he(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const fe=/^-?\d+$/,pe=/^-?\d+(?:\.\d+)?/,me=/^(?:true|false)$/i,ge=/^[^A-Z]*$/,ye=/^[^a-z]*$/,we=e("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),be={number:"number",bigint:"bigint",object:"date"},ve=e("$ZodCheckLessThan",(e,t)=>{we.init(e,t);const n=be[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),xe=e("$ZodCheckGreaterThan",(e,t)=>{we.init(e,t);const n=be[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ee=e("$ZodCheckMultipleOf",(e,t)=>{we.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value===BigInt(0):0===function(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let i=(r.split(".")[1]||"").length;if(0===i&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}const o=n>i?n:i;return Number.parseInt(e.toFixed(o).replace(".",""))%Number.parseInt(t.toFixed(o).replace(".",""))/10**o}(n.value,t.value))||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Ae=e("$ZodCheckNumberFormat",(e,t)=>{we.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[i,o]=A[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=o,n&&(r.pattern=fe)}),e._zod.check=a=>{const s=a.value;if(n){if(!Number.isInteger(s))return void a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});if(!Number.isSafeInteger(s))return void(s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}))}s<i&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>o&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:o,inst:e})}}),Re=e("$ZodCheckMaxLength",(e,t)=>{var n;we.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!s(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const i=T(r);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Se=e("$ZodCheckMinLength",(e,t)=>{var n;we.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!s(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const i=T(r);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Ie=e("$ZodCheckLengthEquals",(e,t)=>{var n;we.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!s(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,i=r.length;if(i===t.length)return;const o=T(r),a=i>t.length;n.issues.push({origin:o,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),ke=e("$ZodCheckStringFormat",(e,t)=>{var n,r;we.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Te=e("$ZodCheckRegex",(e,t)=>{ke.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Be=e("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=ge),ke.init(e,t)}),Oe=e("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=ye),ke.init(e,t)}),De=e("$ZodCheckIncludes",(e,t)=>{we.init(e,t);const n=v(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Ce=e("$ZodCheckStartsWith",(e,t)=>{we.init(e,t);const n=new RegExp(`^${v(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),$e=e("$ZodCheckEndsWith",(e,t)=>{we.init(e,t);const n=new RegExp(`.*${v(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),ze=e("$ZodCheckOverwrite",(e,t)=>{we.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class Fe{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const e of r)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const Pe={major:4,minor:1,patch:13},Ue=e("$ZodType",(e,n)=>{var r;e??(e={}),e._zod.def=n,e._zod.bag=e._zod.bag||{},e._zod.version=Pe;const i=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&i.unshift(e);for(const t of i)for(const n of t._zod.onattach)n(e);if(0===i.length)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const n=(e,n,r)=>{let i,o=R(e);for(const a of n){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(o)continue;const n=e.issues.length,s=a._zod.check(e);if(s instanceof Promise&&!1===r?.async)throw new t;if(i||s instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await s;e.issues.length!==n&&(o||(o=R(e,n)))});else{if(e.issues.length===n)continue;o||(o=R(e,n))}}return i?i.then(()=>e):e},r=(r,o,a)=>{if(R(r))return r.aborted=!0,r;const s=n(o,i,a);if(s instanceof Promise){if(!1===a.async)throw new t;return s.then(t=>e._zod.parse(t,a))}return e._zod.parse(s,a)};e._zod.run=(o,a)=>{if(a.skipChecks)return e._zod.parse(o,a);if("backward"===a.direction){const t=e._zod.parse({value:o.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>r(e,o,a)):r(t,o,a)}const s=e._zod.parse(o,a);if(s instanceof Promise){if(!1===a.async)throw new t;return s.then(e=>n(e,i,a))}return n(s,i,a)}}e["~standard"]={validate:t=>{try{const n=P(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return q(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}}),qe=e("$ZodString",(e,t)=>{var n;Ue.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ne=e("$ZodStringFormat",(e,t)=>{ke.init(e,t),qe.init(e,t)}),Me=e("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ee),Ne.init(e,t)}),_e=e("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=te(e))}else t.pattern??(t.pattern=te());Ne.init(e,t)}),Ve=e("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ne),Ne.init(e,t)}),Le=e("$ZodURL",(e,t)=>{Ne.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),i=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=i.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),je=e("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ne.init(e,t)}),Ge=e("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=Y),Ne.init(e,t)}),Ke=e("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=H),Ne.init(e,t)}),He=e("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=W),Ne.init(e,t)}),We=e("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Z),Ne.init(e,t)}),Ze=e("$ZodXID",(e,t)=>{t.pattern??(t.pattern=J),Ne.init(e,t)}),Je=e("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=X),Ne.init(e,t)}),Xe=e("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=he({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${le}T(?:${r})$`)}(t)),Ne.init(e,t)}),Ye=e("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=de),Ne.init(e,t)}),Qe=e("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${he(t)}$`)),Ne.init(e,t)}),et=e("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Q),Ne.init(e,t)}),tt=e("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=re),Ne.init(e,t),e._zod.bag.format="ipv4"}),nt=e("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=ie),Ne.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),rt=e("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=oe),Ne.init(e,t)}),it=e("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=ae),Ne.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function ot(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const at=e("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=se),Ne.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{ot(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});const st=e("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=ce),Ne.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!ce.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return ot(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),ct=e("$ZodE164",(e,t)=>{t.pattern??(t.pattern=ue),Ne.init(e,t)});const ut=e("$ZodJWT",(e,t)=>{Ne.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&"JWT"!==i?.typ||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),lt=e("$ZodNumber",(e,t)=>{Ue.init(e,t),e._zod.pattern=e._zod.bag.pattern??pe,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(e){}const i=n.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return n;const o="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}}),dt=e("$ZodNumberFormat",(e,t)=>{Ae.init(e,t),lt.init(e,t)}),ht=e("$ZodBoolean",(e,t)=>{Ue.init(e,t),e._zod.pattern=me,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(e){}const i=n.value;return"boolean"==typeof i||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),ft=e("$ZodUnknown",(e,t)=>{Ue.init(e,t),e._zod.parse=e=>e}),pt=e("$ZodNever",(e,t)=>{Ue.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function mt(e,t,n){e.issues.length&&t.issues.push(...S(n,e.issues)),t.value[n]=e.value}const gt=e("$ZodArray",(e,t)=>{Ue.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const o=[];for(let e=0;e<i.length;e++){const a=i[e],s=t.element._zod.run({value:a,issues:[]},r);s instanceof Promise?o.push(s.then(t=>mt(t,n,e))):mt(s,n,e)}return o.length?Promise.all(o).then(()=>n):n}});function yt(e,t,n,r){e.issues.length&&t.issues.push(...S(n,e.issues)),void 0===e.value?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function wt(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const n=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function bt(e,t,n,r,i,o){const a=[],s=i.keySet,c=i.catchall._zod,u=c.def.type;for(const i in t){if(s.has(i))continue;if("never"===u){a.push(i);continue}const o=c.run({value:t[i],issues:[]},r);o instanceof Promise?e.push(o.then(e=>yt(e,n,i,t))):yt(o,n,i,t)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}const vt=e("$ZodObject",(e,t)=>{Ue.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const r=a(()=>wt(t));l(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(const e of r.values)n[t].add(e)}}return n});const i=m,o=t.catchall;let s;e._zod.parse=(t,n)=>{s??(s=r.value);const a=t.value;if(!i(a))return t.issues.push({expected:"object",code:"invalid_type",input:a,inst:e}),t;t.value={};const c=[],u=s.shape;for(const e of s.keys){const r=u[e]._zod.run({value:a[e],issues:[]},n);r instanceof Promise?c.push(r.then(n=>yt(n,t,e,a))):yt(r,t,e,a)}return o?bt(c,a,t,n,r.value,e):c.length?Promise.all(c).then(()=>t):t}}),xt=e("$ZodObjectJIT",(e,t)=>{vt.init(e,t);const n=e._zod.parse,i=a(()=>wt(t));let o;const s=m,c=!r.jitless,u=c&&g.value,l=t.catchall;let d;e._zod.parse=(r,a)=>{d??(d=i.value);const h=r.value;return s(h)?c&&u&&!1===a?.async&&!0!==a.jitless?(o||(o=(e=>{const t=new Fe(["shape","payload","ctx"]),n=i.value,r=e=>{const t=f(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const o=Object.create(null);let a=0;for(const e of n.keys)o[e]="key_"+a++;t.write("const newResult = {};");for(const e of n.keys){const n=o[e],i=f(e);t.write(`const ${n} = ${r(e)};`),t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${i}, ...iss.path] : [${i}]\n })));\n }\n \n \n if (${n}.value === undefined) {\n if (${i} in input) {\n newResult[${i}] = undefined;\n }\n } else {\n newResult[${i}] = ${n}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");const s=t.compile();return(t,n)=>s(e,t,n)})(t.shape)),r=o(r,a),l?bt([],h,r,a,d,e):r):n(r,a):(r.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),r)}});function Et(e,t,n,r){for(const n of e)if(0===n.issues.length)return t.value=n.value,t;const o=e.filter(e=>!R(e));return 1===o.length?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>k(e,r,i())))}),t)}const At=e("$ZodUnion",(e,t)=>{Ue.init(e,t),l(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),l(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),l(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),l(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>c(e.source)).join("|")})$`)}});const n=1===t.options.length,r=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(n)return r(i,o);let a=!1;const s=[];for(const e of t.options){const t=e._zod.run({value:i.value,issues:[]},o);if(t instanceof Promise)s.push(t),a=!0;else{if(0===t.issues.length)return t;s.push(t)}}return a?Promise.all(s).then(t=>Et(t,i,e,o)):Et(s,i,e,o)}}),Rt=e("$ZodDiscriminatedUnion",(e,t)=>{At.init(e,t);const n=e._zod.parse;l(e._zod,"propValues",()=>{const e={};for(const n of t.options){const r=n._zod.propValues;if(!r||0===Object.keys(r).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(r)){e[t]||(e[t]=new Set);for(const r of n)e[t].add(r)}}return e});const r=a(()=>{const e=t.options,n=new Map;for(const r of e){const e=r._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const t of e){if(n.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,o)=>{const a=i.value;if(!m(a))return i.issues.push({code:"invalid_type",expected:"object",input:a,inst:e}),i;const s=r.value.get(a?.[t.discriminator]);return s?s._zod.run(i,o):t.unionFallback?n(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:a,path:[t.discriminator],inst:e}),i)}}),St=e("$ZodIntersection",(e,t)=>{Ue.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,i=t.left._zod.run({value:r,issues:[]},n),o=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([t,n])=>kt(e,t,n)):kt(e,i,o)}});function It(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(y(e)&&y(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),i={...e,...t};for(const n of r){const r=It(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const i=It(e[r],t[r]);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function kt(e,t,n){if(t.issues.length&&e.issues.push(...t.issues),n.issues.length&&e.issues.push(...n.issues),R(e))return e;const r=It(t.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return e.value=r.data,e}const Tt=e("$ZodRecord",(e,t)=>{Ue.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!y(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;const a=[],s=t.keyType._zod.values;if(s){n.value={};const i=new Set;for(const e of s)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){i.add("number"==typeof e?e.toString():e);const s=t.valueType._zod.run({value:o[e],issues:[]},r);s instanceof Promise?a.push(s.then(t=>{t.issues.length&&n.issues.push(...S(e,t.issues)),n.value[e]=t.value})):(s.issues.length&&n.issues.push(...S(e,s.issues)),n.value[e]=s.value)}let c;for(const e in o)i.has(e)||(c=c??[],c.push(e));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c})}else{n.value={};for(const s of Reflect.ownKeys(o)){if("__proto__"===s)continue;const c=t.keyType._zod.run({value:s,issues:[]},r);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(c.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(e=>k(e,r,i())),input:s,path:[s],inst:e}),n.value[c.value]=c.value;continue}const u=t.valueType._zod.run({value:o[s],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...S(s,e.issues)),n.value[c.value]=e.value})):(u.issues.length&&n.issues.push(...S(s,u.issues)),n.value[c.value]=u.value)}}return a.length?Promise.all(a).then(()=>n):n}}),Bt=e("$ZodEnum",(e,t)=>{Ue.init(e,t);const n=function(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>b.has(typeof e)).map(e=>"string"==typeof e?v(e):e.toString()).join("|")})$`),e._zod.parse=(t,i)=>{const o=t.value;return r.has(o)||t.issues.push({code:"invalid_value",values:n,input:o,inst:e}),t}}),Ot=e("$ZodLiteral",(e,t)=>{if(Ue.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?v(e):e?v(e.toString()):String(e)).join("|")})$`),e._zod.parse=(r,i)=>{const o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),Dt=e("$ZodTransform",(e,r)=>{Ue.init(e,r),e._zod.parse=(i,o)=>{if("backward"===o.direction)throw new n(e.constructor.name);const a=r.transform(i.value,i);if(o.async){return(a instanceof Promise?a:Promise.resolve(a)).then(e=>(i.value=e,i))}if(a instanceof Promise)throw new t;return i.value=a,i}});function Ct(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}const $t=e("$ZodOptional",(e,t)=>{Ue.init(e,t),e._zod.optin="optional",e._zod.optout="optional",l(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),l(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${c(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>Ct(t,e.value)):Ct(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),zt=e("$ZodNullable",(e,t)=>{Ue.init(e,t),l(e._zod,"optin",()=>t.innerType._zod.optin),l(e._zod,"optout",()=>t.innerType._zod.optout),l(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${c(e.source)}|null)$`):void 0}),l(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),Ft=e("$ZodDefault",(e,t)=>{Ue.init(e,t),e._zod.optin="optional",l(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Pt(e,t)):Pt(r,t)}});function Pt(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const Ut=e("$ZodPrefault",(e,t)=>{Ue.init(e,t),e._zod.optin="optional",l(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),qt=e("$ZodNonOptional",(e,t)=>{Ue.init(e,t),l(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Nt(t,e)):Nt(i,e)}});function Nt(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Mt=e("$ZodCatch",(e,t)=>{Ue.init(e,t),l(e._zod,"optin",()=>t.innerType._zod.optin),l(e._zod,"optout",()=>t.innerType._zod.optout),l(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>k(e,n,i()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>k(e,n,i()))},input:e.value}),e.issues=[]),e)}}),_t=e("$ZodPipe",(e,t)=>{Ue.init(e,t),l(e._zod,"values",()=>t.in._zod.values),l(e._zod,"optin",()=>t.in._zod.optin),l(e._zod,"optout",()=>t.out._zod.optout),l(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Vt(e,t.in,n)):Vt(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Vt(e,t.out,n)):Vt(r,t.out,n)}});function Vt(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Lt=e("$ZodReadonly",(e,t)=>{Ue.init(e,t),l(e._zod,"propValues",()=>t.innerType._zod.propValues),l(e._zod,"values",()=>t.innerType._zod.values),l(e._zod,"optin",()=>t.innerType?._zod?.optin),l(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(jt):jt(r)}});function jt(e){return e.value=Object.freeze(e.value),e}const Gt=e("$ZodCustom",(e,t)=>{we.init(e,t),Ue.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Kt(t,n,r,e));Kt(i,n,r,e)}});function Kt(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(B(e))}}var Ht;class Wt{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];if(this._map.set(e,n),n&&"object"==typeof n&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}(Ht=globalThis).__zod_globalRegistry??(Ht.__zod_globalRegistry=new Wt);const Zt=globalThis.__zod_globalRegistry;function Jt(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...E(t)})}function Xt(e,t){return new ve({check:"less_than",...E(t),value:e,inclusive:!1})}function Yt(e,t){return new ve({check:"less_than",...E(t),value:e,inclusive:!0})}function Qt(e,t){return new xe({check:"greater_than",...E(t),value:e,inclusive:!1})}function en(e,t){return new xe({check:"greater_than",...E(t),value:e,inclusive:!0})}function tn(e,t){return new Ee({check:"multiple_of",...E(t),value:e})}function nn(e,t){return new Re({check:"max_length",...E(t),maximum:e})}function rn(e,t){return new Se({check:"min_length",...E(t),minimum:e})}function on(e,t){return new Ie({check:"length_equals",...E(t),length:e})}function an(e){return new ze({check:"overwrite",tx:e})}function sn(e){const t=function(e,t){const n=new we({check:"custom",...E(t)});return n._zod.check=e,n}(n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(B(e,n.value,t._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(B(r))}},e(n.value,n)));return t}const cn=e("ZodISODateTime",(e,t)=>{Xe.init(e,t),Fn.init(e,t)});function un(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...E(t)})}(cn,e)}const ln=e("ZodISODate",(e,t)=>{Ye.init(e,t),Fn.init(e,t)});function dn(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...E(t)})}(ln,e)}const hn=e("ZodISOTime",(e,t)=>{Qe.init(e,t),Fn.init(e,t)});function fn(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...E(t)})}(hn,e)}const pn=e("ZodISODuration",(e,t)=>{et.init(e,t),Fn.init(e,t)});function mn(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...E(t)})}(pn,e)}const gn=(e,t)=>{D.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},r=e=>{for(const i of e.issues)if("invalid_union"===i.code&&i.errors.length)i.errors.map(e=>r({issues:e}));else if("invalid_key"===i.code)r({issues:i.issues});else if("invalid_element"===i.code)r({issues:i.issues});else if(0===i.path.length)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){const n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,o,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,o,2)}},isEmpty:{get:()=>0===e.issues.length}})},yn=e("ZodError",gn),wn=e("ZodError",gn,{Parent:Error}),bn=$(wn),vn=z(wn),xn=F(wn),En=U(wn),An=N(wn),Rn=M(wn),Sn=_(wn),In=V(wn),kn=L(wn),Tn=j(wn),Bn=G(wn),On=K(wn),Dn=e("ZodType",(e,t)=>(Ue.init(e,t),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(h(t,{checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]})),e.clone=(t,n)=>x(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>bn(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>xn(e,t,n),e.parseAsync=async(t,n)=>vn(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>En(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>An(e,t,n),e.decode=(t,n)=>Rn(e,t,n),e.encodeAsync=async(t,n)=>Sn(e,t,n),e.decodeAsync=async(t,n)=>In(e,t,n),e.safeEncode=(t,n)=>kn(e,t,n),e.safeDecode=(t,n)=>Tn(e,t,n),e.safeEncodeAsync=async(t,n)=>Bn(e,t,n),e.safeDecodeAsync=async(t,n)=>On(e,t,n),e.refine=(t,n)=>e.check(function(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...E(n)})}(qr,e,t)}(t,n)),e.superRefine=t=>e.check(sn(t)),e.overwrite=t=>e.check(an(t)),e.optional=()=>Tr(e),e.nullable=()=>Or(e),e.nullish=()=>Tr(Or(e)),e.nonoptional=t=>function(e,t){return new $r({type:"nonoptional",innerType:e,...E(t)})}(e,t),e.array=()=>hr(e),e.or=t=>gr([e,t]),e.and=t=>new br({type:"intersection",left:e,right:t}),e.transform=t=>Pr(e,Ir(t)),e.default=t=>{return n=t,new Dr({type:"default",innerType:e,get defaultValue(){return"function"==typeof n?n():w(n)}});var n},e.prefault=t=>{return n=t,new Cr({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof n?n():w(n)}});var n},e.catch=t=>{return new zr({type:"catch",innerType:e,catchValue:"function"==typeof(n=t)?n:()=>n});var n},e.pipe=t=>Pr(e,t),e.readonly=()=>new Ur({type:"readonly",innerType:e}),e.describe=t=>{const n=e.clone();return Zt.add(n,{description:t}),n},Object.defineProperty(e,"description",{get:()=>Zt.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Zt.get(e);const n=e.clone();return Zt.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Cn=e("_ZodString",(e,t)=>{qe.init(e,t),Dn.init(e,t);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(function(e,t){return new Te({check:"string_format",format:"regex",...E(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new De({check:"string_format",format:"includes",...E(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new Ce({check:"string_format",format:"starts_with",...E(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new $e({check:"string_format",format:"ends_with",...E(t),suffix:e})}(...t)),e.min=(...t)=>e.check(rn(...t)),e.max=(...t)=>e.check(nn(...t)),e.length=(...t)=>e.check(on(...t)),e.nonempty=(...t)=>e.check(rn(1,...t)),e.lowercase=t=>e.check(function(e){return new Be({check:"string_format",format:"lowercase",...E(e)})}(t)),e.uppercase=t=>e.check(function(e){return new Oe({check:"string_format",format:"uppercase",...E(e)})}(t)),e.trim=()=>e.check(an(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){return an(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(an(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(an(e=>e.toUpperCase())),e.slugify=()=>e.check(an(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}),$n=e("ZodString",(e,t)=>{qe.init(e,t),Cn.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...E(t)})}(Pn,t)),e.url=t=>e.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...E(t)})}(Nn,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...E(t)})}(er,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...E(t)})}(Mn,t)),e.guid=t=>e.check(Jt(Un,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...E(t)})}(qn,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...E(t)})}(qn,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...E(t)})}(qn,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...E(t)})}(qn,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...E(t)})}(_n,t)),e.guid=t=>e.check(Jt(Un,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...E(t)})}(Vn,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...E(t)})}(Ln,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...E(t)})}(jn,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...E(t)})}(Xn,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...E(t)})}(Yn,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...E(t)})}(Gn,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...E(t)})}(Kn,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...E(t)})}(Hn,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...E(t)})}(Wn,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...E(t)})}(Zn,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...E(t)})}(Jn,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...E(t)})}(Qn,t)),e.datetime=t=>e.check(un(t)),e.date=t=>e.check(dn(t)),e.time=t=>e.check(fn(t)),e.duration=t=>e.check(mn(t))});function zn(e){return function(e,t){return new e({type:"string",...E(t)})}($n,e)}const Fn=e("ZodStringFormat",(e,t)=>{Ne.init(e,t),Cn.init(e,t)}),Pn=e("ZodEmail",(e,t)=>{Ve.init(e,t),Fn.init(e,t)}),Un=e("ZodGUID",(e,t)=>{Me.init(e,t),Fn.init(e,t)}),qn=e("ZodUUID",(e,t)=>{_e.init(e,t),Fn.init(e,t)}),Nn=e("ZodURL",(e,t)=>{Le.init(e,t),Fn.init(e,t)}),Mn=e("ZodEmoji",(e,t)=>{je.init(e,t),Fn.init(e,t)}),_n=e("ZodNanoID",(e,t)=>{Ge.init(e,t),Fn.init(e,t)}),Vn=e("ZodCUID",(e,t)=>{Ke.init(e,t),Fn.init(e,t)}),Ln=e("ZodCUID2",(e,t)=>{He.init(e,t),Fn.init(e,t)}),jn=e("ZodULID",(e,t)=>{We.init(e,t),Fn.init(e,t)}),Gn=e("ZodXID",(e,t)=>{Ze.init(e,t),Fn.init(e,t)}),Kn=e("ZodKSUID",(e,t)=>{Je.init(e,t),Fn.init(e,t)}),Hn=e("ZodIPv4",(e,t)=>{tt.init(e,t),Fn.init(e,t)}),Wn=e("ZodIPv6",(e,t)=>{nt.init(e,t),Fn.init(e,t)}),Zn=e("ZodCIDRv4",(e,t)=>{rt.init(e,t),Fn.init(e,t)}),Jn=e("ZodCIDRv6",(e,t)=>{it.init(e,t),Fn.init(e,t)}),Xn=e("ZodBase64",(e,t)=>{at.init(e,t),Fn.init(e,t)}),Yn=e("ZodBase64URL",(e,t)=>{st.init(e,t),Fn.init(e,t)}),Qn=e("ZodE164",(e,t)=>{ct.init(e,t),Fn.init(e,t)}),er=e("ZodJWT",(e,t)=>{ut.init(e,t),Fn.init(e,t)}),tr=e("ZodNumber",(e,t)=>{lt.init(e,t),Dn.init(e,t),e.gt=(t,n)=>e.check(Qt(t,n)),e.gte=(t,n)=>e.check(en(t,n)),e.min=(t,n)=>e.check(en(t,n)),e.lt=(t,n)=>e.check(Xt(t,n)),e.lte=(t,n)=>e.check(Yt(t,n)),e.max=(t,n)=>e.check(Yt(t,n)),e.int=t=>e.check(ir(t)),e.safe=t=>e.check(ir(t)),e.positive=t=>e.check(Qt(0,t)),e.nonnegative=t=>e.check(en(0,t)),e.negative=t=>e.check(Xt(0,t)),e.nonpositive=t=>e.check(Yt(0,t)),e.multipleOf=(t,n)=>e.check(tn(t,n)),e.step=(t,n)=>e.check(tn(t,n)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function nr(e){return function(e,t){return new e({type:"number",checks:[],...E(t)})}(tr,e)}const rr=e("ZodNumberFormat",(e,t)=>{dt.init(e,t),tr.init(e,t)});function ir(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...E(t)})}(rr,e)}const or=e("ZodBoolean",(e,t)=>{ht.init(e,t),Dn.init(e,t)});function ar(e){return function(e,t){return new e({type:"boolean",...E(t)})}(or,e)}const sr=e("ZodUnknown",(e,t)=>{ft.init(e,t),Dn.init(e,t)});function cr(){return new sr({type:"unknown"})}const ur=e("ZodNever",(e,t)=>{pt.init(e,t),Dn.init(e,t)});function lr(e){return function(e,t){return new e({type:"never",...E(t)})}(ur,e)}const dr=e("ZodArray",(e,t)=>{gt.init(e,t),Dn.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(rn(t,n)),e.nonempty=t=>e.check(rn(1,t)),e.max=(t,n)=>e.check(nn(t,n)),e.length=(t,n)=>e.check(on(t,n)),e.unwrap=()=>e.element});function hr(e,t){return function(e,t,n){return new e({type:"array",element:t,...E(n)})}(dr,e,t)}const fr=e("ZodObject",(e,t)=>{xt.init(e,t),Dn.init(e,t),l(e,"shape",()=>t.shape),e.keyof=()=>Er(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:cr()}),e.loose=()=>e.clone({...e._zod.def,catchall:cr()}),e.strict=()=>e.clone({...e._zod.def,catchall:lr()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!y(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const r=h(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return d(this,"shape",n),n},checks:[]});return x(e,r)}(e,t),e.safeExtend=t=>function(e,t){if(!y(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n={...e._zod.def,get shape(){const n={...e._zod.def.shape,...t};return d(this,"shape",n),n},checks:e._zod.def.checks};return x(e,n)}(e,t),e.merge=t=>function(e,t){const n=h(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return d(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:[]});return x(e,n)}(e,t),e.pick=t=>function(e,t){const n=e._zod.def;return x(e,h(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return d(this,"shape",e),e},checks:[]}))}(e,t),e.omit=t=>function(e,t){const n=e._zod.def,r=h(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return d(this,"shape",r),r},checks:[]});return x(e,r)}(e,t),e.partial=(...t)=>function(e,t,n){const r=h(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)i[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return d(this,"shape",i),i},checks:[]});return x(t,r)}(kr,e,t[0]),e.required=(...t)=>function(e,t,n){const r=h(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t in n){if(!(t in i))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)i[t]=new e({type:"nonoptional",innerType:r[t]});return d(this,"shape",i),i},checks:[]});return x(t,r)}($r,e,t[0])});function pr(e,t){const n={type:"object",shape:e??{},...E(t)};return new fr(n)}const mr=e("ZodUnion",(e,t)=>{At.init(e,t),Dn.init(e,t),e.options=t.options});function gr(e,t){return new mr({type:"union",options:e,...E(t)})}const yr=e("ZodDiscriminatedUnion",(e,t)=>{mr.init(e,t),Rt.init(e,t)});function wr(e,t,n){return new yr({type:"union",options:t,discriminator:e,...E(n)})}const br=e("ZodIntersection",(e,t)=>{St.init(e,t),Dn.init(e,t)});const vr=e("ZodRecord",(e,t)=>{Tt.init(e,t),Dn.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});const xr=e("ZodEnum",(e,t)=>{Bt.init(e,t),Dn.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const i={};for(const r of e){if(!n.has(r))throw new Error(`Key ${r} not found in enum`);i[r]=t.entries[r]}return new xr({...t,checks:[],...E(r),entries:i})},e.exclude=(e,r)=>{const i={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete i[t]}return new xr({...t,checks:[],...E(r),entries:i})}});function Er(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new xr({type:"enum",entries:n,...E(t)})}const Ar=e("ZodLiteral",(e,t)=>{Ot.init(e,t),Dn.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Rr(e,t){return new Ar({type:"literal",values:Array.isArray(e)?e:[e],...E(t)})}const Sr=e("ZodTransform",(e,t)=>{Dt.init(e,t),Dn.init(e,t),e._zod.parse=(r,i)=>{if("backward"===i.direction)throw new n(e.constructor.name);r.addIssue=n=>{if("string"==typeof n)r.issues.push(B(n,r.value,t));else{const t=n;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=r.value),t.inst??(t.inst=e),r.issues.push(B(t))}};const o=t.transform(r.value,r);return o instanceof Promise?o.then(e=>(r.value=e,r)):(r.value=o,r)}});function Ir(e){return new Sr({type:"transform",transform:e})}const kr=e("ZodOptional",(e,t)=>{$t.init(e,t),Dn.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Tr(e){return new kr({type:"optional",innerType:e})}const Br=e("ZodNullable",(e,t)=>{zt.init(e,t),Dn.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Or(e){return new Br({type:"nullable",innerType:e})}const Dr=e("ZodDefault",(e,t)=>{Ft.init(e,t),Dn.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});const Cr=e("ZodPrefault",(e,t)=>{Ut.init(e,t),Dn.init(e,t),e.unwrap=()=>e._zod.def.innerType});const $r=e("ZodNonOptional",(e,t)=>{qt.init(e,t),Dn.init(e,t),e.unwrap=()=>e._zod.def.innerType});const zr=e("ZodCatch",(e,t)=>{Mt.init(e,t),Dn.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});const Fr=e("ZodPipe",(e,t)=>{_t.init(e,t),Dn.init(e,t),e.in=t.in,e.out=t.out});function Pr(e,t){return new Fr({type:"pipe",in:e,out:t})}const Ur=e("ZodReadonly",(e,t)=>{Lt.init(e,t),Dn.init(e,t),e.unwrap=()=>e._zod.def.innerType});const qr=e("ZodCustom",(e,t)=>{Gt.init(e,t),Dn.init(e,t)});function Nr(e,t={error:`Input not instance of ${e.name}`}){const n=new qr({type:"custom",check:"custom",fn:t=>t instanceof e,abort:!0,...E(t)});return n._zod.bag.Class=e,n}function Mr(e,t){return Pr(Ir(e),t)}var _r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Vr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Lr,jr={};var Gr=(Lr||(Lr=1,function(e){var t;async function n(e){return new Promise((t,n)=>e.then(n,t))}async function r(e){return new Promise(t=>setTimeout(()=>{t(!0)},e))}function i(e,t=Math.random){for(let n=e.length-1;n>0;n--){const r=Math.floor(t()*(n+1)),i=e[n];e[n]=e[r],e[r]=i}return e}function o(e,t,n=Math.random){return i(K(0,e.length-1),n).slice(0,t)}function a(e,t,n=Math.random){return Math.floor(n()*(t-e+1))+e}function s(e,t,n){return t>=e.x&&t<e.x+e.width&&n>=e.y&&n<e.y+e.height}function c(e,t=Math.random){return t()<e}function u(e,t=Math.random){return e[Math.floor(e.length*t())]}function l(e){if(!e.length)throw Error("Received empty array");return e[e.length-1]}function d(e,t,n){return n(t.reduce((e,t)=>t(e),e))}function h(e,t){if(null==e)return null;const n=t.split(".");let r=e;for(const e of n){if(null===r[e]||void 0===r[e])return null;r=r[e]}return r}function f(e,t,n){const r=t.split(/\.|\[/);let i=e;for(let e=0;e<r.length;e++){const t=r[e],o=e<r.length-1&&r[e+1].includes("]"),a=t.includes("]")?t.replace(/\[|\]/g,""):t;if(e===r.length-1)return i[a]=n,n;m(i[a])||(i[a]=o?[]:{}),i=i[a]}return n}function p(e,t){return Math.round(e/t)*t}function m(e,t=!0){return!(!e||t&&!w(e._readableState)||t&&e.constructor&&(e.constructor.isBuffer||"AbortController"==e.constructor.name||"AbortSignal"==e.constructor.name||"Uint8Array"==e.constructor.name||"ArrayBuffer"===e.constructor.name||"ReadableStream"===e.constructor.name))&&"object"==typeof e}function g(e){return m(e)&&!Array.isArray(e)}function y(e){return Array.isArray(e)&&0===e.length}function w(e){return void 0===e}function b(e){return"[object Function]"===Object.prototype.toString.call(e)||"[object AsyncFunction]"===Object.prototype.toString.call(e)}function v(e){return"[object String]"===Object.prototype.toString.call(e)}function x(e){return"number"==typeof e&&isFinite(e)}function E(e){return!0===e||!1===e}function A(e){return"[object Date]"===Object.prototype.toString.call(e)}function R(e){return!v(e)||0===e.trim().length}function S(e){return x(e)&&Number.isInteger(e)&&e>=1}function I(e){return v(e)&&null!==e.match(/^-?\d+$/)}function k(e){return v(e)&&null!==e.match(/^(0x)?[0-9a-f]+$/i)}Object.defineProperty(e,"__esModule",{value:!0}),e.Vector=e.Cache=e.Assertions=e.Strings=e.Types=e.Objects=e.Dates=e.Promises=e.Numbers=e.System=e.Arrays=e.Random=e.Elliptic=e.Binary=e.Lock=e.Solver=e.RollingValueProvider=e.TrieRouter=e.AsyncQueue=e.PubSubChannel=e.FixedPointNumber=e.MerkleTree=e.Chunk=e.Uint8ArrayWriter=e.Uint8ArrayReader=e.AsyncLazy=e.Lazy=e.Optional=void 0;const T="!@#$%^&*()_+-=[]{}|;:<>?,./".split(""),B="abcdefghijklmnopqrstuvwxyz",O=B+"ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890",D=O+"!@#$%^&*()_+-=[]{}|;:<>?,./",C=["—","\\","東","京","都","𝖆","𝖇","𝖈","👾","🙇","💁","🙅","ᚠ","ᛇ","ᚻ","ᛦ"],$="0123456789abcdef";function z(e,t){if(R(e))throw new TypeError(`Expected string${t?.name?` for ${t.name}`:""}, got: `+e);if(t&&(void 0!==t.min&&e.length<t.min||void 0!==t.max&&e.length>t.max))throw RangeError(`Expected string${t?.name?` for ${t.name}`:""} length in range: ${t.min??"-inf"}..${t.max??"inf"}; got: ${e.length}`);return e}function F(e,t){if(void 0!==t.min&&e<t.min||void 0!==t.max&&e>t.max)throw RangeError(`Expected value${t?.name?` for ${t.name}`:""} in range: ${t.min??"-inf"}..${t.max??"inf"}; got: ${e}`)}function P(e,t){if(x(e))return t&&F(e,t),e;if(!v(e)||!e.match(/^-?\d+(\.\d+)?$/))throw new TypeError(`Expected number${t?.name?` for ${t.name}`:""}, got: `+e);const n=parseFloat(e);return t&&F(n,t),n}function U(e,t){return Math.trunc(P(e,t))}function q(e,t){if(!g(e))throw new TypeError(`Expected object${t?.name?` for ${t.name}`:""}, got: `+e);return e}function N(e){return v(e)&&null!==e.match(/^https?:\/\/.+/)}function M(e){return"bigint"==typeof e}function _(e,t){if(!M(e))throw new TypeError(`Expected bigint${t?.name?` for ${t.name}`:""}, got: `+e);if(void 0!==t?.min&&e<t?.min||void 0!==t?.max&&e>t?.max)throw RangeError(`Expected value${t?.name?` for ${t.name}`:""} in range: ${t.min??"-inf"}..${t.max??"inf"}; got: ${e}`);return e}function V(e,t){for(const[n,r]of Object.entries(t))if(!r(e[n]))throw TypeError(`${n} in value does not exist or match shape`);for(const n of Object.keys(e))if(!t[n])throw TypeError(`${n} exists in value but not in shape`);return!0}function L(e,t){if(g(e)&&g(t))for(const n in t)g(t[n])?(e[n]||(e[n]={}),L(e[n],t[n])):Array.isArray(t[n])?e[n]=[...t[n]]:(null!==t[n]&&void 0!==t[n]||null===e[n]||void 0===e[n])&&(e[n]=t[n]);return e}function j(e,t){const n={};for(const r of e)for(const e of Object.keys(r))n[e]?n[e]=t(n[e],r[e]):n[e]=r[e];return n}function G(e,t){Array.prototype.push.apply(e,t)}function K(e,t){const n=[];for(let r=e;r<=t;r++)n.push(r);return n}function H(e,t=()=>!1){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").split("").map(e=>/[a-z0-9]/.test(e)||t(e)?e:"-").join("").replace(/-+/g,"-").replace(/^-|-$/g,"")}function W(e,t){if(0===t.length)return 0;const n=e.toLowerCase(),r=t.toLowerCase();return e===t?1e4:n.startsWith(r)?1e4-e.length:n.includes(r)?5e3-e.length:new RegExp(".*"+r.split("").join(".*")+".*").test(n)?1e3-e.length:0}const Z={"&":"&",""":'"',"'":"'",">":">","<":"<"};function J(e,t){const n=e.indexOf(t);return-1===n?null:e.slice(0,n)}function X(e,t){const n=e.indexOf(t);return-1===n?null:e.slice(n+t.length)}function Y(e,t){const n=e.lastIndexOf(t);return-1===n?null:e.slice(0,n)}function Q(e,t){const n=e.lastIndexOf(t);return-1===n?null:e.slice(n+t.length)}function ee(e,t,n=!1){const r=n?e.lastIndexOf(t):e.indexOf(t);return-1===r?n?[null,e]:[e,null]:[e.slice(0,r),e.slice(r+t.length)]}function te(e,t){let n=[e];for(const e of t)n=n.flatMap(t=>t.split(e));return n.filter(e=>e)}function ne(e){const t=l(e.split(/\\|\//g)),n=t.lastIndexOf(".",t.length-1);return n<=0?"":t.slice(n+1)}function re(e){const t=l(e.split(/\\|\//g)),n=t.lastIndexOf(".",t.length-1);return n<=0?t:t.slice(0,n)}function ie(e){return e.split("\n").map(e=>e.trim().replace(/\s+/g," ")).filter(e=>e.length>0).join("\n")}function oe(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ae(e){return e.charAt(0).toLowerCase()+e.slice(1)}function se(e){if(!e)return!1;const t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122}function ce(e){if(!e)return!1;const t=e.charCodeAt(0);return t>=48&&t<=57}function ue(e){return se(e)||ce(e)}const le=" \n\t\r.,?!:;\"'`(){}[]~@#$%^&*-+=|<>/\\".split("");function de(e){return le.includes(e)}function he(e,t,n=0){const r=t.exec(e.slice(n));return r?{index:r.index,match:r[0]}:null}function fe(e,t,n=!0){if(!n)return t.every(t=>t instanceof RegExp?t.test(e):-1!==e.indexOf(t,0));let r=0;for(const n of t)if(n instanceof RegExp){const t=he(e,n,r);if(!t)return!1;r=t.index+t.match.length}else{const t=e.indexOf(n,r);if(-1===t)return!1;r=t+n.length}return!0}function pe(e,t,n=0){const r=[];let i=e.indexOf(t,n);for(;-1!==i;)r.push(i),i=e.indexOf(t,i+t.length);return r}function me(e,t,n=0){let r=-1;for(const i of t){const t=e.indexOf(i,n);-1!==t&&(-1===r||t<r)&&(r=t)}return r}function ge(e,t=0){for(let n=t;n<e.length;n++)if(de(e[n]))return n;return-1}function ye(e,t=0){for(let n=t;n<e.length;n++)if("#"===e[n]&&ue(e[n+1]))return n;return-1}function we(e,t,n=0){return e.slice(0,n).lastIndexOf(t)}function be(e,t=0,n="{",r="}"){let i=1;for(let o=t;o<e.length;o++)if(e.slice(o,o+r.length)===r){if(0===--i)return o}else e.slice(o,o+n.length)===n&&i++;return-1}function ve(e,t){const n=t.wordBoundary?me(e,[`${t.opening} `,`${t.opening}\n`],t.start||0):e.indexOf(t.opening,t.start||0);if(-1===n)return null;const r=be(e,n+t.opening.length,t.opening,t.closing);return-1===r?null:t.exclusive?e.slice(n+t.opening.length,r):e.slice(n,r+t.closing.length)}const xe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ee="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function Ae(e,t){const n=t.length;let r=0,i=0;const o=[];for(let a=0;a<e.length;a++){const s=e[a];if("="===s)break;const c=t.indexOf(s);if(-1===c)throw new Error(`Invalid character: ${s}`);i=i<<Math.log2(n)|c,r+=Math.log2(n),r>=8&&(r-=8,o.push(i>>r&255))}return new Uint8Array(o)}function Re(e,t){const n=t.length;let r=0,i=0,o="";for(let a=0;a<e.length;a++)for(i=i<<8|e[a],r+=8;r>=Math.log2(n);)r-=Math.log2(n),o+=t[i>>r&n-1];return r>0&&(o+=t[i<<Math.log2(n)-r&n-1]),o.length%4!=0&&(o+="=".repeat(4-o.length%4)),o}function Se(e,t,n){const r=[];for(const i of n)i!==t&&r.push(e.replace(t,i));return r}function Ie(e){const t=e.lastIndexOf(" ");return-1===t?{line:e,rest:""}:{line:e.slice(0,t),rest:e.slice(t+1)}}function ke(e){const t=e.reduce((e,t)=>e.length<t.length?e:t);let n="";for(let r=0;r<t.length;r++){const i=t[r];if(!e.every(e=>e[r]===i))break;n+=i}return n}function Te(e,t){return new RegExp(`\\b${t}\\b`).test(e)}function Be(e,t,n=[]){let r="";for(;t<e.length&&(ue(e[t])||n.includes(e[t]));)r+=e[t++];return r}function Oe(e,t,n,r="$",i=":"){if(""===n)return e;let o=e.indexOf(`${r}${t}`);for(;-1!==o;){if(e[o+t.length+1]===i)if(e[o+t.length+2]===i)e=e.replace(`${r}${t}${i}${i}`,n);else{const a=Be(e,o+t.length+2,["_"]);e=e.replace(`${r}${t}${i}${a}`,n)}else e=e.replace(`${r}${t}`,n);o=e.indexOf(`${r}${t}`,o+n.length)}return e}function De(e,t="$",n=":"){let r=e.indexOf(t);for(;-1!==r;){const i=Be(e,r+1);if(e[r+i.length+1]===n)if(e[r+i.length+2]===n)e=e.replace(`${t}${i}${n}${n}`,"");else{const o=Be(e,r+i.length+2);e=e.replace(`${t}${i}${n}${o}`,o)}r=e.indexOf(t,r+1)}return e}function Ce(e,t=!0){const n=Object.entries(e).filter(([e,t])=>null!=t).map(([e,t])=>`${e}=${encodeURIComponent(t)}`).join("&");return n?(t?"?":"")+n:""}function $e(e){return String(Math.floor(e)).padStart(2,"0")}function ze(e){const t=Math.floor(e/36e5);e%=36e5;const n=Math.floor(e/6e4);e%=6e4;const r=Math.floor(e/1e3);return t?`${$e(t)}:${$e(n)}:${$e(r)}`:`${$e(n)}:${$e(r)}`}function Fe(e){return Math.floor((A(e)?e.getTime():e)/864e5)}const Pe={today:(e,t)=>$e(e)+":"+$e(t),yesterday:()=>"Yesterday",monday:()=>"Mon",tuesday:()=>"Tue",wednesday:()=>"Wed",thursday:()=>"Thu",friday:()=>"Fri",saturday:()=>"Sat",sunday:()=>"Sun",weeks:e=>`${e}w`},Ue={now:()=>"A few seconds",seconds:e=>`${e} seconds`,minutes:e=>`${e} minutes`,hours:e=>`${e} hours`,days:e=>`${e} days`,weeks:e=>`${e} weeks`};function qe(t,n){const r=n?.now??Date.now(),i=n?.labels||Ue;let o=(r-(e.Types.isDate(t)?t.getTime():t))/1e3;return o<10?i.now():o<120?i.seconds(Math.floor(o)):(o/=60,o<120?i.minutes(Math.floor(o)):(o/=60,o<48?i.hours(Math.floor(o)):(o/=24,o<14?i.days(Math.floor(o)):(o/=7,i.weeks(Math.floor(o))))))}const Ne={},Me={s:1e3,m:6e4,h:36e5,d:864e5},_e={0:"sunday",1:"monday",2:"tuesday",3:"wednesday",4:"thursday",5:"friday",6:"saturday"};function Ve(e){return{zeroBasedIndex:e,day:_e[e]}}function Le(e){return Ve(e.getDay())}const je={ms:1,milli:1,millis:1,millisecond:1,milliseconds:1,s:1e3,sec:1e3,second:1e3,seconds:1e3,m:6e4,min:6e4,minute:6e4,minutes:6e4,h:36e5,hour:36e5,hours:36e5,d:864e5,day:864e5,days:864e5,w:6048e5,week:6048e5,weeks:6048e5,month:2592e6,months:2592e6,y:31536e6,year:31536e6,years:31536e6},Ge={b:0,byte:0,bytes:0,kb:1,kilobyte:1,kilobytes:1,mb:2,megabyte:2,megabytes:2,gb:3,gigabyte:3,gigabytes:3,tb:4,terabyte:4,terabytes:4},Ke=new Map;function He(e,t=!1){e=e.filter(e=>e),t&&v(e[1])&&(e[1]="../"+e[1]);let n="";v(e[0])&&e[0].includes("://")&&(n=J(e[0],"://")??"",e[0]=X(e[0],"://")??"");const r=e.map(e=>String(e)).flatMap(e=>e.split("/")),i=[];for(let e=0;e<r.length;e++)"."!==r[e]&&(".."===r[e]?(!n||i.length>1)&&i.pop():i.push(r[e]));return(n?n+"://":"")+i.join("/").replaceAll(/\/{2,}/g,"/")}function We(e){const t=Object.keys(e).sort((e,t)=>e.localeCompare(t)),n={};for(const r of t)n[r]=Je(e[r]);return n}function Ze(e){const t=[];return e.sort((e,t)=>JSON.stringify(Je(e)).localeCompare(JSON.stringify(Je(t)))).forEach(e=>t.push(Je(e))),t}function Je(e){return Array.isArray(e)?Ze(e):m(e)?We(e):e}function Xe(e,t){return JSON.stringify(Je(e))===JSON.stringify(Je(t))}function Ye(e){const t=Object.keys(e);return t[Math.floor(Math.random()*t.length)]}const Qe=[1e3,1e6,1e9,1e12,1e15,1e18,1e21,1e24,1e27,1e30,1e9,1e16,1e18,1e18,1e18,1e33],et=["thousand","million","billion","trillion","quadrillion","quintillion","sextillion","septillion","octillion","nonillion","gwei","bzz","btc","eth","dai","decillion"],tt=["K","M","B","T","Qa","Qi","Sx","Sp","O","N","gwei","bzz","eth","btc","dai","D"];function nt(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeNumber got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim(),r=tt.findIndex(e=>e.toLowerCase()===n.toLowerCase());return-1===r?t:t*Qe[r]}function rt(e,t,n){return e<t?t:e>n?n:e}function it(e,t,n){return e+(n?"["+t+"]":(e.length?".":"")+t)}function ot(e,t,n,r,i){if(!m(t))return t;for(const[o,a]of Object.entries(t)){const t=it(n,o,r);Array.isArray(a)?i?ot(e,a,t,!0,i):e[t]=a.map(e=>ot(Array.isArray(e)?[]:{},e,"",!1,i)):m(a)?ot(e,a,t,!1,i):e[t]=a}return e}function at(e,t){const n={};for(const r of e)n[t(r)]=r;return n}function st(e,t){const n=Math.ceil(e.length/t),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r}function ct(e,t){const n=[],r=Math.ceil(e.length/t);for(let i=0;i<r;i++)n.push(e.slice(i*t,i*t+t));return n}function ut(e,t){return Object.fromEntries(Object.entries(e).sort(t))}function lt(e,t){const n=[];let r=[];return e.forEach((i,o)=>{(0===o||!t(i,e[o-1]))&&(r=[],n.push(r)),r.push(i)}),n}function dt(e,t,n,r=100){if(e.map.has(t)){const n=e.keys.indexOf(t);e.keys.splice(n,1)}if(e.map.set(t,n),e.keys.push(t),e.keys.length>r){const t=e.keys.shift();t&&e.map.delete(t)}}class ht{constructor(e){this.value=e}static of(e){return new ht(e)}static empty(){return new ht(null)}map(e){return new ht(null!==this.value&&void 0!==this.value?e(this.value):null)}mapAsync(e){return null!==this.value&&void 0!==this.value?e(this.value).then(e=>ht.of(e)):Promise.resolve(ht.empty())}ifPresent(e){return null!==this.value&&void 0!==this.value&&e(this.value),this}ifPresentAsync(e){return null!==this.value&&void 0!==this.value?e(this.value).then(()=>this):Promise.resolve(this)}ifAbsent(e){return(null===this.value||void 0===this.value)&&e(),this}ifAbsentAsync(e){return null===this.value||void 0===this.value?e().then(()=>this):Promise.resolve(this)}getOrFallback(e){return this.value??e()}getOrFallbackAsync(e){return null!==this.value&&void 0!==this.value?Promise.resolve(this.value):e()}getOrThrow(){if(null===this.value||void 0===this.value)throw Error("Optional.value is empty");return this.value}}e.Optional=ht,e.Lazy=class{constructor(e){this.supplier=e,this.value=null}get(){return this.value||(this.value=this.supplier()),this.value}},e.AsyncLazy=class{constructor(e){this.supplier=e,this.value=null}async get(){return this.value||(this.value=await this.supplier()),this.value}};class ft{constructor(e){this.value=e,this.children=[]}}function pt(e,t){if(Math.log2(e.length)%1!=0)throw new Error("Array length must be a power of 2");let n=[...e];for(;n.length>1;){const e=[];for(let r=0;r<n.length;r+=2){const i=n[r+1];e.push(t(n[r],i))}n=e}return n[0]}function mt(...e){const t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t);let r=0;return e.forEach(e=>{n.set(e,r),r+=e.length}),n}function gt(e){return 137===e[0]&&80===e[1]&&78===e[2]&&71===e[3]}function yt(e){return 255===e[0]&&216===e[1]}function wt(e){return 87===e[8]&&69===e[9]&&66===e[10]&&80===e[11]}function bt(e,t){const n=new ArrayBuffer(8);return new DataView(n).setBigUint64(0,BigInt(e),"LE"===t),new Uint8Array(n)}function vt(e,t){const n=new Uint8Array(32);let r=e;if("LE"===t){for(let e=0;e<32;e++)n[e]=Number(0xffn&r),r>>=8n;return n}for(let e=31;e>=0;e--)n[e]=Number(0xffn&r),r>>=8n;return n}function xt(e,t){let n=0n;if("LE"===t){for(let t=31;t>=0;t--)n=n<<8n|BigInt(e[t]);return n}for(let t=0;t<32;t++)n=n<<8n|BigInt(e[t]);return n}function Et(e,t){const n=[];for(let r=0;r<e.length;r+=t)n.push(e.subarray(r,r+t));return n}const At=[0,1,0,32898,2147483648,32906,2147483648,2147516416,0,32907,0,2147483649,2147483648,2147516545,2147483648,32777,0,138,0,136,0,2147516425,0,2147483658,0,2147516555,2147483648,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,0,32778,2147483648,2147483658,2147483648,2147516545,2147483648,32896,0,2147483649,2147483648,2147516424];function Rt(e){for(let t=0;t<24;t++){const n=e[0]^e[10]^e[20]^e[30]^e[40],r=e[1]^e[11]^e[21]^e[31]^e[41],i=e[2]^e[12]^e[22]^e[32]^e[42],o=e[3]^e[13]^e[23]^e[33]^e[43],a=e[4]^e[14]^e[24]^e[34]^e[44],s=e[5]^e[15]^e[25]^e[35]^e[45],c=e[6]^e[16]^e[26]^e[36]^e[46],u=e[7]^e[17]^e[27]^e[37]^e[47],l=e[8]^e[18]^e[28]^e[38]^e[48],d=e[9]^e[19]^e[29]^e[39]^e[49],h=l^(i<<1|o>>>31),f=d^(o<<1|i>>>31),p=n^(a<<1|s>>>31),m=r^(s<<1|a>>>31),g=i^(c<<1|u>>>31),y=o^(u<<1|c>>>31),w=a^(l<<1|d>>>31),b=s^(d<<1|l>>>31),v=c^(n<<1|r>>>31),x=u^(r<<1|n>>>31);e[0]^=h,e[1]^=f,e[2]^=p,e[3]^=m,e[4]^=g,e[5]^=y,e[6]^=w,e[7]^=b,e[8]^=v,e[9]^=x,e[10]^=h,e[11]^=f,e[12]^=p,e[13]^=m,e[14]^=g,e[15]^=y,e[16]^=w,e[17]^=b,e[18]^=v,e[19]^=x,e[20]^=h,e[21]^=f,e[22]^=p,e[23]^=m,e[24]^=g,e[25]^=y,e[26]^=w,e[27]^=b,e[28]^=v,e[29]^=x,e[30]^=h,e[31]^=f,e[32]^=p,e[33]^=m,e[34]^=g,e[35]^=y,e[36]^=w,e[37]^=b,e[38]^=v,e[39]^=x,e[40]^=h,e[41]^=f,e[42]^=p,e[43]^=m,e[44]^=g,e[45]^=y,e[46]^=w,e[47]^=b,e[48]^=v,e[49]^=x;const E=e[0],A=e[1],R=e[2]<<1|e[3]>>>31,S=e[3]<<1|e[2]>>>31,I=e[5]<<30|e[4]>>>2,k=e[4]<<30|e[5]>>>2,T=e[6]<<28|e[7]>>>4,B=e[7]<<28|e[6]>>>4,O=e[8]<<27|e[9]>>>5,D=e[9]<<27|e[8]>>>5,C=e[11]<<4|e[10]>>>28,$=e[10]<<4|e[11]>>>28,z=e[13]<<12|e[12]>>>20,F=e[12]<<12|e[13]>>>20,P=e[14]<<6|e[15]>>>26,U=e[15]<<6|e[14]>>>26,q=e[17]<<23|e[16]>>>9,N=e[16]<<23|e[17]>>>9,M=e[18]<<20|e[19]>>>12,_=e[19]<<20|e[18]>>>12,V=e[20]<<3|e[21]>>>29,L=e[21]<<3|e[20]>>>29,j=e[22]<<10|e[23]>>>22,G=e[23]<<10|e[22]>>>22,K=e[25]<<11|e[24]>>>21,H=e[24]<<11|e[25]>>>21,W=e[26]<<25|e[27]>>>7,Z=e[27]<<25|e[26]>>>7,J=e[29]<<7|e[28]>>>25,X=e[28]<<7|e[29]>>>25,Y=e[31]<<9|e[30]>>>23,Q=e[30]<<9|e[31]>>>23,ee=e[33]<<13|e[32]>>>19,te=e[32]<<13|e[33]>>>19,ne=e[34]<<15|e[35]>>>17,re=e[35]<<15|e[34]>>>17,ie=e[36]<<21|e[37]>>>11,oe=e[37]<<21|e[36]>>>11,ae=e[38]<<8|e[39]>>>24,se=e[39]<<8|e[38]>>>24,ce=e[40]<<18|e[41]>>>14,ue=e[41]<<18|e[40]>>>14,le=e[42]<<2|e[43]>>>30,de=e[43]<<2|e[42]>>>30,he=e[45]<<29|e[44]>>>3,fe=e[44]<<29|e[45]>>>3,pe=e[47]<<24|e[46]>>>8,me=e[46]<<24|e[47]>>>8,ge=e[48]<<14|e[49]>>>18,ye=e[49]<<14|e[48]>>>18;e[0]=E^~z&K,e[1]=A^~F&H,e[2]=z^~K&ie,e[3]=F^~H&oe,e[4]=K^~ie&ge,e[5]=H^~oe&ye,e[6]=ie^~ge&E,e[7]=oe^~ye&A,e[8]=ge^~E&z,e[9]=ye^~A&F,e[10]=T^~M&V,e[11]=B^~_&L,e[12]=M^~V&ee,e[13]=_^~L&te,e[14]=V^~ee&he,e[15]=L^~te&fe,e[16]=ee^~he&T,e[17]=te^~fe&B,e[18]=he^~T&M,e[19]=fe^~B&_,e[20]=R^~P&W,e[21]=S^~U&Z,e[22]=P^~W&ae,e[23]=U^~Z&se,e[24]=W^~ae&ce,e[25]=Z^~se&ue,e[26]=ae^~ce&R,e[27]=se^~ue&S,e[28]=ce^~R&P,e[29]=ue^~S&U,e[30]=O^~C&j,e[31]=D^~$&G,e[32]=C^~j&ne,e[33]=$^~G&re,e[34]=j^~ne&pe,e[35]=G^~re&me,e[36]=ne^~pe&O,e[37]=re^~me&D,e[38]=pe^~O&C,e[39]=me^~D&$,e[40]=I^~q&J,e[41]=k^~N&X,e[42]=q^~J&Y,e[43]=N^~X&Q,e[44]=J^~Y&le,e[45]=X^~Q&de,e[46]=Y^~le&I,e[47]=Q^~de&k,e[48]=le^~I&q,e[49]=de^~k&N,e[0]^=At[2*t],e[1]^=At[2*t+1]}}function St(e){const t=[];for(let n=0;n<e.length;n+=4)t.push(e[n]|e[n+1]<<8|e[n+2]<<16|e[n+3]<<24);return t}function It(e,t){if(!e.length){const e=new Uint8Array(136);return e[0]=t,e[135]=128,[St(e)]}const n=Et(e,136),r=n[n.length-1];if(r.length<136){const e=new Uint8Array(136);e.set(r),e[r.length]=t,e[135]|=128,n[n.length-1]=e}if(136===r.length){const e=new Uint8Array(136);e[0]=t,e[135]=128,n.push(e)}return n.map(St)}function kt(e,t){for(const n of t){for(let t=0;t<34;t+=2)e[t]^=n[t+1],e[t+1]^=n[t];Rt(e)}return e}function Tt(e){return new Uint8Array([e[1],e[1]>>-24,e[1]>>-16,e[1]>>-8,e[0],e[0]>>8,e[0]>>16,e[0]>>24,e[3],e[3]>>-24,e[3]>>-16,e[3]>>-8,e[2],e[2]>>8,e[2]>>16,e[2]>>24,e[5],e[5]>>-24,e[5]>>-16,e[5]>>-8,e[4],e[4]>>8,e[4]>>16,e[4]>>24,e[7],e[7]>>-24,e[7]>>-16,e[7]>>-8,e[6],e[6]>>8,e[6]>>16,e[6]>>24])}function Bt(e){return Tt(kt(new Array(50).fill(0),It(e,1)))}function Ot(e,t,n=0){if(e.length>=t)return e;const r=new Uint8Array(t);return r.fill(n),r.set(e,t-e.length),r}function Dt(e,t,n=0){if(e.length>=t)return e;const r=new Uint8Array(t);return r.fill(n),r.set(e,0),r}function Ct(e,t){return(e%t+t)%t}function $t(e,t){e=Ct(e,t);let[n,r]=[0n,1n],[i,o]=[t,e];for(;0n!==o;){const e=i/o;[n,r]=[r,n-e*r],[i,o]=[o,i-e*o]}if(i>1n)throw new Error("a is not invertible");return n<0n&&(n+=t),n}function zt(e,t){return 0n===Ct(e,t)?0n:t%4n==3n?function(e,t,n){let r=1n;for(e=Ct(e,n);t>0;)t%2n==1n&&(r=Ct(r*e,n)),e=Ct(e*e,n),t/=2n;return r}(e,(t+1n)/4n,t):null}const Ft=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,Pt=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,Ut=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,qt=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n;function Nt(e,t,n){if(0n===t)return[0n,0n];const r=Ct(3n*e*e*$t(2n*t,n),n),i=Ct(r*r-2n*e,n);return[i,Ct(r*(e-i)-t,n)]}function Mt(e,t,n,r,i){if(0n===e&&0n===t)return[n,r];if(0n===n&&0n===r)return[e,t];if(e===n&&t===Ct(-r,i))return[0n,0n];if(e===n&&t===r)return Nt(e,t,i);const o=Ct((r-t)*$t(n-e,i),i),a=Ct(o*o-e-n,i);return[a,Ct(o*(e-a)-t,i)]}function _t(e,t,n,r){let i=[0n,0n],o=[e,t];const a=n.toString(2);for(const e of a)"0"===e?(o=Mt(i[0],i[1],o[0],o[1],r),i=Nt(i[0],i[1],r)):(i=Mt(i[0],i[1],o[0],o[1],r),o=Nt(o[0],o[1],r));return i}function Vt(e,t,n){if(t<=0n||t>=Pt)throw new Error("Invalid private key");if(n||(n=Ct(xt(Bt(mt(Bt(vt(t,"BE")),vt(e,"BE"))),"BE"),Pt)),n<=0n||n>=Pt)throw new Error("Invalid nonce");const r=Ct(e,Pt),i=_t(Ut,qt,n,Ft),o=Ct(i[0],Pt);let a=Ct((r+Ct(o,Pt)*t)*$t(n,Pt),Pt);if(0n===o||0n===a)throw new Error("Invalid r or s value");let s=i[1]%2n==0n?27n:28n;return a>Pt/2n&&(a=Pt-a,s=27n===s?28n:27n),[o,a,s]}class Lt{constructor(e){this.cursor=0,this.buffer=e}read(e){const t=this.buffer.subarray(this.cursor,this.cursor+e);return this.cursor+=e,t}max(){return this.buffer.length-this.cursor}}e.Uint8ArrayReader=Lt;class jt{constructor(e){this.buffer=e,this.cursor=0}write(e){const t=Math.min(this.max(),e.max());return this.buffer.set(e.read(t),this.cursor),this.cursor+=t,t}max(){return this.buffer.length-this.cursor}}e.Uint8ArrayWriter=jt;class Gt{constructor(e,t=0n){this.span=t,this.writer=new jt(new Uint8Array(e))}build(){return mt(bt(this.span,"LE"),this.writer.buffer)}hash(){const e=pt(Et(this.writer.buffer,32),(e,t)=>Gt.hashFunction(mt(e,t)));return Gt.hashFunction(mt(bt(this.span,"LE"),e))}}e.Chunk=Gt,Gt.hashFunction=Bt;class Kt{constructor(e,t=4096){this.counters=[1],this.capacity=t,this.chunks=[new Gt(t)],this.onChunk=e}static async root(e,n=4096){const r=new t(t.NOOP,n);return await r.append(e),r.finalize()}async append(e,t=0,n=0n){const r=new Lt(e);for(;r.max()>0;){0===this.chunks[t].writer.max()&&await this.elevate(t);const e=this.chunks[t].writer.write(r);n?this.chunks[t].span+=n:this.chunks[0].span+=BigInt(e)}}async elevate(e){this.counters[e]=++this.counters[e]%(this.capacity/32),this.chunks[e+1]||(this.chunks.push(new Gt(this.capacity)),this.counters.push(1)),await this.append(this.chunks[e].hash(),e+1,this.chunks[e].span),await this.onChunk(this.chunks[e]),this.chunks[e]=new Gt(this.capacity)}async finalize(e=0){return this.chunks[e+1]?1===this.counters[e]?(await this.elevate(e+1),this.chunks[e+1]=this.chunks[e],this.finalize(e+1)):(await this.elevate(e),this.finalize(e+1)):(await this.onChunk(this.chunks[e]),this.chunks[e])}}e.MerkleTree=Kt,t=Kt,Kt.NOOP=async e=>{};class Ht{constructor(e,t){if(t<0)throw Error("Scale must be non-negative");this.value=BigInt(e),this.scale=t}static cast(e){if(!e)throw Error("Cannot cast falsy value to FixedPointNumber");if(e instanceof Ht)return e;const t=_(e.value),n=P(e.scale);return new Ht(t,n)}static fromDecimalString(e,t){/e\-\d+$/i.test(e)&&(e=parseFloat(e).toFixed(t));let[n,r]=e.split(".");return r=(r||"").padEnd(t,"0").slice(0,t),new Ht(BigInt(n+r),t)}static fromFloat(e,t){return Ht.fromDecimalString(e.toString(),t)}add(e){return this.assertSameScale(e),new Ht(this.value+e.value,this.scale)}subtract(e){return this.assertSameScale(e),new Ht(this.value-e.value,this.scale)}multiply(e){return new Ht(this.value*e,this.scale)}divmod(e){if(0n===e)throw new Error("Division by zero is not allowed");const t=this.value/e,n=this.value%e;return[new Ht(t,this.scale),new Ht(n,this.scale)]}exchange(e,t,n){if("*"===e){const e=this.value*t.value/10n**BigInt(this.scale);return new Ht(e,n)}this.assertSameScale(t);const r=this.value*10n**BigInt(n)/t.value;return new Ht(r,n)}compare(e){return this.assertSameScale(e),this.value>e.value?1:this.value<e.value?-1:0}toDecimalString(){if(0===this.scale)return this.value.toString();const e=this.value.toString();return`${e.slice(0,-this.scale)||"0"}.${e.slice(-this.scale).padStart(this.scale,"0")}`}toString(){return this.value.toString()}toJSON(){return this.toString()}toFloat(){return parseFloat(this.toDecimalString())}assertSameScale(e){if(this.scale!==e.scale)throw new Error(`Scale mismatch: expected ${this.scale}, but got ${e.scale}`)}}function Wt(e,t,n,r){const i=e.findIndex(e=>e===`--${t}`||e.startsWith(`--${t}=`)),o=e[i];if(!o)return(n||{})[r||t||""]||null;if(o.includes("="))return o.split("=")[1];const a=e[i+1];return a&&!a.startsWith("-")?a:(n||{})[r||t||""]||null}function Zt(e,t,n,r){const i=Wt(e,t,n,r);if(!i)throw new Error(`Missing argument ${t}`);return i}function Jt(e,t){const n=e[t];e.splice(t,1),e.unshift(n)}function Xt(e,t){return{x:e.x+t.x,y:e.y+t.y}}function Yt(e,t){return{x:e.x*t,y:e.y*t}}function Qt(e,t,n){return{x:e.x+Math.cos(t)*n,y:e.y+Math.sin(t)*n}}function en(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function tn(e,t,n="row-first"){const r=[];if("column-first"===n)for(let n=0;n<e.length;n++)for(let i=0;i<e[0].length;i++)t(n,i)&&r.push({x:n,y:i});else for(let n=0;n<e[0].length;n++)for(let i=0;i<e.length;i++)t(i,n)&&r.push({x:i,y:n});return r}function nn(e,t,n){return!e[t-1]?.[n]}function rn(e,t,n){return!e[t+1]?.[n]}function on(e,t,n){return!e[t][n-1]}function an(e,t,n){return!e[t][n+1]}function sn(e,t,n){const r=[];return e[t][n]?function(e,t,n){return e[t+1]?.[n]&&e[t-1]?.[n]&&!e[t][n-1]&&!e[t][n+1]}(e,t,n)||function(e,t,n){return e[t][n+1]&&e[t][n-1]&&!e[t-1]?.[n]&&!e[t+1]?.[n]}(e,t,n)?[]:(!e[t-1]?.[n-1]&&nn(e,t,n)&&on(e,t,n)&&r.push({x:t,y:n}),!e[t+1]?.[n-1]&&rn(e,t,n)&&on(e,t,n)&&r.push({x:t+1,y:n}),!e[t-1]?.[n+1]&&nn(e,t,n)&&an(e,t,n)&&r.push({x:t,y:n+1}),!e[t+1]?.[n+1]&&rn(e,t,n)&&an(e,t,n)&&r.push({x:t+1,y:n+1}),r):(e[t-1]?.[n]&&e[t][n-1]&&r.push({x:t,y:n}),e[t+1]?.[n]&&e[t][n-1]&&r.push({x:t+1,y:n}),e[t-1]?.[n]&&e[t][n+1]&&r.push({x:t,y:n+1}),e[t+1]?.[n]&&e[t][n+1]&&r.push({x:t+1,y:n+1}),r)}function cn(e,t){return t.map(t=>function(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}(e,t)).sort((e,t)=>e-t)}function un(e,t,n,r){const i=(r.y-n.y)*(t.x-e.x)-(r.x-n.x)*(t.y-e.y);if(0===i)return null;let o=e.y-n.y,a=e.x-n.x;const s=(r.x-n.x)*o-(r.y-n.y)*a,c=(t.x-e.x)*o-(t.y-e.y)*a;return o=s/i,a=c/i,o>0&&o<1&&a>0&&a<1?{x:e.x+o*(t.x-e.x),y:e.y+o*(t.y-e.y)}:null}function ln(e,t,n){const r=[],i=Qt(e,n,1e4);for(const n of t){const t=un(e,i,n.start,n.end);t&&r.push(t)}return r.length?r.reduce((t,n)=>en(e,n)<en(e,t)?n:t):null}e.FixedPointNumber=Ht;class dn{constructor(){this.subscribers=[]}subscribe(e){return this.subscribers.push(e),()=>{this.subscribers=this.subscribers.filter(t=>t!==e)}}publish(e){this.subscribers.forEach(t=>t(e))}clear(){this.subscribers=[]}getSubscriberCount(){return this.subscribers.length}}e.PubSubChannel=dn,e.AsyncQueue=class{constructor(e,t){this.queue=[],this.running=0,this.onProcessed=new dn,this.onDrained=new dn,this.concurrency=e,this.capacity=t}process(){if(this.running>=this.concurrency)return;const e=this.queue.shift();e&&(this.running++,e().finally(()=>{this.running--,this.process(),this.onProcessed.publish(),0===this.running&&this.onDrained.publish()}))}enqueue(e){if(this.queue.length<this.capacity)return this.queue.push(e),this.process(),Promise.resolve();if(this.onProcessed.getSubscriberCount())throw Error("Queue capacity is full");return new Promise(t=>{this.onProcessed.subscribe(()=>{this.queue.length<this.capacity&&(this.queue.push(e),this.process(),this.onProcessed.clear(),t())})})}drain(){if(0===this.running)return Promise.resolve();if(this.onDrained.getSubscriberCount())throw Error("Already draining");return new Promise(e=>{this.onDrained.subscribe(()=>{this.onDrained.clear(),e()})})}};class hn{constructor(){this.forks=new Map}insert(e,t){if(0===e.length)return void(this.handler=t);const n=e[0];let r,i=n;if(n.startsWith(":")&&(i=":",r=n.slice(1)),!this.forks.has(i)){const e=new hn;r&&(e.variableName=r),this.forks.set(i,e)}this.forks.get(i).insert(e.slice(1),t)}async handle(e,t,n,r){if(0===e.length)return!!this.handler&&(await this.handler(t,n,r),!0);const i=e[0],o=this.forks.get(i);if(o)return o.handle(e.slice(1),t,n,r);const a=this.forks.get(":");if(a)return a.variableName&&r.set(a.variableName,decodeURIComponent(i)),a.handle(e.slice(1),t,n,r);const s=this.forks.get("*");return!!s&&(r.set("wildcard",e.join("/")),!!s.handler&&(await s.handler(t,n,r),!0))}}e.TrieRouter=hn,e.RollingValueProvider=class{constructor(e){this.index=0,this.values=e}current(){return this.values[this.index]}next(){return this.index=(this.index+1)%this.values.length,this.values[this.index]}},e.Solver=class{constructor(){this.status="pending",this.steps=[],this.onStatusChange=async()=>{},this.onStepChange=async()=>{},this.onFinish=async()=>{},this.onError=async()=>{},this.context=new Map}getStatus(){return this.status}createInitialState(){return Object.fromEntries(this.steps.map(e=>[e.name,"pending"]))}setHooks(e){e.onStatusChange&&(this.onStatusChange=e.onStatusChange),e.onStepChange&&(this.onStepChange=e.onStepChange),e.onFinish&&(this.onFinish=e.onFinish),e.onError&&(this.onError=e.onError)}addStep(e){if(this.steps.find(t=>t.name===e.name))throw Error(`Step with name ${e.name} already exists`);this.steps.push(e)}async execute(){if("pending"!==this.status)throw Error(`Cannot execute solver in status ${this.status}`);this.status="in-progress",await this.onStatusChange(this.status);let e=this.createInitialState();for(const t of this.steps)try{if(t.transientSkipStepName){const n=e[t.transientSkipStepName];if("skipped"===n||"failed"===n){e={...e,[t.name]:"skipped"},await this.onStepChange(e);continue}}if(t.precondition&&!await t.precondition(this.context)){e={...e,[t.name]:"skipped"},await this.onStepChange(e);continue}e={...e,[t.name]:"in-progress"},await this.onStepChange(e);for(let e=0;"retry"===await t.action(this.context,e);e++);e={...e,[t.name]:"completed"},await this.onStepChange(e)}catch(n){throw e={...e,[t.name]:"failed"},this.status="failed",await this.onStatusChange(this.status),await this.onStepChange(e),await this.onError(n),n}return this.status="completed",await this.onStatusChange(this.status),await this.onFinish(),this.context}},e.Lock=class{constructor(e){this.queryFunction=e.queryFunction,this.lockFunction=e.lockFunction,this.unlockFunction=e.unlockFunction,this.timeoutMillis=e.timeoutMillis}async couldLock(){const e=await this.queryFunction();try{const t=U(e);if(Date.now()<t+this.timeoutMillis)return new Date(t+this.timeoutMillis)}catch{}return await this.lockFunction(Date.now().toString()),!0}async unlock(){await this.unlockFunction()}},e.Binary={hexToUint8Array:function(e){(e.startsWith("0x")||e.startsWith("0X"))&&(e=e.slice(2));const t=e.length/2,n=new Uint8Array(t);for(let r=0;r<t;r++){const t=parseInt(e.slice(2*r,2*r+2),16);n[r]=t}return n},uint8ArrayToHex:function(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")},binaryToUint8Array:function(e){const t=Math.ceil(e.length/8),n=new Uint8Array(t);for(let r=0;r<t;r++){const t=parseInt(e.slice(8*r,8*r+8),2);n[r]=t}return n},uint8ArrayToBinary:function(e){return Array.from(e).map(e=>e.toString(2).padStart(8,"0")).join("")},base64ToUint8Array:function(e){return Ae(e,xe)},uint8ArrayToBase64:function(e){return Re(e,xe)},base32ToUint8Array:function(e){return Ae(e,Ee)},uint8ArrayToBase32:function(e){return Re(e,Ee)},log2Reduce:pt,partition:Et,concatBytes:mt,numberToUint8:function(e){return new Uint8Array([e])},uint8ToNumber:function(e){return e[0]},numberToUint16:function(e,t){const n=new ArrayBuffer(2);return new DataView(n).setUint16(0,e,"LE"===t),new Uint8Array(n)},uint16ToNumber:function(e,t){return new DataView(e.buffer).getUint16(e.byteOffset,"LE"===t)},numberToUint32:function(e,t){const n=new ArrayBuffer(4);return new DataView(n).setUint32(0,e,"LE"===t),new Uint8Array(n)},uint32ToNumber:function(e,t){return new DataView(e.buffer).getUint32(e.byteOffset,"LE"===t)},numberToUint64:bt,uint64ToNumber:function(e,t){return new DataView(e.buffer).getBigUint64(e.byteOffset,"LE"===t)},numberToUint256:vt,uint256ToNumber:xt,sliceBytes:function(e,t){const n=[];let r=0;for(const i of t)n.push(e.subarray(r,r+i)),r+=i;return n},keccak256:Bt,sha3_256:function(e){return Tt(kt(new Array(50).fill(0),It(e,6)))},proximity:function(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e[r]^t[r];for(let e=0;e<8;e++)if(n>>7-e&1)return 8*r+e}return 8*Math.min(e.length,t.length)},commonPrefix:function(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++)if(e[r]!==t[r])return e.subarray(0,r);return e.subarray(0,n)},setBit:function(e,t,n,r){const i=Math.floor(t/8),o=t%8;1===n?e[i]|=1<<("BE"===r?7-o:o):e[i]&=~(1<<("BE"===r?7-o:o))},getBit:function(e,t,n){const r=t%8;return e[Math.floor(t/8)]>>("BE"===n?7-r:r)&1},indexOf:function(e,t,n=0){for(let r=n;r<e.length;r++)for(let n=0;n<t.length&&e[r+n]===t[n];n++)if(n===t.length-1)return r;return-1},equals:function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},padStart:Ot,padStartToMultiple:function(e,t,n=0){const r=e.length%t;return 0===r?e:Ot(e,e.length+t-r,n)},padEnd:Dt,padEndToMultiple:function(e,t,n=0){const r=e.length%t;return 0===r?e:Dt(e,e.length+t-r,n)},xorCypher:function(e,t){const n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r%t.length];return n},isUtf8:function(e){for(let t=0;t<e.length;t++){const n=e[t];if(!(n<128))if(192==(224&n)){if(t+1>=e.length||128!=(192&e[t+1]))return!1;t+=1}else if(224==(240&n)){if(t+2>=e.length||128!=(192&e[t+1])||128!=(192&e[t+2]))return!1;t+=2}else{if(240!=(248&n))return!1;if(t+3>=e.length||128!=(192&e[t+1])||128!=(192&e[t+2])||128!=(192&e[t+3]))return!1;t+=3}}return!0}},e.Elliptic={privateKeyToPublicKey:function(e){if(e<=0n||e>=Pt)throw new Error("Invalid private key");return _t(Ut,qt,e,Ft)},compressPublicKey:function(e){const t=e[1]%2n==0n?2:3;return new Uint8Array([t,...vt(e[0],"BE")])},publicKeyFromCompressed:function(e){if(33!==e.length||2!==e[0]&&3!==e[0])throw new Error("Invalid compressed public key");const t=xt(e.slice(1),"BE"),n=zt(Ct(t**3n+7n,Ft),Ft);if(!n)throw Error("Invalid x: does not correspond to a valid curve point");const r=Ct(-n,Ft),i=n%2n==0n;return[t,2===e[0]?i?n:r:i?r:n]},publicKeyToAddress:function(e){const t=new Uint8Array(20),n=Bt(mt(vt(e[0],"BE"),vt(e[1],"BE")));return t.set(n.subarray(12)),t},signMessage:function(e,t,n){return Vt(xt(Bt(e),"BE"),t,n)},signHash:Vt,verifySignature:function(e,t,n,r){const i=Ct(xt(Bt(e),"BE"),Pt),o=$t(r,Pt),a=Ct(i*o,Pt),s=Ct(n*o,Pt),c=_t(Ut,qt,a,Ft),u=_t(t[0],t[1],s,Ft);return n===Ct(Mt(c[0],c[1],u[0],u[1],Ft)[0],Pt)},recoverPublicKey:function(e,t,n,r){const i=zt(Ct(t**3n+7n,Ft),Ft);if(!i)throw new Error("Invalid r: does not correspond to a valid curve point");const o=i%2n==(27n===r?0n:1n)?i:Ft-i,a=Ct(xt(Bt(e),"BE"),Pt),s=_t(t,o,n,Ft),c=_t(Ut,qt,a,Ft),u=Mt(s[0],s[1],c[0],Ct(-c[1],Ft),Ft);return _t(u[0],u[1],$t(t,Pt),Ft)},checksumEncode:function(t){const n=e.Binary.uint8ArrayToHex(t),r=e.Binary.uint8ArrayToHex(e.Binary.keccak256(new Uint8Array([...n].map(e=>e.charCodeAt(0)))));let i="0x";for(let e=0;e<n.length;e++)parseInt(r[e],16)>7?i+=n[e].toUpperCase():i+=n[e];return i}},e.Random={intBetween:a,floatBetween:function(e,t,n=Math.random){return n()*(t-e)+e},chance:c,signed:function(){return 2*Math.random()-1},makeSeededRng:function(e){let t=e,n=3405648695,r=3735928559;return function(){return t+=n,n^=t<<7,t*=r,r^=t<<13,t^=n^r,(t>>>0)/4294967296}},point:function(e,t,n,r=Math.random){let i,o;do{i=a(0,e-1,r),o=a(0,t-1,r)}while(n&&s(n,i,o));return[i,o]},procs:function(e,t=Math.random){const n=Math.floor(e);return c(e-n,t)?n+1:n}},e.Arrays={countUnique:function(e,t,n,r,i){const o=t?e.map(t):e,a={};for(const e of o)a[e]=(a[e]||0)+1;const s=r?ut(a,i?(e,t)=>e[1]-t[1]:(e,t)=>t[1]-e[1]):a;return n?Object.keys(s):s},makeUnique:function(e,t){return Object.values(at(e,t))},splitBySize:function(e,t){const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n},splitByCount:st,index:at,indexCollection:function(e,t){const n={};for(const r of e){const e=t(r);n[e]||(n[e]=[]),n[e].push(r)}return n},onlyOrThrow:function(e){if(1===e.length)return e[0];throw Error(`Expected exactly one element, actual: ${e.length}`)},onlyOrNull:function(e){return 1===e.length?e[0]:null},firstOrThrow:function(e){if(!e.length)throw Error("Received empty array");return e[0]},firstOrNull:function(e){return e.length>0?e[0]:null},shuffle:i,initialize:function(e,t){const n=[];for(let r=0;r<e;r++)n.push(t(r));return n},initialize2D:function(e,t,n){const r=[];for(let i=0;i<e;i++){r.push([]);for(let e=0;e<t;e++)r[i].push(n)}return r},rotate2D:function(e){const t=[];for(let n=0;n<e[0].length;n++){t.push([]);for(let r=0;r<e.length;r++)t[n].push(e[r][n])}return t},containsShape:function(e,t,n,r){if(n<0||r<0||r+t[0].length>e[0].length||n+t.length>e.length)return!1;for(let i=0;i<t.length;i++)for(let o=0;o<t[i].length;o++)if(void 0!==t[i][o]&&e[n+i][r+o]!==t[i][o])return!1;return!0},glue:function(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e[r]),r<e.length-1&&(b(t)?n.push(t()):n.push(t));return n},pluck:function(e,t){return e.map(e=>e[t])},pick:u,pickMany:function(e,t,n=Math.random){if(t>e.length)throw new Error(`Count (${t}) is greater than array length (${e.length})`);return o(e,t,n).map(t=>e[t])},pickManyUnique:function(e,t,n,r=Math.random){if(t>e.length)throw new Error(`Count (${t}) is greater than array length (${e.length})`);const i=[];for(;i.length<t;){const t=u(e,r);i.some(e=>n(e,t))||i.push(t)}return i},pickWeighted:function(e,t,n){if(void 0===n&&(n=Math.random()),e.length!==t.length)throw new Error("Array length mismatch");let r=t.reduce((e,t)=>e+t,0);const i=n*r;for(let n=0;n<e.length-1;n++)if(r-=t[n],i>=r)return e[n];return l(e)},pickRandomIndices:o,pickGuaranteed:function(t,n,r,o,a,s=Math.random){const c=t.filter(e=>e!==n&&e!==r),u=[];for(null!==n&&u.push(n);c.length&&u.length<o;){const t=e.Random.intBetween(0,c.length-1,s);a(c[t],u)&&u.push(c[t]),c.splice(t,1)}return i(u,s),{values:u,indexOfGuaranteed:null!==n?u.indexOf(n):-1}},last:l,pipe:d,makePipe:function(e,t){return n=>d(n,e,t)},sortWeighted:function(e,t,n=Math.random){const r=t.map(e=>n()*e),i=[];for(let t=0;t<e.length;t++)i.push([e[t],r[t]]);return i.sort((e,t)=>t[1]-e[1]).map(e=>e[0])},pushAll:G,unshiftAll:function(e,t){Array.prototype.unshift.apply(e,t)},filterAndRemove:function(e,t){const n=[];for(let r=e.length-1;r>=0;r--)t(e[r])&&n.push(e.splice(r,1)[0]);return n},merge:function(e,t){const n=Object.keys(t);for(const r of n)Array.isArray(t[r])&&Array.isArray(e[r])&&G(e[r],t[r])},empty:function(e){return e.splice(0,e.length),e},pushToBucket:function(e,t,n){e[t]||(e[t]=[]),e[t].push(n)},unshiftAndLimit:function(e,t,n){for(e.unshift(t);e.length>n;)e.pop()},atRolling:function(e,t){let n=t%e.length;return n<0&&(n+=e.length),e[n]},group:lt,createOscillator:function(e){let t=0;return{next:()=>e[t++%e.length]}},organiseWithLimits:function(e,t,n,r,i){const o={};for(const e of Object.keys(t))o[e]=[];o[r]=[],i&&(e=e.sort(i));for(const i of e){const e=i[n],a=t[e]?e:r;o[a].length>=t[a]?o[r].push(i):o[a].push(i)}return o},tickPlaybook:function(e){if(0===e.length)return null;const t=e[0];return t.ttlMax?--t.ttl<=0&&e.shift():t.ttlMax=t.ttl,{progress:(t.ttlMax-t.ttl)/t.ttlMax,data:t.data}},getArgument:Wt,getBooleanArgument:function(e,t,n,r){const i=e.some(e=>e.endsWith("-"+t)),o=Wt(e,t,n,r);if(!o&&i)return!0;if(!o&&!i)return null;if(["true","1","yes","y","on"].includes(o.toLowerCase()))return!0;if(["false","0","no","n","off"].includes(o.toLowerCase()))return!1;throw Error(`Invalid boolean argument ${t}: ${o}`)},getNumberArgument:function(e,t,n,r){const i=Wt(e,t,n,r);if(!i)return null;try{return nt(i)}catch{throw new Error(`Invalid number argument ${t}: ${i}`)}},requireStringArgument:Zt,requireNumberArgument:function(e,t,n,r){const i=Zt(e,t,n,r);try{return nt(i)}catch{throw new Error(`Invalid argument ${t}: ${i}`)}},bringToFront:function(e,t){const n=[...e];return Jt(n,t),n},bringToFrontInPlace:Jt,findInstance:function(e,t){const n=e.find(e=>e instanceof t);return ht.of(n)},filterInstances:function(e,t){return e.filter(e=>e instanceof t)},interleave:function(e,t){const n=[],r=Math.max(e.length,t.length);for(let i=0;i<r;i++)e[i]&&n.push(e[i]),t[i]&&n.push(t[i]);return n},toggle:function(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]},createHierarchy:function(e,t,n,r,i=!1){const o=new Map,a=[];e.forEach(e=>{const n=new ft(e);o.set(e[t],n)}),e.forEach(e=>{const r=o.get(e[t]);if(!r)return;const i=e[n];if(i){const e=o.get(i);e&&e.children.push(r)}else a.push(r)});const s=e=>{e.children.sort((e,t)=>{const n=e.value[r],o=t.value[r];return i?o-n:n-o}),e.children.forEach(s)};return a.forEach(s),a},multicall:function(e){return()=>e.forEach(e=>e())},maxBy:function(e,t){return e.reduce((e,n)=>t(e)>t(n)?e:n)}},e.System={sleepMillis:r,forever:async function(e,t,n){for(;;){try{await e()}catch(e){n&&n("Error in forever",e)}await r(t)}},scheduleMany:function(e,t){for(let n=0;n<e.length;n++){const r=e[n],i=t[n],o=Math.max(0,i.getTime()-Date.now());setTimeout(r,o)}},waitFor:async function(e,t){let n=t.requiredConsecutivePasses||1,i=0;for(let o=0;o<t.attempts;o++){try{if(await e()){if(i++,i>=n)return}else i=0}catch{i=0}o<t.attempts-1&&await r(t.waitMillis)}throw Error("Timed out waiting for predicate")},expandError:function(e,t){if(v(e))return e;const n=Object.keys(e);e.message&&!n.includes("message")&&n.push("message");const r=n.map(t=>`${t}: ${e[t]}`).join("; ");return t&&e.stack?r+"\n"+e.stack:r},runAndSetInterval:function(e,t){e();const n=setInterval(()=>{e()},t);return()=>clearInterval(n)},whereAmI:function(){const e=globalThis.process;return e?!0===e.browser?"browser":"node":"browser"},withRetries:async function(e,t,n,i,o,a){let s=null;for(let c=0;c<=t;c++)try{return await e()}catch(e){if(s=e,c===t)break;const u=n+c/(t-1)*(i-n);o&&o("Error in withRetries, retrying",{attempt:c+1,allowedFailures:t,delayMillis:u,error:e}),a&&a(),await r(u)}throw s}},e.Numbers={make:nt,sum:function(e){return e.reduce((e,t)=>e+t,0)},average:function(e){return e.reduce((e,t)=>e+t,0)/e.length},median:function(e){const t=[...e].sort((e,t)=>e-t),n=Math.floor(t.length/2);return t.length%2==0?(t[n]+t[n-1])/2:t[n]},getDistanceFromMidpoint:function(e,t){return e-(t-1)/2},clamp:rt,range:K,interpolate:function(e,t,n){return e+(t-e)*n},createSequence:function(){let e=0;return{next:()=>e++}},increment:function(e,t,n){const r=e+t;return r>n?n:r},decrement:function(e,t,n){const r=e-t;return r<n?n:r},format:function(e,t){const n=t?.longForm??!1,r=t?.unit?` ${t.unit}`:"",i=n?et:tt,o=t?.precision??1;if(e<Qe[0])return`${e}${r}`;for(let t=0;t<Qe.length-1;t++)if(e<Qe[t+1])return`${(e/Qe[t]).toFixed(o)}${n?" ":""}${i[t]}${r}`;return`${(e/Qe[Qe.length-1]).toFixed(o)}${n?" ":""}${i[Qe.length-1]}${r}`},fromDecimals:function(e,t,n){let r=e.length-t;if(r<=0)return"0."+"0".repeat(-r)+e+(n?" "+n:"");let i=e.substring(0,r);return""===i&&(i="0"),i+"."+e.substring(r)+(n?" "+n:"")},makeStorage:function(e,t=1024){const n=parseFloat(e);if(isNaN(n))throw Error("makeStorage got NaN for input");const r=e.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),i=""===r?0:Ge[r];if(null==i)throw Error(`Unknown unit: "${r}"`);return Math.ceil(n*t**i)},asMegabytes:function(e){return e/1024/1024},convertBytes:function(e,t=1024){return e>=t*t*t*t?(e/t/t/t/t).toFixed(3)+" TB":e>=t*t*t?(e/t/t/t).toFixed(3)+" GB":e>=t*t?(e/t/t).toFixed(3)+" MB":e>=t?(e/t).toFixed(3)+" KB":e+" B"},hexToRgb:function(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e.toLowerCase());if(!t)throw new Error("Invalid hex color: "+e);return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]},rgbToHex:function(e){return"#"+e.map(e=>e.toString(16).padStart(2,"0")).join("")},haversineDistanceToMeters:function(e,t,n,r){const i=e*Math.PI/180,o=n*Math.PI/180,a=(n-e)*Math.PI/180,s=(r-t)*Math.PI/180,c=Math.sin(a/2)*Math.sin(a/2)+Math.cos(i)*Math.cos(o)*Math.sin(s/2)*Math.sin(s/2);return 2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c))*6371e3},roundToNearest:p,formatDistance:function(e){return e>1e3?(e/1e3).toFixed(0)+" km":e>=500?p(e,100)+" m":e>=100?p(e,50)+" m":p(e,10)+" m"},triangularNumber:function(e){return e*(e+1)/2},searchFloat:function(e){const t=e.match(/-?\d+(\.\d+)?/);if(!t)throw Error("No float found in "+e);return parseFloat(t[0])},binomialSample:function(e,t,n=Math.random){const r=e*t,i=Math.sqrt(e*t*(1-t)),o=(n()+n()+n()+n()+n()+n()-3)*Math.SQRT2,a=Math.round(r+i*o);return Math.max(0,Math.min(e,a))},toSignificantDigits:function(e,t){if(!e.includes("."))return e;if(0===parseFloat(e))return"0";const[n,r]=e.split("."),i=n.replace("-",""),o=i.length;if(o>=t)return n;if("0"!==i){const e=t-o,i=r.slice(0,e);return/[1-9]/.test(i)?`${n}.${i.replace(/0+$/,"")}`:n}const a=t+(r.match(/^0*/)?.[0].length??0);return`${n}.${r.slice(0,a)}`}},e.Promises={raceFulfilled:async function(e){return n(Promise.all(e.map(n)))},invert:n,runInParallelBatches:async function(e,t=1){const n=st(e,t),r=[],i=n.map(async e=>{for(const t of e)r.push(await t())});return await Promise.all(i),r}},e.Dates={getTimestamp:function(e,t){const n=new Date(t?.now||Date.now()),r=t?.labels||Pe,i=A(e)?e:new Date(e);if(Fe(n)===Fe(i))return r.today(i.getUTCHours(),i.getUTCMinutes(),i.getUTCHours()>12);if(Fe(n)-Fe(i)===1)return r.yesterday();const o=Le(i);return Fe(n)-Fe(i)<7?r[o.day]():r.weeks(Math.round((n.getTime()-i.getTime())/6048e5))},getTimeDelta:qe,secondsToHumanTime:function(e,t=Ue){return qe(0,{now:1e3*e,labels:t})},countCycles:function(e,t,n){const r=(n?.now??Date.now())-e;return{cycles:Math.floor(r/t),remaining:t/(n?.precision??1)-Math.ceil(r%t/(n?.precision??1))}},isoDate:function(e){return(e||new Date).toISOString().slice(0,10)},throttle:function(e,t){return(!Ne[e]||Date.now()>Ne[e])&&(Ne[e]=Date.now()+t,!0)},timeSince:function(e,t,n){return t=A(t)?t.getTime():t,((n=n?A(n)?n.getTime():n:Date.now())-t)/Me[e]},dateTimeSlug:function(e){return(e||new Date).toISOString().slice(0,19).replace(/T|:/g,"-")},unixTimestamp:function(e){return Math.ceil((e||Date.now())/1e3)},fromUtcString:function(e){const t=new Date(e);return new Date(t.getTime()-6e4*t.getTimezoneOffset())},fromMillis:function(e){return new Date(e)},getProgress:function(e,t,n,r){r||(r=Date.now());const i=r-e,o=i/t,a=o*n;return{deltaMs:i,progress:t/n,baseTimeMs:o,totalTimeMs:a,remainingTimeMs:a-i}},humanizeTime:ze,humanizeProgress:function(e){return`[${Math.floor(100*e.progress)}%] ${ze(e.deltaMs)} out of ${ze(e.totalTimeMs)} (${ze(e.remainingTimeMs)} left) [${Math.round(e.baseTimeMs)} ms each]`},createTimeDigits:$e,mapDayNumber:Ve,getDayInfoFromDate:Le,getDayInfoFromDateTimeString:function(e){return Le(new Date(e))},seconds:function(e){return 1e3*e},minutes:function(e){return 6e4*e},hours:function(e){return 36e5*e},days:function(e){return 864e5*e},make:function(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeDate got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),r=""===n?1:je[n];if(!r)throw Error(`Unknown unit: "${n}"`);return Math.ceil(t*r)},normalizeTime:function(e){let[t,n]=e.split(":");x(parseInt(t,10))||(t="0"),x(parseInt(n,10))||(n="0");let r=rt(U(t),0,23),i=rt(U(n),0,59);return`${$e(r)}:${$e(i)}`},absoluteDays:Fe},e.Objects={safeParse:function(e){try{return JSON.parse(e)}catch{return null}},deleteDeep:function(e,t){const n=Y(t,"."),r=Q(t,".");if(!n||!r)return;const i=h(e,n);i&&delete i[r]},getDeep:h,setDeep:f,incrementDeep:function(e,t,n=1){const r=h(e,t)||0;return f(e,t,r+n),r},ensureDeep:function(e,t,n){return h(e,t)||f(e,t,n)},replaceDeep:function(e,t,n){const r=h(e,t);if(!r)throw new Error("Key '"+t+"' does not exist.");return f(e,t,n),r},getFirstDeep:function(e,t,n){for(const n of t){const t=h(e,n);if(t)return t}if(n){const t=Object.values(e);if(t.length)return t[0]}return null},deepMergeInPlace:L,deepMerge2:function(e,t){const n={};return L(n,e),L(n,t),n},deepMerge3:function(e,t,n){const r={};return L(r,e),L(r,t),L(r,n),r},mapAllAsync:async function(e,t){const n=[];for(const r of e)n.push(await t(r));return n},cloneWithJson:function(e){return JSON.parse(JSON.stringify(e))},sortObject:We,sortArray:Ze,sortAny:Je,deepEquals:Xe,deepEqualsEvery:function(...e){for(let t=1;t<e.length;t++)if(!Xe(e[t-1],e[t]))return!1;return!0},runOn:function(e,t){return t(e),e},ifPresent:function(e,t){e&&t(e)},zip:j,zipSum:function(e){return j(e,(e,t)=>e+t)},removeEmptyArrays:function(e){for(const t of Object.keys(e))(y(e[t])||Array.isArray(e[t])&&e[t].every(e=>null==e))&&delete e[t];return e},removeEmptyValues:function(e){for(const t of Object.entries(e))(null===t[1]||void 0===t[1]||v(t[1])&&R(t[1]))&&delete e[t[0]];return e},flatten:function(e,t=!1,n){return ot({},e,n||"",!1,t)},unflatten:function e(t){if(!m(t))return t;const n=Array.isArray(t)?[]:{};for(const[r,i]of Object.entries(t))Array.isArray(i)?f(n,r,i.map(t=>e(t))):f(n,r,i);return n},match:function(e,t,n){return t[e]?t[e]:n},sort:ut,map:function(e,t){const n={};for(const r of Object.entries(e))n[r[0]]=t(r[1]);return n},mapIterable:function(e,t){const n=[];let r=0;for(const i of e)n.push(t(i,r++));return n},filterKeys:function(e,t){const n={};for(const[r,i]of Object.entries(e))t(r)&&(n[r]=i);return n},filterValues:function(e,t){const n={};for(const[r,i]of Object.entries(e))t(i)&&(n[r]=i);return n},rethrow:async function(e,t){try{return await e()}catch{throw t}},setSomeOnObject:function(e,t,n){null!=n&&(e[t]=n)},setSomeDeep:function(e,t,n,r){const i=h(n,r);null!=i&&f(e,t,i)},flip:function(e){const t={};for(const[n,r]of Object.entries(e))t[r]=n;return t},getAllPermutations:function(e){const t=Object.keys(e),n=t.map(t=>e[t].length),r=n.reduce((e,t)=>e*t);let i=1;const o=[1];for(let e=0;e<n.length-1;e++)i*=n[e],o.push(i);const a=[];for(let n=0;n<r;n++){const r={};for(let i=0;i<t.length;i++){const a=e[t[i]],s=Math.floor(n/o[i])%a.length;r[t[i]]=a[s]}a.push(r)}return a},countTruthyValues:function(e){return Object.values(e).filter(e=>e).length},transformToArray:function(e){const t=[],n=Object.keys(e),r=e[n[0]].length;for(let i=0;i<r;i++){const r={};for(const t of n)r[t]=e[t][i];t.push(r)}return t},setMulti:function(e,t,n){for(const r of e)r[t]=n},incrementMulti:function(e,t,n=1){for(const r of e)r[t]+=n},createBidirectionalMap:function(){return{map:new Map,keys:[]}},createTemporalBidirectionalMap:function(){return{map:new Map,keys:[]}},pushToBidirectionalMap:dt,unshiftToBidirectionalMap:function(e,t,n,r=100){if(e.map.has(t)){const n=e.keys.indexOf(t);e.keys.splice(n,1)}if(e.map.set(t,n),e.keys.unshift(t),e.keys.length>r){const t=e.keys.shift();t&&e.map.delete(t)}},addToTemporalBidirectionalMap:function(e,t,n,r,i=100){dt(e,t,{validUntil:Date.now()+r,data:n},i)},getFromTemporalBidirectionalMap:function(e,t){const n=e.map.get(t);return n&&n.validUntil>Date.now()?n.data:null},createStatefulToggle:function(e){let t;return n=>{const r=n===e&&t!==e;return t=n,r}},diffKeys:function(e,t){const n=Object.keys(e),r=Object.keys(t);return{uniqueToA:n.filter(e=>!r.includes(e)),uniqueToB:r.filter(e=>!n.includes(e))}},pickRandomKey:Ye,mapRandomKey:function(e,t){const n=Ye(e);return e[n]=t(e[n]),n},fromObjectString:function(e){return e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=e.replace(/\r\n/g,"\n")).replace(/(\w+)\((.+)\)/g,(e,t,n)=>`${t}(${n.replaceAll(",",",")})`)).replace(/(,)(\s+})/g,"$2")).replace(/\.\.\..+?,/g,"")).replace(/({\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',")).replace(/(,\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',")).replace(/:(.+)\?(.+):/g,(e,t,n)=>`: (${t.trim()} && ${n.trim()}) ||`)).replace(/([a-zA-Z0-9]+)( ?: ?{)/g,'"$1"$2')).replace(/([a-zA-Z0-9]+) ?: ?(.+?)(,|\n|})/g,(e,t,n,r)=>`"${t}":"${n.trim()}"${r}`)).replace(/("'|'")/g,'"')).replaceAll(",",","),JSON.parse(e)},toQueryString:Ce,parseQueryString:function(e){const t={},n=e.split("&");for(const e of n){const[n,r]=e.split("=");n&&r&&(t[n]=decodeURIComponent(r))}return t},hasKey:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},selectMax:function(e,t){let n=null,r=-1/0;for(const[i,o]of Object.entries(e)){const e=t(o);e>r&&(r=e,n=i)}return n?[n,e[n]]:null},reposition:function(e,t,n,r){const i=e.find(e=>e[t]===n),o=e.find(e=>e[t]===n+r);i&&o?(i[t]=n+r,o[t]=n):i&&(i[t]=n+r),e.sort((e,n)=>P(e[t])-P(n[t])),e.forEach((e,n)=>e[t]=n+1)},unwrapSingleKey:function(e){const t=Object.keys(e);if(1===t.length)return e[t[0]];throw new Error("Expected object to have a single key")},parseKeyValues:function(e,t=":"){return Object.fromEntries(e.map(e=>ee(e,t)).map(e=>e[0]&&e[1]?[ie(e[0]),ie(e[1])]:null).filter(e=>e))},errorMatches:function(e,t){if(!e)return!1;const n=e.message;return"string"==typeof n&&n.includes(t)}},e.Types={isFunction:b,isObject:m,isStrictlyObject:g,isEmptyArray:y,isEmptyObject:function(e){return g(e)&&0===Object.keys(e).length},isUndefined:w,isString:v,isNumber:x,isBoolean:E,isDate:A,isBlank:R,isId:S,isIntegerString:I,isHexString:k,isUrl:N,isBigint:M,isNullable:function(e,t){return null==t||e(t)},asString:z,asHexString:function(e,t){if(!k(e))throw new TypeError(`Expected hex string${t?.name?` for ${t.name}`:""}, got: `+e);if(t?.strictPrefix&&!e.startsWith("0x")&&!e.startsWith("0X"))throw new TypeError(`Expected hex string with 0x prefix${t?.name?` for ${t.name}`:""}, got: `+e);const n=e.replace(/^0x/i,"");if(n.length%2!=0&&!t?.uneven)throw RangeError(`Expected even number of hex digits${t?.name?` for ${t.name}`:""}; got: `+e);if(t&&t.byteLength&&n.length!==2*t.byteLength)throw RangeError(`Expected hex string${t?.name?` for ${t.name}`:""} of byte length ${t.byteLength}; got: `+n);return`0x${n}`},asSafeString:function(e,t){if(!z(e,t).split("").every(e=>"_"===e||ue(e)))throw new TypeError(`Expected safe string${t?.name?` for ${t.name}`:""}, got: `+e);return e},asIntegerString:function(e,t){if(!I(e))throw new TypeError(`Expected integer string${t?.name?` for ${t.name}`:""}, got: `+e);const n=BigInt(e);if(t&&(t.min&&n<t.min||t.max&&n>t.max))throw RangeError(`Expected integer string${t?.name?` for ${t.name}`:""} in range: ${t.min??"-inf"}..${t.max??"inf"}; got: `+n);return e},asNumber:P,asFunction:function(e,t){if(!b(e))throw new TypeError(`Expected function${t?.name?` for ${t.name}`:""}, got: `+e);return e},asInteger:U,asBoolean:function(e,t){if("true"===e)return!0;if("false"===e)return!1;if(!E(e))throw new TypeError(`Expected boolean${t?.name?` for ${t.name}`:""}, got: `+e);return e},asDate:function(e,t){if(!A(e))throw new TypeError(`Expected date${t?.name?` for ${t.name}`:""}, got: `+e);return e},asNullableString:function(e){return R(e)?null:e},asEmptiableString:function(e,t){if(!v(e))throw new TypeError(`Expected string${t?.name?` for ${t.name}`:""}, got: `+e);return e},asId:function(e,t){if(S(e))return e;const n=parseInt(e,10);if(!S(n))throw new TypeError(`Expected id${t?.name?` for ${t.name}`:""}, got: `+e);return n},asTime:function(e,t){if(!v(e))throw new TypeError(`Expected time${t?.name?` for ${t.name}`:""}, got: `+e);const n=e.split(":");if(2!==n.length)throw new TypeError(`Expected time${t?.name?` for ${t.name}`:""}, got: `+e);const r=parseInt(n[0],10),i=parseInt(n[1],10);if(!x(r)||!x(i)||r<0||r>23||i<0||i>59)throw new TypeError(`Expected time, got${t?.name?` for ${t.name}`:""}: `+e);return`${String(r).padStart(2,"0")}:${String(i).padStart(2,"0")}`},asArray:function(e,t){if(!Array.isArray(e))throw new TypeError(`Expected array${t?.name?` for ${t.name}`:""}, got: `+e);return e},asObject:q,asNullableObject:function(e,t){return null===e?null:q(e,t)},asStringMap:function(e,t){const n=q(e,t);for(const r of Object.keys(n))if(!v(n[r]))throw new TypeError(`Expected string map${t?.name?` for ${t.name}`:""}, got: `+e);return n},asNumericDictionary:function(e,t){const n=q(e),r=Object.keys(n),i=Object.values(n);if(!r.every(v)||!i.every(x))throw new TypeError(`Expected numeric dictionary${t?.name?` for ${t.name}`:""}, got: `+e);return n},asUrl:function(e,t){if(!N(e))throw new TypeError(`Expected url${t?.name?` for ${t.name}`:""}, got: `+e);return e},asBigint:_,asEmptiable:function(e,t){return""===t?void 0:e(t)},asNullable:function(e,t){return null==t?null:e(t)},asOptional:function(e,t){return null==t?void 0:e(t)},enforceObjectShape:V,enforceArrayShape:function(e,t){return e.every(e=>V(e,t))},isPng:gt,isJpg:yt,isWebp:wt,isImage:function(e){return gt(e)||yt(e)||wt(e)}},e.Strings={tokenizeByCount:function(e,t){return ct(e,Math.ceil(e.length/t))},tokenizeByLength:ct,searchHex:function(e,t){const n=new RegExp(`[0-9a-f]{${t}}`,"i"),r=e.match(n);return r?r[0]:null},searchSubstring:function(e,t,n=T){const r=te(e,n);for(const e of r)if(t(e))return e;return null},randomHex:function(e,t=Math.random){let n="";for(let r=0;r<e;r++)n+=$[Math.floor(16*t())];return n},randomLetter:function(e,t=Math.random){let n="";for(let r=0;r<e;r++)n+=B[Math.floor(26*t())];return n},randomAlphanumeric:function(e,t=Math.random){let n="";for(let r=0;r<e;r++)n+=O[Math.floor(62*t())];return n},randomRichAscii:function(e,t=Math.random){let n="";for(let r=0;r<e;r++)n+=D[Math.floor(89*t())];return n},randomUnicode:function(e,t=Math.random){let n="";for(let r=0;r<e;r++)n+=C[Math.floor(t()*C.length)];return n},includesAny:function(e,t){return t.some(t=>e.includes(t))},slugify:H,normalForm:function(e){return H(e).replaceAll("-","")},enumify:function(e){return H(e).replace(/-/g,"_").toUpperCase()},escapeHtml:function(e){return e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")},decodeHtmlEntities:function(e){let t=e.replace(/&#(\d+);/g,(e,t)=>String.fromCharCode(t)).replace(/&#x(\d+);/g,(e,t)=>String.fromCharCode(parseInt(t,16)));for(const[e,n]of Object.entries(Z))t=t.replaceAll(e,n);return t},after:X,afterLast:Q,before:J,beforeLast:Y,betweenWide:function(e,t,n){const r=Y(e,n);return r?X(r,t):null},betweenNarrow:function(e,t,n){const r=X(e,t);return r?J(r,n):null},getPreLine:function(e){return e.replace(/ +/g," ").replace(/^ /gm,"")},containsWord:Te,containsWords:function(e,t,n){return"any"===n?t.some(t=>Te(e,t)):t.every(t=>Te(e,t))},joinUrl:He,getFuzzyMatchScore:W,sortByFuzzyScore:function(e,t){return e.filter(e=>W(e,t)).sort((e,n)=>W(n,t)-W(e,t))},splitOnce:ee,splitAll:te,randomize:function(e,t=Math.random){return e.replace(/\{(.+?)\}/g,(e,n)=>u(n.split("|"),t))},expand:function e(t){const n=t.match(/\{(.+?)\}/);if(!n||!n.index)return[t];const r=n[1].split(","),i=t.slice(0,n.index),o=t.slice(n.index+n[0].length);let a=[];for(const t of r){const n=e(i+t+o);a=a.concat(n)}return a},shrinkTrim:ie,capitalize:oe,decapitalize:ae,csvEscape:function(e){return e.match(/"|,/)?`"${e.replace(/"/g,'""')}"`:e},parseCsv:function(e,t=",",n='"'){const r=[];let i="",o=!1;const a=e.split("");for(const e of a)e!==t||o?e!==n||(i||o)&&!o?i+=e:o=!o:(r.push(i),i="");return r.push(i),r},surroundInOut:function(e,t){return t+e.split("").join(t)+t},getExtension:ne,getBasename:re,normalizeEmail:function(e){let[t,n]=e.split("@");t=ie(t.replaceAll(".","").toLowerCase()).replaceAll(" ","");const[r]=t.split("+");if(!r||!n||-1===n.indexOf(".")||n.indexOf(".")===n.length-1)throw new Error("Invalid email");return n=ie(n.toLowerCase()).replaceAll(" ",""),`${r}@${n}`},normalizeFilename:function(e){const t=re(e),n=ne(e);return n?`${t}.${n}`:t},parseFilename:function(e){const t=re(e),n=ne(e);return{basename:t,extension:n,filename:n?`${t}.${n}`:t}},camelToTitle:function(e){return oe(e.replace(/([A-Z])/g," $1"))},slugToTitle:function(e){return e.split("-").map(oe).join(" ")},slugToCamel:function(e){return ae(e.split("-").map(oe).join(""))},joinHumanly:function(e,t=", ",n=" and "){return e&&e.length?1===e.length?e[0]:2===e.length?`${e[0]}${n}${e[1]}`:`${e.slice(0,e.length-1).join(t)}${n}${e[e.length-1]}`:""},findWeightedPair:be,extractBlock:ve,extractAllBlocks:function(e,t){const n=[];let r=t.wordBoundary?me(e,[`${t.opening} `,`${t.opening}\n`],t.start||0):e.indexOf(t.opening,t.start||0);for(;;){if(-1===r)return n;const i=ve(e,{...t,start:r});if(!i)return n;n.push(i),r=t.wordBoundary?me(e,[`${t.opening} `,`${t.opening}\n`],r+i.length):e.indexOf(t.opening,r+i.length)}},replaceBlocks:function(t,n,r){let i=0;for(;;){const o=e.Strings.extractBlock(t,{...r,start:i});if(!o)return t;const a=n(o);i=t.indexOf(o,i)+a.length,t=t.replace(o,a)}},indexOfEarliest:me,lastIndexOfBefore:we,parseHtmlAttributes:function(e){const t={},n=e.match(/([a-z\-]+)="([^"]+)"/g);if(n)for(const e of n){const[n,r]=ee(e,"=");t[n]=r.slice(1,r.length-1)}return t},readNextWord:Be,readWordsAfterAll:function(e,t,n=[]){const r=pe(e,t),i=[];for(const o of r)i.push(Be(e,o+t.length,n));return i},resolveVariables:function(e,t,n="$",r=":"){for(const i in t)e=Oe(e,i,t[i],n,r);return e=De(e)},resolveVariableWithDefaultSyntax:Oe,resolveRemainingVariablesWithDefaults:De,isLetter:se,isDigit:ce,isLetterOrDigit:ue,isValidObjectPathCharacter:function(e){return ue(e)||"."===e||"["===e||"]"===e||"_"===e},insert:function(e,t,n,r,i){return e.slice(0,t)+r+e.slice(t,t+n)+i+e.slice(t+n)},indexOfRegex:he,allIndexOf:pe,lineMatches:fe,linesMatchInOrder:function(e,t,n=!0){let r=0;for(const i of t){let t=!1;for(;!t&&r<e.length;)fe(e[r],i,n)&&(t=!0),r++;if(!t)return!1}return!0},represent:function e(t,n="json",r=0){if(t&&b(t.represent)){const e=t.represent();if(v(e))return"json"===n&&0===r?JSON.stringify(e):e}if(m(t,!1)){if(r>1)return"[object Object]";if("json"===n){if(Array.isArray(t)){const n=t.map(t=>e(t,"json",r+1));return 0===r?JSON.stringify(n):n}const n={};t.message&&(n.message=e(t.message,"json",r+1));for(const[i,o]of Object.entries(t))n[i]=e(o,"json",r+1);return 0===r?JSON.stringify(n):n}if("key-value"===n){const n=Object.keys(t);return t.message&&!n.includes("message")&&n.unshift("message"),n.map(n=>`${n}=${JSON.stringify(e(t[n],"json",r+1))}`).join(" ")}}return w(t)&&(t="undefined"),0===r?JSON.stringify(t):t},resolveMarkdownLinks:function(e,t){let n=e.indexOf("](");for(;-1!==n;){const r=we(e,"[",n),i=e.indexOf(")",n);if(-1!==r&&-1!==i){const[n,o]=e.slice(r+1,i).split("]("),a=t(n,o);e=e.slice(0,r)+a+e.slice(i+1)}n=e.indexOf("](",n+1)}return e},buildUrl:function(e,t,n){return He([e,t])+Ce(n||{})},isChinese:function(e){return/^[\u4E00-\u9FA5]+$/.test(e)},replaceBetweenStrings:function(e,t,n,r,i=!0){const o=e.indexOf(t),a=e.indexOf(n,o+t.length);if(-1===o||-1===a)throw Error("Start or end not found");return i?e.substring(0,o+t.length)+r+e.substring(a):e.substring(0,o)+r+e.substring(a+n.length)},describeMarkdown:function(e){let t="p";return e.startsWith("#")?(t="h1",e=e.slice(1).trim()):e.startsWith("-")&&(t="li",e=e.slice(1).trim()),{type:t,isCapitalized:e[0]===e[0].toUpperCase(),hasPunctuation:/[.?!]$/.test(e),endsWithColon:/:$/.test(e)}},isBalanced:function(e,t="(",n=")"){let r=0,i=0;for(;i<e.length;)if(e.startsWith(t,i)?(r++,i+=t.length):e.startsWith(n,i)?(r--,i+=n.length):i++,r<0)return!1;return t===n?r%2==0:0===r},textToFormat:function(e){let t=(e=e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")).length;for(;(e=e.replace(/(\w+)[\s,']+\w+/g,"$1")).length!==t;)t=e.length;return e=(e=(e=e.replaceAll(/[A-Z][a-zA-Z0-9]*/g,"A")).replaceAll(/[a-z][a-zA-Z0-9]*/g,"a")).replaceAll(/[\u4E00-\u9FA5]+/g,"Z")},splitFormatting:function(e,t){const n=[];let r=0;for(;r<e.length;){const i=e.indexOf(t,r);if(-1===i){n.push({string:e.slice(r),symbol:null});break}const o=e.indexOf(t,i+t.length);if(i>r&&-1!==o&&n.push({string:e.slice(r,i),symbol:null}),-1===o){n.push({string:e.slice(r),symbol:null});break}n.push({string:e.slice(i+t.length,o),symbol:t}),r=o+t.length}return n},splitHashtags:function(e){const t=[];let n=0;for(;n<e.length;){const r=ye(e,n);if(-1===r){t.push({string:e.slice(n),symbol:null});break}const i=ge(e,r+1);if(-1===i){t.push({string:e.slice(n,r),symbol:null}),t.push({string:e.slice(r+1),symbol:"#"});break}r>n&&t.push({string:e.slice(n,r),symbol:null}),t.push({string:e.slice(r+1,i),symbol:"#"}),n=i}return t},splitUrls:function(e){const t=[];let n=0;for(;n<e.length;){const r=me(e,["http://","https://"],n);if(-1===r){t.push({string:e.slice(n),symbol:null});break}const i=me(e,[" ","\n"],r);if(-1===i){r>n&&t.push({string:e.slice(n,r),symbol:null}),t.push({string:e.slice(r),symbol:"http"});break}r>n&&t.push({string:e.slice(n,r),symbol:null}),t.push({string:e.slice(r,i),symbol:"http"}),n=i}return t},route:function(e,t){const n=e.split("/").filter(e=>e),r=t.split("/").filter(e=>e);if(n.length!==r.length)return null;const i={};for(let e=0;e<n.length;e++){const t=n[e];if(t.startsWith(":"))i[t.slice(1)]=r[e];else if(t!==r[e])return null}return i},explodeReplace:Se,generateVariants:function(t,n,r,i=Math.random){const o=e.Arrays.shuffle(n.map(t=>({variants:e.Arrays.shuffle(t.variants.map(e=>e),i),avoid:t.avoid})),i),a=[];for(const e of o){const n=e.variants.filter(t=>t!==e.avoid),i=n.find(e=>t.includes(e));if(i&&(G(a,Se(t,i,n)),a.length>=r))break}if(a.length<r)for(const e of o){const n=e.variants.find(e=>t.includes(e));if(n&&(G(a,Se(t,n,e.variants)),a.length>=r))break}return a.slice(0,r)},replaceWord:function(e,t,n,r=!1){const i=new RegExp(r?`(?<=\\s|^)${t}(?=\\s|$)`:`\\b${t}\\b`,"g");return e.replace(i,n)},replacePascalCaseWords:function(e,t){return e.replace(/\b[A-Z][a-zA-Z0-9]*\b/g,e=>e.toUpperCase()===e?e:t(e))},stripHtml:function(e){return e.replace(/<[^>]*>/g,"")},breakLine:Ie,measureTextWidth:function(e,t={}){return[...e].reduce((e,n)=>e+(t[n]||1),0)},toLines:function(e,t,n={}){const r=[];let i="",o=0;for(let a=0;a<e.length;a++){const s=e[a];if(i+=s,o+=n[s]||1,o>t){const{line:e,rest:t}=Ie(i);r.push(e),i=t,o=t.split("").map(e=>n[e]||1).reduce((e,t)=>e+t,0)}}return i&&r.push(i),r},levenshteinDistance:function(e,t){const n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=e.length;r++)for(let i=1;i<=t.length;i++){const o=e[r-1]===t[i-1]?0:1;n[r][i]=Math.min(n[r-1][i]+1,n[r][i-1]+1,n[r-1][i-1]+o)}return n[e.length][t.length]},findCommonPrefix:ke,findCommonDirectory:function(e){const t=ke(e),n=t.lastIndexOf("/");return-1===n?"":t.slice(0,n+1)}},e.Assertions={asEqual:function(e,t){if(e!==t)throw Error(`Expected [${e}] to equal [${t}]`);return[e,t]},asTrue:function(e){if(!0!==e)throw Error(`Expected [true], got: [${e}]`);return e},asTruthy:function(e){if(!e)throw Error(`Expected truthy value, got: [${e}]`);return e},asFalse:function(e){if(!1!==e)throw Error(`Expected [false], got: [${e}]`);return e},asFalsy:function(e){if(e)throw Error(`Expected falsy value, got: [${e}]`);return e},asEither:function(e,t){if(!t.includes(e))throw Error(`Expected any of [${t.join(", ")}], got: [${e}]`);return e}},e.Cache={get:async function(e,t,n){const r=Date.now(),i=Ke.get(e);if(i&&i.validUntil>r)return i.value;const o=await n(),a=r+t;return Ke.set(e,{value:o,validUntil:a}),o},delete:function(e){Ke.delete(e)},deleteExpired:function(){const e=Date.now();for(const[t,n]of Ke.entries())n.validUntil<=e&&Ke.delete(t)},size:function(){return Ke.size}},e.Vector={addPoint:Xt,subtractPoint:function(e,t){return{x:e.x-t.x,y:e.y-t.y}},multiplyPoint:Yt,normalizePoint:function(e){const t=Math.sqrt(e.x*e.x+e.y*e.y);return{x:e.x/t,y:e.y/t}},pushPoint:Qt,filterCoordinates:tn,findCorners:function(e,t,n,r){const i=[{x:0,y:0},{x:n,y:0},{x:0,y:r},{x:n,y:r}];for(let t=0;t<e.length;t++)for(let n=0;n<e[0].length;n++){const r=sn(e,t,n);for(const e of r)i.some(t=>t.x===e.x&&t.y===e.y)||i.push(e)}return i.map(e=>({x:e.x*t,y:e.y*t}))},findLines:function(e,t){const n=tn(e,(t,n)=>0===e[t][n]&&0!==e[t][n+1],"row-first").map(e=>({...e,dx:1,dy:0})),r=tn(e,(t,n)=>0===e[t][n]&&0!==e[t][n-1],"row-first").map(e=>({...e,dx:1,dy:0})),i=tn(e,(t,n)=>0===e[t][n]&&0!==e[t-1]?.[n],"column-first").map(e=>({...e,dx:0,dy:1})),o=tn(e,(t,n)=>0===e[t][n]&&0!==e[t+1]?.[n],"column-first").map(e=>({...e,dx:0,dy:1}));return n.forEach(e=>e.y++),o.forEach(e=>e.x++),[...lt([...i,...o],(e,t)=>e.x===t.x&&e.y-1===t.y),...lt([...r,...n],(e,t)=>e.y===t.y&&e.x-1===t.x)].map(e=>({start:e[0],end:l(e)})).map(e=>({start:Yt(e.start,t),end:Yt(Xt(e.end,{x:e.start.dx,y:e.start.dy}),t)}))},raycast:ln,raycastCircle:function(e,t,n){const r=cn(e,n),i=[];for(const n of r){const r=ln(e,t,n-.001),o=ln(e,t,n+.001);r&&i.push(r),o&&i.push(o)}return i},getLineIntersectionPoint:un}}(jr)),jr),Kr=Vr(Gr);Kr.Arrays,Kr.Assertions;const Hr=Kr.Binary;Kr.Cache;const Wr=Kr.Dates,Zr=Kr.Elliptic,Jr=Kr.Numbers,Xr=Kr.Objects;Kr.Pagination,Kr.Promises,Kr.Random;const Yr=Kr.Strings,Qr=Kr.System,ei=Kr.Types,ti=Kr.Optional;Kr.Vector,Kr.PubSubChannel,Kr.Chunk;const ni=Kr.MerkleTree,ri=Kr.FixedPointNumber;Kr.Lazy,Kr.AsyncLazy;const ii=Kr.AsyncQueue,oi=Kr.Uint8ArrayReader;Kr.Uint8ArrayWriter,Kr.TrieRouter,Kr.RollingValueProvider,Kr.Solver,Kr.Lock;var ai,si,ci,ui,li,di={exports:{}};function hi(){if(si)return ai;si=1;var e=1e3,t=60*e,n=60*t,r=24*n,i=7*r,o=365.25*r;function a(e,t,n,r){var i=t>=1.5*n;return Math.round(e/n)+" "+r+(i?"s":"")}return ai=function(s,c){c=c||{};var u=typeof s;if("string"===u&&s.length>0)return function(a){if((a=String(a)).length>100)return;var s=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(a);if(!s)return;var c=parseFloat(s[1]);switch((s[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*o;case"weeks":case"week":case"w":return c*i;case"days":case"day":case"d":return c*r;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(s);if("number"===u&&isFinite(s))return c.long?function(i){var o=Math.abs(i);if(o>=r)return a(i,o,r,"day");if(o>=n)return a(i,o,n,"hour");if(o>=t)return a(i,o,t,"minute");if(o>=e)return a(i,o,e,"second");return i+" ms"}(s):function(i){var o=Math.abs(i);if(o>=r)return Math.round(i/r)+"d";if(o>=n)return Math.round(i/n)+"h";if(o>=t)return Math.round(i/t)+"m";if(o>=e)return Math.round(i/e)+"s";return i+"ms"}(s);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(s))}}var fi=(li||(li=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,i=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(r++,"%c"===e&&(i=r))}),t.splice(i,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=(ui||(ui=1,ci=function(e){function t(e){let r,i,o,a=null;function s(...e){if(!s.enabled)return;const n=s,i=Number(new Date),o=i-(r||i);n.diff=o,n.prev=r,n.curr=i,r=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(r,i)=>{if("%%"===r)return"%";a++;const o=t.formatters[i];if("function"==typeof o){const t=e[a];r=o.call(n,t),e.splice(a,1),a--}return r}),t.formatArgs.call(n,e),(n.log||t.log).apply(n,e)}return s.namespace=e,s.useColors=t.useColors(),s.color=t.selectColor(e),s.extend=n,s.destroy=t.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(i!==t.namespaces&&(i=t.namespaces,o=t.enabled(e)),o),set:e=>{a=e}}),"function"==typeof t.init&&t.init(s),s}function n(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function r(e,t){let n=0,r=0,i=-1,o=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||"*"===t[r]))"*"===t[r]?(i=r,o=n,r++):(n++,r++);else{if(-1===i)return!1;r=i+1,o++,n=o}for(;r<t.length&&"*"===t[r];)r++;return r===t.length}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of n)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const n of t.skips)if(r(e,n))return!1;for(const n of t.names)if(r(e,n))return!0;return!1},t.humanize=hi(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(n=>{t[n]=e[n]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t}),ci)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(di,di.exports)),di.exports),pi=Vr(fi);const mi=pi("bee-js:bytes"),gi=new TextDecoder,yi=new TextEncoder;class wi{constructor(e,t){if(!e)throw Error(`Bytes#constructor: constructor parameter is falsy: ${e}`);if(e instanceof wi)this.bytes=e.bytes;else if("string"==typeof e)this.bytes=Hr.hexToUint8Array(ei.asHexString(e,{name:"Bytes#constructor(bytes)"}));else if(e instanceof ArrayBuffer)this.bytes=new Uint8Array(e);else if(e instanceof Uint8Array)this.bytes=e;else{const t=e,n=Xr.getDeep(t,"toHex");if(!ei.isFunction(n))throw mi("bytes",e),new Error("Bytes#constructor: unsupported type: "+typeof e);{const e=n.call(t);this.bytes=Hr.hexToUint8Array(ei.asHexString(e,{name:"Bytes#constructor(bytes)"}))}}if(this.length=this.bytes.length,t)if(Array.isArray(t)){if(!t.includes(this.length))throw new Error(`Bytes#checkByteLength: bytes length is ${this.length} but expected ${t.join(" or ")}`)}else if(this.length!==t)throw new Error(`Bytes#checkByteLength: bytes length is ${this.length} but expected ${t}`)}static keccak256(e){return new wi(Hr.keccak256(new wi(e).toUint8Array()))}static fromUtf8(e){return new wi(yi.encode(e))}static fromSlice(e,t,n){return new wi(void 0===n?e.slice(t):e.slice(t,t+n))}offset(e){return new Uint8Array(this.bytes.slice(e))}toUint8Array(){return new Uint8Array(this.bytes)}toHex(){return Hr.uint8ArrayToHex(this.bytes)}toBase64(){return Hr.uint8ArrayToBase64(this.bytes)}toBase32(){return Hr.uint8ArrayToBase32(this.bytes)}toString(){return this.toHex()}toUtf8(){return gi.decode(this.bytes)}toJSON(){return JSON.parse(this.toUtf8())}equals(e){return this.toHex()===new wi(e).toHex()}represent(){return this.toHex()}}function bi(e){const t=e.match(/^([\d.]+)\s*(B|kB|MB|GB|TB|PB)$/);if(!t)throw new Error(`Invalid size format: ${e}`);const n=parseFloat(t[1]),r=t[2];return Math.ceil(n*{B:1,kB:1e3,MB:1e6,GB:1e3**3,TB:1e3**4,PB:1e3**5}[r])}const vi=250,xi=251,Ei={[vi]:"manifest",[xi]:"feed"};const Ai=new TextEncoder;class Ri extends wi{constructor(e){super(e,32)}publicKey(){const[e,t]=Zr.privateKeyToPublicKey(Hr.uint256ToNumber(this.bytes,"BE"));return new Si(Hr.concatBytes(Hr.numberToUint256(e,"BE"),Hr.numberToUint256(t,"BE")))}sign(e){const t=Hr.concatBytes(Ai.encode("Ethereum Signed Message:\n32"),Hr.keccak256(e instanceof Uint8Array?e:Ai.encode(e))),[n,r,i]=Zr.signMessage(t,Hr.uint256ToNumber(this.bytes,"BE"));return new $i(Hr.concatBytes(Hr.numberToUint256(n,"BE"),Hr.numberToUint256(r,"BE"),new Uint8Array([Number(i)])))}}Ri.LENGTH=32;class Si extends wi{constructor(e){const t=new wi(e);if(33===t.length){const[e,n]=Zr.publicKeyFromCompressed(t.toUint8Array());super(Hr.concatBytes(Hr.numberToUint256(e,"BE"),Hr.numberToUint256(n,"BE")),64)}else super(e,64)}address(){const e=Hr.uint256ToNumber(this.bytes.slice(0,32),"BE"),t=Hr.uint256ToNumber(this.bytes.slice(32,64),"BE");return new Ii(Zr.publicKeyToAddress([e,t]))}toCompressedUint8Array(){const e=Hr.uint256ToNumber(this.bytes.slice(0,32),"BE"),t=Hr.uint256ToNumber(this.bytes.slice(32,64),"BE");return Zr.compressPublicKey([e,t])}toCompressedHex(){return Hr.uint8ArrayToHex(this.toCompressedUint8Array())}}Si.LENGTH=64;class Ii extends wi{constructor(e){super(e,20)}toChecksum(){return Zr.checksumEncode(this.bytes)}}Ii.LENGTH=20;class ki extends wi{constructor(e){super(e,32)}static fromString(e){return new ki(Hr.keccak256(Ai.encode(e)))}}ki.LENGTH=32;class Ti extends wi{constructor(e){if("string"==typeof e&&e.startsWith("bah5")){const t=function(e){const t=Hr.base32ToUint8Array(e.toUpperCase().slice(1)),n=t[1];if(!Ei[n])throw new Error("Unknown codec");const r=new Ti(t.slice(-32));return{type:Ei[n],reference:r}}(e);super(t.reference.bytes,32)}else super(e,[32,64])}toCid(e){return function(e,t){e=new Ti(e);const n=new Uint8Array([1]),r=new Uint8Array(["feed"===t?251:250]),i=new Uint8Array([1]),o=new Uint8Array([27]),a=new Uint8Array([32]);return`b${Hr.uint8ArrayToBase32(Hr.concatBytes(n,r,i,o,a)).replace(/\=+$/,"")}${e.toBase32().replace(/\=+$/,"")}`.toLowerCase()}(this.bytes,e)}static isValid(e){try{return new Ti(e),!0}catch{return!1}}}Ti.LENGTH=32;class Bi extends wi{constructor(e){super(e,32)}}Bi.LENGTH=32;class Oi extends wi{constructor(e){super(e,8)}static fromBigInt(e){return new Oi(Hr.numberToUint64(e,"LE"))}toBigInt(){return Hr.uint64ToNumber(this.bytes,"LE")}static fromSlice(e,t){return new Oi(e.slice(t,t+Oi.LENGTH))}}Oi.LENGTH=8;class Di extends wi{constructor(e){super(e,32)}}Di.LENGTH=32;class Ci extends wi{constructor(e){super(e,32)}}Ci.LENGTH=32;class $i extends wi{constructor(e){super(e,65)}static fromSlice(e,t){return new $i(e.slice(t,t+$i.LENGTH))}recoverPublicKey(e){const t=Hr.uint256ToNumber(this.bytes.slice(0,32),"BE"),n=Hr.uint256ToNumber(this.bytes.slice(32,64),"BE"),r=BigInt(this.bytes[64]),[i,o]=Zr.recoverPublicKey(Hr.concatBytes(Ai.encode("Ethereum Signed Message:\n32"),Hr.keccak256(e instanceof Uint8Array?e:Ai.encode(e))),t,n,r);return new Si(Hr.concatBytes(Hr.numberToUint256(i,"BE"),Hr.numberToUint256(o,"BE")))}isValid(e,t){return this.recoverPublicKey(e).address().equals(t)}}$i.LENGTH=65;class zi extends wi{constructor(e){super(e,32)}static fromString(e){return new zi(Hr.keccak256(Ai.encode(e)))}}zi.LENGTH=32;const Fi=new Uint8Array(8).fill(255,0,8);class Pi extends wi{constructor(e){super(e,8)}static fromBigInt(e){return new Pi(Hr.numberToUint64(e,"BE"))}toBigInt(){return Hr.uint64ToNumber(this.bytes,"BE")}next(){return Hr.equals(this.bytes,Fi)?Pi.fromBigInt(0n):Pi.fromBigInt(this.toBigInt()+1n)}}Pi.LENGTH=8,Pi.MINUS_ONE=new Pi(Fi);class Ui extends Error{constructor(e){super(e)}}class qi extends Ui{constructor(e,t){super(e),this.value=t}}class Ni extends Ui{constructor(e,t,n,r,i,o){super(n),this.method=e,this.url=t,this.responseBody=r,this.status=i,this.statusText=o}}const Mi=4096;function _i(e){const t=e.slice(0,Oi.LENGTH),n=function(e){if(e.length>Mi)throw new qi(`payload size ${e.length} exceeds maximum chunk payload size 4096`,e);const t=new Uint8Array(Mi);return t.set(e),Hr.log2Reduce(Hr.partition(t,32),(e,t)=>Hr.keccak256(Hr.concatBytes(e,t)))}(e.slice(Oi.LENGTH)),r=Hr.keccak256(Hr.concatBytes(t,n));return new Ti(r)}var Vi;function Li(e){switch(e){case"full":return Vi.FULL;case"light":return Vi.LIGHT;case"ultra-light":return Vi.ULTRA_LIGHT;case"dev":return Vi.DEV;default:throw new Error(`Unknown Bee mode: ${e}`)}}!function(e){e.FULL="full",e.LIGHT="light",e.ULTRA_LIGHT="ultra-light",e.DEV="dev"}(Vi||(Vi={}));const ji=4096;var Gi,Ki;!function(e){e[e.OFF=0]="OFF",e[e.MEDIUM=1]="MEDIUM",e[e.STRONG=2]="STRONG",e[e.INSANE=3]="INSANE",e[e.PARANOID=4]="PARANOID"}(Gi||(Gi={})),function(e){e[e.NONE=0]="NONE",e[e.DATA=1]="DATA",e[e.PROX=2]="PROX",e[e.RACE=3]="RACE"}(Ki||(Ki={}));const Hi={ENCRYPTION_OFF:{[Gi.OFF]:[{theoreticalVolume:"536.87 MB",effectiveVolume:"44.70 kB",batchDepth:17,utilizationRate:"0.01%"},{theoreticalVolume:"1.07 GB",effectiveVolume:"6.66 MB",batchDepth:18,utilizationRate:"0.61%"},{theoreticalVolume:"2.15 GB",effectiveVolume:"112.06 MB",batchDepth:19,utilizationRate:"5.09%"},{theoreticalVolume:"4.29 GB",effectiveVolume:"687.62 MB",batchDepth:20,utilizationRate:"15.65%"},{theoreticalVolume:"8.59 GB",effectiveVolume:"2.60 GB",batchDepth:21,utilizationRate:"30.27%"},{theoreticalVolume:"17.18 GB",effectiveVolume:"7.73 GB",batchDepth:22,utilizationRate:"44.99%"},{theoreticalVolume:"34.36 GB",effectiveVolume:"19.94 GB",batchDepth:23,utilizationRate:"58.03%"},{theoreticalVolume:"68.72 GB",effectiveVolume:"47.06 GB",batchDepth:24,utilizationRate:"68.48%"},{theoreticalVolume:"137.44 GB",effectiveVolume:"105.51 GB",batchDepth:25,utilizationRate:"76.77%"},{theoreticalVolume:"274.88 GB",effectiveVolume:"227.98 GB",batchDepth:26,utilizationRate:"82.94%"},{theoreticalVolume:"549.76 GB",effectiveVolume:"476.68 GB",batchDepth:27,utilizationRate:"86.71%"},{theoreticalVolume:"1.10 TB",effectiveVolume:"993.65 GB",batchDepth:28,utilizationRate:"88.37%"},{theoreticalVolume:"2.20 TB",effectiveVolume:"2.04 TB",batchDepth:29,utilizationRate:"92.88%"},{theoreticalVolume:"4.40 TB",effectiveVolume:"4.17 TB",batchDepth:30,utilizationRate:"94.81%"},{theoreticalVolume:"8.80 TB",effectiveVolume:"8.45 TB",batchDepth:31,utilizationRate:"96.06%"},{theoreticalVolume:"17.59 TB",effectiveVolume:"17.07 TB",batchDepth:32,utilizationRate:"97.01%"},{theoreticalVolume:"35.18 TB",effectiveVolume:"34.36 TB",batchDepth:33,utilizationRate:"97.65%"},{theoreticalVolume:"70.37 TB",effectiveVolume:"69.04 TB",batchDepth:34,utilizationRate:"98.11%"},{theoreticalVolume:"140.74 TB",effectiveVolume:"138.54 TB",batchDepth:35,utilizationRate:"98.44%"},{theoreticalVolume:"281.47 TB",effectiveVolume:"277.72 TB",batchDepth:36,utilizationRate:"98.67%"},{theoreticalVolume:"562.95 TB",effectiveVolume:"556.35 TB",batchDepth:37,utilizationRate:"98.83%"},{theoreticalVolume:"1.13 PB",effectiveVolume:"1.11 PB",batchDepth:38,utilizationRate:"98.91%"},{theoreticalVolume:"2.25 PB",effectiveVolume:"2.23 PB",batchDepth:39,utilizationRate:"98.96%"},{theoreticalVolume:"4.50 PB",effectiveVolume:"4.46 PB",batchDepth:40,utilizationRate:"98.98%"},{theoreticalVolume:"9.01 PB",effectiveVolume:"8.93 PB",batchDepth:41,utilizationRate:"99.11%"}],[Gi.MEDIUM]:[{theoreticalVolume:"536.87 MB",effectiveVolume:"41.56 kB",batchDepth:17,utilizationRate:"0.01%"},{theoreticalVolume:"1.07 GB",effectiveVolume:"6.19 MB",batchDepth:18,utilizationRate:"0.57%"},{theoreticalVolume:"2.15 GB",effectiveVolume:"104.18 MB",batchDepth:19,utilizationRate:"4.73%"},{theoreticalVolume:"4.29 GB",effectiveVolume:"639.27 MB",batchDepth:20,utilizationRate:"14.54%"},{theoreticalVolume:"8.59 GB",effectiveVolume:"2.41 GB",batchDepth:21,utilizationRate:"28.11%"},{theoreticalVolume:"17.18 GB",effectiveVolume:"7.18 GB",batchDepth:22,utilizationRate:"41.79%"},{theoreticalVolume:"34.36 GB",effectiveVolume:"18.54 GB",batchDepth:23,utilizationRate:"53.95%"},{theoreticalVolume:"68.72 GB",effectiveVolume:"43.75 GB",batchDepth:24,utilizationRate:"63.66%"},{theoreticalVolume:"137.44 GB",effectiveVolume:"98.09 GB",batchDepth:25,utilizationRate:"71.37%"},{theoreticalVolume:"274.88 GB",effectiveVolume:"211.95 GB",batchDepth:26,utilizationRate:"77.11%"},{theoreticalVolume:"549.76 GB",effectiveVolume:"443.16 GB",batchDepth:27,utilizationRate:"80.61%"},{theoreticalVolume:"1.10 TB",effectiveVolume:"923.78 GB",batchDepth:28,utilizationRate:"82.16%"},{theoreticalVolume:"2.20 TB",effectiveVolume:"1.90 TB",batchDepth:29,utilizationRate:"86.30%"},{theoreticalVolume:"4.40 TB",effectiveVolume:"3.88 TB",batchDepth:30,utilizationRate:"88.14%"},{theoreticalVolume:"8.80 TB",effectiveVolume:"7.86 TB",batchDepth:31,utilizationRate:"89.26%"},{theoreticalVolume:"17.59 TB",effectiveVolume:"15.87 TB",batchDepth:32,utilizationRate:"90.21%"},{theoreticalVolume:"35.18 TB",effectiveVolume:"31.94 TB",batchDepth:33,utilizationRate:"90.77%"},{theoreticalVolume:"70.37 TB",effectiveVolume:"64.19 TB",batchDepth:34,utilizationRate:"91.22%"},{theoreticalVolume:"140.74 TB",effectiveVolume:"128.80 TB",batchDepth:35,utilizationRate:"91.52%"},{theoreticalVolume:"281.47 TB",effectiveVolume:"258.19 TB",batchDepth:36,utilizationRate:"91.73%"},{theoreticalVolume:"562.95 TB",effectiveVolume:"517.23 TB",batchDepth:37,utilizationRate:"91.88%"},{theoreticalVolume:"1.13 PB",effectiveVolume:"1.04 PB",batchDepth:38,utilizationRate:"91.95%"},{theoreticalVolume:"2.25 PB",effectiveVolume:"2.07 PB",batchDepth:39,utilizationRate:"92.00%"},{theoreticalVolume:"4.50 PB",effectiveVolume:"4.15 PB",batchDepth:40,utilizationRate:"92.15%"},{theoreticalVolume:"9.01 PB",effectiveVolume:"8.30 PB",batchDepth:41,utilizationRate:"92.14%"}],[Gi.STRONG]:[{theoreticalVolume:"536.87 MB",effectiveVolume:"37.37 kB",batchDepth:17,utilizationRate:"0.01%"},{theoreticalVolume:"1.07 GB",effectiveVolume:"5.57 MB",batchDepth:18,utilizationRate:"0.51%"},{theoreticalVolume:"2.15 GB",effectiveVolume:"93.68 MB",batchDepth:19,utilizationRate:"4.25%"},{theoreticalVolume:"4.29 GB",effectiveVolume:"574.81 MB",batchDepth:20,utilizationRate:"13.07%"},{theoreticalVolume:"8.59 GB",effectiveVolume:"2.17 GB",batchDepth:21,utilizationRate:"25.26%"},{theoreticalVolume:"17.18 GB",effectiveVolume:"6.46 GB",batchDepth:22,utilizationRate:"37.58%"},{theoreticalVolume:"34.36 GB",effectiveVolume:"16.67 GB",batchDepth:23,utilizationRate:"48.50%"},{theoreticalVolume:"68.72 GB",effectiveVolume:"39.34 GB",batchDepth:24,utilizationRate:"57.24%"},{theoreticalVolume:"137.44 GB",effectiveVolume:"88.20 GB",batchDepth:25,utilizationRate:"64.17%"},{theoreticalVolume:"274.88 GB",effectiveVolume:"190.58 GB",batchDepth:26,utilizationRate:"69.33%"},{theoreticalVolume:"549.76 GB",effectiveVolume:"398.47 GB",batchDepth:27,utilizationRate:"72.48%"},{theoreticalVolume:"1.10 TB",effectiveVolume:"830.63 GB",batchDepth:28,utilizationRate:"73.85%"},{theoreticalVolume:"2.20 TB",effectiveVolume:"1.71 TB",batchDepth:29,utilizationRate:"77.59%"},{theoreticalVolume:"4.40 TB",effectiveVolume:"3.49 TB",batchDepth:30,utilizationRate:"79.27%"},{theoreticalVolume:"8.80 TB",effectiveVolume:"7.07 TB",batchDepth:31,utilizationRate:"80.34%"},{theoreticalVolume:"17.59 TB",effectiveVolume:"14.27 TB",batchDepth:32,utilizationRate:"81.12%"},{theoreticalVolume:"35.18 TB",effectiveVolume:"28.72 TB",batchDepth:33,utilizationRate:"81.63%"},{theoreticalVolume:"70.37 TB",effectiveVolume:"57.71 TB",batchDepth:34,utilizationRate:"82.01%"},{theoreticalVolume:"140.74 TB",effectiveVolume:"115.81 TB",batchDepth:35,utilizationRate:"82.29%"},{theoreticalVolume:"281.47 TB",effectiveVolume:"232.16 TB",batchDepth:36,utilizationRate:"82.48%"},{theoreticalVolume:"562.95 TB",effectiveVolume:"465.07 TB",batchDepth:37,utilizationRate:"82.61%"},{theoreticalVolume:"1.13 PB",effectiveVolume:"931.23 TB",batchDepth:38,utilizationRate:"82.67%"},{theoreticalVolume:"2.25 PB",effectiveVolume:"1.86 PB",batchDepth:39,utilizationRate:"82.71%"},{theoreticalVolume:"4.50 PB",effectiveVolume:"3.73 PB",batchDepth:40,utilizationRate:"82.78%"},{theoreticalVolume:"9.01 PB",effectiveVolume:"7.46 PB",batchDepth:41,utilizationRate:"82.79%"}],[Gi.INSANE]:[{theoreticalVolume:"536.87 MB",effectiveVolume:"33.88 kB",batchDepth:17,utilizationRate:"0.01%"},{theoreticalVolume:"1.07 GB",effectiveVolume:"5.05 MB",batchDepth:18,utilizationRate:"0.46%"},{theoreticalVolume:"2.15 GB",effectiveVolume:"84.92 MB",batchDepth:19,utilizationRate:"3.86%"},{theoreticalVolume:"4.29 GB",effectiveVolume:"521.09 MB",batchDepth:20,utilizationRate:"11.85%"},{theoreticalVolume:"8.59 GB",effectiveVolume:"1.97 GB",batchDepth:21,utilizationRate:"22.90%"},{theoreticalVolume:"17.18 GB",effectiveVolume:"5.86 GB",batchDepth:22,utilizationRate:"34.09%"},{theoreticalVolume:"34.36 GB",effectiveVolume:"15.11 GB",batchDepth:23,utilizationRate:"43.97%"},{theoreticalVolume:"68.72 GB",effectiveVolume:"35.66 GB",batchDepth:24,utilizationRate:"51.90%"},{theoreticalVolume:"137.44 GB",effectiveVolume:"79.96 GB",batchDepth:25,utilizationRate:"58.18%"},{theoreticalVolume:"274.88 GB",effectiveVolume:"172.77 GB",batchDepth:26,utilizationRate:"62.85%"},{theoreticalVolume:"549.76 GB",effectiveVolume:"361.23 GB",batchDepth:27,utilizationRate:"65.70%"},{theoreticalVolume:"1.10 TB",effectiveVolume:"753.00 GB",batchDepth:28,utilizationRate:"66.95%"},{theoreticalVolume:"2.20 TB",effectiveVolume:"1.55 TB",batchDepth:29,utilizationRate:"70.38%"},{theoreticalVolume:"4.40 TB",effectiveVolume:"3.16 TB",batchDepth:30,utilizationRate:"71.92%"},{theoreticalVolume:"8.80 TB",effectiveVolume:"6.41 TB",batchDepth:31,utilizationRate:"72.85%"},{theoreticalVolume:"17.59 TB",effectiveVolume:"12.93 TB",batchDepth:32,utilizationRate:"73.53%"},{theoreticalVolume:"35.18 TB",effectiveVolume:"26.04 TB",batchDepth:33,utilizationRate:"74.01%"},{theoreticalVolume:"70.37 TB",effectiveVolume:"52.32 TB",batchDepth:34,utilizationRate:"74.35%"},{theoreticalVolume:"140.74 TB",effectiveVolume:"104.99 TB",batchDepth:35,utilizationRate:"74.60%"},{theoreticalVolume:"281.47 TB",effectiveVolume:"210.46 TB",batchDepth:36,utilizationRate:"74.77%"},{theoreticalVolume:"562.95 TB",effectiveVolume:"421.61 TB",batchDepth:37,utilizationRate:"74.89%"},{theoreticalVolume:"1.13 PB",effectiveVolume:"844.20 TB",batchDepth:38,utilizationRate:"74.94%"},{theoreticalVolume:"2.25 PB",effectiveVolume:"1.69 PB",batchDepth:39,utilizationRate:"74.98%"},{theoreticalVolume:"4.50 PB",effectiveVolume:"3.38 PB",batchDepth:40,utilizationRate:"75.03%"},{theoreticalVolume:"9.01 PB",effectiveVolume:"6.77 PB",batchDepth:41,utilizationRate:"75.10%"}],[Gi.PARANOID]:[{theoreticalVolume:"536.87 MB",effectiveVolume:"13.27 kB",batchDepth:17,utilizationRate:"0.00%"},{theoreticalVolume:"1.07 GB",effectiveVolume:"1.98 MB",batchDepth:18,utilizationRate:"0.18%"},{theoreticalVolume:"2.15 GB",effectiveVolume:"33.27 MB",batchDepth:19,utilizationRate:"1.51%"},{theoreticalVolume:"4.29 GB",effectiveVolume:"204.14 MB",batchDepth:20,utilizationRate:"4.64%"},{theoreticalVolume:"8.59 GB",effectiveVolume:"771.13 MB",batchDepth:21,utilizationRate:"8.75%"},{theoreticalVolume:"17.18 GB",effectiveVolume:"2.29 GB",batchDepth:22,utilizationRate:"13.34%"},{theoreticalVolume:"34.36 GB",effectiveVolume:"5.92 GB",batchDepth:23,utilizationRate:"17.22%"},{theoreticalVolume:"68.72 GB",effectiveVolume:"13.97 GB",batchDepth:24,utilizationRate:"20.33%"},{theoreticalVolume:"137.44 GB",effectiveVolume:"31.32 GB",batchDepth:25,utilizationRate:"22.79%"},{theoreticalVolume:"274.88 GB",effectiveVolume:"67.68 GB",batchDepth:26,utilizationRate:"24.62%"},{theoreticalVolume:"549.76 GB",effectiveVolume:"141.51 GB",batchDepth:27,utilizationRate:"25.74%"},{theoreticalVolume:"1.10 TB",effectiveVolume:"294.99 GB",batchDepth:28,utilizationRate:"26.23%"},{theoreticalVolume:"2.20 TB",effectiveVolume:"606.90 GB",batchDepth:29,utilizationRate:"27.56%"},{theoreticalVolume:"4.40 TB",effectiveVolume:"1.24 TB",batchDepth:30,utilizationRate:"28.15%"},{theoreticalVolume:"8.80 TB",effectiveVolume:"2.51 TB",batchDepth:31,utilizationRate:"28.54%"},{theoreticalVolume:"17.59 TB",effectiveVolume:"5.07 TB",batchDepth:32,utilizationRate:"28.82%"},{theoreticalVolume:"35.18 TB",effectiveVolume:"10.20 TB",batchDepth:33,utilizationRate:"28.99%"},{theoreticalVolume:"70.37 TB",effectiveVolume:"20.50 TB",batchDepth:34,utilizationRate:"29.13%"},{theoreticalVolume:"140.74 TB",effectiveVolume:"41.13 TB",batchDepth:35,utilizationRate:"29.22%"},{theoreticalVolume:"281.47 TB",effectiveVolume:"82.45 TB",batchDepth:36,utilizationRate:"29.29%"},{theoreticalVolume:"562.95 TB",effectiveVolume:"165.17 TB",batchDepth:37,utilizationRate:"29.34%"},{theoreticalVolume:"1.13 PB",effectiveVolume:"330.72 TB",batchDepth:38,utilizationRate:"29.37%"},{theoreticalVolume:"2.25 PB",effectiveVolume:"661.97 TB",batchDepth:39,utilizationRate:"29.39%"},{theoreticalVolume:"4.50 PB",effectiveVolume:"1.32 PB",batchDepth:40,utilizationRate:"29.41%"},{theoreticalVolume:"9.01 PB",effectiveVolume:"2.65 PB",batchDepth:41,utilizationRate:"29.43%"}]},ENCRYPTION_ON:{[Gi.OFF]:[{theoreticalVolume:"536.87 MB",effectiveVolume:"44.35 kB",batchDepth:17,utilizationRate:"0.01%"},{theoreticalVolume:"1.07 GB",effectiveVolume:"6.61 MB",batchDepth:18,utilizationRate:"0.60%"},{theoreticalVolume:"2.15 GB",effectiveVolume:"111.18 MB",batchDepth:19,utilizationRate:"5.05%"},{theoreticalVolume:"4.29 GB",effectiveVolume:"682.21 MB",batchDepth:20,utilizationRate:"15.52%"},{theoreticalVolume:"8.59 GB",effectiveVolume:"2.58 GB",batchDepth:21,utilizationRate:"30.04%"},{theoreticalVolume:"17.18 GB",effectiveVolume:"7.67 GB",batchDepth:22,utilizationRate:"44.62%"},{theoreticalVolume:"34.36 GB",effectiveVolume:"19.78 GB",batchDepth:23,utilizationRate:"57.56%"},{theoreticalVolume:"68.72 GB",effectiveVolume:"46.69 GB",batchDepth:24,utilizationRate:"67.93%"},{theoreticalVolume:"137.44 GB",effectiveVolume:"104.68 GB",batchDepth:25,utilizationRate:"76.16%"},{theoreticalVolume:"274.88 GB",effectiveVolume:"226.19 GB",batchDepth:26,utilizationRate:"82.29%"},{theoreticalVolume:"549.76 GB",effectiveVolume:"472.93 GB",batchDepth:27,utilizationRate:"86.02%"},{theoreticalVolume:"1.10 TB",effectiveVolume:"985.83 GB",batchDepth:28,utilizationRate:"87.66%"},{theoreticalVolume:"2.20 TB",effectiveVolume:"2.03 TB",batchDepth:29,utilizationRate:"92.25%"},{theoreticalVolume:"4.40 TB",effectiveVolume:"4.14 TB",batchDepth:30,utilizationRate:"94.21%"},{theoreticalVolume:"8.80 TB",effectiveVolume:"8.39 TB",batchDepth:31,utilizationRate:"95.37%"},{theoreticalVolume:"17.59 TB",effectiveVolume:"16.93 TB",batchDepth:32,utilizationRate:"96.22%"},{theoreticalVolume:"35.18 TB",effectiveVolume:"34.09 TB",batchDepth:33,utilizationRate:"96.88%"},{theoreticalVolume:"70.37 TB",effectiveVolume:"68.50 TB",batchDepth:34,utilizationRate:"97.34%"},{theoreticalVolume:"140.74 TB",effectiveVolume:"137.45 TB",batchDepth:35,utilizationRate:"97.67%"},{theoreticalVolume:"281.47 TB",effectiveVolume:"275.53 TB",batchDepth:36,utilizationRate:"97.89%"},{theoreticalVolume:"562.95 TB",effectiveVolume:"551.97 TB",batchDepth:37,utilizationRate:"98.05%"},{theoreticalVolume:"1.13 PB",effectiveVolume:"1.11 PB",batchDepth:38,utilizationRate:"98.13%"},{theoreticalVolume:"2.25 PB",effectiveVolume:"2.21 PB",batchDepth:39,utilizationRate:"98.18%"},{theoreticalVolume:"4.50 PB",effectiveVolume:"4.43 PB",batchDepth:40,utilizationRate:"98.36%"},{theoreticalVolume:"9.01 PB",effectiveVolume:"8.86 PB",batchDepth:41,utilizationRate:"98.37%"}],[Gi.MEDIUM]:[{theoreticalVolume:"536.87 MB",effectiveVolume:"40.89 kB",batchDepth:17,utilizationRate:"0.01%"},{theoreticalVolume:"1.07 GB",effectiveVolume:"6.09 MB",batchDepth:18,utilizationRate:"0.56%"},{theoreticalVolume:"2.15 GB",effectiveVolume:"102.49 MB",batchDepth:19,utilizationRate:"4.65%"},{theoreticalVolume:"4.29 GB",effectiveVolume:"628.91 MB",batchDepth:20,utilizationRate:"14.30%"},{theoreticalVolume:"8.59 GB",effectiveVolume:"2.38 GB",batchDepth:21,utilizationRate:"27.68%"},{theoreticalVolume:"17.18 GB",effectiveVolume:"7.07 GB",batchDepth:22,utilizationRate:"41.15%"},{theoreticalVolume:"34.36 GB",effectiveVolume:"18.24 GB",batchDepth:23,utilizationRate:"53.09%"},{theoreticalVolume:"68.72 GB",effectiveVolume:"43.04 GB",batchDepth:24,utilizationRate:"62.63%"},{theoreticalVolume:"137.44 GB",effectiveVolume:"96.50 GB",batchDepth:25,utilizationRate:"70.21%"},{theoreticalVolume:"274.88 GB",effectiveVolume:"208.52 GB",batchDepth:26,utilizationRate:"75.86%"},{theoreticalVolume:"549.76 GB",effectiveVolume:"435.98 GB",batchDepth:27,utilizationRate:"79.30%"},{theoreticalVolume:"1.10 TB",effectiveVolume:"908.81 GB",batchDepth:28,utilizationRate:"80.82%"},{theoreticalVolume:"2.20 TB",effectiveVolume:"1.87 TB",batchDepth:29,utilizationRate:"84.98%"},{theoreticalVolume:"4.40 TB",effectiveVolume:"3.81 TB",batchDepth:30,utilizationRate:"86.67%"},{theoreticalVolume:"8.80 TB",effectiveVolume:"7.73 TB",batchDepth:31,utilizationRate:"87.84%"},{theoreticalVolume:"17.59 TB",effectiveVolume:"15.61 TB",batchDepth:32,utilizationRate:"88.74%"},{theoreticalVolume:"35.18 TB",effectiveVolume:"31.43 TB",batchDepth:33,utilizationRate:"89.34%"},{theoreticalVolume:"70.37 TB",effectiveVolume:"63.15 TB",batchDepth:34,utilizationRate:"89.74%"},{theoreticalVolume:"140.74 TB",effectiveVolume:"126.71 TB",batchDepth:35,utilizationRate:"90.03%"},{theoreticalVolume:"281.47 TB",effectiveVolume:"254.01 TB",batchDepth:36,utilizationRate:"90.24%"},{theoreticalVolume:"562.95 TB",effectiveVolume:"508.85 TB",batchDepth:37,utilizationRate:"90.39%"},{theoreticalVolume:"1.13 PB",effectiveVolume:"1.02 PB",batchDepth:38,utilizationRate:"90.47%"},{theoreticalVolume:"2.25 PB",effectiveVolume:"2.04 PB",batchDepth:39,utilizationRate:"90.51%"},{theoreticalVolume:"4.50 PB",effectiveVolume:"4.08 PB",batchDepth:40,utilizationRate:"90.64%"},{theoreticalVolume:"9.01 PB",effectiveVolume:"8.17 PB",batchDepth:41,utilizationRate:"90.65%"}],[Gi.STRONG]:[{theoreticalVolume:"536.87 MB",effectiveVolume:"36.73 kB",batchDepth:17,utilizationRate:"0.01%"},{theoreticalVolume:"1.07 GB",effectiveVolume:"5.47 MB",batchDepth:18,utilizationRate:"0.50%"},{theoreticalVolume:"2.15 GB",effectiveVolume:"92.07 MB",batchDepth:19,utilizationRate:"4.18%"},{theoreticalVolume:"4.29 GB",effectiveVolume:"564.95 MB",batchDepth:20,utilizationRate:"12.85%"},{theoreticalVolume:"8.59 GB",effectiveVolume:"2.13 GB",batchDepth:21,utilizationRate:"24.86%"},{theoreticalVolume:"17.18 GB",effectiveVolume:"6.35 GB",batchDepth:22,utilizationRate:"36.97%"},{theoreticalVolume:"34.36 GB",effectiveVolume:"16.38 GB",batchDepth:23,utilizationRate:"47.67%"},{theoreticalVolume:"68.72 GB",effectiveVolume:"38.66 GB",batchDepth:24,utilizationRate:"56.26%"},{theoreticalVolume:"137.44 GB",effectiveVolume:"86.69 GB",batchDepth:25,utilizationRate:"63.07%"},{theoreticalVolume:"274.88 GB",effectiveVolume:"187.31 GB",batchDepth:26,utilizationRate:"68.14%"},{theoreticalVolume:"549.76 GB",effectiveVolume:"391.64 GB",batchDepth:27,utilizationRate:"71.24%"},{theoreticalVolume:"1.10 TB",effectiveVolume:"816.39 GB",batchDepth:28,utilizationRate:"72.59%"},{theoreticalVolume:"2.20 TB",effectiveVolume:"1.68 TB",batchDepth:29,utilizationRate:"76.34%"},{theoreticalVolume:"4.40 TB",effectiveVolume:"3.43 TB",batchDepth:30,utilizationRate:"77.89%"},{theoreticalVolume:"8.80 TB",effectiveVolume:"6.94 TB",batchDepth:31,utilizationRate:"78.86%"},{theoreticalVolume:"17.59 TB",effectiveVolume:"14.02 TB",batchDepth:32,utilizationRate:"79.71%"},{theoreticalVolume:"35.18 TB",effectiveVolume:"28.23 TB",batchDepth:33,utilizationRate:"80.23%"},{theoreticalVolume:"70.37 TB",effectiveVolume:"56.72 TB",batchDepth:34,utilizationRate:"80.60%"},{theoreticalVolume:"140.74 TB",effectiveVolume:"113.82 TB",batchDepth:35,utilizationRate:"80.88%"},{theoreticalVolume:"281.47 TB",effectiveVolume:"228.18 TB",batchDepth:36,utilizationRate:"81.06%"},{theoreticalVolume:"562.95 TB",effectiveVolume:"457.10 TB",batchDepth:37,utilizationRate:"81.20%"},{theoreticalVolume:"1.13 PB",effectiveVolume:"915.26 TB",batchDepth:38,utilizationRate:"81.26%"},{theoreticalVolume:"2.25 PB",effectiveVolume:"1.83 PB",batchDepth:39,utilizationRate:"81.30%"},{theoreticalVolume:"4.50 PB",effectiveVolume:"3.67 PB",batchDepth:40,utilizationRate:"81.43%"},{theoreticalVolume:"9.01 PB",effectiveVolume:"7.34 PB",batchDepth:41,utilizationRate:"81.45%"}],[Gi.INSANE]:[{theoreticalVolume:"536.87 MB",effectiveVolume:"33.26 kB",batchDepth:17,utilizationRate:"0.01%"},{theoreticalVolume:"1.07 GB",effectiveVolume:"4.96 MB",batchDepth:18,utilizationRate:"0.45%"},{theoreticalVolume:"2.15 GB",effectiveVolume:"83.38 MB",batchDepth:19,utilizationRate:"3.79%"},{theoreticalVolume:"4.29 GB",effectiveVolume:"511.65 MB",batchDepth:20,utilizationRate:"11.64%"},{theoreticalVolume:"8.59 GB",effectiveVolume:"1.93 GB",batchDepth:21,utilizationRate:"22.52%"},{theoreticalVolume:"17.18 GB",effectiveVolume:"5.75 GB",batchDepth:22,utilizationRate:"33.50%"},{theoreticalVolume:"34.36 GB",effectiveVolume:"14.84 GB",batchDepth:23,utilizationRate:"43.19%"},{theoreticalVolume:"68.72 GB",effectiveVolume:"35.02 GB",batchDepth:24,utilizationRate:"50.96%"},{theoreticalVolume:"137.44 GB",effectiveVolume:"78.51 GB",batchDepth:25,utilizationRate:"57.12%"},{theoreticalVolume:"274.88 GB",effectiveVolume:"169.64 GB",batchDepth:26,utilizationRate:"61.71%"},{theoreticalVolume:"549.76 GB",effectiveVolume:"354.69 GB",batchDepth:27,utilizationRate:"64.52%"},{theoreticalVolume:"1.10 TB",effectiveVolume:"739.37 GB",batchDepth:28,utilizationRate:"65.74%"},{theoreticalVolume:"2.20 TB",effectiveVolume:"1.52 TB",batchDepth:29,utilizationRate:"69.15%"},{theoreticalVolume:"4.40 TB",effectiveVolume:"3.10 TB",batchDepth:30,utilizationRate:"70.56%"},{theoreticalVolume:"8.80 TB",effectiveVolume:"6.29 TB",batchDepth:31,utilizationRate:"71.48%"},{theoreticalVolume:"17.59 TB",effectiveVolume:"12.70 TB",batchDepth:32,utilizationRate:"72.18%"},{theoreticalVolume:"35.18 TB",effectiveVolume:"25.57 TB",batchDepth:33,utilizationRate:"72.67%"},{theoreticalVolume:"70.37 TB",effectiveVolume:"51.37 TB",batchDepth:34,utilizationRate:"73.00%"},{theoreticalVolume:"140.74 TB",effectiveVolume:"103.08 TB",batchDepth:35,utilizationRate:"73.24%"},{theoreticalVolume:"281.47 TB",effectiveVolume:"206.65 TB",batchDepth:36,utilizationRate:"73.42%"},{theoreticalVolume:"562.95 TB",effectiveVolume:"413.98 TB",batchDepth:37,utilizationRate:"73.54%"},{theoreticalVolume:"1.13 PB",effectiveVolume:"828.91 TB",batchDepth:38,utilizationRate:"73.59%"},{theoreticalVolume:"2.25 PB",effectiveVolume:"1.66 PB",batchDepth:39,utilizationRate:"73.62%"},{theoreticalVolume:"4.50 PB",effectiveVolume:"3.32 PB",batchDepth:40,utilizationRate:"73.72%"},{theoreticalVolume:"9.01 PB",effectiveVolume:"6.64 PB",batchDepth:41,utilizationRate:"73.74%"}],[Gi.PARANOID]:[{theoreticalVolume:"536.87 MB",effectiveVolume:"13.17 kB",batchDepth:17,utilizationRate:"0.00%"},{theoreticalVolume:"1.07 GB",effectiveVolume:"1.96 MB",batchDepth:18,utilizationRate:"0.18%"},{theoreticalVolume:"2.15 GB",effectiveVolume:"33.01 MB",batchDepth:19,utilizationRate:"1.50%"},{theoreticalVolume:"4.29 GB",effectiveVolume:"202.53 MB",batchDepth:20,utilizationRate:"4.61%"},{theoreticalVolume:"8.59 GB",effectiveVolume:"765.05 MB",batchDepth:21,utilizationRate:"8.68%"},{theoreticalVolume:"17.18 GB",effectiveVolume:"2.28 GB",batchDepth:22,utilizationRate:"13.27%"},{theoreticalVolume:"34.36 GB",effectiveVolume:"5.87 GB",batchDepth:23,utilizationRate:"17.08%"},{theoreticalVolume:"68.72 GB",effectiveVolume:"13.86 GB",batchDepth:24,utilizationRate:"20.17%"},{theoreticalVolume:"137.44 GB",effectiveVolume:"31.08 GB",batchDepth:25,utilizationRate:"22.61%"},{theoreticalVolume:"274.88 GB",effectiveVolume:"67.15 GB",batchDepth:26,utilizationRate:"24.43%"},{theoreticalVolume:"549.76 GB",effectiveVolume:"140.40 GB",batchDepth:27,utilizationRate:"25.54%"},{theoreticalVolume:"1.10 TB",effectiveVolume:"292.67 GB",batchDepth:28,utilizationRate:"26.03%"},{theoreticalVolume:"2.20 TB",effectiveVolume:"602.12 GB",batchDepth:29,utilizationRate:"27.35%"},{theoreticalVolume:"4.40 TB",effectiveVolume:"1.23 TB",batchDepth:30,utilizationRate:"27.94%"},{theoreticalVolume:"8.80 TB",effectiveVolume:"2.49 TB",batchDepth:31,utilizationRate:"28.32%"},{theoreticalVolume:"17.59 TB",effectiveVolume:"5.03 TB",batchDepth:32,utilizationRate:"28.60%"},{theoreticalVolume:"35.18 TB",effectiveVolume:"10.12 TB",batchDepth:33,utilizationRate:"28.77%"},{theoreticalVolume:"70.37 TB",effectiveVolume:"20.34 TB",batchDepth:34,utilizationRate:"28.91%"},{theoreticalVolume:"140.74 TB",effectiveVolume:"40.80 TB",batchDepth:35,utilizationRate:"29.00%"},{theoreticalVolume:"281.47 TB",effectiveVolume:"81.80 TB",batchDepth:36,utilizationRate:"29.06%"},{theoreticalVolume:"562.95 TB",effectiveVolume:"163.87 TB",batchDepth:37,utilizationRate:"29.11%"},{theoreticalVolume:"1.13 PB",effectiveVolume:"328.11 TB",batchDepth:38,utilizationRate:"29.14%"},{theoreticalVolume:"2.25 PB",effectiveVolume:"656.76 TB",batchDepth:39,utilizationRate:"29.16%"},{theoreticalVolume:"4.50 PB",effectiveVolume:"1.31 PB",batchDepth:40,utilizationRate:"29.18%"},{theoreticalVolume:"9.01 PB",effectiveVolume:"2.63 PB",batchDepth:41,utilizationRate:"29.19%"}]}};class Wi{constructor(e){this.seconds=Math.ceil(e),e<0&&(this.seconds=0)}static fromMilliseconds(e){return new Wi(e/1e3)}static fromSeconds(e){return new Wi(e)}static fromHours(e){return new Wi(60*e*60)}static fromDays(e){return new Wi(24*e*60*60)}static fromWeeks(e){return new Wi(7*e*24*60*60)}static fromYears(e){return new Wi(365*e*24*60*60)}static fromEndDate(e,t){return new Wi((e.getTime()-(t??new Date).getTime())/1e3)}static parseFromString(e){return Wi.fromSeconds(Wr.make(e)/1e3)}toSeconds(){return this.seconds}toHours(){return this.seconds/60/60}toDays(){return this.seconds/24/60/60}toWeeks(){return this.seconds/7/24/60/60}toYears(){return this.seconds/365/24/60/60}toEndDate(e){return new Date((e??new Date).getTime()+1e3*this.seconds)}represent(){return Wr.secondsToHumanTime(this.seconds)}isZero(){return 0===this.seconds}}Wi.ZERO=new Wi(0);class Zi{constructor(e){if(this.bytes=Math.ceil(e),e<0)throw Error("Size must be at least 0")}static fromBytes(e){return new Zi(e)}static fromKilobytes(e){return new Zi(1e3*e)}static fromMegabytes(e){return new Zi(1e3*e*1e3)}static fromGigabytes(e){return new Zi(1e3*e*1e3*1e3)}static parseFromString(e){return Zi.fromBytes(Jr.makeStorage(e,1e3))}toBytes(){return this.bytes}toGigabytes(){return this.bytes/1e3/1e3/1e3}toFormattedString(){return Jr.convertBytes(this.bytes,1e3)}represent(){return this.toFormattedString()}}class Ji{constructor(e){this.state=e}static fromDecimalString(e){return new Ji(ri.fromDecimalString(e,Ji.DIGITS))}static fromPLUR(e){return new Ji(new ri(e,Ji.DIGITS))}toPLURString(){return this.state.toString()}toPLURBigInt(){return this.state.value}toDecimalString(){return this.state.toDecimalString()}toSignificantDigits(e){return this.toDecimalString().slice(0,this.toDecimalString().indexOf(".")+e+1)}plus(e){return new Ji(this.state.add(e instanceof Ji?e.state:new ri(e,Ji.DIGITS)))}minus(e){return new Ji(this.state.subtract(e instanceof Ji?e.state:new ri(e,Ji.DIGITS)))}divide(e){return new Ji(this.state.divmod(e)[0])}gt(e){return 1===this.state.compare(e.state)}gte(e){return-1!==this.state.compare(e.state)}lt(e){return-1===this.state.compare(e.state)}lte(e){return 1!==this.state.compare(e.state)}eq(e){return 0===this.state.compare(e.state)}exchangeToDAI(e){return Xi.fromWei(this.state.exchange("*",new ri(e.toWeiBigInt(),Xi.DIGITS),Xi.DIGITS).value)}}Ji.DIGITS=16;class Xi{constructor(e){this.state=e}static fromDecimalString(e){return new Xi(ri.fromDecimalString(e,Xi.DIGITS))}static fromWei(e){return new Xi(new ri(e,Xi.DIGITS))}toWeiString(){return this.state.toString()}toWeiBigInt(){return this.state.value}toDecimalString(){return this.state.toDecimalString()}toSignificantDigits(e){return this.toDecimalString().slice(0,this.toDecimalString().indexOf(".")+e+1)}plus(e){return new Xi(this.state.add(e instanceof Xi?e.state:new ri(e,Xi.DIGITS)))}minus(e){return new Xi(this.state.subtract(e instanceof Xi?e.state:new ri(e,Xi.DIGITS)))}divide(e){return new Xi(this.state.divmod(e)[0])}gt(e){return 1===this.state.compare(e.state)}gte(e){return-1!==this.state.compare(e.state)}lt(e){return-1===this.state.compare(e.state)}lte(e){return 1!==this.state.compare(e.state)}eq(e){return 0===this.state.compare(e.state)}exchangeToBZZ(e){return Ji.fromPLUR(this.state.exchange("/",new ri(e.toWeiBigInt(),Xi.DIGITS),Ji.DIGITS).value)}}function Yi(e){if("function"==typeof File&&e instanceof File)return!0;const t=e;return"object"==typeof t&&"string"==typeof t.name&&("function"==typeof t.stream||"function"==typeof t.arrayBuffer)}async function Qi(e){return e.arrayBuffer?e.arrayBuffer():new Promise(t=>{const n=new FileReader;n.onload=()=>t(n.result),n.readAsArrayBuffer(e)})}function eo(e,t){return"bigint"==typeof e&&(e=e.toString()),ei.asIntegerString(e,t)}function to(e){const t=ei.asObject(e,{name:"DownloadOptions"});return{redundancyStrategy:ei.asOptional(e=>ei.asInteger(e,{name:"redundancyStrategy"}),t.redundancyStrategy),fallback:ei.asOptional(e=>ei.asBoolean(e,{name:"fallback"}),t.fallback),timeoutMs:ei.asOptional(e=>ei.asInteger(e,{name:"timeoutMs",min:0}),t.timeoutMs),actPublisher:ei.asOptional(e=>new Si(e),t.actPublisher),actHistoryAddress:ei.asOptional(e=>new Ti(e),t.actHistoryAddress),actTimestamp:ei.asOptional(e=>ei.asNumber(e,{name:"actTimestamp"}),t.actTimestamp)}}function no(e,t="UploadOptions"){const n=ei.asObject(e,{name:t});return{act:ei.asOptional(e=>ei.asBoolean(e,{name:"act"}),n.act),actHistoryAddress:ei.asOptional(e=>new Ti(e),n.actHistoryAddress),deferred:ei.asOptional(e=>ei.asBoolean(e,{name:"deferred"}),n.deferred),encrypt:ei.asOptional(e=>ei.asBoolean(e,{name:"encrypt"}),n.encrypt),pin:ei.asOptional(e=>ei.asBoolean(e,{name:"pin"}),n.pin),tag:ei.asOptional(e=>ei.asInteger(e,{name:"tag",min:0}),n.tag)}}function ro(e){const t=no(e,"CollectionUploadOptions"),n=ei.asObject(e,{name:"CollectionUploadOptions"});return{...t,errorDocument:ei.asOptional(e=>ei.asString(e,{name:"errorDocument"}),n.errorDocument),indexDocument:ei.asOptional(e=>ei.asString(e,{name:"indexDocument"}),n.indexDocument),redundancyLevel:ei.asOptional(e=>ei.asInteger(e,{name:"redundancyLevel",min:0}),n.redundancyLevel)}}function io(e){const t=ei.asObject(e,{name:"PostageBatchOptions"});return{gasPrice:ei.asOptional(e=>eo(e,{name:"gasPrice"}),t.gasPrice),immutableFlag:ei.asOptional(e=>ei.asBoolean(e,{name:"immutableFlag"}),t.immutableFlag),label:ei.asOptional(e=>ei.asString(e,{name:"label"}),t.label),waitForUsable:ei.asOptional(e=>ei.asBoolean(e,{name:"waitForUsable"}),t.waitForUsable),waitForUsableTimeout:ei.asOptional(e=>ei.asInteger(e,{name:"waitForUsableTimeout",min:0}),t.waitForUsableTimeout)}}function oo(e,t="TransactionOptions"){const n=ei.asObject(e,{name:t});return{gasLimit:ei.asOptional(e=>eo(e,{name:"gasLimit",min:0n}),n.gasLimit),gasPrice:ei.asOptional(e=>eo(e,{name:"gasPrice",min:0n}),n.gasPrice)}}function ao(e){if("string"!=typeof e&&!(e instanceof Uint8Array))throw new TypeError("Data must be either string or Uint8Array!")}function so(e){if(null==e)throw new TypeError(`Expected number | Tag | string from tagUid, got: ${e}`);if(function(e){try{const t=ei.asObject(e,{name:"Tag"});return ei.asInteger(t.uid,{name:"Tag.uid"}),!0}catch{return!1}}(e))return e.uid;if("number"==typeof e||"string"==typeof e)return ei.asNumber(e,{name:"tagUid",min:0});throw new TypeError(`Expected number | Tag | string from tagUid, got: ${e}`)}Xi.DIGITS=18;function co(e){return 4096*2**e}const uo=[[17,4089e-8],[18,.00609],[19,.10249],[20,.62891],[21,2.38],[22,7.07],[23,18.24],[24,43.04],[25,96.5],[26,208.52],[27,435.98],[28,908.81],[29,1870],[30,3810],[31,7730],[32,15610],[33,31430],[34,63150]];function lo(e,t,n){if(e<17)return 0;if(void 0!==t&&void 0!==n){const r=Hi[t?"ENCRYPTION_ON":"ENCRYPTION_OFF"][n].find(t=>t.batchDepth===e);if(r?.effectiveVolume)return bi(r.effectiveVolume)}else{const t=uo.find(([t,n])=>{if(e===t)return n});if(t)return 1e3*t[1]*1e3*1e3}return Math.ceil(.9*co(e))}function ho(e,t){return Ji.fromPLUR(2n**BigInt(e)*BigInt(t))}function fo(e,t,n){return BigInt(e.toSeconds())/BigInt(n)*BigInt(t)+1n}function po(e,t,n){if(void 0!==t&&void 0!==n){const r=Hi[t?"ENCRYPTION_ON":"ENCRYPTION_OFF"][n].find(t=>e.toBytes()<=bi(t.effectiveVolume));if(r?.effectiveVolume)return r.batchDepth}else for(const[t,n]of uo)if(e.toBytes()<=1e3*n*1e3*1e3)return t;return 35}function mo(e){return function(e,t,n,r){if(65!==e.length)throw Error("invalid signature length");if(32!==t.length)throw Error("invalid batch ID length");if(8!==n.length)throw Error("invalid timestamp length");if(8!==r.length)throw Error("invalid index length");return new wi(Hr.concatBytes(t,r,n,e))}(e.signature,e.batchId.toUint8Array(),e.timestamp,e.index)}function go(e,t,n){const r=(i=e.utilization,o=e.depth,a=e.bucketDepth,i/Math.pow(2,o-a));var i,o,a;const s=function(e){return Number.isInteger(e)?e<1?1:e>3155695200?3155695200:e:1}(e.batchTTL),c=Wi.fromSeconds(s),u=lo(e.depth,t,n);return{batchID:new Ci(e.batchID),utilization:e.utilization,usable:e.usable,label:e.label,depth:e.depth,amount:eo(e.amount),bucketDepth:e.bucketDepth,blockNumber:e.blockNumber,immutableFlag:e.immutableFlag,usage:r,usageText:`${Math.round(100*r)}%`,size:Zi.fromBytes(u),remainingSize:Zi.fromBytes(Math.ceil(u*(1-r))),theoreticalSize:Zi.fromBytes(co(e.depth)),duration:c,calculateSize(t,n){const r=lo(e.depth,t,n);return Zi.fromBytes(r)},calculateRemainingSize(t,n){const r=lo(e.depth,t,n);return Zi.fromBytes(Math.ceil(r*(1-this.usage)))}}}function yo(e){return{name:function(e){if(!e)throw new Ui("missing content-disposition header");const t=e.match(/filename\*?=['"]?(?:UTF-\d['"]*)?([^;\r\n"']*)['"]?;?/i);if(t&&t.length>0)return t[1];throw new Ui("invalid content-disposition header")}(e["content-disposition"]),tagUid:function(e){if(!e)return;return parseInt(e,10)}(e["swarm-tag-uid"]),contentType:e["content-type"]||void 0}}function wo(e,t){const n={};if(!function(e){if(!ei.isObject(e))return!1;const t=e;return void 0!==t.issuer&&void 0!==t.index&&void 0!==t.signature&&void 0!==t.timestamp&&void 0!==t.batchId}(e)?e&&(e=new Ci(e),n["swarm-postage-batch-id"]=e.toHex()):n["swarm-postage-stamp"]=mo(e).toHex(),!t)return n;const r=ei.asObject(t);return r.size&&(n["content-length"]=String(r.size)),r.contentType&&(n["content-type"]=String(r.contentType)),r.redundancyLevel&&(n["swarm-redundancy-level"]=String(r.redundancyLevel)),ei.isBoolean(r.act)&&(n["swarm-act"]=String(r.act)),ei.isBoolean(r.pin)&&(n["swarm-pin"]=String(r.pin)),ei.isBoolean(r.encrypt)&&(n["swarm-encrypt"]=r.encrypt.toString()),r.tag&&(n["swarm-tag"]=String(r.tag)),ei.isBoolean(r.deferred)&&(n["swarm-deferred-upload"]=r.deferred.toString()),r.redundancyStrategy&&(n["swarm-redundancy-strategy"]=String(r.redundancyStrategy)),ei.isBoolean(r.fallback)&&(n["swarm-redundancy-fallback-mode"]=r.fallback.toString()),r.timeoutMs&&(n["swarm-chunk-retrieval-timeout"]=String(r.timeoutMs)),r.indexDocument&&(n["swarm-index-document"]=String(r.indexDocument)),r.errorDocument&&(n["swarm-error-document"]=String(r.errorDocument)),r.actPublisher&&(n["swarm-act-publisher"]=new Si(r.actPublisher).toCompressedHex()),r.actHistoryAddress&&(n["swarm-act-history-address"]=new Ti(r.actHistoryAddress).toHex()),r.actTimestamp&&(n["swarm-act-timestamp"]=String(r.actTimestamp)),(r.actPublisher||r.actHistoryAddress||r.actTimestamp)&&(n["swarm-act"]="true"),r.gasPrice&&(n["gas-price"]=String(r.gasPrice)),r.gasLimit&&(n["gas-limit"]=String(r.gasLimit)),n}var bo,vo,xo,Eo,Ao,Ro,So,Io,ko,To,Bo,Oo,Do,Co,$o,zo,Fo,Po,Uo,qo,No,Mo,_o,Vo,Lo,jo,Go,Ko,Ho,Wo,Zo,Jo,Xo,Yo,Qo,ea,ta,na,ra,ia,oa,aa,sa,ca,ua,la,da,ha,fa,pa,ma,ga,ya,wa,ba,va,xa,Ea,Aa,Ra,Sa,Ia,ka,Ta,Ba,Oa,Da,Ca,$a,za,Fa,Pa,Ua,qa,Na,Ma,_a,Va,La,ja={exports:{}};function Ga(){return vo||(vo=1,bo=function(e,t){return function(){return e.apply(t,arguments)}}),bo}function Ka(){if(Eo)return xo;Eo=1;var e,t=Ga(),n=Object.prototype.toString,r=(e=Object.create(null),function(t){var r=n.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())});function i(e){return e=e.toLowerCase(),function(t){return r(t)===e}}function o(e){return Array.isArray(e)}function a(e){return void 0===e}var s=i("ArrayBuffer");function c(e){return"number"==typeof e}function u(e){return null!==e&&"object"==typeof e}function l(e){if("object"!==r(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}var d=i("Date"),h=i("File"),f=i("Blob"),p=i("FileList");function m(e){return"[object Function]"===n.call(e)}var g=i("URLSearchParams");function y(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),o(e))for(var n=0,r=e.length;n<r;n++)t.call(null,e[n],n,e);else for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.call(null,e[i],i,e)}var w,b=(w="undefined"!=typeof Uint8Array&&Object.getPrototypeOf(Uint8Array),function(e){return w&&e instanceof w});var v,x=i("HTMLFormElement"),E=(v=Object.prototype.hasOwnProperty,function(e,t){return v.call(e,t)});return xo={isArray:o,isArrayBuffer:s,isBuffer:function(e){return null!==e&&!a(e)&&null!==e.constructor&&!a(e.constructor)&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)},isFormData:function(e){var t="[object FormData]";return e&&("function"==typeof FormData&&e instanceof FormData||n.call(e)===t||m(e.toString)&&e.toString()===t)},isArrayBufferView:function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&s(e.buffer)},isString:function(e){return"string"==typeof e},isNumber:c,isObject:u,isPlainObject:l,isEmptyObject:function(e){return e&&0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype},isUndefined:a,isDate:d,isFile:h,isBlob:f,isFunction:m,isStream:function(e){return u(e)&&m(e.pipe)},isURLSearchParams:g,isStandardBrowserEnv:function(){var e;return("undefined"==typeof navigator||"ReactNative"!==(e=navigator.product)&&"NativeScript"!==e&&"NS"!==e)&&("undefined"!=typeof window&&"undefined"!=typeof document)},forEach:y,merge:function e(){var t={};function n(n,r){"__proto__"!==r&&"constructor"!==r&&"prototype"!==r&&(l(t[r])&&l(n)?t[r]=e(t[r],n):l(n)?t[r]=e({},n):o(n)?t[r]=n.slice():t[r]=n)}for(var r=0,i=arguments.length;r<i;r++)y(arguments[r],n);return t},extend:function(e,n,r){return y(n,function(n,i){e[i]=r&&"function"==typeof n?t(n,r):n}),e},trim:function(e){return e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},stripBOM:function(e){return 65279===e.charCodeAt(0)&&(e=e.slice(1)),e},inherits:function(e,t,n,r){e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,n&&Object.assign(e.prototype,n)},toFlatObject:function(e,t,n,r){var i,o,a,s={};if(t=t||{},null==e)return t;do{for(o=(i=Object.getOwnPropertyNames(e)).length;o-- >0;)a=i[o],r&&!r(a,e,t)||s[a]||(t[a]=e[a],s[a]=!0);e=!1!==n&&Object.getPrototypeOf(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:r,kindOfTest:i,endsWith:function(e,t,n){e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;var r=e.indexOf(t,n);return-1!==r&&r===n},toArray:function(e){if(!e)return null;if(o(e))return e;var t=e.length;if(!c(t))return null;for(var n=new Array(t);t-- >0;)n[t]=e[t];return n},isTypedArray:b,isFileList:p,forEachEntry:function(e,t){for(var n,r=(e&&e[Symbol.iterator]).call(e);(n=r.next())&&!n.done;){var i=n.value;t.call(e,i[0],i[1])}},matchAll:function(e,t){for(var n,r=[];null!==(n=e.exec(t));)r.push(n);return r},isHTMLForm:x,hasOwnProperty:E},xo}function Ha(){if(Ro)return Ao;Ro=1;var e=Ka();function t(e,t,n,r,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),i&&(this.response=i)}e.inherits(t,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}}});var n=t.prototype,r={};return["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(function(e){r[e]={value:e}}),Object.defineProperties(t,r),Object.defineProperty(n,"isAxiosError",{value:!0}),t.from=function(r,i,o,a,s,c){var u=Object.create(n);return e.toFlatObject(r,u,function(e){return e!==Error.prototype}),t.call(u,r.message,i,o,a,s),u.cause=r,u.name=r.name,c&&Object.assign(u,c),u},Ao=t}function Wa(){return To?ko:(To=1,ko=Io?So:(Io=1,So="object"==typeof self?self.FormData:window.FormData))}function Za(){if(Oo)return Bo;Oo=1;var e=Ka(),t=Ha(),n=Wa();function r(t){return e.isPlainObject(t)||e.isArray(t)}function i(t){return e.endsWith(t,"[]")?t.slice(0,-2):t}function o(e,t,n){return e?e.concat(t).map(function(e,t){return e=i(e),!n&&t?"["+e+"]":e}).join(n?".":""):t}var a=e.toFlatObject(e,{},null,function(e){return/^is[A-Z]/.test(e)});return Bo=function(s,c,u){if(!e.isObject(s))throw new TypeError("target must be an object");c=c||new(n||FormData);var l,d=(u=e.toFlatObject(u,{metaTokens:!0,dots:!1,indexes:!1},!1,function(t,n){return!e.isUndefined(n[t])})).metaTokens,h=u.visitor||y,f=u.dots,p=u.indexes,m=(u.Blob||"undefined"!=typeof Blob&&Blob)&&((l=c)&&e.isFunction(l.append)&&"FormData"===l[Symbol.toStringTag]&&l[Symbol.iterator]);if(!e.isFunction(h))throw new TypeError("visitor must be a function");function g(n){if(null===n)return"";if(e.isDate(n))return n.toISOString();if(!m&&e.isBlob(n))throw new t("Blob is not supported. Use a Buffer instead.");return e.isArrayBuffer(n)||e.isTypedArray(n)?m&&"function"==typeof Blob?new Blob([n]):Buffer.from(n):n}function y(t,n,a){var s=t;if(t&&!a&&"object"==typeof t)if(e.endsWith(n,"{}"))n=d?n:n.slice(0,-2),t=JSON.stringify(t);else if(e.isArray(t)&&function(t){return e.isArray(t)&&!t.some(r)}(t)||e.isFileList(t)||e.endsWith(n,"[]")&&(s=e.toArray(t)))return n=i(n),s.forEach(function(t,r){!e.isUndefined(t)&&null!==t&&c.append(!0===p?o([n],r,f):null===p?n:n+"[]",g(t))}),!1;return!!r(t)||(c.append(o(a,n,f),g(t)),!1)}var w=[],b=Object.assign(a,{defaultVisitor:y,convertValue:g,isVisitable:r});if(!e.isObject(s))throw new TypeError("data must be an object");return function t(n,r){if(!e.isUndefined(n)){if(-1!==w.indexOf(n))throw Error("Circular reference detected in "+r.join("."));w.push(n),e.forEach(n,function(n,i){!0===(!(e.isUndefined(n)||null===n)&&h.call(c,n,e.isString(i)?i.trim():i,r,b))&&t(n,r?r.concat(i):[i])}),w.pop()}}(s),c}}function Ja(){if(Co)return Do;Co=1;var e=Za();function t(e){var t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'\(\)~]|%20|%00/g,function(e){return t[e]})}function n(t,n){this._pairs=[],t&&e(t,this,n)}var r=n.prototype;return r.append=function(e,t){this._pairs.push([e,t])},r.toString=function(e){var n=e?function(n){return e.call(this,n,t)}:t;return this._pairs.map(function(e){return n(e[0])+"="+n(e[1])},"").join("&")},Do=n}function Xa(){if(zo)return $o;zo=1;var e=Ka(),t=Ja();function n(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}return $o=function(r,i,o){if(!i)return r;var a=r.indexOf("#");-1!==a&&(r=r.slice(0,a));var s,c=o&&o.encode||n,u=o&&o.serialize;return(s=u?u(i,o):e.isURLSearchParams(i)?i.toString():new t(i,o).toString(c))&&(r+=(-1===r.indexOf("?")?"?":"&")+s),r},$o}function Ya(){if(qo)return Uo;qo=1;var e=Ka();return Uo=function(t,n){e.forEach(t,function(e,r){r!==n&&r.toUpperCase()===n.toUpperCase()&&(t[n]=e,delete t[r])})}}function Qa(){return Mo?No:(Mo=1,No={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1})}function es(){if(Vo)return _o;Vo=1;var e=Ja();return _o="undefined"!=typeof URLSearchParams?URLSearchParams:e}function ts(){return Wo?Ho:(Wo=1,Ho=Ko?Go:(Ko=1,Go={isBrowser:!0,classes:{URLSearchParams:es(),FormData:jo?Lo:(jo=1,Lo=FormData),Blob:Blob},protocols:["http","https","file","blob","url","data"]}))}function ns(){if(Jo)return Zo;Jo=1;var e=Ka(),t=Za(),n=ts();return Zo=function(r,i){return t(r,new n.classes.URLSearchParams,Object.assign({visitor:function(t,r,i,o){return n.isNode&&e.isBuffer(t)?(this.append(r,t.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)}},i))},Zo}function rs(){if(Yo)return Xo;Yo=1;var e=Ka();return Xo=function(t){function n(t,r,i,o){var a=t[o++];if("__proto__"===a)return!0;var s=Number.isFinite(+a),c=o>=t.length;return a=!a&&e.isArray(i)?i.length:a,c?(e.hasOwnProperty(i,a)?i[a]=[i[a],r]:i[a]=r,!s):(i[a]&&e.isObject(i[a])||(i[a]=[]),n(t,r,i[a],o)&&e.isArray(i[a])&&(i[a]=function(e){var t,n,r={},i=Object.keys(e),o=i.length;for(t=0;t<o;t++)r[n=i[t]]=e[n];return r}(i[a])),!s)}if(e.isFormData(t)&&e.isFunction(t.entries)){var r={};return e.forEachEntry(t,function(t,i){n(function(t){return e.matchAll(/\w+|\[(\w*)]/g,t).map(function(e){return"[]"===e[0]?"":e[1]||e[0]})}(t),i,r,0)}),r}return null}}function is(){if(ea)return Qo;ea=1;var e=Ha();return Qo=function(t,n,r){var i=r.config.validateStatus;r.status&&i&&!i(r.status)?n(new e("Request failed with status code "+r.status,[e.ERR_BAD_REQUEST,e.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):t(r)}}function os(){if(na)return ta;na=1;var e=Ka();return ta=e.isStandardBrowserEnv()?{write:function(t,n,r,i,o,a){var s=[];s.push(t+"="+encodeURIComponent(n)),e.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),e.isString(i)&&s.push("path="+i),e.isString(o)&&s.push("domain="+o),!0===a&&s.push("secure"),document.cookie=s.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}}function as(){return ia?ra:(ia=1,ra=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)})}function ss(){return aa?oa:(aa=1,oa=function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e})}function cs(){if(ca)return sa;ca=1;var e=as(),t=ss();return sa=function(n,r,i){var o=!e(r);return n&&(o||!1===i)?t(n,r):r}}function us(){if(la)return ua;la=1;var e=Ka(),t=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];return ua=function(n){var r,i,o,a={};return n?(e.forEach(n.split("\n"),function(n){if(o=n.indexOf(":"),r=e.trim(n.slice(0,o)).toLowerCase(),i=e.trim(n.slice(o+1)),r){if(a[r]&&t.indexOf(r)>=0)return;a[r]="set-cookie"===r?(a[r]?a[r]:[]).concat([i]):a[r]?a[r]+", "+i:i}}),a):a}}function ls(){if(ha)return da;ha=1;var e=Ka();return da=e.isStandardBrowserEnv()?function(){var t,n=/(msie|trident)/i.test(navigator.userAgent),r=document.createElement("a");function i(e){var t=e;return n&&(r.setAttribute("href",t),t=r.href),r.setAttribute("href",t),{href:r.href,protocol:r.protocol?r.protocol.replace(/:$/,""):"",host:r.host,search:r.search?r.search.replace(/^\?/,""):"",hash:r.hash?r.hash.replace(/^#/,""):"",hostname:r.hostname,port:r.port,pathname:"/"===r.pathname.charAt(0)?r.pathname:"/"+r.pathname}}return t=i(window.location.href),function(n){var r=e.isString(n)?i(n):n;return r.protocol===t.protocol&&r.host===t.host}}():function(){return!0}}function ds(){if(pa)return fa;pa=1;var e=Ha();function t(t,n,r){e.call(this,null==t?"canceled":t,e.ERR_CANCELED,n,r),this.name="CanceledError"}return Ka().inherits(t,e,{__CANCEL__:!0}),fa=t}function hs(){return ga?ma:(ga=1,ma=function(e){var t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""})}function fs(){if(wa)return ya;wa=1;var e=Ka(),t=is(),n=os(),r=Xa(),i=cs(),o=us(),a=ls(),s=Qa(),c=Ha(),u=ds(),l=hs(),d=ts();return ya=function(h){return new Promise(function(f,p){var m,g=h.data,y=h.headers,w=h.responseType,b=h.withXSRFToken;function v(){h.cancelToken&&h.cancelToken.unsubscribe(m),h.signal&&h.signal.removeEventListener("abort",m)}e.isFormData(g)&&e.isStandardBrowserEnv()&&delete y["Content-Type"];var x=new XMLHttpRequest;if(h.auth){var E=h.auth.username||"",A=h.auth.password?unescape(encodeURIComponent(h.auth.password)):"";y.Authorization="Basic "+btoa(E+":"+A)}var R=i(h.baseURL,h.url,h.allowAbsoluteUrls);function S(){if(x){var e="getAllResponseHeaders"in x?o(x.getAllResponseHeaders()):null,n={data:w&&"text"!==w&&"json"!==w?x.response:x.responseText,status:x.status,statusText:x.statusText,headers:e,config:h,request:x};t(function(e){f(e),v()},function(e){p(e),v()},n),x=null}}if(x.open(h.method.toUpperCase(),r(R,h.params,h.paramsSerializer),!0),x.timeout=h.timeout,"onloadend"in x?x.onloadend=S:x.onreadystatechange=function(){x&&4===x.readyState&&(0!==x.status||x.responseURL&&0===x.responseURL.indexOf("file:"))&&setTimeout(S)},x.onabort=function(){x&&(p(new c("Request aborted",c.ECONNABORTED,h,x)),x=null)},x.onerror=function(){p(new c("Network Error",c.ERR_NETWORK,h,x)),x=null},x.ontimeout=function(){var e=h.timeout?"timeout of "+h.timeout+"ms exceeded":"timeout exceeded",t=h.transitional||s;h.timeoutErrorMessage&&(e=h.timeoutErrorMessage),p(new c(e,t.clarifyTimeoutError?c.ETIMEDOUT:c.ECONNABORTED,h,x)),x=null},e.isStandardBrowserEnv()&&(b&&e.isFunction(b)&&(b=b(h)),b||!1!==b&&a(R))){var I=h.xsrfHeaderName&&h.xsrfCookieName&&n.read(h.xsrfCookieName);I&&(y[h.xsrfHeaderName]=I)}"setRequestHeader"in x&&e.forEach(y,function(e,t){void 0===g&&"content-type"===t.toLowerCase()?delete y[t]:x.setRequestHeader(t,e)}),e.isUndefined(h.withCredentials)||(x.withCredentials=!!h.withCredentials),w&&"json"!==w&&(x.responseType=h.responseType),"function"==typeof h.onDownloadProgress&&x.addEventListener("progress",h.onDownloadProgress),"function"==typeof h.onUploadProgress&&x.upload&&x.upload.addEventListener("progress",h.onUploadProgress),(h.cancelToken||h.signal)&&(m=function(e){x&&(p(!e||e.type?new u(null,h,x):e),x.abort(),x=null)},h.cancelToken&&h.cancelToken.subscribe(m),h.signal&&(h.signal.aborted?m():h.signal.addEventListener("abort",m))),g||!1===g||0===g||""===g||(g=null);var k=l(R);k&&-1===d.protocols.indexOf(k)?p(new c("Unsupported protocol "+k+":",c.ERR_BAD_REQUEST,h)):x.send(g)})},ya}function ps(){if(va)return ba;va=1;var e=Ka(),t=Ya(),n=Ha(),r=Qa(),i=Za(),o=ns(),a=ts(),s=rs(),c={"Content-Type":"application/x-www-form-urlencoded"};function u(t,n){!e.isUndefined(t)&&e.isUndefined(t["Content-Type"])&&(t["Content-Type"]=n)}var l,d={transitional:r,adapter:(("undefined"!=typeof XMLHttpRequest||"undefined"!=typeof process&&"[object process]"===Object.prototype.toString.call(process))&&(l=fs()),l),transformRequest:[function(n,r){t(r,"Accept"),t(r,"Content-Type");var a,c=r&&r["Content-Type"]||"",l=c.indexOf("application/json")>-1,d=e.isObject(n);if(d&&e.isHTMLForm(n)&&(n=new FormData(n)),e.isFormData(n))return l?JSON.stringify(s(n)):n;if(e.isArrayBuffer(n)||e.isBuffer(n)||e.isStream(n)||e.isFile(n)||e.isBlob(n))return n;if(e.isArrayBufferView(n))return n.buffer;if(e.isURLSearchParams(n))return u(r,"application/x-www-form-urlencoded;charset=utf-8"),n.toString();if(d){if(-1!==c.indexOf("application/x-www-form-urlencoded"))return o(n,this.formSerializer).toString();if((a=e.isFileList(n))||c.indexOf("multipart/form-data")>-1){var h=this.env&&this.env.FormData;return i(a?{"files[]":n}:n,h&&new h,this.formSerializer)}}return d||l?(u(r,"application/json"),function(t,n,r){if(e.isString(t))try{return(n||JSON.parse)(t),e.trim(t)}catch(e){if("SyntaxError"!==e.name)throw e}return(r||JSON.stringify)(t)}(n)):n}],transformResponse:[function(t){var r=this.transitional||d.transitional,i=r&&r.forcedJSONParsing,o="json"===this.responseType;if(t&&e.isString(t)&&(i&&!this.responseType||o)){var a=!(r&&r.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(e){if(a){if("SyntaxError"===e.name)throw n.from(e,n.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:a.classes.FormData,Blob:a.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};return e.forEach(["delete","get","head"],function(e){d.headers[e]={}}),e.forEach(["post","put","patch"],function(t){d.headers[t]=e.merge(c)}),ba=d}function ms(){if(Ea)return xa;Ea=1;var e=Ka(),t=ps();return xa=function(n,r,i,o){var a=this||t;return e.forEach(o,function(e){n=e.call(a,n,r,i)}),n},xa}function gs(){return Ra?Aa:(Ra=1,Aa=function(e){return!(!e||!e.__CANCEL__)})}function ys(){if(Ia)return Sa;Ia=1;var e=Ka(),t=ms(),n=gs(),r=ps(),i=ds(),o=Ya();function a(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new i}return Sa=function(i){return a(i),i.headers=i.headers||{},i.data=t.call(i,i.data,i.headers,null,i.transformRequest),o(i.headers,"Accept"),o(i.headers,"Content-Type"),i.headers=e.merge(i.headers.common||{},i.headers[i.method]||{},i.headers),e.forEach(["delete","get","head","post","put","patch","common"],function(e){delete i.headers[e]}),(i.adapter||r.adapter)(i).then(function(e){return a(i),e.data=t.call(i,e.data,e.headers,e.status,i.transformResponse),e},function(e){return n(e)||(a(i),e&&e.response&&(e.response.data=t.call(i,e.response.data,e.response.headers,e.response.status,i.transformResponse))),Promise.reject(e)})},Sa}function ws(){if(Ta)return ka;Ta=1;var e=Ka();return ka=function(t,n){n=n||{};var r={};function i(t,n){return e.isPlainObject(t)&&e.isPlainObject(n)?e.merge(t,n):e.isEmptyObject(n)?e.merge({},t):e.isPlainObject(n)?e.merge({},n):e.isArray(n)?n.slice():n}function o(r){return e.isUndefined(n[r])?e.isUndefined(t[r])?void 0:i(void 0,t[r]):i(t[r],n[r])}function a(t){if(!e.isUndefined(n[t]))return i(void 0,n[t])}function s(r){return e.isUndefined(n[r])?e.isUndefined(t[r])?void 0:i(void 0,t[r]):i(void 0,n[r])}function c(e){return e in n?i(t[e],n[e]):e in t?i(void 0,t[e]):void 0}var u={url:a,method:a,data:a,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:c};return e.forEach(Object.keys(t).concat(Object.keys(n)),function(t){if("__proto__"!==t&&"constructor"!==t&&"prototype"!==t){var n=e.hasOwnProperty(u,t)?u[t]:o,i=n(t);e.isUndefined(i)&&n!==c||(r[t]=i)}}),r},ka}function bs(){return Oa?Ba:(Oa=1,Ba={version:"0.30.3"})}function vs(){if(Ca)return Da;Ca=1;var e=bs().version,t=Ha(),n={};["object","boolean","number","function","string","symbol"].forEach(function(e,t){n[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});var r={};return n.transitional=function(n,i,o){function a(t,n){return"[Axios v"+e+"] Transitional option '"+t+"'"+n+(o?". "+o:"")}return function(e,o,s){if(!1===n)throw new t(a(o," has been removed"+(i?" in "+i:"")),t.ERR_DEPRECATED);return i&&!r[o]&&(r[o]=!0,console.warn(a(o," has been deprecated since v"+i+" and will be removed in the near future"))),!n||n(e,o,s)}},Da={assertOptions:function(e,n,r){if("object"!=typeof e)throw new t("options must be an object",t.ERR_BAD_OPTION_VALUE);for(var i=Object.keys(e),o=i.length;o-- >0;){var a=i[o],s=n[a];if(s){var c=e[a],u=void 0===c||s(c,a,e);if(!0!==u)throw new t("option "+a+" must be "+u,t.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new t("Unknown option "+a,t.ERR_BAD_OPTION)}},validators:n}}function xs(){if(za)return $a;za=1;var e=Ka(),t=Xa(),n=function(){if(Po)return Fo;Po=1;var e=Ka();function t(){this.handlers=[]}return t.prototype.use=function(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1},t.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},t.prototype.clear=function(){this.handlers&&(this.handlers=[])},t.prototype.forEach=function(t){e.forEach(this.handlers,function(e){null!==e&&t(e)})},Fo=t}(),r=ys(),i=ws(),o=cs(),a=vs(),s=a.validators;function c(e){this.defaults=e,this.interceptors={request:new n,response:new n}}return c.prototype.request=function(t,n){"string"==typeof t?(n=n||{}).url=t:n=t||{},(n=i(this.defaults,n)).method?n.method=n.method.toLowerCase():this.defaults.method?n.method=this.defaults.method.toLowerCase():n.method="get";var o=n.transitional;void 0!==o&&a.assertOptions(o,{silentJSONParsing:s.transitional(s.boolean),forcedJSONParsing:s.transitional(s.boolean),clarifyTimeoutError:s.transitional(s.boolean)},!1);var c=n.paramsSerializer;null!=c&&(e.isFunction(c)?n.paramsSerializer={serialize:c}:a.assertOptions(c,{encode:s.function,serialize:s.function},!0));var u=[],l=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(n)||(l=l&&e.synchronous,u.unshift(e.fulfilled,e.rejected))});var d,h=[];if(this.interceptors.response.forEach(function(e){h.push(e.fulfilled,e.rejected)}),!l){var f=[r,void 0];for(Array.prototype.unshift.apply(f,u),f=f.concat(h),d=Promise.resolve(n);f.length;)d=d.then(f.shift(),f.shift());return d}for(var p=n;u.length;){var m=u.shift(),g=u.shift();try{p=m(p)}catch(e){g(e);break}}try{d=r(p)}catch(e){return Promise.reject(e)}for(;h.length;)d=d.then(h.shift(),h.shift());return d},c.prototype.getUri=function(e){e=i(this.defaults,e);var n=o(e.baseURL,e.url,e.allowAbsoluteUrls);return t(n,e.params,e.paramsSerializer)},e.forEach(["delete","get","head","options"],function(e){c.prototype[e]=function(t,n){return this.request(i(n||{},{method:e,url:t,data:(n||{}).data}))}}),e.forEach(["post","put","patch"],function(e){function t(t){return function(n,r,o){return this.request(i(o||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:r}))}}c.prototype[e]=t(),c.prototype[e+"Form"]=t(!0)}),$a=c}function Es(){if(_a)return ja.exports;_a=1;var e=Ka(),t=Ga(),n=xs(),r=ws(),i=ps(),o=rs();var a=function i(o){var a=new n(o),s=t(n.prototype.request,a);return e.extend(s,n.prototype,a),e.extend(s,a),s.create=function(e){return i(r(o,e))},s}(i);return a.Axios=n,a.CanceledError=ds(),a.CancelToken=function(){if(Pa)return Fa;Pa=1;var e=ds();function t(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var n;this.promise=new Promise(function(e){n=e});var r=this;this.promise.then(function(e){if(r._listeners){for(var t=r._listeners.length;t-- >0;)r._listeners[t](e);r._listeners=null}}),this.promise.then=function(e){var t,n=new Promise(function(e){r.subscribe(e),t=e}).then(e);return n.cancel=function(){r.unsubscribe(t)},n},t(function(t,i,o){r.reason||(r.reason=new e(t,i,o),n(r.reason))})}return t.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},t.prototype.subscribe=function(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]},t.prototype.unsubscribe=function(e){if(this._listeners){var t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}},t.source=function(){var e;return{token:new t(function(t){e=t}),cancel:e}},Fa=t}(),a.isCancel=gs(),a.VERSION=bs().version,a.toFormData=Za(),a.AxiosError=Ha(),a.Cancel=a.CanceledError,a.all=function(e){return Promise.all(e)},a.spread=qa?Ua:(qa=1,Ua=function(e){return function(t){return e.apply(null,t)}}),a.isAxiosError=function(){if(Ma)return Na;Ma=1;var e=Ka();return Na=function(t){return e.isObject(t)&&!0===t.isAxiosError}}(),a.formToJSON=function(t){return o(e.isHTMLForm(t)?new FormData(t):t)},ja.exports=a,ja.exports.default=a,ja.exports}var As=Vr(La?Va:(La=1,Va=Es()));const Rs=pi("bee-js:http"),{AxiosError:Ss}=As,Is=Wr.minutes(1)/200,ks={headers:{accept:"application/json, text/plain, */*"},maxBodyLength:1/0,maxContentLength:1/0};function Ts(e,t,n,r){if(e?.aborted)throw new Ni(t.method||"get",t.url||"<unknown>","Request aborted",n,r,"ERR_CANCELED")}async function Bs(e,t){const n=Xr.deepMerge3(ks,t,e);if(e.signal&&(n.signal=e.signal,Ts(e.signal,t)),function(e){e.data&&e.data instanceof Uint8Array&&(e.data=e.data.buffer.slice(e.data.byteOffset,e.data.byteOffset+e.data.byteLength));e.data&&"undefined"!=typeof Buffer&&Buffer.isBuffer(e.data)&&(e.data=e.data.buffer.slice(e.data.byteOffset,e.data.byteOffset+e.data.byteLength))}(n),n.params){const e=Object.keys(n.params);for(const t of e){void 0===n.params[t]&&delete n.params[t]}}let r=0;for(;r<1e5;){Ts(e.signal,t);try{Rs(`${n.method||"get"} ${Yr.joinUrl([n.baseURL,n.url])}`,{headers:{...n.headers},params:n.params}),Os(e,n);return await As(n)}catch(n){if(!(n instanceof Ss))throw n;if("ERR_CANCELED"===n.code&&Ts({aborted:!0},t,n.response?.data,n.response?.status),"ECONNABORTED"!==n.code||!e.endlesslyRetry)throw new Ni(t.method||"get",t.url||"<unknown>",n.message,n.response?.data,n.response?.status,n.response?.statusText);r++,await Qr.sleepMillis(r<Is?200:1e3)}}throw Error("Max number of failed attempts reached")}function Os(e,t){e.onRequest&&e.onRequest({method:t.method||"GET",url:Yr.joinUrl([t.baseURL,t.url]),headers:{...t.headers},params:t.params})}const Ds="chunks";async function Cs(e,t,n){t=new Ti(t);const r=await Bs(e,{responseType:"arraybuffer",url:`${Ds}/${t}`,headers:wo(null,n)});return new Uint8Array(r.data)}const $s=ki.LENGTH,zs=ki.LENGTH+$i.LENGTH,Fs=ki.LENGTH+$i.LENGTH+Oi.LENGTH;function Ps(e,t){e=e instanceof wi?e.toUint8Array():e,t=new Ti(t);const n=function(e){const t=_i(e.slice(zs)),n=$i.fromSlice(e,$s),r=wi.fromSlice(e,0,ki.LENGTH),i=Hr.concatBytes(r.toUint8Array(),t.toUint8Array());return n.recoverPublicKey(i).address()}(e),r=wi.fromSlice(e,0,ki.LENGTH),i=new Ti(Hr.keccak256(Hr.concatBytes(r.toUint8Array(),n.toUint8Array())));if(!Hr.equals(t.toUint8Array(),i.toUint8Array()))throw new Ui("SOC data does not match given address!");return{data:e,identifier:r,signature:$i.fromSlice(e,$s),span:Oi.fromSlice(e,zs),payload:wi.fromSlice(e,Fs),address:i,owner:n}}function Us(e,t){return new Ti(Hr.keccak256(Hr.concatBytes(e.toUint8Array(),t.toUint8Array())))}function qs(e,t,n,r,i){const o=Us(r=new ki(r),(i=new Ri(i)).publicKey().address()),a=i.sign(Hr.concatBytes(r.toUint8Array(),e.toUint8Array()));return{data:Hr.concatBytes(r.toUint8Array(),a.toUint8Array(),t.toUint8Array(),n.toUint8Array()),identifier:r,signature:a,span:t,payload:n,address:o,owner:i.publicKey().address()}}async function Ns(e,t,n,r){const i=Hr.concatBytes(t.span.toUint8Array(),t.payload.toUint8Array());return async function(e,t,n,r,i,o,a){const s=await Bs(e,{method:"post",url:`soc/${t}/${n}`,data:i,headers:{"content-type":"application/octet-stream",...wo(o,a)},responseType:"json",params:{sig:r.toHex()}}),c=ei.asObject(s.data,{name:"response.data"});return{reference:new Ti(ei.asHexString(c.reference)),tagUid:s.headers["swarm-tag"]?so(s.headers["swarm-tag"]):void 0,historyAddress:s.headers["swarm-act-history-address"]?ti.of(new Ti(s.headers["swarm-act-history-address"])):ti.empty()}}(e,t.owner,t.identifier,t.signature,i,n,r)}async function Ms(e,t,n,r,i,o){t=new Ri(t),r=new ki(r);return Ns(e,Gs(i).toSingleOwnerChunk(r,t),n,o)}async function _s(e,t,n){const r=Us(n=new ki(n),t=new Ii(t));return Ps(await Cs(e,r.toHex()),r)}const Vs=1,Ls=4096;function js(e){return Gs((e=new wi(e)).toUint8Array().slice(Oi.LENGTH),Oi.fromSlice(e.toUint8Array(),0))}function Gs(e,t){if(ei.isString(e)&&(e=wi.fromUtf8(e)),e.length<Vs||e.length>Ls)throw new RangeError(`payload size ${e.length} exceeds limits [${Vs}, ${Ls}]`);const n=t?"bigint"==typeof t?Oi.fromBigInt(t):t:Oi.fromBigInt(BigInt(e.length)),r=new wi(e),i=Hr.concatBytes(n.toUint8Array(),r.toUint8Array()),o=_i(i);return{data:i,span:n,payload:r,address:o,toSingleOwnerChunk:(e,t)=>qs(o,n,r,e,t)}}const Ks="bytes";async function Hs(e,t,n,r){const i=await Bs(e,{url:Ks,method:"post",responseType:"json",data:t,headers:{"content-type":"application/octet-stream",...wo(n,r)}}),o=ei.asObject(i.data,{name:"response.data"});return{reference:new Ti(ei.asHexString(o.reference)),tagUid:i.headers["swarm-tag"]?so(i.headers["swarm-tag"]):void 0,historyAddress:i.headers["swarm-act-history-address"]?ti.of(new Ti(i.headers["swarm-act-history-address"])):ti.empty()}}async function Ws(e,t,n){n&&(n=to(n));const r=await Bs(e,{responseType:"arraybuffer",url:`${Ks}/${t}`,headers:wo(null,n)});return new wi(r.data)}const Zs="feeds";function Js(e){const t=e["swarm-feed-index"],n=e["swarm-feed-index-next"];if(!t)throw new Ui("Response did not contain expected swarm-feed-index!");if(!n)throw new Ui("Response did not contain expected swarm-feed-index-next!");return{feedIndex:new Pi(t),feedIndexNext:new Pi(n)}}async function Xs(e,t,n,r){const i=await Bs(e,{responseType:"arraybuffer",url:`${Zs}/${t}/${n}`,params:r});return{payload:new wi(i.data),...Js(i.headers)}}class Ys{constructor(e){this.raw=e}toString(){return ei.isString(this.raw)&&this.raw.includes(".eth")?this.raw:new Ti(this.raw).toHex()}}function Qs(e,t){return t="number"==typeof t?Pi.fromBigInt(BigInt(t)):t,new ki(Hr.keccak256(Hr.concatBytes(e.toUint8Array(),t.toUint8Array())))}async function ec(e,t,n){try{const r=await Xs(e,t,n);if(!r.feedIndexNext)throw Error("Feed index next is not defined. This should happen when fetching an exact index.");return r.feedIndexNext}catch(e){if(e instanceof Ni)return Pi.fromBigInt(0n);throw e}}async function tc(e,t,n,r,i,o){const a=Qs(n,o?.index??await ec(e,t.publicKey().address(),n));if(r.length>4096){const n=await Hs(e,r,i,o);return async function(e,t,n,r,i,o){return t=new Ri(t),r=new ki(r),Ns(e,i.toSingleOwnerChunk(r,t),n,o)}(e,t,i,a,js(await Cs(e,n.reference)),o)}return Ms(e,t,i,a,ei.isString(r)?wi.fromUtf8(r).toUint8Array():r,o)}function nc(e,t,n){const r=Qs(t,n);return new Ti(Hr.keccak256(Hr.concatBytes(r.toUint8Array(),e.toUint8Array())))}async function rc(e,t,n,r,i=!1){const o=nc(t,n,r="number"==typeof r?Pi.fromBigInt(BigInt(r)):r),a=Ps(await Cs(e,o.toHex()),o);let s=ti.empty();if(i){const e=wi.fromSlice(a.payload.toUint8Array(),0,8);s=ti.of(Number(Hr.uint64ToNumber(e.toUint8Array(),"BE")))}return{timestamp:s,payload:new wi(a.payload.offset(i?8:0))}}async function ic(e,t,n,r){const i=nc(t,n,r="number"==typeof r?Pi.fromBigInt(BigInt(r)):r),o=Ps(await Cs(e,i),i);return Gs(o.payload,o.span)}function oc(e,t,n){const r=async r=>{if(void 0===r?.index)return Xs(e,n,t);const i=await rc(e,n,t,r.index,r.hasTimestamp??!0),o="number"==typeof r.index?Pi.fromBigInt(BigInt(r.index)):r.index;return{payload:i.payload,feedIndex:o,feedIndexNext:o.next()}};return{download:r,downloadPayload:async r=>{if(void 0===r?.index)return Xs(e,n,t);const i=await ic(e,n,t,r.index),o=i.span.toBigInt()<=4096n?i.payload:await Ws(e,new Ys(i.address)),a="number"==typeof r.index?Pi.fromBigInt(BigInt(r.index)):r.index;return{payload:o,feedIndex:a,feedIndexNext:a.next()}},downloadReference:async i=>{let o=i?.index;void 0===o&&(o=(await async function(e,t,n){return Js((await Bs(e,{responseType:"arraybuffer",url:`${Zs}/${t}/${n}`,params:{"Swarm-Only-Root-Chunk":!0}})).headers)}(e,n,t)).feedIndex);const a=await r({...i,index:o});return{reference:new Ti(a.payload.toUint8Array()),feedIndex:a.feedIndex,feedIndexNext:a.feedIndexNext??a.feedIndex.next()}},owner:n,topic:t}}function ac(e,t,n){const r=async(r,i,o)=>async function(e,t,n,r,i,o){r=new Ti(r);const a=Qs(n,o?.index??await ec(e,t.publicKey().address(),n)),s=o?.at??Date.now()/1e3,c=Hr.numberToUint64(BigInt(Math.floor(s)),"BE");return Ms(e,t,i,a,Hr.concatBytes(c,r.toUint8Array()),o)}(e,n,t,i,r,o);return{...oc(e,t,n.publicKey().address()),upload:r,uploadReference:r,uploadPayload:async(r,i,o)=>tc(e,n,t,i,r,o)}}async function sc(e,t,n,r,i,o){const a=function(e,t,n){const r=n.toBigInt(),i=[];for(let n=0n;n<=r;n++)i.push(nc(e,t,Pi.fromBigInt(n)));return i}(t,n,r).map(async t=>async function(e,t,n,r){try{return await e.downloadChunk(t,n,r),!0}catch(e){const t=Xr.getDeep(e,"status");if(404===t||500===t)return!1;throw e}}(e,t,i,o));return(await Promise.all(a)).every(e=>e)}function cc(e){if(!function(e){return!!Array.isArray(e)&&e.every(e=>"object"==typeof e&&e.path&&void 0!==e.size)}(e))throw new qi("invalid collection",e)}function uc(e){if(e.webkitRelativePath&&""!==e.webkitRelativePath)return e.webkitRelativePath.replace(/.*?\//i,"");if(e.name)return e.name;throw new TypeError("file is not valid File object")}class lc{constructor(){this.pieces=[],this.currentFileSize=0}get output(){return this.pieces.reduce((e,t)=>{const n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n})}beginFile(e,t){if(e.length>100)throw new Error(`File name too long: ${e}`);const n=function(e,t){const n=new TextEncoder;function r(e,t,r){const o=n.encode(e);i.set(o.slice(0,r),t)}const i=new Uint8Array(512);i.fill(0,0,512),r(e.slice(0,100).padEnd(100,"\0"),0,100),r("0000777\0",100,8),r("0001750\0",108,8),r("0001750\0",116,8),r(t.toString(8).padStart(11,"0")+"\0",124,12);r(Math.floor((new Date).getTime()/1e3).toString(8).padStart(11,"0")+"\0",136,12),r(" ",148,8),r("0",156,1),r("ustar\0\0",257,8);let o=0;for(let e=0;e<512;e++)o+=i[e];return r(o.toString(8).padStart(6,"0")+"\0 ",148,8),i}(e,t);this.pieces.push(n),this.currentFileSize=0}async appendFile(e){this.pieces.push(e),this.currentFileSize+=e.length}async endFile(){const e=this.currentFileSize%512==0?0:512-this.currentFileSize%512;e>0&&this.pieces.push(new Uint8Array(e))}async end(){this.pieces.push(new Uint8Array(1024))}}async function dc(e,t,n,r){const i=new lc;await async function(e,t){for(const n of e){if(!n.file)throw new Error("Invalid collection item");t.beginFile(n.path,n.file.size),await t.appendFile(new Uint8Array(await Qi(n.file))),await t.endFile()}}(t,i),await i.end();return await Bs(e,{method:"post",url:"bzz",data:i.output,responseType:"json",headers:{"content-type":"application/x-tar","swarm-collection":"true",...wo(n,r)}})}const hc="bzz";async function fc(e,t,n,r,i){const o=await Bs(e,{method:"post",url:hc,data:t,headers:wo(n,i),params:{name:r},responseType:"json"}),a=ei.asObject(o.data,{name:"response.data"});return{reference:new Ti(ei.asHexString(a.reference)),tagUid:o.headers["swarm-tag"]?so(o.headers["swarm-tag"]):void 0,historyAddress:o.headers["swarm-act-history-address"]?ti.of(new Ti(o.headers["swarm-act-history-address"])):ti.empty()}}async function pc(e,t,n,r){cc(t);const i=await dc(e,t,n,r),o=ei.asObject(i.data,{name:"response.data"});return{reference:new Ti(ei.asHexString(o.reference)),tagUid:i.headers["swarm-tag"]?so(i.headers["swarm-tag"]):void 0,historyAddress:i.headers["swarm-act-history-address"]?ti.of(new Ti(i.headers["swarm-act-history-address"])):ti.empty()}}const mc="balances",gc="consumed";const yc="chequebook";async function wc(e,t){const n=await Bs(e,{url:yc+`/cashout/${t}`,responseType:"json"}),r=ei.asObject(n.data,{name:"response.data"});return{peer:ei.asString(r.peer,{name:"peer"}),uncashedAmount:Ji.fromPLUR(eo(r.uncashedAmount,{name:"uncashedAmount"})),transactionHash:ei.asNullableString(r.transactionHash),lastCashedCheque:ei.asNullable(e=>bc(e),r.lastCashedCheque),result:ei.asNullable(e=>function(e){const t=ei.asObject(e,{name:"cashout result"});return{recipient:ei.asString(t.recipient,{name:"recipient"}),lastPayout:Ji.fromPLUR(eo(t.lastPayout,{name:"lastPayout"})),bounced:ei.asBoolean(t.bounced,{name:"bounced"})}}(e),r.result)}}function bc(e){const t=ei.asObject(e,{name:"cheque"});return{beneficiary:new Ii(ei.asString(t.beneficiary,{name:"beneficiary"})),chequebook:new Ii(ei.asString(t.chequebook,{name:"chequebook"})),payout:Ji.fromPLUR(eo(t.payout,{name:"payout"}))}}function vc(e,t){const n=ei.asObject(e,{name:t});return n.disconnectedPeers||(n.disconnectedPeers=[]),n.connectedPeers||(n.connectedPeers=[]),{population:ei.asNumber(n.population,{name:"population"}),connected:ei.asNumber(n.connected,{name:"connected"}),connectedPeers:ei.asArray(n.connectedPeers,{name:"connectedPeers"}).map(e=>({address:ei.asString(ei.asObject(e,{name:"connectedPeer"}).address,{name:"address"})})),disconnectedPeers:ei.asArray(n.disconnectedPeers,{name:"disconnectedPeers"}).map(e=>({address:ei.asString(ei.asObject(e,{name:"disconnectedPeer"}).address,{name:"address"})}))}}const xc="settlements";const Ec="stake";const Ac="stamps";async function Rc(e){const t=await Bs(e,{method:"get",url:"batches",responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return ei.asArray(n.batches,{name:"batches"}).map(e=>ei.asObject(e,{name:"batch"})).map(e=>({batchID:new Ci(ei.asString(e.batchID,{name:"batchID"})),batchTTL:ei.asNumber(e.batchTTL,{name:"batchTTL"}),bucketDepth:ei.asNumber(e.bucketDepth,{name:"bucketDepth"}),depth:ei.asNumber(e.depth,{name:"depth"}),immutable:ei.asBoolean(e.immutable,{name:"immutable"}),owner:new Ii(ei.asString(e.owner,{name:"owner"})),start:ei.asNumber(e.start,{name:"start"}),value:eo(e.value,{name:"value"})}))}async function Sc(e){const t=await Bs(e,{method:"get",url:`${Ac}`,responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return ei.asArray(n.stamps,{name:"stamps"}).map(e=>ei.asObject(e,{name:"stamp"})).map(e=>go(Ic(e)))}function Ic(e){return{amount:eo(e.amount,{name:"amount"}),batchID:ei.asString(e.batchID,{name:"batchID"}),batchTTL:ei.asNumber(e.batchTTL,{name:"batchTTL"}),bucketDepth:ei.asNumber(e.bucketDepth,{name:"bucketDepth"}),blockNumber:ei.asNumber(e.blockNumber,{name:"blockNumber"}),depth:ei.asNumber(e.depth,{name:"depth"}),immutableFlag:ei.asBoolean(e.immutableFlag,{name:"immutableFlag"}),label:ei.asEmptiableString(e.label,{name:"label"}),usable:ei.asBoolean(e.usable,{name:"usable"}),utilization:ei.asNumber(e.utilization,{name:"utilization"})}}const kc="wallet";var Tc,Bc,Oc,Dc;function Cc(){if(Bc)return Tc;Bc=1;const e="object"==typeof process&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};return Tc=e}function $c(){if(Dc)return Oc;Dc=1;const e=Number.MAX_SAFE_INTEGER||9007199254740991;return Oc={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:e,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}}var zc,Fc,Pc,Uc,qc,Nc,Mc,_c,Vc,Lc={exports:{}};function jc(){return zc||(zc=1,function(e,t){const{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=$c(),o=Cc(),a=(t=e.exports={}).re=[],s=t.safeRe=[],c=t.src=[],u=t.safeSrc=[],l=t.t={};let d=0;const h="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",i],[h,r]],p=(e,t,n)=>{const r=(e=>{for(const[t,n]of f)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e})(t),i=d++;o(e,i,t),l[e]=i,c[i]=t,u[i]=r,a[i]=new RegExp(t,n?"g":void 0),s[i]=new RegExp(r,n?"g":void 0)};p("NUMERICIDENTIFIER","0|[1-9]\\d*"),p("NUMERICIDENTIFIERLOOSE","\\d+"),p("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`),p("MAINVERSION",`(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})\\.(${c[l.NUMERICIDENTIFIER]})`),p("MAINVERSIONLOOSE",`(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})\\.(${c[l.NUMERICIDENTIFIERLOOSE]})`),p("PRERELEASEIDENTIFIER",`(?:${c[l.NONNUMERICIDENTIFIER]}|${c[l.NUMERICIDENTIFIER]})`),p("PRERELEASEIDENTIFIERLOOSE",`(?:${c[l.NONNUMERICIDENTIFIER]}|${c[l.NUMERICIDENTIFIERLOOSE]})`),p("PRERELEASE",`(?:-(${c[l.PRERELEASEIDENTIFIER]}(?:\\.${c[l.PRERELEASEIDENTIFIER]})*))`),p("PRERELEASELOOSE",`(?:-?(${c[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[l.PRERELEASEIDENTIFIERLOOSE]})*))`),p("BUILDIDENTIFIER",`${h}+`),p("BUILD",`(?:\\+(${c[l.BUILDIDENTIFIER]}(?:\\.${c[l.BUILDIDENTIFIER]})*))`),p("FULLPLAIN",`v?${c[l.MAINVERSION]}${c[l.PRERELEASE]}?${c[l.BUILD]}?`),p("FULL",`^${c[l.FULLPLAIN]}$`),p("LOOSEPLAIN",`[v=\\s]*${c[l.MAINVERSIONLOOSE]}${c[l.PRERELEASELOOSE]}?${c[l.BUILD]}?`),p("LOOSE",`^${c[l.LOOSEPLAIN]}$`),p("GTLT","((?:<|>)?=?)"),p("XRANGEIDENTIFIERLOOSE",`${c[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),p("XRANGEIDENTIFIER",`${c[l.NUMERICIDENTIFIER]}|x|X|\\*`),p("XRANGEPLAIN",`[v=\\s]*(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:\\.(${c[l.XRANGEIDENTIFIER]})(?:${c[l.PRERELEASE]})?${c[l.BUILD]}?)?)?`),p("XRANGEPLAINLOOSE",`[v=\\s]*(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[l.XRANGEIDENTIFIERLOOSE]})(?:${c[l.PRERELEASELOOSE]})?${c[l.BUILD]}?)?)?`),p("XRANGE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAIN]}$`),p("XRANGELOOSE",`^${c[l.GTLT]}\\s*${c[l.XRANGEPLAINLOOSE]}$`),p("COERCEPLAIN",`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),p("COERCE",`${c[l.COERCEPLAIN]}(?:$|[^\\d])`),p("COERCEFULL",c[l.COERCEPLAIN]+`(?:${c[l.PRERELEASE]})?`+`(?:${c[l.BUILD]})?(?:$|[^\\d])`),p("COERCERTL",c[l.COERCE],!0),p("COERCERTLFULL",c[l.COERCEFULL],!0),p("LONETILDE","(?:~>?)"),p("TILDETRIM",`(\\s*)${c[l.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",p("TILDE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAIN]}$`),p("TILDELOOSE",`^${c[l.LONETILDE]}${c[l.XRANGEPLAINLOOSE]}$`),p("LONECARET","(?:\\^)"),p("CARETTRIM",`(\\s*)${c[l.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",p("CARET",`^${c[l.LONECARET]}${c[l.XRANGEPLAIN]}$`),p("CARETLOOSE",`^${c[l.LONECARET]}${c[l.XRANGEPLAINLOOSE]}$`),p("COMPARATORLOOSE",`^${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]})$|^$`),p("COMPARATOR",`^${c[l.GTLT]}\\s*(${c[l.FULLPLAIN]})$|^$`),p("COMPARATORTRIM",`(\\s*)${c[l.GTLT]}\\s*(${c[l.LOOSEPLAIN]}|${c[l.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",p("HYPHENRANGE",`^\\s*(${c[l.XRANGEPLAIN]})\\s+-\\s+(${c[l.XRANGEPLAIN]})\\s*$`),p("HYPHENRANGELOOSE",`^\\s*(${c[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[l.XRANGEPLAINLOOSE]})\\s*$`),p("STAR","(<|>)?=?\\s*\\*"),p("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),p("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")}(Lc,Lc.exports)),Lc.exports}function Gc(){if(Mc)return Nc;Mc=1;const e=Cc(),{MAX_LENGTH:t,MAX_SAFE_INTEGER:n}=$c(),{safeRe:r,t:i}=jc(),o=function(){if(Pc)return Fc;Pc=1;const e=Object.freeze({loose:!0}),t=Object.freeze({});return Fc=n=>n?"object"!=typeof n?e:n:t}(),{compareIdentifiers:a}=function(){if(qc)return Uc;qc=1;const e=/^[0-9]+$/,t=(t,n)=>{if("number"==typeof t&&"number"==typeof n)return t===n?0:t<n?-1:1;const r=e.test(t),i=e.test(n);return r&&i&&(t=+t,n=+n),t===n?0:r&&!i?-1:i&&!r?1:t<n?-1:1};return Uc={compareIdentifiers:t,rcompareIdentifiers:(e,n)=>t(n,e)}}();class s{constructor(a,c){if(c=o(c),a instanceof s){if(a.loose===!!c.loose&&a.includePrerelease===!!c.includePrerelease)return a;a=a.version}else if("string"!=typeof a)throw new TypeError(`Invalid version. Must be a string. Got type "${typeof a}".`);if(a.length>t)throw new TypeError(`version is longer than ${t} characters`);e("SemVer",a,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;const u=a.trim().match(c.loose?r[i.LOOSE]:r[i.FULL]);if(!u)throw new TypeError(`Invalid Version: ${a}`);if(this.raw=a,this.major=+u[1],this.minor=+u[2],this.patch=+u[3],this.major>n||this.major<0)throw new TypeError("Invalid major version");if(this.minor>n||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>n||this.patch<0)throw new TypeError("Invalid patch version");u[4]?this.prerelease=u[4].split(".").map(e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&t<n)return t}return e}):this.prerelease=[],this.build=u[5]?u[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(t){if(e("SemVer.compare",this.version,this.options,t),!(t instanceof s)){if("string"==typeof t&&t===this.version)return 0;t=new s(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(e){return e instanceof s||(e=new s(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(t){if(t instanceof s||(t=new s(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let n=0;do{const r=this.prerelease[n],i=t.prerelease[n];if(e("prerelease compare",n,r,i),void 0===r&&void 0===i)return 0;if(void 0===i)return 1;if(void 0===r)return-1;if(r!==i)return a(r,i)}while(++n)}compareBuild(t){t instanceof s||(t=new s(t,this.options));let n=0;do{const r=this.build[n],i=t.build[n];if(e("build compare",n,r,i),void 0===r&&void 0===i)return 0;if(void 0===i)return 1;if(void 0===r)return-1;if(r!==i)return a(r,i)}while(++n)}inc(e,t,n){if(e.startsWith("pre")){if(!t&&!1===n)throw new Error("invalid increment argument: identifier is empty");if(t){const e=`-${t}`.match(this.options.loose?r[i.PRERELEASELOOSE]:r[i.PRERELEASE]);if(!e||e[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,n),this.inc("pre",t,n);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",t,n),this.inc("pre",t,n);break;case"release":if(0===this.prerelease.length)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":0===this.minor&&0===this.patch&&0!==this.prerelease.length||this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":0===this.patch&&0!==this.prerelease.length||this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":{const e=Number(n)?1:0;if(0===this.prerelease.length)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)"number"==typeof this.prerelease[r]&&(this.prerelease[r]++,r=-2);if(-1===r){if(t===this.prerelease.join(".")&&!1===n)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let r=[t,e];!1===n&&(r=[t]),0===a(this.prerelease[0],t)?isNaN(this.prerelease[1])&&(this.prerelease=r):this.prerelease=r}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return Nc=s}var Kc=Vr(function(){if(Vc)return _c;Vc=1;const e=Gc();return _c=(t,n)=>new e(t,n).major}());const Hc="2.7.0-6ddf9b45";Hc.split("-")[0];const Wc="7.3.0";async function Zc(e){const t=await Bs(e,{method:"get",url:"health",responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return{apiVersion:ei.asString(n.apiVersion,{name:"apiVersion"}),version:ei.asString(n.version,{name:"version"}),status:ei.asString(n.status,{name:"status"})}}const Jc="transactions";function Xc(e){const t=ei.asObject(e,{name:"transaction"});return{transactionHash:new Bi(ei.asString(t.transactionHash,{name:"transactionHash"})),to:ei.asString(t.to,{name:"to"}),nonce:ei.asNumber(t.nonce,{name:"nonce"}),gasPrice:eo(t.gasPrice,{name:"gasPrice"}),gasLimit:ei.asNumber(t.gasLimit,{name:"gasLimit"}),data:ei.asString(t.data,{name:"data"}),created:ei.asString(t.created,{name:"created"}),description:ei.asString(t.description,{name:"description"}),value:eo(t.value,{name:"value"})}}const Yc="grantee";var Qc,eu;var tu=Vr(function(){if(eu)return Qc;eu=1;var e=null;return"undefined"!=typeof WebSocket?e=WebSocket:"undefined"!=typeof MozWebSocket?e=MozWebSocket:void 0!==_r?e=_r.WebSocket||_r.MozWebSocket:"undefined"!=typeof window?e=window.WebSocket||window.MozWebSocket:"undefined"!=typeof self&&(e=self.WebSocket||self.MozWebSocket),Qc=e}());const nu="gsoc";const ru="pins";const iu="pss";async function ou(e,t,n,r,i,o){await Bs(e,{method:"post",url:`${iu}/send/${t}/${n}`,data:r,responseType:"json",params:{recipient:o},headers:wo(i)})}async function au(e){await Bs(e,{url:""})}const su="stewardship";const cu="tags";const uu=pi("bee-js:manifest"),lu=new TextEncoder,du=new TextDecoder,hu=new Uint8Array([47]),fu=Hr.hexToUint8Array("5768b3b6a7db56d21d1abff40d41cebfc83448fed8d7e9b06ec0d3b073f28f7b");class pu{constructor(e,t){this.prefix=e,this.node=t}static split(e,t){const n=Hr.commonPrefix(e.prefix,t.prefix);if(n.length===e.prefix.length){const r=t.prefix.slice(n.length);return t.node.path=t.prefix.slice(n.length),t.prefix=t.prefix.slice(n.length),t.node.parent=e.node,e.node.forks.set(r[0],t),e}if(n.length===t.prefix.length){const r=e.prefix.slice(n.length);return e.node.path=e.prefix.slice(n.length),e.prefix=e.prefix.slice(n.length),e.node.parent=t.node,t.node.forks.set(r[0],e),t}const r=new mu({path:n}),i=new pu(e.prefix.slice(n.length),e.node),o=new pu(t.prefix.slice(n.length),t.node);return e.node.path=e.prefix.slice(n.length),t.node.path=t.prefix.slice(n.length),e.prefix=e.prefix.slice(n.length),t.prefix=t.prefix.slice(n.length),r.forks.set(i.prefix[0],i),r.forks.set(o.prefix[0],o),i.node.parent=r,o.node.parent=r,new pu(n,r)}marshal(){if(!this.node.selfAddress)throw Error("Fork#marshal node.selfAddress is not set");const e=[];if(e.push(new Uint8Array([this.node.determineType()])),e.push(Hr.numberToUint8(this.prefix.length)),e.push(this.prefix),this.prefix.length<30&&e.push(new Uint8Array(30-this.prefix.length)),e.push(this.node.selfAddress),uu("marshalling fork",{prefixLength:this.prefix.length,prefix:du.decode(this.prefix),address:Hr.uint8ArrayToHex(this.node.selfAddress)}),this.node.metadata){const t=Hr.padEndToMultiple(new Uint8Array([0,0,...lu.encode(JSON.stringify(this.node.metadata))]),32,10),n=Hr.numberToUint16(t.length-2,"BE");t.set(n,0),e.push(t)}return Hr.concatBytes(...e)}static unmarshal(e,t){const n=Hr.uint8ToNumber(e.read(1)),r=Hr.uint8ToNumber(e.read(1)),i=e.read(r);r<30&&e.read(30-r);const o=e.read(t);let a;if(uu("unmarshalling fork",{type:n,prefixLength:r,prefix:du.decode(i),addressLength:t,address:Hr.uint8ArrayToHex(o)}),function(e,t){return(e&t)===t}(n,16)){const t=Hr.uint16ToNumber(e.read(2),"BE");a=JSON.parse(du.decode(e.read(t)))}return new pu(i,new mu({selfAddress:o,metadata:a,path:i}))}}class mu{constructor(e){this.obfuscationKey=new Uint8Array(32),this.selfAddress=null,this.targetAddress=new Uint8Array(32),this.metadata=null,this.path=new Uint8Array(0),this.forks=new Map,this.parent=null,e?.targetAddress&&(this.targetAddress=e.targetAddress),e?.selfAddress&&(this.selfAddress=e.selfAddress),e?.metadata&&(this.metadata=e.metadata),e?.obfuscationKey&&(this.obfuscationKey=e.obfuscationKey),e?.path&&(this.path=e.path),e?.parent&&(this.parent=e.parent)}get fullPath(){return Hr.concatBytes(this.parent?.fullPath??new Uint8Array(0),this.path)}get fullPathString(){return du.decode(this.fullPath)}getRootMetadata(){const e=this.find("/");return e&&e.metadata?ti.of(e.metadata):ti.empty()}getDocsMetadata(){const e=this.find("/");return e&&e.metadata?{indexDocument:e.metadata["website-index-document"]??null,errorDocument:e.metadata["website-error-document"]??null}:{indexDocument:null,errorDocument:null}}async resolveFeed(e,t){const n=this.find("/");if(!n||!n.metadata)return ti.empty();const r=n.metadata["swarm-feed-owner"],i=n.metadata["swarm-feed-topic"];return r&&i?ti.of(await e.fetchLatestFeedUpdate(i,r,t)):ti.empty()}async marshal(){for(const e of this.forks.values())e.node.selfAddress||(e.node.selfAddress=(await e.node.calculateSelfAddress()).toUint8Array());const e=new Uint8Array(32);e.set(fu,0),e.set(Hr.equals(this.targetAddress,Au)&&Hr.equals(this.path,new Uint8Array([47]))?Hr.numberToUint8(0):Hr.numberToUint8(this.targetAddress.length),31);const t=new Uint8Array(32);for(const e of this.forks.keys())Hr.setBit(t,e,1,"LE");const n=[];for(let e=0;e<256;e++)Hr.getBit(t,e,"LE")&&n.push(this.forks.get(e).marshal());const r=Hr.xorCypher(Hr.concatBytes(e,Hr.equals(this.targetAddress,Au)&&Hr.equals(this.path,new Uint8Array([47]))?new Uint8Array(0):this.targetAddress,t,...n),this.obfuscationKey);return Hr.concatBytes(this.obfuscationKey,r)}static async unmarshal(e,t,n,r){t=new Ti(t);const i=(await e.downloadData(t,n,r)).toUint8Array();return this.unmarshalFromData(i,t.toUint8Array())}static unmarshalFromData(e,t){const n=e.subarray(0,32),r=Hr.xorCypher(e.subarray(32),n),i=new oi(r),o=i.read(31);if(!Hr.equals(o,fu.slice(0,31)))throw new Error("MantarayNode#unmarshal invalid version hash");const a=Hr.uint8ToNumber(i.read(1)),s=a?i.read(a):Au,c=new mu({selfAddress:t,targetAddress:s,obfuscationKey:n}),u=i.read(32);for(let e=0;e<256;e++)if(Hr.getBit(u,e,"LE")){const n=pu.unmarshal(i,t.length);c.forks.set(e,n),n.node.parent=c}return c}addFork(e,t,n){this.selfAddress=null,e=e instanceof Uint8Array?e:lu.encode(e),uu("adding fork",{path:du.decode(e),reference:new Ti(t).represent()});let r=this;for(;e.length;){const i=e.slice(0,30),o=0===(e=e.slice(30)).length,[a,s]=r.findClosest(i),c=i.slice(s.length);if(s.length&&(r=a),!c.length)continue;const u=new pu(c,new mu({targetAddress:o?new Ti(t).toUint8Array():void 0,metadata:o?n:void 0,path:c})),l=a.forks.get(c[0]);if(l){const e=pu.split(u,l);r.forks.set(c[0],e),e.node.parent=r,r.selfAddress=null,r=u.node}else r.forks.set(c[0],u),u.node.parent=r,r.selfAddress=null,r=u.node}}removeFork(e){if(this.selfAddress=null,0===(e=e instanceof Uint8Array?e:lu.encode(e)).length)throw Error("MantarayNode#removeFork [path] parameter cannot be empty");const t=this.find(e);if(!t)throw Error("MantarayNode#removeFork fork not found");const[n,r]=this.findClosest(e.slice(0,e.length-1));n.forks.delete(e.slice(r.length)[0]);for(const e of t.forks.values())n.addFork(Hr.concatBytes(t.path,e.prefix),e.node.targetAddress,e.node.metadata)}async calculateSelfAddress(){return this.selfAddress?new Ti(this.selfAddress):new Ti((await ni.root(await this.marshal())).hash())}async saveRecursively(e,t,n,r){for(const i of this.forks.values()){const o=await i.node.saveRecursively(e,t,n,r);if(n?.act){let e;o.historyAddress.ifPresent(t=>e=t),e&&(i.node.metadata||(i.node.metadata={}),i.node.metadata["swarm-act-history-address"]=e.toHex())}}const i=await e.uploadData(t,await this.marshal(),n,r);return this.selfAddress=i.reference.toUint8Array(),i}async loadRecursively(e,t,n){for(const r of this.forks.values()){if(!r.node.selfAddress)throw Error("MantarayNode#loadRecursively fork.node.selfAddress is not set");let i=t;r.node.metadata&&r.node.metadata["swarm-act-history-address"]&&(i={...t,actHistoryAddress:r.node.metadata["swarm-act-history-address"]});const o=await mu.unmarshal(e,r.node.selfAddress,i,n);r.node.targetAddress=o.targetAddress,r.node.forks=o.forks,r.node.path=r.prefix,r.node.parent=this,await r.node.loadRecursively(e,t,n)}}find(e){const[t,n]=this.findClosest(e);return n.length===e.length?t:null}findClosest(e,t=new Uint8Array){if(0===(e=e instanceof Uint8Array?e:lu.encode(e)).length)return[this,t];const n=this.forks.get(e[0]);return n&&Hr.commonPrefix(n.prefix,e).length===n.prefix.length?n.node.findClosest(e.slice(n.prefix.length),Hr.concatBytes(t,n.prefix)):[this,t]}collect(e=[]){for(const t of this.forks.values())Hr.equals(t.node.targetAddress,Au)||e.push(t.node),t.node.collect(e);return e}collectAndMap(){const e=this.collect(),t={};for(const n of e)t[n.fullPathString]=new Ti(n.targetAddress).toHex();return t}determineType(){let e=0;return Hr.equals(this.targetAddress,Au)&&!Hr.equals(this.path,hu)||(e|=2),this.forks.size>0&&(e|=4),-1===Hr.indexOf(this.path,hu)||Hr.equals(this.path,hu)||(e|=8),this.metadata&&(e|=16),e}}function gu(e){return function e(t){return t<=1?t:t+e(Math.ceil(t/128))}(Math.ceil(e/4096))}const yu={aac:"audio/aac",abw:"application/x-abiword",ai:"application/postscript",arc:"application/octet-stream",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",dll:"application/octet-stream",dmg:"application/x-apple-diskimage",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"application/javascript",json:"application/json",mid:"audio/midi",midi:"audio/midi",mp2:"audio/mpeg",mp3:"audio/mpeg",mp4:"video/mp4",mpa:"video/mpeg",mpe:"video/mpeg",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odp:"application/vnd.oasis.opendocument.presentation",ods:"application/vnd.oasis.opendocument.spreadsheet",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",otf:"font/otf",png:"image/png",pdf:"application/pdf",ppt:"application/vnd.ms-powerpoint",rar:"application/x-rar-compressed",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"application/typescript",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/x-wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.ms-excel",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3gp2":"video/3gpp2","7z":"application/x-7z-compressed"};function wu(e){return["text/html","text/css"].includes(e)?`${e}; charset=utf-8`:e}async function bu(e){if("string"==typeof e)return(new TextEncoder).encode(e);if(e instanceof ArrayBuffer)return new Uint8Array(e);if(e instanceof Blob)return new Uint8Array(await new Response(e).arrayBuffer());throw new TypeError("unknown websocket data type")}function vu(e){if(!function(e){try{if("string"!=typeof e)return!1;const t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch(e){return!1}}(e))throw new qi("URL is not valid!",e)}class xu{constructor(e,t){vu(e),this.url=function(e){return e.endsWith("/")?e.slice(0,-1):e}(e),t?.signer&&(this.signer=new Ri(t.signer)),this.network=t?.network??"gnosis",this.requestOptions={baseURL:this.url,timeout:t?.timeout??0,headers:t?.headers,onRequest:t?.onRequest,httpAgent:t?.httpAgent,httpsAgent:t?.httpsAgent}}async uploadData(e,t,n,r){return e=new Ci(e),ao(t),n&&(n=function(e,t="UploadOptions"){const n=no(e,t),r=ei.asObject(e,{name:t});return{...n,redundancyLevel:ei.asOptional(e=>ei.asInteger(e,{name:"redundancyLevel",min:0}),r.redundancyLevel)}}(n)),Hs(this.getRequestOptionsForCall(r),t,e,n)}async probeData(e,t){return e=new Ti(e),async function(e,t){t=new Ti(t);const n=await Bs(e,{url:`${Ks}/${t}`,method:"head",responseType:"json"});return{contentLength:parseInt(n.headers["content-length"])}}(this.getRequestOptionsForCall(t),e)}async downloadData(e,t,n){return t&&(t=to(t)),Ws(this.getRequestOptionsForCall(n),new Ys(e),t)}async downloadReadableData(e,t,n){return t&&(t=to(t)),async function(e,t,n){return n&&(n=to(n)),(await Bs(e,{responseType:"stream",url:`${Ks}/${t}`,headers:wo(null,n)})).data}(this.getRequestOptionsForCall(n),new Ys(e),t)}async uploadChunk(e,t,n,r){const i="identifier"in t&&"signature"in t&&"owner"in t;if(t=t instanceof Uint8Array?t:t.data,n&&(n=no(n)),t.length<Oi.LENGTH)throw new qi(`Chunk has to have size of at least ${Oi.LENGTH}.`,t);if(!i&&t.length>ji+Oi.LENGTH)throw new qi(`Content Addressed Chunk must not exceed ${ji+Oi.LENGTH} bytes.`,t);if(i&&t.length>ji+Oi.LENGTH+$i.LENGTH+ki.LENGTH)throw new qi(`Single Owner Chunk must not exceed ${ji+Oi.LENGTH+$i.LENGTH+ki.LENGTH} bytes.`,t);return async function(e,t,n,r){const i=await Bs(e,{method:"post",url:`${Ds}`,data:t,headers:{"content-type":"application/octet-stream",...wo(n,r)},responseType:"json"}),o=ei.asObject(i.data,{name:"response.data"});return{reference:new Ti(ei.asString(o.reference,{name:"reference"})),tagUid:i.headers["swarm-tag"]?so(i.headers["swarm-tag"]):void 0,historyAddress:i.headers["swarm-act-history-address"]?ti.of(new Ti(i.headers["swarm-act-history-address"])):ti.empty()}}(this.getRequestOptionsForCall(r),t,e,n)}async downloadChunk(e,t,n){return e=new Ti(e),t&&(t=to(t)),Cs(this.getRequestOptionsForCall(n),e,t)}async createGrantees(e,t,n){return e=new Ci(e),t=t.map(e=>new Si(e)),async function(e,t,n){const r=await Bs(e,{method:"post",url:Yc,data:{grantees:n.map(e=>e.toCompressedHex())},headers:wo(t),responseType:"json"}),i=ei.asObject(r.data,{name:"response.data"});return{status:r.status,statusText:r.statusText,ref:new Ti(ei.asString(i.ref,{name:"ref"})),historyref:new Ti(ei.asString(i.historyref,{name:"historyref"}))}}(this.getRequestOptionsForCall(n),e,t)}async getGrantees(e,t){return async function(e,t){const n=await Bs(t,{method:"get",url:`${Yc}/${e}`,responseType:"json"}),r=ei.asArray(n.data,{name:"response.data"}).map(e=>new Si(ei.asString(e,{name:"grantee"})));return{status:n.status,statusText:n.statusText,grantees:r}}(e=new Ti(e),this.getRequestOptionsForCall(t))}async patchGrantees(e,t,n,r,i){return async function(e,t,n,r,i){const o=await Bs(i,{method:"patch",url:`${Yc}/${t}`,data:{add:r.add?.map(e=>e.toCompressedHex()),revoke:r.revoke?.map(e=>e.toCompressedHex())},headers:{...wo(e),"swarm-act-history-address":n.toHex()},responseType:"json"}),a=ei.asObject(o.data,{name:"response.data"});return{status:o.status,statusText:o.statusText,ref:new Ti(ei.asString(a.ref,{name:"ref"})),historyref:new Ti(ei.asString(a.historyref,{name:"historyref"}))}}(e=new Ci(e),t=new Ti(t),n=new Ti(n),{add:r.add?.map(e=>new Si(e))??[],revoke:r.revoke?.map(e=>new Si(e))??[]},this.getRequestOptionsForCall(i))}async uploadFile(e,t,n,r,i){if(e=new Ci(e),function(e){if(!("string"==typeof e||e instanceof Uint8Array||Yi(e)))throw new TypeError("Data must be either string, Readable, Uint8Array or File!")}(t),r&&(r=function(e){const t=no(e,"FileUploadOptions"),n=ei.asObject(e,{name:"FileUploadOptions"});return{...t,size:ei.asOptional(e=>ei.asInteger(e,{name:"size",min:0}),n.size),contentType:ei.asOptional(e=>ei.asString(e,{name:"contentType"}),n.contentType),redundancyLevel:ei.asOptional(e=>ei.asInteger(e,{name:"redundancyLevel",min:0}),n.redundancyLevel)}}(r)),n&&"string"!=typeof n)throw new TypeError("name has to be string or undefined!");if(Yi(t)){const o=await Qi(t),a=n??t.name,s={contentType:t.type,...r};return fc(this.getRequestOptionsForCall(i),o,e,a,s)}return fc(this.getRequestOptionsForCall(i),t,e,n,r)}async downloadFile(e,t="",n,r){return n&&(n=to(n)),async function(e,t,n="",r){const i=await Bs(e,{method:"GET",responseType:"arraybuffer",url:`${hc}/${t}/${n}`,headers:wo(null,r)});return{...yo(i.headers),data:new wi(i.data)}}(this.getRequestOptionsForCall(r),new Ys(e),t,n)}async downloadReadableFile(e,t="",n,r){return e=new Ti(e),n&&(n=to(n)),async function(e,t,n="",r){t=new Ti(t);const i=await Bs(e,{method:"GET",responseType:"stream",url:`${hc}/${t}/${n}`,headers:wo(null,r)});return{...yo(i.headers),data:i.data}}(this.getRequestOptionsForCall(r),e,t,n)}async uploadFiles(e,t,n,r){e=new Ci(e),n&&(n=ro(n));const i=function(e){return Array.from(e).map(e=>({path:uc(e),size:e.size,file:e}))}(t);return pc(this.getRequestOptionsForCall(r),i,e,n)}async hashDirectory(e){return async function(){throw new Error("Hashing directories is not supported in browsers!")}()}async streamDirectory(e,t,n,r,i){return e=new Ci(e),async function(){throw new Error("Streaming directories is not supported in browsers!")}(0,0,0,0,0,this.getRequestOptionsForCall(i))}async streamFiles(e,t,n,r,i){return async function(e,t,n,r,i,o){const a=o?.signal;if(a?.aborted)throw new Error("Request aborted");const s=new ii(64,64);let c=0,u=0;for(const e of t)c+=gu(e.size);async function l(t){await s.enqueue(async()=>{if(!a?.aborted)try{await e.uploadChunk(n,t.build(),i,o),r?.({total:c,processed:++u})}catch(e){if(a?.aborted)return;throw e}})}n=new Ci(n);const d=new mu;for(const e of t){if(a?.aborted)throw new Error("Request aborted");const t=await new Promise((t,n)=>{const r=new ni(l);let i=0;const o=new FileReader;o.onerror=()=>{n(o.error)};const s=async()=>{if(a?.aborted)return void n(new Error("Request aborted"));if(i>=e.size){const e=await r.finalize();return void t(e)}const s=e.slice(i,i+4096);o.readAsArrayBuffer(s)};o.onload=async e=>{if(!e.target)return void n("No event target");const t=e.target.result;t&&(await r.append(new Uint8Array(t)),i+=4096),s()},s()});await s.drain();const{filename:n,extension:r}=Yr.parseFilename(e.name);d.addFork(uc(e),t.hash(),{"Content-Type":wu(yu[r.toLowerCase()]||"application/octet-stream"),Filename:n}),"index.html"===e.name&&d.addFork("/",Au,{"website-index-document":"index.html"})}if(a?.aborted)throw new Error("Request aborted");return d.saveRecursively(e,n,i,o)}(this,t,e=new Ci(e),n,r,this.getRequestOptionsForCall(i))}async uploadCollection(e,t,n,r){return e=new Ci(e),cc(t),n&&(n=ro(n)),pc(this.getRequestOptionsForCall(r),t,e,n)}async uploadFilesFromDirectory(e,t,n,r){e=new Ci(e),n&&(n=ro(n));const i=await async function(){throw new Error("Creating Collection from File System is not supported in browsers!")}();return pc(this.getRequestOptionsForCall(r),i,e,n)}async createTag(e){return async function(e){const t=await Bs(e,{method:"post",url:cu,responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return{address:ei.asEmptiableString(n.address,{name:"address"}),seen:ei.asNumber(n.seen,{name:"seen"}),sent:ei.asNumber(n.sent,{name:"sent"}),split:ei.asNumber(n.split,{name:"split"}),startedAt:ei.asString(n.startedAt,{name:"startedAt"}),stored:ei.asNumber(n.stored,{name:"stored"}),synced:ei.asNumber(n.synced,{name:"synced"}),uid:ei.asNumber(n.uid,{name:"uid"})}}(this.getRequestOptionsForCall(e))}async getAllTags(e,t){return e&&(e=function(e){const t=ei.asObject(e,{name:"AllTagsOptions"});return{limit:ei.asOptional(e=>ei.asInteger(e,{name:"limit",min:1,max:1e3}),t.limit),offset:ei.asOptional(e=>ei.asInteger(e,{name:"offset",min:0}),t.offset)}}(e)),async function(e,t,n){const r=await Bs(e,{url:cu,params:{offset:t,limit:n},responseType:"json"}),i=ei.asObject(r.data,{name:"response.data"});return ei.asArray(i.tags,{name:"tags"}).map(e=>ei.asObject(e,{name:"tag"})).map(e=>({address:ei.asEmptiableString(e.address,{name:"address"}),seen:ei.asNumber(e.seen,{name:"seen"}),sent:ei.asNumber(e.sent,{name:"sent"}),split:ei.asNumber(e.split,{name:"split"}),startedAt:ei.asString(e.startedAt,{name:"startedAt"}),stored:ei.asNumber(e.stored,{name:"stored"}),synced:ei.asNumber(e.synced,{name:"synced"}),uid:ei.asNumber(e.uid,{name:"uid"})}))}(this.getRequestOptionsForCall(t),e?.offset,e?.limit)}async retrieveTag(e,t){return e=so(e),async function(e,t){const n=await Bs(e,{url:`${cu}/${t}`,responseType:"json"}),r=ei.asObject(n.data,{name:"response.data"});return{address:ei.asEmptiableString(r.address,{name:"address"}),seen:ei.asNumber(r.seen,{name:"seen"}),sent:ei.asNumber(r.sent,{name:"sent"}),split:ei.asNumber(r.split,{name:"split"}),startedAt:ei.asString(r.startedAt,{name:"startedAt"}),stored:ei.asNumber(r.stored,{name:"stored"}),synced:ei.asNumber(r.synced,{name:"synced"}),uid:ei.asNumber(r.uid,{name:"uid"})}}(this.getRequestOptionsForCall(t),e)}async deleteTag(e,t){return e=so(e),async function(e,t){await Bs(e,{method:"delete",url:`${cu}/${t}`})}(this.getRequestOptionsForCall(t),e)}async updateTag(e,t,n){return t=new Ti(t),e=so(e),async function(e,t,n){await Bs(e,{method:"patch",url:`${cu}/${t}`,data:{reference:n}})}(this.getRequestOptionsForCall(n),e,t)}async pin(e,t){return e=new Ti(e),async function(e,t){await Bs(e,{method:"post",responseType:"json",url:`${ru}/${t}`})}(this.getRequestOptionsForCall(t),e)}async unpin(e,t){return e=new Ti(e),async function(e,t){await Bs(e,{method:"delete",responseType:"json",url:`${ru}/${t}`})}(this.getRequestOptionsForCall(t),e)}async getAllPins(e){return async function(e){const t=await Bs(e,{method:"get",responseType:"json",url:`${ru}`}),n=ei.asObject(t.data,{name:"response.data"});return null===n.references?[]:ei.asArray(n.references,{name:"references"}).map(e=>ei.asString(e,{name:"reference"})).map(e=>new Ti(e))}(this.getRequestOptionsForCall(e))}async getPin(e,t){return e=new Ti(e),async function(e,t){const n=await Bs(e,{method:"get",responseType:"json",url:`${ru}/${t}`}),r=ei.asObject(n.data,{name:"response.data"});return{reference:new Ti(ei.asString(r.reference,{name:"reference"}))}}(this.getRequestOptionsForCall(t),e)}async reuploadPinnedData(e,t,n){e=new Ci(e),t=new Ti(t),await async function(e,t,n){await Bs(e,{method:"put",url:`${su}/${n}`,headers:{"swarm-postage-batch-id":t.toHex()}})}(this.getRequestOptionsForCall(n),e,t)}async isReferenceRetrievable(e,t){return e=new Ti(e),async function(e,t){t=new Ti(t);const n=await Bs(e,{method:"get",responseType:"json",url:`${su}/${t}`}),r=ei.asObject(n.data,{name:"response.data"});return ei.asBoolean(r.isRetrievable,{name:"isRetrievable"})}(this.getRequestOptionsForCall(t),e)}async isFeedRetrievable(e,t,n,r,i){if(e=new Ii(e),t=new zi(t),r&&(r=to(r)),!n)try{return await this.makeFeedReader(t,e,i).download(),!0}catch(e){const t=Xr.getDeep(e,"status");if(404===t||500===t)return!1;throw e}return sc(this,e,t,n,r,this.getRequestOptionsForCall(i))}async pssSend(e,t,n,r,i,o){return e=new Ci(e),ao(r),i?(i=new Si(i),ou(this.getRequestOptionsForCall(o),t,n,r,e,i)):ou(this.getRequestOptionsForCall(o),t,n,r,e)}pssSubscribe(e,t){t=function(e){const t=ei.asObject(e,{name:"PssMessageHandler"});return{onMessage:ei.asFunction(t.onMessage,{name:"onMessage"}),onError:ei.asFunction(t.onError,{name:"onError"}),onClose:ei.asFunction(t.onClose,{name:"onClose"})}}(t);const n=function(e,t,n){const r=e.replace(/^http/i,"ws");return"browser"===Qr.whereAmI()?new tu(`${r}/${iu}/subscribe/${t.toHex()}`):new tu(`${r}/${iu}/subscribe/${t.toHex()}`,{headers:n})}(this.url,e,this.requestOptions.headers);let r=!1;const i={topic:e,cancel:()=>{r||(r=!0,n.terminate?n.terminate():n.close())}};return n.onmessage=async e=>{const n=await bu(e.data);n.length&&t.onMessage(new wi(n),i)},n.onerror=e=>{r||t.onError(new Ui(e.message),i)},n.onclose=()=>{t.onClose(i)},i}async pssReceive(e,t=0){if("number"!=typeof t)throw new TypeError("timeoutMsc parameter has to be a number!");return new Promise((n,r)=>{let i;const o=this.pssSubscribe(e,{onError:e=>{clearTimeout(i),o.cancel(),r(e.message)},onMessage:e=>{clearTimeout(i),o.cancel(),n(e)},onClose:()=>{clearTimeout(i),o.cancel()}});t>0&&(i=setTimeout(()=>{o.cancel(),r(new Ui("pssReceive timeout"))},t))})}gsocMine(e,t,n=12){e=new Di(e),t=new ki(t);for(let r=0n;r<0xffffn;r++){const i=new Ri(Hr.numberToUint256(2867n+r,"BE")),o=Us(t,i.publicKey().address());if(256-Hr.proximity(o.toUint8Array(),e.toUint8Array())<=256-n)return i}throw Error("Could not mine a valid signer")}async gsocSend(e,t,n,r,i,o){e=new Ci(e),t=new Ri(t),n=new ki(n);const a=Gs(r).toSingleOwnerChunk(n,t);return async function(e,t,n,r){return Ns(e,t,n,r)}(this.getRequestOptionsForCall(o),a,e,i)}gsocSubscribe(e,t,n){e=new Ii(e),t=new ki(t),n=function(e){const t=ei.asObject(e,{name:"GsocMessageHandler"});return{onMessage:ei.asFunction(t.onMessage,{name:"onMessage"}),onError:ei.asFunction(t.onError,{name:"onError"}),onClose:ei.asFunction(t.onClose,{name:"onClose"})}}(n);const r=Us(t,e),i=function(e,t,n){const r=e.replace(/^http/i,"ws");return"browser"===Qr.whereAmI()?new tu(`${r}/${nu}/subscribe/${t.toHex()}`):new tu(`${r}/${nu}/subscribe/${t.toHex()}`,{headers:n})}(this.url,r,this.requestOptions.headers);let o=!1;const a={address:e,cancel:()=>{o||(o=!0,i.terminate?i.terminate():i.close())}};return i.onmessage=async e=>{const t=await bu(e.data);t.length&&n.onMessage(new wi(t),a)},i.onerror=e=>{o||n.onError(new Ui(e.message),a)},i.onclose=()=>{n.onClose(a)},a}async createFeedManifest(e,t,n,r,i){return e=new Ci(e),t=new zi(t),n=new Ii(n),r&&(r=no(r)),async function(e,t,n,r,i){const o=await Bs(e,{method:"post",responseType:"json",url:`${Zs}/${t}/${n}`,headers:wo(r,i)}),a=ei.asObject(o.data,{name:"response.data"});return new Ti(ei.asHexString(a.reference))}(this.getRequestOptionsForCall(i),n,t,e,r)}makeFeedReader(e,t,n){return e=new zi(e),t=new Ii(t),oc(this.getRequestOptionsForCall(n),e,t)}makeFeedWriter(e,t,n){if(e=new zi(e),!(t=t?new Ri(t):this.signer))throw Error("No signer provided");return ac(this.getRequestOptionsForCall(n),e,t)}async fetchLatestFeedUpdate(e,t,n){return e=new zi(e),t=new Ii(t),Xs(this.getRequestOptionsForCall(n),t,e)}makeContentAddressedChunk(e,t){return Gs(e,t)}unmarshalContentAddressedChunk(e){return js(e)}makeSingleOwnerChunk(e,t,n,r,i){return qs(e,t,n,r,i)}calculateSingleOwnerChunkAddress(e,t){return Us(e,t)}unmarshalSingleOwnerChunk(e,t){return Ps(e,t)}makeSOCReader(e,t){return{owner:e=new Ii(e),download:_s.bind(null,this.getRequestOptionsForCall(t),e)}}makeSOCWriter(e,t){if(!(e=e?new Ri(e):this.signer))throw Error("No signer provided");return{...this.makeSOCReader(e.publicKey().address(),t),upload:Ms.bind(null,this.getRequestOptionsForCall(t),e)}}async createEnvelope(e,t,n){return e=new Ci(e),t=new Ti(t),async function(e,t,n){const r=await Bs(e,{method:"post",responseType:"json",url:`envelope/${n}`,headers:{"swarm-postage-batch-id":t.toHex()}}),i=ei.asObject(r.data,{name:"response.data"});return{issuer:Hr.hexToUint8Array(ei.asHexString(i.issuer,{name:"issuer",byteLength:20})),index:Hr.hexToUint8Array(ei.asHexString(i.index,{name:"index",byteLength:8})),timestamp:Hr.hexToUint8Array(ei.asHexString(i.timestamp,{name:"timestamp",byteLength:8})),signature:Hr.hexToUint8Array(ei.asHexString(i.signature,{name:"signature",byteLength:65})),batchId:t}}(this.getRequestOptionsForCall(n),e,t)}async rchash(e,t,n,r){return async function(e,t,n,r){const i=await Bs(e,{responseType:"json",url:`rchash/${t}/${n}/${r}`}),o=ei.asObject(i.data,{name:"response.data"});return ei.asNumber(o.durationSeconds,{name:"durationSeconds"})}(this.getRequestOptionsForCall(r),e,t,n)}async checkConnection(e){return au(this.getRequestOptionsForCall(e))}async isConnected(e){try{await au(this.getRequestOptionsForCall(e))}catch(e){return!1}return!0}async isGateway(e){return async function(e){try{const t=await Bs(e,{url:"/gateway"}),n=ei.asObject(t.data);return ei.asBoolean(n.gateway)}catch(e){return!1}}(this.getRequestOptionsForCall(e))}async getNodeAddresses(e){return async function(e){const t=await Bs(e,{url:"addresses",responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return{overlay:new Di(ei.asString(n.overlay,{name:"overlay"})),underlay:ei.asArray(n.underlay,{name:"underlay"}).map(e=>ei.asString(e,{name:"underlay"})),ethereum:new Ii(ei.asString(n.ethereum,{name:"ethereum"})),publicKey:new Si(ei.asString(n.publicKey,{name:"publicKey"})),pssPublicKey:new Si(ei.asString(n.pssPublicKey,{name:"pssPublicKey"}))}}(this.getRequestOptionsForCall(e))}async getBlocklist(e){return async function(e){return(await Bs(e,{url:"blocklist",responseType:"json"})).data.peers}(this.getRequestOptionsForCall(e))}async getPeers(e){return async function(e){const t=await Bs(e,{url:"peers",responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return ei.asArray(n.peers,{name:"peers"}).map(e=>({address:ei.asString(ei.asObject(e,{name:"peer"}).address,{name:"address"}),fullNode:ei.asBoolean(ei.asObject(e,{name:"peer"}).fullNode,{name:"fullNode"})}))}(this.getRequestOptionsForCall(e))}async removePeer(e,t){return e=new Di(e),async function(e,t){return(await Bs(e,{url:`peers/${t}`,responseType:"json",method:"DELETE"})).data}(this.getRequestOptionsForCall(t),e)}async getTopology(e){return async function(e){const t=await Bs(e,{url:"topology",responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"}),r=ei.asObject(n.bins,{name:"bins"});return{baseAddr:ei.asString(n.baseAddr,{name:"baseAddr"}),population:ei.asNumber(n.population,{name:"population"}),connected:ei.asNumber(n.connected,{name:"connected"}),timestamp:ei.asString(n.timestamp,{name:"timestamp"}),nnLowWatermark:ei.asNumber(n.nnLowWatermark,{name:"nnLowWatermark"}),depth:ei.asNumber(n.depth,{name:"depth"}),reachability:ei.asString(n.reachability,{name:"reachability"}),networkAvailability:ei.asString(n.networkAvailability,{name:"networkAvailability"}),bins:{bin_0:vc(r.bin_0,"bin_0"),bin_1:vc(r.bin_1,"bin_1"),bin_2:vc(r.bin_2,"bin_2"),bin_3:vc(r.bin_3,"bin_3"),bin_4:vc(r.bin_4,"bin_4"),bin_5:vc(r.bin_5,"bin_5"),bin_6:vc(r.bin_6,"bin_6"),bin_7:vc(r.bin_7,"bin_7"),bin_8:vc(r.bin_8,"bin_8"),bin_9:vc(r.bin_9,"bin_9"),bin_10:vc(r.bin_10,"bin_10"),bin_11:vc(r.bin_11,"bin_11"),bin_12:vc(r.bin_12,"bin_12"),bin_13:vc(r.bin_13,"bin_13"),bin_14:vc(r.bin_14,"bin_14"),bin_15:vc(r.bin_15,"bin_15"),bin_16:vc(r.bin_16,"bin_16"),bin_17:vc(r.bin_17,"bin_17"),bin_18:vc(r.bin_18,"bin_18"),bin_19:vc(r.bin_19,"bin_19"),bin_20:vc(r.bin_20,"bin_20"),bin_21:vc(r.bin_21,"bin_21"),bin_22:vc(r.bin_22,"bin_22"),bin_23:vc(r.bin_23,"bin_23"),bin_24:vc(r.bin_24,"bin_24"),bin_25:vc(r.bin_25,"bin_25"),bin_26:vc(r.bin_26,"bin_26"),bin_27:vc(r.bin_27,"bin_27"),bin_28:vc(r.bin_28,"bin_28"),bin_29:vc(r.bin_29,"bin_29"),bin_30:vc(r.bin_30,"bin_30"),bin_31:vc(r.bin_31,"bin_31")}}}(this.getRequestOptionsForCall(e))}async pingPeer(e,t){return e=new Di(e),async function(e,t){return(await Bs(e,{url:`pingpong/${t}`,responseType:"json",method:"POST"})).data}(this.getRequestOptionsForCall(t),e)}async getAllBalances(e){return async function(e){const t=await Bs(e,{url:mc,responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return{balances:ei.asArray(n.balances,{name:"balances"}).map(e=>ei.asObject(e,{name:"balance"})).map(e=>({peer:ei.asString(e.peer,{name:"peer"}),balance:Ji.fromPLUR(eo(e.balance,{name:"balance"}))}))}}(this.getRequestOptionsForCall(e))}async getPeerBalance(e,t){return e=new Di(e),async function(e,t){const n=await Bs(e,{url:`${mc}/${t}`,responseType:"json"}),r=ei.asObject(n.data,{name:"response.data"});return{peer:ei.asString(r.peer,{name:"peer"}),balance:Ji.fromPLUR(eo(r.balance,{name:"balance"}))}}(this.getRequestOptionsForCall(t),e)}async getPastDueConsumptionBalances(e){return async function(e){const t=await Bs(e,{url:gc,responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return{balances:ei.asArray(n.balances,{name:"balances"}).map(e=>ei.asObject(e,{name:"balance"})).map(e=>({peer:ei.asString(e.peer,{name:"peer"}),balance:Ji.fromPLUR(eo(e.balance,{name:"balance"}))}))}}(this.getRequestOptionsForCall(e))}async getPastDueConsumptionPeerBalance(e,t){return e=new Di(e),async function(e,t){const n=await Bs(e,{url:`${gc}/${t}`,responseType:"json"}),r=ei.asObject(n.data,{name:"response.data"});return{peer:ei.asString(r.peer,{name:"peer"}),balance:Ji.fromPLUR(eo(r.balance,{name:"balance"}))}}(this.getRequestOptionsForCall(t),e)}async getChequebookAddress(e){return async function(e){const t=await Bs(e,{url:yc+"/address",responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return{chequebookAddress:new Ii(ei.asString(n.chequebookAddress,{name:"chequebookAddress"}))}}(this.getRequestOptionsForCall(e))}async getChequebookBalance(e){return async function(e){const t=await Bs(e,{url:yc+"/balance",responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return{availableBalance:Ji.fromPLUR(eo(n.availableBalance,{name:"availableBalance"})),totalBalance:Ji.fromPLUR(eo(n.totalBalance,{name:"totalBalance"}))}}(this.getRequestOptionsForCall(e))}async getLastCheques(e){return async function(e){const t=await Bs(e,{url:yc+"/cheque",responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return{lastcheques:ei.asArray(n.lastcheques,{name:"lastcheques"}).map(e=>ei.asObject(e,{name:"lastcheque"})).map(e=>({peer:ei.asString(e.peer,{name:"peer"}),lastreceived:ei.asNullable(e=>bc(e),e.lastreceived),lastsent:ei.asNullable(e=>bc(e),e.lastsent)}))}}(this.getRequestOptionsForCall(e))}async getLastChequesForPeer(e,t){return e=new Di(e),async function(e,t){const n=await Bs(e,{url:yc+`/cheque/${t}`,responseType:"json"}),r=ei.asObject(n.data,{name:"response.data"});return{peer:ei.asString(r.peer,{name:"peer"}),lastreceived:ei.asNullable(e=>bc(e),r.lastreceived),lastsent:ei.asNullable(e=>bc(e),r.lastsent)}}(this.getRequestOptionsForCall(t),e)}async getLastCashoutAction(e,t){return e=new Di(e),wc(this.getRequestOptionsForCall(t),e)}async cashoutLastCheque(e,t,n){return e=new Di(e),t&&oo(t),async function(e,t,n){const r=await Bs(e,{method:"post",url:yc+`/cashout/${t}`,responseType:"json",headers:wo(null,n)}),i=ei.asObject(r.data,{name:"response.data"});return new Bi(ei.asString(i.transactionHash,{name:"transactionHash"}))}(this.getRequestOptionsForCall(n),e,t)}async depositTokens(e,t,n){return this.depositBZZToChequebook(e,t,n)}async depositBZZToChequebook(e,t,n){const r=e instanceof Ji?e.toPLURString():eo(e,{min:1n,name:"amount"});let i;return t&&(i=eo(e,{min:0n,name:"gasPrice"})),async function(e,t,n){const r={};n&&(r["gas-price"]=n.toString());const i=await Bs(e,{method:"post",url:yc+"/deposit",responseType:"json",params:{amount:t.toString(10)},headers:r}),o=ei.asObject(i.data,{name:"response.data"});return new Bi(ei.asString(o.transactionHash,{name:"transactionHash"}))}(this.getRequestOptionsForCall(n),r,i)}async withdrawTokens(e,t,n){return this.withdrawBZZFromChequebook(e,t,n)}async withdrawBZZFromChequebook(e,t,n){const r=e instanceof Ji?e.toPLURString():eo(e,{min:1n,name:"amount"});let i;return t&&(i=eo(e,{min:0n,name:"gasPrice"})),async function(e,t,n){const r={};n&&(r["gas-price"]=n.toString());const i=await Bs(e,{method:"post",url:yc+"/withdraw",responseType:"json",params:{amount:t.toString(10)},headers:r}),o=ei.asObject(i.data,{name:"response.data"});return new Bi(ei.asString(o.transactionHash,{name:"transactionHash"}))}(this.getRequestOptionsForCall(n),r,i)}async withdrawBZZToExternalWallet(e,t,n){return e=e instanceof Ji?e:Ji.fromPLUR(e),t=new Ii(t),async function(e,t,n){const r=await Bs(e,{method:"post",url:`${kc}/withdraw/bzz`,responseType:"json",params:{amount:t.toPLURString(),address:n.toHex()}}),i=ei.asObject(r.data,{name:"response.data"});return new Bi(ei.asString(i.transactionHash,{name:"transactionHash"}))}(this.getRequestOptionsForCall(n),e,t)}async withdrawDAIToExternalWallet(e,t,n){return e=e instanceof Xi?e:Xi.fromWei(e),t=new Ii(t),async function(e,t,n){const r=await Bs(e,{method:"post",url:`${kc}/withdraw/nativetoken`,responseType:"json",params:{amount:t.toWeiString(),address:n.toHex()}}),i=ei.asObject(r.data,{name:"response.data"});return new Bi(ei.asString(i.transactionHash,{name:"transactionHash"}))}(this.getRequestOptionsForCall(n),e,t)}async getSettlements(e,t){return e=new Di(e),async function(e,t){const n=await Bs(e,{url:`${xc}/${t}`,responseType:"json"}),r=ei.asObject(n.data,{name:"response.data"});return{peer:ei.asString(r.peer,{name:"peer"}),sent:Ji.fromPLUR(eo(r.sent,{name:"sent"})),received:Ji.fromPLUR(eo(r.received,{name:"received"}))}}(this.getRequestOptionsForCall(t),e)}async getAllSettlements(e){return async function(e){const t=await Bs(e,{url:xc,responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return{totalSent:Ji.fromPLUR(eo(n.totalSent,{name:"totalSent"})),totalReceived:Ji.fromPLUR(eo(n.totalReceived,{name:"totalReceived"})),settlements:ei.asArray(n.settlements,{name:"settlements"}).map(e=>ei.asObject(e,{name:"settlement"})).map(e=>({peer:ei.asString(e.peer,{name:"peer"}),sent:Ji.fromPLUR(eo(e.sent,{name:"sent"})),received:Ji.fromPLUR(eo(e.received,{name:"received"}))}))}}(this.getRequestOptionsForCall(e))}async getStatus(e){return async function(e){const t=await Bs(e,{method:"get",url:"status",responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return{overlay:ei.asString(n.overlay,{name:"overlay"}),proximity:ei.asNumber(n.proximity,{name:"proximity"}),beeMode:Li(ei.asString(n.beeMode,{name:"beeMode"})),reserveSize:ei.asNumber(n.reserveSize,{name:"reserveSize"}),reserveSizeWithinRadius:ei.asNumber(n.reserveSizeWithinRadius,{name:"reserveSizeWithinRadius"}),pullsyncRate:ei.asNumber(n.pullsyncRate,{name:"pullsyncRate"}),storageRadius:ei.asNumber(n.storageRadius,{name:"storageRadius"}),connectedPeers:ei.asNumber(n.connectedPeers,{name:"connectedPeers"}),neighborhoodSize:ei.asNumber(n.neighborhoodSize,{name:"neighborhoodSize"}),batchCommitment:ei.asNumber(n.batchCommitment,{name:"batchCommitment"}),isReachable:ei.asBoolean(n.isReachable,{name:"isReachable"}),lastSyncedBlock:ei.asNumber(n.lastSyncedBlock,{name:"lastSyncedBlock"}),committedDepth:ei.asNumber(n.committedDepth,{name:"committedDepth"}),isWarmingUp:ei.asBoolean(n.isWarmingUp,{name:"isWarmingUp"})}}(this.getRequestOptionsForCall(e))}async getHealth(e){return Zc(this.getRequestOptionsForCall(e))}async getReadiness(e){return async function(e){const t=await Bs(e,{method:"get",url:"readiness"}),n=ei.asObject(t.data,{name:"response.data"});return{apiVersion:ei.asString(n.apiVersion,{name:"apiVersion"}),version:ei.asString(n.version,{name:"version"}),status:ei.asString(n.status,{name:"status"})}}(this.getRequestOptionsForCall(e))}async getNodeInfo(e){return async function(e){const t=await Bs(e,{method:"get",url:"node",responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return{beeMode:Li(ei.asString(n.beeMode,{name:"beeMode"})),chequebookEnabled:ei.asBoolean(n.chequebookEnabled,{name:"chequebookEnabled"}),swapEnabled:ei.asBoolean(n.swapEnabled,{name:"swapEnabled"})}}(this.getRequestOptionsForCall(e))}async isSupportedExactVersion(e){return async function(e){const{version:t}=await Zc(e);return t===Hc}(this.getRequestOptionsForCall(e))}async isSupportedApiVersion(e){return async function(e){const{apiVersion:t}=await Zc(e);return Kc(t)===Kc(Wc)}(this.getRequestOptionsForCall(e))}async getVersions(e){return async function(e){const{version:t,apiVersion:n}=await Zc(e);return{supportedBeeVersion:Hc,supportedBeeApiVersion:Wc,beeVersion:t,beeApiVersion:n}}(this.getRequestOptionsForCall(e))}async getReserveState(e){return async function(e){const t=await Bs(e,{method:"get",url:"reservestate",responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return{commitment:ei.asNumber(n.commitment,{name:"commitment"}),radius:ei.asNumber(n.radius,{name:"radius"}),storageRadius:ei.asNumber(n.storageRadius,{name:"storageRadius"}),reserveCapacityDoubling:ei.asNumber(n.reserveCapacityDoubling,{name:"reserveCapacityDoubling"})}}(this.getRequestOptionsForCall(e))}async getChainState(e){return async function(e){const t=await Bs(e,{method:"get",url:"chainstate",responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return{block:ei.asNumber(n.block,{name:"block"}),chainTip:ei.asNumber(n.chainTip,{name:"chainTip"}),totalAmount:eo(n.totalAmount,{name:"totalAmount"}),currentPrice:(r=ei.asNumber(n.currentPrice,{name:"currentPrice"}),Number.isInteger(r)?r<24e3?24e3:r:24e3)};var r}(this.getRequestOptionsForCall(e))}async getWalletBalance(e){return async function(e){const t=await Bs(e,{method:"get",url:`${kc}`,responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return{bzzBalance:Ji.fromPLUR(eo(n.bzzBalance,{name:"bzzBalance"})),nativeTokenBalance:Xi.fromWei(eo(n.nativeTokenBalance,{name:"nativeTokenBalance"})),chainID:ei.asNumber(n.chainID,{name:"chainID"}),chequebookContractAddress:ei.asString(n.chequebookContractAddress,{name:"chequebookContractAddress"}),walletAddress:ei.asString(n.walletAddress,{name:"walletAddress"})}}(this.getRequestOptionsForCall(e))}async createPostageBatch(e,t,n,r){const i=eo(e,{min:0n,name:"amount"});if(n&&(n=io(n)),t<17||t>255)throw new qi("Depth has to be between 17..255",t);const o=await this.getChainState(),a=17280n*BigInt(o.currentPrice)+1n;if(BigInt(i)<a)throw new qi(`Amount has to be at least ${a} (1 day at current price ${o.currentPrice})`,i);const s=await async function(e,t,n,r){const i={};r?.gasPrice&&(i["gas-price"]=r.gasPrice.toString()),void 0!==r?.immutableFlag&&(i.immutable=String(r.immutableFlag));const o=await Bs(e,{method:"post",url:`${Ac}/${t}/${n}`,responseType:"json",params:{label:r?.label},headers:i}),a=ei.asObject(o.data,{name:"response.data"});return new Ci(ei.asString(a.batchID,{name:"batchID"}))}(this.getRequestOptionsForCall(r),i,t,n);return!1!==n?.waitForUsable&&await this.waitForUsablePostageStamp(s,n?.waitForUsableTimeout),s}async buyStorage(e,t,n,r,i,o){const a=fo(t,(await this.getChainState(r)).currentPrice,"gnosis"===this.network?5:15),s=po(e,i,o);return n&&(n=io(n)),this.createPostageBatch(a,s,n,r)}async getStorageCost(e,t,n,r,i){const o=fo(t,(await this.getChainState(n)).currentPrice,"gnosis"===this.network?5:15);return ho(po(e,r,i),o)}async extendStorage(e,t,n,r,i,o){const a=await this.getPostageBatch(e,r),s=po(t,i,o),c=await this.getChainState(r),u=s-a.depth,l=u<=0?1n:2n**BigInt(u),d="gnosis"===this.network?5:15,h=fo(n,c.currentPrice,d),f=fo(a.duration,c.currentPrice,d),p=(n.isZero()?f*l:(f+h)*l)-f,m=await this.topUpBatch(a.batchID,p,r);return u>0?this.diluteBatch(a.batchID,s,r):m}async extendStorageSize(e,t,n,r,i){const o=await this.getChainState(n),a=await this.getPostageBatch(e,n),s=po(t,r,i),c=s-a.depth;if(c<=0)throw new qi("New depth has to be greater than the original depth",s);const u=fo(a.duration,o.currentPrice,"gnosis"===this.network?5:15);return await this.topUpBatch(a.batchID,u*(2n**BigInt(c)-1n)+1n,n),this.diluteBatch(a.batchID,s,n)}async extendStorageDuration(e,t,n){const r=await this.getPostageBatch(e,n),i=fo(t,(await this.getChainState(n)).currentPrice,"gnosis"===this.network?5:15);return this.topUpBatch(r.batchID,i,n)}async getExtensionCost(e,t,n,r,i,o){const a=await this.getPostageBatch(e,r),s=await this.getChainState(r),c="gnosis"===this.network?5:15,u=n.isZero()?0n:fo(n,s.currentPrice,c),l=po(t,i,o),d=fo(a.duration,s.currentPrice,c),h=ho(a.depth,d);return ho(Math.max(a.depth,l),d+u).minus(h)}async getSizeExtensionCost(e,t,n,r,i){const o=await this.getPostageBatch(e,n),a=await this.getChainState(n),s=po(t,r,i);if(s-o.depth<=0)throw new qi("New depth has to be greater than the original depth",s);const c=fo(o.duration,a.currentPrice,"gnosis"===this.network?5:15),u=ho(o.depth,c);return ho(s,c).minus(u)}async getDurationExtensionCost(e,t,n){const r=await this.getPostageBatch(e,n),i=fo(t,(await this.getChainState(n)).currentPrice,"gnosis"===this.network?5:15);return ho(r.depth,i)}async topUpBatch(e,t,n){e=new Ci(e);const r=eo(t,{min:1n,name:"amount"});return async function(e,t,n){const r=await Bs(e,{method:"patch",url:`${Ac}/topup/${t}/${n}`,responseType:"json"}),i=ei.asObject(r.data,{name:"response.data"});return new Ci(ei.asString(i.batchID,{name:"batchID"}))}(this.getRequestOptionsForCall(n),e,r)}async diluteBatch(e,t,n){return e=new Ci(e),t=ei.asNumber(t,{name:"depth",min:18,max:255}),async function(e,t,n){const r=await Bs(e,{method:"patch",url:`${Ac}/dilute/${t}/${n}`,responseType:"json"}),i=ei.asObject(r.data,{name:"response.data"});return new Ci(ei.asString(i.batchID,{name:"batchID"}))}(this.getRequestOptionsForCall(n),e,t)}async getPostageBatch(e,t,n,r){return e=new Ci(e),async function(e,t,n,r){const i=await Bs(e,{method:"get",url:`${Ac}/${t}`,responseType:"json"});return go(Ic(ei.asObject(i.data,{name:"response.data"})),n,r)}(this.getRequestOptionsForCall(t),e,n,r)}async getPostageBatchBuckets(e,t){return e=new Ci(e),async function(e,t){const n=await Bs(e,{method:"get",url:`${Ac}/${t}/buckets`,responseType:"json"}),r=ei.asObject(n.data,{name:"response.data"});return{depth:ei.asNumber(r.depth,{name:"depth"}),bucketDepth:ei.asNumber(r.bucketDepth,{name:"bucketDepth"}),bucketUpperBound:ei.asNumber(r.bucketUpperBound,{name:"bucketUpperBound"}),buckets:ei.asArray(r.buckets,{name:"buckets"}).map(e=>ei.asObject(e,{name:"bucket"})).map(e=>({bucketID:ei.asNumber(e.bucketID,{name:"bucketID"}),collisions:ei.asNumber(e.collisions,{name:"collisions"})}))}}(this.getRequestOptionsForCall(t),e)}async getAllPostageBatch(e){return Sc(this.getRequestOptionsForCall(e))}async getAllGlobalPostageBatch(e){return Rc(this.getRequestOptionsForCall(e))}async getPostageBatches(e){return Sc(this.getRequestOptionsForCall(e))}async getGlobalPostageBatches(e){return Rc(this.getRequestOptionsForCall(e))}async getAllPendingTransactions(e){return async function(e){const t=await Bs(e,{url:Jc,responseType:"json"}),n=ei.asObject(t.data,{name:"response.data"});return ei.asArray(n.pendingTransactions,{name:"pendingTransactions"}).map(Xc)}(this.getRequestOptionsForCall(e))}async getPendingTransaction(e,t){return e=new Bi(e),async function(e,t){const n=await Bs(e,{url:`${Jc}/${t}`,responseType:"json"});return Xc(ei.asObject(n.data,{name:"response.data"}))}(this.getRequestOptionsForCall(t),e)}async rebroadcastPendingTransaction(e,t){return e=new Bi(e),async function(e,t){const n=await Bs(e,{method:"post",url:`${Jc}/${t}`,responseType:"json"}),r=ei.asObject(n.data,{name:"response.data"});return new Bi(ei.asString(r.transactionHash,{name:"transactionHash"}))}(this.getRequestOptionsForCall(t),e)}async cancelPendingTransaction(e,t,n){let r;return e=new Bi(e),t&&(r=eo(t,{min:0n,name:"gasPrice"})),async function(e,t,n){const r={};n&&(r["gas-price"]=n.toString());const i=await Bs(e,{method:"delete",headers:r,url:`${Jc}/${t}`,responseType:"json"}),o=ei.asObject(i.data,{name:"response.data"});return new Bi(ei.asString(o.transactionHash,{name:"transactionHash"}))}(this.getRequestOptionsForCall(n),e,r)}async getStake(e){return async function(e){const t=await Bs(e,{method:"get",responseType:"json",url:`${Ec}`}),n=ei.asObject(t.data,{name:"response.data"});return Ji.fromPLUR(eo(n.stakedAmount,{name:"stakedAmount"}))}(this.getRequestOptionsForCall(e))}async getWithdrawableStake(e){return async function(e){const t=await Bs(e,{method:"get",responseType:"json",url:`${Ec}/withdrawable`}),n=ei.asObject(t.data,{name:"response.data"});return Ji.fromPLUR(eo(n.withdrawableAmount,{name:"withdrawableAmount"}))}(this.getRequestOptionsForCall(e))}async withdrawSurplusStake(e){return async function(e){const t=await Bs(e,{method:"delete",responseType:"json",url:`${Ec}/withdrawable`}),n=ei.asObject(t.data,{name:"response.data"});return new Bi(ei.asHexString(n.txHash,{name:"txHash"}))}(this.getRequestOptionsForCall(e))}async migrateStake(e){return async function(e){const t=await Bs(e,{method:"delete",responseType:"json",url:Ec}),n=ei.asObject(t.data,{name:"response.data"});return new Bi(ei.asHexString(n.txHash,{name:"txHash"}))}(this.getRequestOptionsForCall(e))}async depositStake(e,t,n){const r=e instanceof Ji?e.toPLURString():eo(e,{min:1n,name:"amount"});return t&&(t=oo(t)),async function(e,t,n){const r=await Bs(e,{method:"post",responseType:"json",url:`${Ec}/${t}`,headers:wo(null,n)}),i=ei.asObject(r.data,{name:"response.data"});return new Bi(ei.asHexString(i.txHash,{name:"txHash"}))}(this.getRequestOptionsForCall(n),r,t)}async getRedistributionState(e){return async function(e){const t=await Bs(e,{method:"get",responseType:"json",url:"redistributionstate"}),n=ei.asObject(t.data,{name:"response.data"});return{minimumGasFunds:Xi.fromWei(eo(n.minimumGasFunds,{name:"minimumGasFunds"})),hasSufficientFunds:ei.asBoolean(n.hasSufficientFunds,{name:"hasSufficientFunds"}),isFrozen:ei.asBoolean(n.isFrozen,{name:"isFrozen"}),isFullySynced:ei.asBoolean(n.isFullySynced,{name:"isFullySynced"}),phase:ei.asString(n.phase,{name:"phase"}),round:ei.asNumber(n.round,{name:"round"}),lastWonRound:ei.asNumber(n.lastWonRound,{name:"lastWonRound"}),lastPlayedRound:ei.asNumber(n.lastPlayedRound,{name:"lastPlayedRound"}),lastFrozenRound:ei.asNumber(n.lastFrozenRound,{name:"lastFrozenRound"}),lastSelectedRound:ei.asNumber(n.lastSelectedRound,{name:"lastSelectedRound"}),lastSampleDurationSeconds:ei.asNumber(n.lastSampleDurationSeconds,{name:"lastSampleDurationSeconds"}),block:ei.asNumber(n.block,{name:"block"}),reward:Ji.fromPLUR(eo(n.reward,{name:"reward"})),fees:Xi.fromWei(eo(n.fees,{name:"fees"})),isHealthy:ei.asBoolean(n.isHealthy,{name:"isHealthy"})}}(this.getRequestOptionsForCall(e))}async waitForUsablePostageStamp(e,t=24e4){for(let n=0;n<t;n+=3e3){try{if((await this.getPostageBatch(e)).usable)return}catch(e){}await Qr.sleepMillis(3e3)}throw new Ui("Timeout on waiting for postage stamp to become usable")}getRequestOptionsForCall(e){return e&&(e=function(e){const t=ei.asObject(e,{name:"BeeRequestOptions"});return{baseURL:ei.asOptional(e=>ei.asString(e,{name:"baseURL"}),t.baseURL),timeout:ei.asOptional(e=>ei.asInteger(e,{name:"timeout",min:0}),t.timeout),headers:ei.asOptional(e=>ei.asStringMap(e,{name:"headers"}),t.headers),onRequest:ei.asOptional(e=>ei.asFunction(e,{name:"onRequest"}),t.onRequest),httpAgent:t.httpAgent,httpsAgent:t.httpsAgent,endlesslyRetry:ei.asOptional(e=>ei.asBoolean(e,{name:"endlesslyRetry"}),t.endlesslyRetry),signal:t.signal}}(e)),e?Xr.deepMerge2(this.requestOptions,e):this.requestOptions}}class Eu{constructor(e,t,n,r){this.signer=new Ri(e),this.batchId=new Ci(t),this.buckets=n,this.depth=r,this.maxSlot=2**(this.depth-16)}static fromBlank(e,t,n){return new Eu(e,t,new Uint32Array(65536),n)}static fromState(e,t,n,r){return new Eu(e,t,n,r)}stamp(e){const t=e.hash(),n=Hr.uint16ToNumber(t,"BE"),r=this.buckets[n];if(r>=this.maxSlot)throw Error("Bucket is full");this.buckets[n]++;const i=Hr.concatBytes(Hr.numberToUint32(n,"BE"),Hr.numberToUint32(r,"BE")),o=Hr.numberToUint64(BigInt(Date.now()),"BE"),a=this.signer.sign(Hr.concatBytes(t,this.batchId.toUint8Array(),i,o));return{batchId:this.batchId,index:i,issuer:this.signer.publicKey().address().toUint8Array(),signature:a.toUint8Array(),timestamp:o}}getState(){return this.buckets}}new Ci("0000000000000000000000000000000000000000000000000000000000000000"),new zi("0000000000000000000000000000000000000000000000000000000000000000");const Au=new Uint8Array(32);Gi.MEDIUM,Gi.STRONG,Gi.INSANE,Gi.PARANOID;const Ru="https://api.gateway.ethswarm.org/",Su="https://xdai.fairdatasociety.org/",Iu=e=>zn().regex(new RegExp(`^[0-9a-fA-F]{${e}}$`),{message:`Must be a ${e}-character hex string`}),ku=zn().regex(/^[0-9a-fA-F]{64}$|^[0-9a-fA-F]{128}$/,{message:"Reference must be 64 hex chars (32 bytes) or 128 hex chars (64 bytes for encrypted)"}),Tu=Iu(64),Bu=Iu(40),Ou=Iu(64),Du=Iu(64),Cu=Iu(64),$u=Iu(130),zu=Mr(e=>"bigint"==typeof e?e.toString():e,gr([nr(),zn()])),Fu=Mr(e=>"bigint"==typeof e?e.toString():e,gr([nr(),zn()])),Pu=zn().length(40).transform(e=>new Ii(e)),Uu=zn().length(64).transform(e=>new Ci(e)),qu=zn().length(64).transform(e=>new Ri(e)),Nu=hr(nr()).transform(e=>new wi(new Uint8Array(e))),Mu=wr("type",[pr({id:Pu,name:zn(),createdAt:nr(),type:Rr("passkey"),credentialId:zn(),swarmEncryptionKey:zn().length(64),defaultPostageStampBatchID:Uu.optional()}),pr({id:Pu,name:zn(),createdAt:nr(),type:Rr("ethereum"),ethereumAddress:Pu,encryptedMasterKey:Nu,encryptionSalt:Nu,encryptedSecretSeed:Nu,swarmEncryptionKey:zn().length(64),defaultPostageStampBatchID:Uu.optional()}),pr({id:Pu,name:zn(),createdAt:nr(),type:Rr("agent"),swarmEncryptionKey:zn().length(64),defaultPostageStampBatchID:Uu.optional()})]),_u=pr({id:Bu,accountId:Pu,name:zn(),defaultPostageStampBatchID:Uu.optional(),createdAt:nr(),settings:pr({appSessionDuration:nr().optional()}).optional()}),Vu=pr({appUrl:zn(),appName:zn(),lastConnectedAt:nr(),identityId:zn(),appIcon:zn().optional(),appDescription:zn().optional(),connectedUntil:nr().optional(),appSecret:zn().optional()}),Lu=pr({accountId:zn().length(40),batchID:Uu,signerKey:qu,utilization:nr(),usable:ar(),depth:nr(),amount:zn().transform(e=>BigInt(e)),bucketDepth:nr(),blockNumber:nr(),immutableFlag:ar(),exists:ar(),batchTTL:nr().optional(),createdAt:nr()}),ju=pr({accountName:zn(),defaultPostageStampBatchID:zn().length(64).optional(),createdAt:nr(),lastModified:nr()}),Gu=pr({version:Rr(1),timestamp:nr(),accountId:zn().length(40),metadata:ju,identities:hr(_u),connectedApps:hr(Vu),postageStamps:hr(Lu)}),Ku=pr({beeNodeUrl:zn().url(),gnosisRpcUrl:zn().url()}),Hu=pr({index:nr().int().min(0).max(65535),value:nr().int().min(0)}),Wu=pr({type:Rr("utilization-updated"),batchId:zn().length(64),buckets:hr(Hu)}),Zu="swarm-secret-",Ju="swarm-id-network-settings",Xu="swarm-storage-challenge",Yu=pr({pin:ar().optional(),encrypt:ar().optional(),encryptManifest:ar().optional(),tag:nr().optional(),deferred:ar().optional(),redundancyLevel:nr().min(0).max(4).optional()}),Qu=Yu.optional(),el=Yu.extend({beeCompatible:ar().optional()}).optional(),tl=pr({timeout:nr().optional(),headers:(nl=zn(),rl=zn(),new vr({type:"record",keyType:nl,valueType:rl,...E(il)})).optional(),endlesslyRetry:ar().optional()}).optional();var nl,rl,il;const ol=pr({redundancyStrategy:gr([Rr(0),Rr(1),Rr(2),Rr(3)]).optional(),fallback:ar().optional(),timeoutMs:nr().optional(),actPublisher:gr([Nr(Uint8Array),zn()]),actHistoryAddress:gr([Nr(Uint8Array),zn()]),actTimestamp:gr([nr(),zn()])}).optional(),al=pr({reference:ku,tagUid:nr().optional()});al.extend({encryptionKey:zn(),owner:Bu}),al.extend({encryptionKey:zn().optional(),owner:Bu});const sl=pr({name:zn(),data:Nr(Uint8Array)}),cl=pr({batchID:Tu,utilization:nr(),usable:ar(),label:zn(),depth:nr(),amount:zn(),bucketDepth:nr(),blockNumber:nr(),immutableFlag:ar(),exists:ar(),batchTTL:nr().optional()}),ul=pr({authenticated:ar(),origin:zn().optional()});pr({canUpload:ar(),storagePartitioned:ar().optional(),identity:pr({id:zn(),name:zn(),address:Bu}).optional()});const ll=pr({backgroundColor:zn().optional(),color:zn().optional(),border:zn().optional(),borderRadius:zn().optional(),padding:zn().optional(),fontSize:zn().optional(),fontFamily:zn().optional(),fontWeight:zn().optional(),cursor:zn().optional(),width:zn().optional(),height:zn().optional()}).optional(),dl=pr({name:zn().min(1).max(100),description:zn().max(500).optional(),icon:zn().optional().refine(e=>{if(!e)return!0;if(!e.startsWith("data:image/"))return!1;if(!e.match(/^data:image\/(svg\+xml|png);/))return!1;const t=e.match(/base64,(.+)$/);if(t){if(3*t[1].length/4>4096)return!1}return!0},{message:"Icon must be a data URL with SVG or PNG mime type, max 4KB"})}),hl=pr({connectText:zn().optional(),disconnectText:zn().optional(),loadingText:zn().optional(),backgroundColor:zn().optional(),color:zn().optional(),borderRadius:zn().optional()}).optional(),fl=pr({type:Rr("parentIdentify"),beeApiUrl:zn().url().optional(),popupMode:Er(["popup","window"]).optional(),metadata:dl,buttonConfig:hl}),pl=pr({type:Rr("checkAuth"),requestId:zn()}),ml=pr({type:Rr("disconnect"),requestId:zn()}),gl=pr({type:Rr("requestAuth"),styles:ll}),yl=pr({type:Rr("uploadData"),requestId:zn(),data:Nr(Uint8Array),options:Qu,requestOptions:tl,enableProgress:ar().optional()}),wl=pr({type:Rr("downloadData"),requestId:zn(),reference:ku,options:ol,requestOptions:tl}),bl=pr({type:Rr("uploadFile"),requestId:zn(),data:Nr(Uint8Array),name:zn().optional(),options:Qu,requestOptions:tl}),vl=pr({type:Rr("downloadFile"),requestId:zn(),reference:ku,path:zn().optional(),options:ol,requestOptions:tl}),xl=pr({type:Rr("uploadChunk"),requestId:zn(),data:Nr(Uint8Array),options:Qu,requestOptions:tl}),El=pr({type:Rr("downloadChunk"),requestId:zn(),reference:ku,options:ol,requestOptions:tl}),Al=pr({type:Rr("getConnectionInfo"),requestId:zn()}),Rl=pr({type:Rr("isConnected"),requestId:zn()}),Sl=pr({type:Rr("getNodeInfo"),requestId:zn()}),Il=pr({type:Rr("gsocMine"),requestId:zn(),targetOverlay:zn(),identifier:zn(),proximity:nr().optional()}),kl=pr({type:Rr("gsocSend"),requestId:zn(),signer:zn(),identifier:zn(),data:Nr(Uint8Array),options:Qu,requestOptions:tl}),Tl=pr({type:Rr("socUpload"),requestId:zn(),identifier:Cu,data:Nr(Uint8Array),signer:Ou.optional(),options:Qu,requestOptions:tl}),Bl=pr({type:Rr("socRawUpload"),requestId:zn(),identifier:Cu,data:Nr(Uint8Array),signer:Ou.optional(),options:Qu,requestOptions:tl}),Ol=pr({type:Rr("socDownload"),requestId:zn(),owner:Bu.optional(),identifier:Cu,encryptionKey:Du,requestOptions:tl}),Dl=pr({type:Rr("socRawDownload"),requestId:zn(),owner:Bu.optional(),identifier:Cu,encryptionKey:Du.optional(),requestOptions:tl}),Cl=pr({type:Rr("socGetOwner"),requestId:zn()}),$l=pr({type:Rr("epochFeedDownloadReference"),requestId:zn(),topic:Cu,owner:Bu.optional(),at:zu,after:zu.optional(),encryptionKey:Du.optional(),requestOptions:tl}),zl=pr({lastEpoch:pr({start:zn(),level:nr()}).optional(),lastTimestamp:zn().optional()}).optional(),Fl=pr({type:Rr("epochFeedUploadReference"),requestId:zn(),topic:Cu,signer:Ou.optional(),at:zu,reference:ku,encryptionKey:Du.optional(),hints:zl,requestOptions:tl}),Pl=pr({type:Rr("feedGetOwner"),requestId:zn()}),Ul=pr({type:Rr("seqFeedGetOwner"),requestId:zn()}),ql=pr({type:Rr("seqFeedDownloadPayload"),requestId:zn(),topic:Cu,owner:Bu.optional(),index:Fu.optional(),at:zu.optional(),hasTimestamp:ar().optional(),lookupTimeoutMs:nr().optional(),encryptionKey:Du,requestOptions:tl}),Nl=pr({type:Rr("seqFeedDownloadRawPayload"),requestId:zn(),topic:Cu,owner:Bu.optional(),index:Fu.optional(),at:zu.optional(),hasTimestamp:ar().optional(),lookupTimeoutMs:nr().optional(),encryptionKey:Du.optional(),requestOptions:tl}),Ml=pr({type:Rr("seqFeedDownloadReference"),requestId:zn(),topic:Cu,owner:Bu.optional(),index:Fu.optional(),at:zu.optional(),hasTimestamp:ar().optional(),lookupTimeoutMs:nr().optional(),encryptionKey:Du,requestOptions:tl}),_l=pr({type:Rr("seqFeedUploadPayload"),requestId:zn(),topic:Cu,signer:Ou.optional(),data:Nr(Uint8Array),index:Fu.optional(),at:zu.optional(),hasTimestamp:ar().optional(),lookupTimeoutMs:nr().optional(),options:Qu,requestOptions:tl}),Vl=pr({type:Rr("seqFeedUploadRawPayload"),requestId:zn(),topic:Cu,signer:Ou.optional(),data:Nr(Uint8Array),index:Fu.optional(),at:zu.optional(),hasTimestamp:ar().optional(),lookupTimeoutMs:nr().optional(),encryptionKey:Du.optional(),options:Qu,requestOptions:tl}),Ll=pr({type:Rr("seqFeedUploadReference"),requestId:zn(),topic:Cu,signer:Ou.optional(),reference:ku,index:Fu.optional(),at:zu.optional(),hasTimestamp:ar().optional(),lookupTimeoutMs:nr().optional(),options:Qu,requestOptions:tl}),jl=pr({type:Rr("createFeedManifest"),requestId:zn(),topic:Cu,owner:Bu.optional(),feedType:Er(["Sequence","Epoch"]).optional(),uploadOptions:Qu,requestOptions:tl}),Gl=pr({type:Rr("actUploadData"),requestId:zn(),data:Nr(Uint8Array),grantees:hr(zn()),options:el,requestOptions:tl,enableProgress:ar().optional()}),Kl=pr({type:Rr("actDownloadData"),requestId:zn(),encryptedReference:ku,historyReference:ku,publisherPubKey:zn(),timestamp:nr().optional(),requestOptions:tl}),Hl=pr({type:Rr("actAddGrantees"),requestId:zn(),historyReference:ku,grantees:hr(zn()),requestOptions:tl}),Wl=pr({type:Rr("actRevokeGrantees"),requestId:zn(),historyReference:ku,encryptedReference:ku,revokeGrantees:hr(zn()),requestOptions:tl}),Zl=pr({type:Rr("actGetGrantees"),requestId:zn(),historyReference:ku,requestOptions:tl}),Jl=wr("type",[fl,pl,ml,gl,yl,wl,bl,vl,xl,El,Al,Rl,Sl,Il,kl,Tl,Bl,Ol,Dl,Cl,$l,Fl,Pl,Ul,ql,Nl,Ml,_l,Vl,Ll,jl,Gl,Kl,Hl,Wl,Zl,pr({type:Rr("getPostageBatch"),requestId:zn()}),pr({type:Rr("connect"),requestId:zn(),agent:ar().optional(),popupMode:Er(["popup","window"]).optional()})]),Xl=pr({type:Rr("proxyReady"),authenticated:ar(),parentOrigin:zn()}),Yl=pr({type:Rr("initError"),error:zn()}),Ql=pr({type:Rr("authStatusResponse"),requestId:zn(),authenticated:ar(),origin:zn().optional()}),ed=pr({type:Rr("disconnectResponse"),requestId:zn(),success:ar()}),td=pr({type:Rr("authSuccess"),origin:zn()}),nd=pr({type:Rr("uploadDataResponse"),requestId:zn(),reference:ku,tagUid:nr().optional()}),rd=pr({type:Rr("downloadDataResponse"),requestId:zn(),data:Nr(Uint8Array)}),id=pr({type:Rr("uploadFileResponse"),requestId:zn(),reference:ku,tagUid:nr().optional()}),od=pr({type:Rr("downloadFileResponse"),requestId:zn(),name:zn(),data:Nr(Uint8Array)}),ad=pr({type:Rr("uploadChunkResponse"),requestId:zn(),reference:ku}),sd=pr({type:Rr("downloadChunkResponse"),requestId:zn(),data:Nr(Uint8Array)}),cd=pr({type:Rr("uploadProgress"),requestId:zn(),total:nr(),processed:nr()}),ud=pr({type:Rr("error"),requestId:zn(),error:zn()}),ld=pr({type:Rr("connectionInfoResponse"),requestId:zn(),canUpload:ar(),storagePartitioned:ar().optional(),identity:pr({id:zn(),name:zn(),address:Bu}).optional()}),dd=pr({type:Rr("connectResponse"),requestId:zn(),success:ar()}),hd=pr({type:Rr("isConnectedResponse"),requestId:zn(),connected:ar()}),fd=pr({type:Rr("getNodeInfoResponse"),requestId:zn(),beeMode:zn(),chequebookEnabled:ar(),swapEnabled:ar()}),pd=pr({type:Rr("gsocMineResponse"),requestId:zn(),signer:zn()}),md=pr({type:Rr("gsocSendResponse"),requestId:zn(),reference:ku,tagUid:nr().optional()}),gd=pr({type:Rr("socUploadResponse"),requestId:zn(),reference:ku,tagUid:nr().optional(),encryptionKey:zn(),owner:Bu}),yd=pr({type:Rr("socRawUploadResponse"),requestId:zn(),reference:ku,tagUid:nr().optional(),encryptionKey:zn().optional(),owner:Bu}),wd=pr({type:Rr("socDownloadResponse"),requestId:zn(),data:Nr(Uint8Array),identifier:Cu,signature:$u,span:nr(),payload:Nr(Uint8Array),address:ku,owner:Bu}),bd=pr({type:Rr("socRawDownloadResponse"),requestId:zn(),data:Nr(Uint8Array),identifier:Cu,signature:$u,span:nr(),payload:Nr(Uint8Array),address:ku,owner:Bu}),vd=pr({type:Rr("socGetOwnerResponse"),requestId:zn(),owner:Bu}),xd=pr({type:Rr("epochFeedDownloadReferenceResponse"),requestId:zn(),reference:ku.optional()}),Ed=pr({type:Rr("epochFeedUploadReferenceResponse"),requestId:zn(),socAddress:ku,encryptionKey:Du.optional(),epoch:pr({start:zn(),level:nr()}),timestamp:zn()}),Ad=pr({type:Rr("feedGetOwnerResponse"),requestId:zn(),owner:Bu}),Rd=pr({type:Rr("seqFeedGetOwnerResponse"),requestId:zn(),owner:Bu}),Sd=pr({type:Rr("seqFeedDownloadPayloadResponse"),requestId:zn(),payload:Nr(Uint8Array),timestamp:nr().optional(),feedIndex:zn(),feedIndexNext:zn()}),Id=pr({type:Rr("seqFeedDownloadRawPayloadResponse"),requestId:zn(),payload:Nr(Uint8Array),timestamp:nr().optional(),feedIndex:zn(),feedIndexNext:zn()}),kd=pr({type:Rr("seqFeedDownloadReferenceResponse"),requestId:zn(),reference:ku,feedIndex:zn(),feedIndexNext:zn()}),Td=pr({type:Rr("seqFeedUploadPayloadResponse"),requestId:zn(),reference:ku,feedIndex:zn(),owner:Bu,encryptionKey:zn().optional(),tagUid:nr().optional()}),Bd=pr({type:Rr("seqFeedUploadRawPayloadResponse"),requestId:zn(),reference:ku,feedIndex:zn(),owner:Bu,encryptionKey:zn().optional(),tagUid:nr().optional()}),Od=pr({type:Rr("seqFeedUploadReferenceResponse"),requestId:zn(),reference:ku,feedIndex:zn(),owner:Bu,encryptionKey:zn().optional(),tagUid:nr().optional()}),Dd=pr({type:Rr("createFeedManifestResponse"),requestId:zn(),reference:ku}),Cd=pr({type:Rr("actUploadDataResponse"),requestId:zn(),encryptedReference:ku,historyReference:ku,granteeListReference:ku,publisherPubKey:zn(),actReference:ku,tagUid:nr().optional()}),$d=pr({type:Rr("actDownloadDataResponse"),requestId:zn(),data:Nr(Uint8Array)}),zd=pr({type:Rr("actAddGranteesResponse"),requestId:zn(),historyReference:ku,granteeListReference:ku,actReference:ku}),Fd=pr({type:Rr("actRevokeGranteesResponse"),requestId:zn(),encryptedReference:ku,historyReference:ku,granteeListReference:ku,actReference:ku}),Pd=pr({type:Rr("actGetGranteesResponse"),requestId:zn(),grantees:hr(zn())}),Ud=wr("type",[Xl,Yl,Ql,ed,td,nd,rd,id,od,ad,sd,cd,ud,ld,dd,hd,fd,pd,md,gd,yd,wd,bd,vd,xd,Ed,Ad,Rd,Sd,Id,kd,Td,Bd,Od,Dd,Cd,$d,zd,Fd,Pd,pr({type:Rr("getPostageBatchResponse"),requestId:zn(),postageBatch:cl.optional(),error:zn().optional()})]),qd=pr({secret:zn(),postageBatchId:Tu.optional(),signerKey:Ou.optional(),networkSettings:Ku.optional(),identityId:zn().optional(),identityName:zn().optional(),identityAddress:Bu.optional()}),Nd=pr({type:Rr("setSecret"),appOrigin:zn(),challenge:zn(),data:qd}),Md=wr("type",[Nd]);async function _d(e,t){const n=new TextEncoder,r=Ld(e),i=n.encode(t),o=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await crypto.subtle.sign("HMAC",o,i);return jd(new Uint8Array(a))}async function Vd(){const e=new Uint8Array(32);crypto.getRandomValues(e);return jd(e)}function Ld(e){const t=e.replace(/\s/g,"");if(t.length%2!=0)throw new Error("Invalid hex string: length must be even");const n=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)n[e/2]=parseInt(t.substring(e,e+2),16);return n}function jd(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")}async function Gd(e,t,n){return await _d(e,t)===n}async function Kd(e,t){const n=new TextEncoder,r=Ld(e),i=n.encode(t),o=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),a=await crypto.subtle.sign("HMAC",o,i);return jd(new Uint8Array(a))}async function Hd(e,t){return _d(e,`account:${t}`)}async function Wd(e){return _d(e,"swarm-encryption")}function Zd(e){return new Ri(e)}const Jd={hexToUint8Array:Ld,uint8ArrayToHex:jd};class Xd{constructor(e){this.ready=!1,this.pendingRequests=new Map,this.requestIdCounter=0,this.iframeOrigin=e.iframeOrigin,this.iframePath=e.iframePath||"/proxy",this.timeout=e.timeout??3e4,this.initializationTimeout=e.initializationTimeout??3e4,this.onAuthChange=e.onAuthChange,this.popupMode=e.popupMode||"window",this.metadata=e.metadata,this.buttonConfig=e.buttonConfig,this.containerId=e.containerId;try{dl.parse(this.metadata)}catch(e){throw new Error(`Invalid app metadata: ${e}`)}this.readyPromise=new Promise((e,t)=>{this.readyResolve=e,this.readyReject=t,setTimeout(()=>{t(new Error(`Proxy initialization timeout - proxy did not respond within ${this.initializationTimeout}ms`))},this.initializationTimeout)}),this.proxyInitializedPromise=new Promise((e,t)=>{this.proxyInitializedResolve=e,this.proxyInitializedReject=t,setTimeout(()=>{this.proxyInitializedReject&&this.proxyInitializedReject(new Error(`Proxy initialization timeout - proxy did not signal readiness within ${this.initializationTimeout}ms`))},this.initializationTimeout)}),this.setupMessageListener()}async initialize(){if(this.iframe)throw new Error("SwarmIdClient already initialized");let e;if(this.iframe=document.createElement("iframe"),this.iframe.src=`${this.iframeOrigin}${this.iframePath}`,this.iframe.style.border="none",this.iframe.style.backgroundColor="transparent",this.iframe.style.borderRadius=this.buttonConfig?.borderRadius||"0",this.containerId){if(e=document.getElementById(this.containerId)||void 0,!e)throw new Error(`Container element with ID "${this.containerId}" not found`);this.iframe.style.width="100%",this.iframe.style.height="100%",this.iframe.style.display="block"}else this.iframe.style.display="none",this.iframe.style.position="fixed",this.iframe.style.bottom="20px",this.iframe.style.right="20px",this.iframe.style.width="300px",this.iframe.style.height="50px",this.iframe.style.zIndex="999999";await new Promise((t,n)=>{this.iframe.onload=()=>t(),this.iframe.onerror=()=>n(new Error("Failed to load Swarm ID iframe")),e?e.appendChild(this.iframe):document.body.appendChild(this.iframe)}),await this.proxyInitializedPromise,this.sendMessage({type:"parentIdentify",popupMode:this.popupMode,metadata:this.metadata,buttonConfig:this.buttonConfig}),await this.readyPromise}setupMessageListener(){this.messageListener=e=>{if("proxyInitialized"===e.data?.type)return void(this.iframe&&e.source===this.iframe.contentWindow?this.proxyInitializedResolve&&(this.proxyInitializedResolve(),this.proxyInitializedResolve=void 0):console.warn("[SwarmIdClient] Rejected proxyInitialized from unknown source"));const t=new URL(this.iframeOrigin).origin;if(e.origin!==t)return void console.warn("[SwarmIdClient] Rejected message from unauthorized origin:",e.origin);let n;try{n=Ud.parse(e.data)}catch(t){return void console.warn("[SwarmIdClient] Invalid message format:",e.data,t)}this.handleIframeMessage(n)},window.addEventListener("message",this.messageListener)}handleIframeMessage(e){switch(e.type){case"proxyReady":this.ready=!0,this.readyResolve&&this.readyResolve(),this.iframe&&(this.iframe.style.display="block"),this.onAuthChange&&this.onAuthChange(e.authenticated);break;case"authStatusResponse":if(this.iframe&&(this.iframe.style.display="block"),this.onAuthChange&&this.onAuthChange(e.authenticated),"requestId"in e){const t=this.pendingRequests.get(e.requestId);t&&(clearTimeout(t.timeoutId),this.pendingRequests.delete(e.requestId),t.resolve(e))}break;case"authSuccess":this.iframe&&(this.iframe.style.display="block"),this.onAuthChange&&this.onAuthChange(!0);break;case"initError":console.error("[SwarmIdClient] Proxy initialization error:",e.error),this.readyReject&&this.readyReject(new Error(e.error));break;case"disconnectResponse":if(this.onAuthChange&&this.onAuthChange(!1),"requestId"in e){const t=this.pendingRequests.get(e.requestId);t&&(clearTimeout(t.timeoutId),this.pendingRequests.delete(e.requestId),t.resolve(e))}break;case"error":{const t=this.pendingRequests.get(e.requestId);t&&(clearTimeout(t.timeoutId),this.pendingRequests.delete(e.requestId),t.reject(new Error(e.error)));break}default:if("requestId"in e){const t=this.pendingRequests.get(e.requestId);t&&(clearTimeout(t.timeoutId),this.pendingRequests.delete(e.requestId),t.resolve(e))}}}sendMessage(e){if(!this.iframe||!this.iframe.contentWindow)throw new Error("Iframe not initialized");try{Jl.parse(e)}catch(e){throw new Error(`Invalid message format: ${e}`)}this.iframe.contentWindow.postMessage(e,this.iframeOrigin)}async sendRequest(e){return new Promise((t,n)=>{const r=setTimeout(()=>{this.pendingRequests.delete(e.requestId),n(new Error(`Request timeout after ${this.timeout}ms`))},this.timeout);this.pendingRequests.set(e.requestId,{resolve:t,reject:n,timeoutId:r}),this.sendMessage(e)})}generateRequestId(){return`req-${++this.requestIdCounter}-${Date.now()}`}normalizeSocIdentifier(e){return e instanceof ki?e.toHex():e instanceof Uint8Array?jd(e):e}normalizeSocKey(e){return e instanceof Uint8Array?jd(e):e}normalizeFeedTopic(e){return e instanceof zi?jd(e.toUint8Array()):e instanceof ki?e.toHex():e instanceof Uint8Array?jd(e):e}normalizeReference(e){return e instanceof Uint8Array?jd(e):e}normalizeFeedTimestamp(e){return"bigint"==typeof e?e.toString():"number"==typeof e?BigInt(Math.floor(e)).toString():e}normalizeFeedIndex(e){return"bigint"==typeof e?e.toString():"number"==typeof e?BigInt(Math.floor(e)).toString():e}normalizePayload(e){return e instanceof Uint8Array?e:(new TextEncoder).encode(e)}socChunkFromResponse(e){return{data:e.data,identifier:e.identifier,signature:e.signature,span:e.span,payload:e.payload,address:e.address,owner:e.owner}}ensureReady(){if(!this.ready)throw new Error("SwarmIdClient not initialized. Call initialize() first.")}getAuthIframe(){if(this.ensureReady(),!this.iframe)throw new Error("Iframe not initialized");return this.iframe}async checkAuthStatus(){this.ensureReady();const e=this.generateRequestId(),t=await this.sendRequest({type:"checkAuth",requestId:e});return{authenticated:t.authenticated,origin:t.origin}}async getPostageBatch(){this.ensureReady();const e=this.generateRequestId(),t=await this.sendRequest({type:"getPostageBatch",requestId:e});if(t.error)throw new Error(t.error);return t.postageBatch}async disconnect(){this.ensureReady();const e=this.generateRequestId();if(!(await this.sendRequest({type:"disconnect",requestId:e})).success)throw new Error("Failed to disconnect");this.onAuthChange&&this.onAuthChange(!1)}async connect(e={}){this.ensureReady();const t=this.generateRequestId();if(!(await this.sendRequest({type:"connect",requestId:t,agent:e.agent,popupMode:e.popupMode})).success)throw new Error("Failed to open authentication popup")}async getConnectionInfo(){this.ensureReady();const e=this.generateRequestId(),t=await this.sendRequest({type:"getConnectionInfo",requestId:e});return{canUpload:t.canUpload,storagePartitioned:t.storagePartitioned,identity:t.identity}}async isBeeConnected(){try{this.ensureReady();const e=this.generateRequestId();return(await this.sendRequest({type:"isConnected",requestId:e})).connected}catch{return!1}}async getNodeInfo(){this.ensureReady();const e=this.generateRequestId(),t=await this.sendRequest({type:"getNodeInfo",requestId:e});return{beeMode:t.beeMode,chequebookEnabled:t.chequebookEnabled,swapEnabled:t.swapEnabled}}async uploadData(e,t,n){this.ensureReady();const r=this.generateRequestId(),{onProgress:i,...o}=t??{};let a;i&&(a=e=>{if(e.origin===new URL(this.iframeOrigin).origin)try{const t=Ud.parse(e.data);"uploadProgress"===t.type&&t.requestId===r&&i({total:t.total,processed:t.processed})}catch{}},window.addEventListener("message",a));try{const t=await this.sendRequest({type:"uploadData",requestId:r,data:new Uint8Array(e),options:o,requestOptions:n,enableProgress:!!i});return{reference:t.reference,tagUid:t.tagUid}}finally{a&&window.removeEventListener("message",a)}}async downloadData(e,t,n){this.ensureReady();const r=this.generateRequestId();return(await this.sendRequest({type:"downloadData",requestId:r,reference:e,options:t,requestOptions:n})).data}async uploadFile(e,t,n,r){this.ensureReady();const i=this.generateRequestId(),{onProgress:o,...a}=n??{};let s,c=t;if(e instanceof File){const t=await e.arrayBuffer();s=new Uint8Array(t),c=c||e.name}else s=new Uint8Array(e.buffer.slice(0),e.byteOffset,e.byteLength);const u=await this.sendRequest({type:"uploadFile",requestId:i,data:s,name:c,options:a,requestOptions:r});return{reference:u.reference,tagUid:u.tagUid}}async downloadFile(e,t,n,r){this.ensureReady();const i=this.generateRequestId(),o=await this.sendRequest({type:"downloadFile",requestId:i,reference:e,path:t,options:n,requestOptions:r});return{name:o.name,data:new Uint8Array(o.data)}}async uploadChunk(e,t,n){this.ensureReady();const r=this.generateRequestId(),{onProgress:i,...o}=t??{};return{reference:(await this.sendRequest({type:"uploadChunk",requestId:r,data:e,options:o,requestOptions:n})).reference}}async downloadChunk(e,t,n){this.ensureReady();const r=this.generateRequestId(),i=await this.sendRequest({type:"downloadChunk",requestId:r,reference:e,options:t,requestOptions:n});return new Uint8Array(i.data)}makeSOCReader(e,t){this.ensureReady();const n=new Ii(e).toHex(),r=async(e,r)=>{const i=this.generateRequestId(),o=await this.sendRequest({type:"socDownload",requestId:i,owner:n,identifier:this.normalizeSocIdentifier(e),encryptionKey:this.normalizeSocKey(r),requestOptions:t});return this.socChunkFromResponse(o)},i=async(e,r)=>{const i=this.generateRequestId(),o=await this.sendRequest({type:"socRawDownload",requestId:i,owner:n,identifier:this.normalizeSocIdentifier(e),encryptionKey:r?this.normalizeSocKey(r):void 0,requestOptions:t});return this.socChunkFromResponse(o)};return{getOwner:async()=>n,rawDownload:(e,t)=>i(e,t),download:(e,t)=>r(e,t)}}makeSOCWriter(e,t){this.ensureReady();const n=e?new Ri(e):void 0,r=n?n.toHex():void 0;let i=n?n.publicKey().address().toHex():void 0;const o=async(e,n)=>{const r=this.generateRequestId(),o=await this.sendRequest({type:"socDownload",requestId:r,owner:i,identifier:this.normalizeSocIdentifier(e),encryptionKey:this.normalizeSocKey(n),requestOptions:t});return this.socChunkFromResponse(o)},a=async(e,n)=>{const r=this.generateRequestId(),o=await this.sendRequest({type:"socRawDownload",requestId:r,owner:i,identifier:this.normalizeSocIdentifier(e),encryptionKey:n?this.normalizeSocKey(n):void 0,requestOptions:t});return this.socChunkFromResponse(o)},s=async(e,n,o)=>{const a=this.generateRequestId(),s=await this.sendRequest({type:"socUpload",requestId:a,identifier:this.normalizeSocIdentifier(e),data:new Uint8Array(n),signer:r,options:o,requestOptions:t});return i=s.owner,{reference:s.reference,tagUid:s.tagUid,encryptionKey:s.encryptionKey,owner:s.owner}},c=async(e,n,o)=>{const a=this.generateRequestId(),s=await this.sendRequest({type:"socRawUpload",requestId:a,identifier:this.normalizeSocIdentifier(e),data:new Uint8Array(n),signer:r,options:o,requestOptions:t});return i=s.owner,{reference:s.reference,tagUid:s.tagUid,encryptionKey:s.encryptionKey,owner:s.owner}};return{getOwner:async()=>{if(i)return i;const e=this.generateRequestId(),t=await this.sendRequest({type:"socGetOwner",requestId:e});return i=t.owner,i},rawDownload:(e,t)=>a(e,t),download:(e,t)=>o(e,t),upload:(e,t,n)=>s(e,t,n),rawUpload:(e,t,n)=>c(e,t,n)}}makeEpochFeedReader(e,t){this.ensureReady();const n=this.normalizeFeedTopic(e.topic);let r=e.owner?new Ii(e.owner).toHex():void 0;const i=async e=>{const i=void 0!==e?.at?e.at:BigInt(Math.floor(Date.now()/1e3)),o=this.generateRequestId(),a=(await this.sendRequest({type:"epochFeedDownloadReference",requestId:o,topic:n,owner:r,at:this.normalizeFeedTimestamp(i),after:void 0!==e?.after?this.normalizeFeedTimestamp(e.after):void 0,encryptionKey:void 0!==e?.encryptionKey?this.normalizeSocKey(e.encryptionKey):void 0,requestOptions:t})).reference,s=a&&a.startsWith("0x")?a.slice(2):a;return{reference:a,encryptionKey:s&&128===s.length?s.slice(64):void 0}},o=async e=>{const i=void 0!==e?.at?e.at:BigInt(Math.floor(Date.now()/1e3)),o=this.generateRequestId();return{reference:(await this.sendRequest({type:"epochFeedDownloadReference",requestId:o,topic:n,owner:r,at:this.normalizeFeedTimestamp(i),after:void 0!==e?.after?this.normalizeFeedTimestamp(e.after):void 0,encryptionKey:void 0,requestOptions:t})).reference,encryptionKey:void 0}};return{getOwner:async()=>{if(r)return r;const e=this.generateRequestId(),t=await this.sendRequest({type:"feedGetOwner",requestId:e});return r=t.owner,r},downloadReference:i,downloadPayload:async e=>{const n=await i(e);if(!n.reference)return{reference:void 0,payload:void 0,encryptionKey:void 0};const r=await this.downloadData(n.reference,void 0,t);return{reference:n.reference,payload:r,encryptionKey:n.encryptionKey}},downloadRawReference:o,downloadRawPayload:async e=>{const n=await o(e);if(!n.reference)return{reference:void 0,payload:void 0,encryptionKey:void 0};const r=await this.downloadData(n.reference,void 0,t);return{reference:n.reference,payload:r,encryptionKey:void 0}}}}makeEpochFeedWriter(e,t){this.ensureReady();const n=this.normalizeFeedTopic(e.topic),r=e.signer?new Ri(e.signer):void 0,i=r?r.toHex():void 0;let o=r?r.publicKey().address().toHex():void 0;const a=async e=>{const r=void 0!==e?.at?e.at:BigInt(Math.floor(Date.now()/1e3)),i=this.generateRequestId(),a=(await this.sendRequest({type:"epochFeedDownloadReference",requestId:i,topic:n,owner:o,at:this.normalizeFeedTimestamp(r),after:void 0!==e?.after?this.normalizeFeedTimestamp(e.after):void 0,encryptionKey:void 0!==e?.encryptionKey?this.normalizeSocKey(e.encryptionKey):void 0,requestOptions:t})).reference,s=a&&a.startsWith("0x")?a.slice(2):a;return{reference:a,encryptionKey:s&&128===s.length?s.slice(64):void 0}},s=async e=>{const r=void 0!==e?.at?e.at:BigInt(Math.floor(Date.now()/1e3)),i=this.generateRequestId();return{reference:(await this.sendRequest({type:"epochFeedDownloadReference",requestId:i,topic:n,owner:o,at:this.normalizeFeedTimestamp(r),after:void 0!==e?.after?this.normalizeFeedTimestamp(e.after):void 0,encryptionKey:void 0,requestOptions:t})).reference,encryptionKey:void 0}};return{getOwner:async()=>{if(o)return o;const e=this.generateRequestId(),t=await this.sendRequest({type:"feedGetOwner",requestId:e});return o=t.owner,o},downloadReference:a,downloadPayload:async e=>{const n=await a(e);if(!n.reference)return{reference:void 0,payload:void 0,encryptionKey:void 0};const r=await this.downloadData(n.reference,void 0,t);return{reference:n.reference,payload:r,encryptionKey:n.encryptionKey}},downloadRawReference:s,downloadRawPayload:async e=>{const n=await s(e);if(!n.reference)return{reference:void 0,payload:void 0,encryptionKey:void 0};const r=await this.downloadData(n.reference,void 0,t);return{reference:n.reference,payload:r,encryptionKey:void 0}},uploadReference:async(e,r)=>{const o=void 0!==r?.at?r.at:BigInt(Math.floor(Date.now()/1e3)),a=this.normalizeReference(e),s=a.startsWith("0x")?a.slice(2):a,c=128===s.length?s.slice(64):void 0,u=r?.encryptionKey??c,l=this.generateRequestId(),d=await this.sendRequest({type:"epochFeedUploadReference",requestId:l,topic:n,signer:i,at:this.normalizeFeedTimestamp(o),reference:a,encryptionKey:void 0!==u?this.normalizeSocKey(u):void 0,hints:r?.hints,requestOptions:t});return{socAddress:d.socAddress,reference:a,encryptionKey:c,epoch:d.epoch,timestamp:d.timestamp}},uploadPayload:async(e,r)=>{const o=void 0!==r?.at?r.at:BigInt(Math.floor(Date.now()/1e3)),a=!1!==r?.encrypt,s=await this.uploadData(this.normalizePayload(e),{...r?.uploadOptions,encrypt:a},t),c=s.reference.startsWith("0x")?s.reference.slice(2):s.reference,u=128===c.length?c.slice(64):void 0,l=r?.encryptionKey??u,d=this.generateRequestId(),h=await this.sendRequest({type:"epochFeedUploadReference",requestId:d,topic:n,signer:i,at:this.normalizeFeedTimestamp(o),reference:s.reference,encryptionKey:void 0!==l?this.normalizeSocKey(l):void 0,hints:r?.hints,requestOptions:t}),f=u;return{socAddress:h.socAddress,reference:s.reference,encryptionKey:f,epoch:h.epoch,timestamp:h.timestamp}},uploadRawReference:async(e,r)=>{const o=void 0!==r?.at?r.at:BigInt(Math.floor(Date.now()/1e3)),a=this.normalizeReference(e),s=this.generateRequestId(),c=await this.sendRequest({type:"epochFeedUploadReference",requestId:s,topic:n,signer:i,at:this.normalizeFeedTimestamp(o),reference:a,encryptionKey:void 0,hints:r?.hints,requestOptions:t});return{socAddress:c.socAddress,reference:a,encryptionKey:void 0,epoch:c.epoch,timestamp:c.timestamp}},uploadRawPayload:async(e,r)=>{const o=void 0!==r?.at?r.at:BigInt(Math.floor(Date.now()/1e3)),a=await this.uploadData(this.normalizePayload(e),{...r?.uploadOptions,encrypt:!1},t),s=this.generateRequestId(),c=await this.sendRequest({type:"epochFeedUploadReference",requestId:s,topic:n,signer:i,at:this.normalizeFeedTimestamp(o),reference:a.reference,encryptionKey:void 0,hints:r?.hints,requestOptions:t});return{socAddress:c.socAddress,reference:a.reference,encryptionKey:void 0,epoch:c.epoch,timestamp:c.timestamp}}}}makeSequentialFeedReader(e,t){this.ensureReady();const n=this.normalizeFeedTopic(e.topic);let r=e.owner?new Ii(e.owner).toHex():void 0;return{getOwner:async()=>{if(r)return r;const e=this.generateRequestId(),t=await this.sendRequest({type:"seqFeedGetOwner",requestId:e});return r=t.owner,r},downloadPayload:async(e,i)=>{const o=this.generateRequestId(),a=await this.sendRequest({type:"seqFeedDownloadPayload",requestId:o,topic:n,owner:r,index:void 0!==i?.index?this.normalizeFeedIndex(i.index):void 0,at:void 0!==i?.at?this.normalizeFeedTimestamp(i.at):void 0,hasTimestamp:i?.hasTimestamp,lookupTimeoutMs:i?.lookupTimeoutMs,encryptionKey:this.normalizeSocKey(e),requestOptions:t});return{payload:a.payload,timestamp:a.timestamp,feedIndex:a.feedIndex,feedIndexNext:a.feedIndexNext}},downloadRawPayload:async e=>{const i=this.generateRequestId(),o=await this.sendRequest({type:"seqFeedDownloadRawPayload",requestId:i,topic:n,owner:r,index:void 0!==e?.index?this.normalizeFeedIndex(e.index):void 0,at:void 0!==e?.at?this.normalizeFeedTimestamp(e.at):void 0,hasTimestamp:e?.hasTimestamp,lookupTimeoutMs:e?.lookupTimeoutMs,encryptionKey:e?.encryptionKey?this.normalizeSocKey(e.encryptionKey):void 0,requestOptions:t});return{payload:o.payload,timestamp:o.timestamp,feedIndex:o.feedIndex,feedIndexNext:o.feedIndexNext}},downloadReference:async(e,i)=>{const o=this.generateRequestId(),a=await this.sendRequest({type:"seqFeedDownloadReference",requestId:o,topic:n,owner:r,index:void 0!==i?.index?this.normalizeFeedIndex(i.index):void 0,at:void 0!==i?.at?this.normalizeFeedTimestamp(i.at):void 0,hasTimestamp:i?.hasTimestamp,lookupTimeoutMs:i?.lookupTimeoutMs,encryptionKey:this.normalizeSocKey(e),requestOptions:t});return{reference:a.reference,feedIndex:a.feedIndex,feedIndexNext:a.feedIndexNext}}}}makeSequentialFeedWriter(e,t){this.ensureReady();const n=this.normalizeFeedTopic(e.topic),r=e.signer?new Ri(e.signer):void 0,i=r?r.toHex():void 0;let o=r?r.publicKey().address().toHex():void 0;return{getOwner:async()=>{if(o)return o;const e=this.generateRequestId(),t=await this.sendRequest({type:"seqFeedGetOwner",requestId:e});return o=t.owner,o},downloadPayload:async(e,r)=>{const i=this.generateRequestId(),a=await this.sendRequest({type:"seqFeedDownloadPayload",requestId:i,topic:n,owner:o,index:void 0!==r?.index?this.normalizeFeedIndex(r.index):void 0,at:void 0!==r?.at?this.normalizeFeedTimestamp(r.at):void 0,hasTimestamp:r?.hasTimestamp,encryptionKey:this.normalizeSocKey(e),requestOptions:t});return{payload:a.payload,timestamp:a.timestamp,feedIndex:a.feedIndex,feedIndexNext:a.feedIndexNext}},downloadRawPayload:async e=>{const r=this.generateRequestId(),i=await this.sendRequest({type:"seqFeedDownloadRawPayload",requestId:r,topic:n,owner:o,index:void 0!==e?.index?this.normalizeFeedIndex(e.index):void 0,at:void 0!==e?.at?this.normalizeFeedTimestamp(e.at):void 0,hasTimestamp:e?.hasTimestamp,encryptionKey:e?.encryptionKey?this.normalizeSocKey(e.encryptionKey):void 0,requestOptions:t});return{payload:i.payload,timestamp:i.timestamp,feedIndex:i.feedIndex,feedIndexNext:i.feedIndexNext}},downloadReference:async(e,r)=>{const i=this.generateRequestId(),a=await this.sendRequest({type:"seqFeedDownloadReference",requestId:i,topic:n,owner:o,index:void 0!==r?.index?this.normalizeFeedIndex(r.index):void 0,at:void 0!==r?.at?this.normalizeFeedTimestamp(r.at):void 0,hasTimestamp:r?.hasTimestamp,encryptionKey:this.normalizeSocKey(e),requestOptions:t});return{reference:a.reference,feedIndex:a.feedIndex,feedIndexNext:a.feedIndexNext}},uploadPayload:async(e,r)=>{const a=this.generateRequestId(),s=await this.sendRequest({type:"seqFeedUploadPayload",requestId:a,topic:n,signer:i,data:this.normalizePayload(e),index:void 0!==r?.index?this.normalizeFeedIndex(r.index):void 0,at:void 0!==r?.at?this.normalizeFeedTimestamp(r.at):void 0,hasTimestamp:r?.hasTimestamp,lookupTimeoutMs:r?.lookupTimeoutMs,options:r,requestOptions:t});return o=s.owner,{reference:s.reference,feedIndex:s.feedIndex,owner:s.owner,encryptionKey:s.encryptionKey,tagUid:s.tagUid}},uploadRawPayload:async(e,r)=>{const a=this.generateRequestId(),s=await this.sendRequest({type:"seqFeedUploadRawPayload",requestId:a,topic:n,signer:i,data:this.normalizePayload(e),index:void 0!==r?.index?this.normalizeFeedIndex(r.index):void 0,at:void 0!==r?.at?this.normalizeFeedTimestamp(r.at):void 0,hasTimestamp:r?.hasTimestamp,lookupTimeoutMs:r?.lookupTimeoutMs,encryptionKey:r?.encryptionKey?this.normalizeSocKey(r.encryptionKey):void 0,options:r,requestOptions:t});return o=s.owner,{reference:s.reference,feedIndex:s.feedIndex,owner:s.owner,encryptionKey:s.encryptionKey,tagUid:s.tagUid}},uploadReference:async(e,r)=>{const a=this.generateRequestId(),s=await this.sendRequest({type:"seqFeedUploadReference",requestId:a,topic:n,signer:i,reference:this.normalizeReference(e),index:void 0!==r?.index?this.normalizeFeedIndex(r.index):void 0,at:void 0!==r?.at?this.normalizeFeedTimestamp(r.at):void 0,hasTimestamp:r?.hasTimestamp,lookupTimeoutMs:r?.lookupTimeoutMs,options:r,requestOptions:t});return o=s.owner,{reference:s.reference,feedIndex:s.feedIndex,owner:s.owner,encryptionKey:s.encryptionKey,tagUid:s.tagUid}}}}async createFeedManifest(e,t,n){this.ensureReady();const r=this.normalizeFeedTopic(e),i=this.generateRequestId();return(await this.sendRequest({type:"createFeedManifest",requestId:i,topic:r,owner:t?.owner,feedType:t?.feedType,uploadOptions:t?.uploadOptions,requestOptions:n})).reference}async gsocMine(e,t,n){this.ensureReady();const r=this.generateRequestId();return(await this.sendRequest({type:"gsocMine",requestId:r,targetOverlay:e,identifier:t,proximity:n})).signer}async gsocSend(e,t,n,r,i){this.ensureReady();const o=this.generateRequestId(),a=await this.sendRequest({type:"gsocSend",requestId:o,signer:e,identifier:t,data:new Uint8Array(n),options:r,requestOptions:i});return{reference:a.reference,tagUid:a.tagUid}}async actUploadData(e,t,n,r){this.ensureReady();const i=this.generateRequestId(),{onProgress:o,...a}=n??{};let s;o&&(s=e=>{if(e.origin===new URL(this.iframeOrigin).origin)try{const t=Ud.parse(e.data);"uploadProgress"===t.type&&t.requestId===i&&o({total:t.total,processed:t.processed})}catch{}},window.addEventListener("message",s));try{const n=await this.sendRequest({type:"actUploadData",requestId:i,data:new Uint8Array(e),grantees:t,options:a,requestOptions:r,enableProgress:!!o});return{encryptedReference:n.encryptedReference,historyReference:n.historyReference,granteeListReference:n.granteeListReference,publisherPubKey:n.publisherPubKey,actReference:n.actReference,tagUid:n.tagUid}}finally{s&&window.removeEventListener("message",s)}}async actDownloadData(e,t,n,r,i){this.ensureReady();const o=this.generateRequestId();return(await this.sendRequest({type:"actDownloadData",requestId:o,encryptedReference:e,historyReference:t,publisherPubKey:n,timestamp:r,requestOptions:i})).data}async actAddGrantees(e,t,n){this.ensureReady();const r=this.generateRequestId(),i=await this.sendRequest({type:"actAddGrantees",requestId:r,historyReference:e,grantees:t,requestOptions:n});return{historyReference:i.historyReference,granteeListReference:i.granteeListReference,actReference:i.actReference}}async actRevokeGrantees(e,t,n,r){this.ensureReady();const i=this.generateRequestId(),o=await this.sendRequest({type:"actRevokeGrantees",requestId:i,historyReference:e,encryptedReference:t,revokeGrantees:n,requestOptions:r});return{encryptedReference:o.encryptedReference,historyReference:o.historyReference,granteeListReference:o.granteeListReference,actReference:o.actReference}}async actGetGrantees(e,t){this.ensureReady();const n=this.generateRequestId();return(await this.sendRequest({type:"actGetGrantees",requestId:n,historyReference:e,requestOptions:t})).grantees}destroy(){this.pendingRequests.forEach(e=>{clearTimeout(e.timeoutId),e.reject(new Error("Client destroyed"))}),this.pendingRequests.clear(),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=void 0),this.iframe&&this.iframe.parentNode&&(this.iframe.parentNode.removeChild(this.iframe),this.iframe=void 0),this.ready=!1}}const Yd=4096,Qd=32;var eh,th={};var nh=(eh||(eh=1,function(e){var t;async function n(e){return new Promise((t,n)=>e.then(n,t))}async function r(e){return new Promise(t=>setTimeout(()=>{t(!0)},e))}function i(e,t=Math.random){for(let n=e.length-1;n>0;n--){const r=Math.floor(t()*(n+1)),i=e[n];e[n]=e[r],e[r]=i}return e}function o(e,t,n=Math.random){return i(j(0,e.length-1),n).slice(0,t)}function a(e,t,n=Math.random){return Math.floor(n()*(t-e+1))+e}function s(e,t,n){return t>=e.x&&t<e.x+e.width&&n>=e.y&&n<e.y+e.height}function c(e,t=Math.random){return t()<e}function u(e,t=Math.random){return e[Math.floor(e.length*t())]}function l(e){if(!e.length)throw Error("Received empty array");return e[e.length-1]}function d(e,t,n){return n(t.reduce((e,t)=>t(e),e))}function h(e,t){if(null==e)return null;const n=t.split(".");let r=e;for(const e of n){if(null===r[e]||void 0===r[e])return null;r=r[e]}return r}function f(e,t,n){const r=t.split(/\.|\[/);let i=e;for(let e=0;e<r.length;e++){const t=r[e],o=e<r.length-1&&r[e+1].includes("]"),a=t.includes("]")?t.replace(/\[|\]/g,""):t;if(e===r.length-1)return i[a]=n,n;m(i[a])||(i[a]=o?[]:{}),i=i[a]}return n}function p(e,t){return Math.round(e/t)*t}function m(e,t=!0){return!(!e||t&&!w(e._readableState)||t&&e.constructor&&(e.constructor.isBuffer||"Uint8Array"==e.constructor.name||"ArrayBuffer"===e.constructor.name||"ReadableStream"===e.constructor.name))&&"object"==typeof e}function g(e){return m(e)&&!Array.isArray(e)}function y(e){return Array.isArray(e)&&0===e.length}function w(e){return void 0===e}function b(e){return"[object Function]"===Object.prototype.toString.call(e)||"[object AsyncFunction]"===Object.prototype.toString.call(e)}function v(e){return"[object String]"===Object.prototype.toString.call(e)}function x(e){return"number"==typeof e&&isFinite(e)}function E(e){return!0===e||!1===e}function A(e){return"[object Date]"===Object.prototype.toString.call(e)}function R(e){return!v(e)||0===e.trim().length}function S(e){return x(e)&&Number.isInteger(e)&&e>=1}function I(e){return v(e)&&null!==e.match(/^-?\d+$/)}function k(e){return v(e)&&null!==e.match(/^(0x)?[0-9a-f]+$/i)}Object.defineProperty(e,"__esModule",{value:!0}),e.Vector=e.Cache=e.Assertions=e.Strings=e.Types=e.Objects=e.Dates=e.Promises=e.Numbers=e.System=e.Arrays=e.Random=e.Elliptic=e.Binary=e.RollingValueProvider=e.TrieRouter=e.AsyncQueue=e.PubSubChannel=e.FixedPointNumber=e.MerkleTree=e.Chunk=e.Uint8ArrayWriter=e.Uint8ArrayReader=e.AsyncLazy=e.Lazy=e.Optional=void 0;const T="!@#$%^&*()_+-=[]{}|;:<>?,./".split(""),B="abcdefghijklmnopqrstuvwxyz",O=B+"ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890",D=O+"!@#$%^&*()_+-=[]{}|;:<>?,./",C=["—","\\","東","京","都","𝖆","𝖇","𝖈","👾","🙇","💁","🙅","ᚠ","ᛇ","ᚻ","ᛦ"],$="0123456789abcdef";function z(e,t){if(R(e))throw new TypeError(`Expected string${t?.name?` for ${t.name}`:""}, got: `+e);if(t&&(void 0!==t.min&&e.length<t.min||void 0!==t.max&&e.length>t.max))throw RangeError(`Expected string${t?.name?` for ${t.name}`:""} length in range: ${t.min??"-inf"}..${t.max??"inf"}; got: ${e.length}`);return e}function F(e,t){if(void 0!==t.min&&e<t.min||void 0!==t.max&&e>t.max)throw RangeError(`Expected value${t?.name?` for ${t.name}`:""} in range: ${t.min??"-inf"}..${t.max??"inf"}; got: ${e}`)}function P(e,t){if(x(e))return t&&F(e,t),e;if(!v(e)||!e.match(/^-?\d+(\.\d+)?$/))throw new TypeError(`Expected number${t?.name?` for ${t.name}`:""}, got: `+e);const n=parseFloat(e);return t&&F(n,t),n}function U(e,t){return Math.trunc(P(e,t))}function q(e,t){if(!g(e))throw new TypeError(`Expected object${t?.name?` for ${t.name}`:""}, got: `+e);return e}function N(e){return v(e)&&null!==e.match(/^https?:\/\/.+/)}function M(e,t){for(const[n,r]of Object.entries(t))if(!r(e[n]))throw TypeError(`${n} in value does not exist or match shape`);for(const n of Object.keys(e))if(!t[n])throw TypeError(`${n} exists in value but not in shape`);return!0}function _(e,t){if(g(e)&&g(t))for(const n in t)g(t[n])?(e[n]||(e[n]={}),_(e[n],t[n])):Array.isArray(t[n])?e[n]=[...t[n]]:(null!==t[n]&&void 0!==t[n]||null===e[n]||void 0===e[n])&&(e[n]=t[n]);return e}function V(e,t){const n={};for(const r of e)for(const e of Object.keys(r))n[e]?n[e]=t(n[e],r[e]):n[e]=r[e];return n}function L(e,t){Array.prototype.push.apply(e,t)}function j(e,t){const n=[];for(let r=e;r<=t;r++)n.push(r);return n}function G(e,t=()=>!1){return e.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").split("").map(e=>/[a-z0-9]/.test(e)||t(e)?e:"-").join("").replace(/-+/g,"-").replace(/^-|-$/g,"")}function K(e,t){if(0===t.length)return 0;const n=e.toLowerCase(),r=t.toLowerCase();return e===t?1e4:n.startsWith(r)?1e4-e.length:n.includes(r)?5e3-e.length:new RegExp(".*"+r.split("").join(".*")+".*").test(n)?1e3-e.length:0}const H={"&":"&",""":'"',"'":"'",">":">","<":"<"};function W(e,t){const n=e.indexOf(t);return-1===n?null:e.slice(0,n)}function Z(e,t){const n=e.indexOf(t);return-1===n?null:e.slice(n+t.length)}function J(e,t){const n=e.lastIndexOf(t);return-1===n?null:e.slice(0,n)}function X(e,t){const n=e.lastIndexOf(t);return-1===n?null:e.slice(n+t.length)}function Y(e,t,n=!1){const r=n?e.lastIndexOf(t):e.indexOf(t);return-1===r?n?[null,e]:[e,null]:[e.slice(0,r),e.slice(r+t.length)]}function Q(e,t){let n=[e];for(const e of t)n=n.flatMap(t=>t.split(e));return n.filter(e=>e)}function ee(e){const t=l(e.split(/\\|\//g)),n=t.lastIndexOf(".",t.length-1);return n<=0?"":t.slice(n+1)}function te(e){const t=l(e.split(/\\|\//g)),n=t.lastIndexOf(".",t.length-1);return n<=0?t:t.slice(0,n)}function ne(e){return e.split("\n").map(e=>e.trim().replace(/\s+/g," ")).filter(e=>e.length>0).join("\n")}function re(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ie(e){return e.charAt(0).toLowerCase()+e.slice(1)}function oe(e){if(!e)return!1;const t=e.charCodeAt(0);return t>=65&&t<=90||t>=97&&t<=122}function ae(e){if(!e)return!1;const t=e.charCodeAt(0);return t>=48&&t<=57}function se(e){return oe(e)||ae(e)}const ce=" \n\t\r.,?!:;\"'`(){}[]~@#$%^&*-+=|<>/\\".split("");function ue(e){return ce.includes(e)}function le(e,t,n=0){const r=t.exec(e.slice(n));return r?{index:r.index,match:r[0]}:null}function de(e,t,n=!0){if(!n)return t.every(t=>t instanceof RegExp?t.test(e):-1!==e.indexOf(t,0));let r=0;for(const n of t)if(n instanceof RegExp){const t=le(e,n,r);if(!t)return!1;r=t.index+t.match.length}else{const t=e.indexOf(n,r);if(-1===t)return!1;r=t+n.length}return!0}function he(e,t,n=0){const r=[];let i=e.indexOf(t,n);for(;-1!==i;)r.push(i),i=e.indexOf(t,i+t.length);return r}function fe(e,t,n=0){let r=-1;for(const i of t){const t=e.indexOf(i,n);-1!==t&&(-1===r||t<r)&&(r=t)}return r}function pe(e,t=0){for(let n=t;n<e.length;n++)if(ue(e[n]))return n;return-1}function me(e,t=0){for(let n=t;n<e.length;n++)if("#"===e[n]&&se(e[n+1]))return n;return-1}function ge(e,t,n=0){return e.slice(0,n).lastIndexOf(t)}function ye(e,t=0,n="{",r="}"){let i=1;for(let o=t;o<e.length;o++)if(e.slice(o,o+r.length)===r){if(0===--i)return o}else e.slice(o,o+n.length)===n&&i++;return-1}function we(e,t){const n=t.wordBoundary?fe(e,[`${t.opening} `,`${t.opening}\n`],t.start||0):e.indexOf(t.opening,t.start||0);if(-1===n)return null;const r=ye(e,n+t.opening.length,t.opening,t.closing);return-1===r?null:t.exclusive?e.slice(n+t.opening.length,r):e.slice(n,r+t.closing.length)}const be="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ve="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function xe(e,t){const n=t.length;let r=0,i=0;const o=[];for(let a=0;a<e.length;a++){const s=e[a];if("="===s)break;const c=t.indexOf(s);if(-1===c)throw new Error(`Invalid character: ${s}`);i=i<<Math.log2(n)|c,r+=Math.log2(n),r>=8&&(r-=8,o.push(i>>r&255))}return new Uint8Array(o)}function Ee(e,t){const n=t.length;let r=0,i=0,o="";for(let a=0;a<e.length;a++)for(i=i<<8|e[a],r+=8;r>=Math.log2(n);)r-=Math.log2(n),o+=t[i>>r&n-1];return r>0&&(o+=t[i<<Math.log2(n)-r&n-1]),o.length%4!=0&&(o+="=".repeat(4-o.length%4)),o}function Ae(e,t,n){const r=[];for(const i of n)i!==t&&r.push(e.replace(t,i));return r}function Re(e){const t=e.lastIndexOf(" ");return-1===t?{line:e,rest:""}:{line:e.slice(0,t),rest:e.slice(t+1)}}function Se(e){const t=e.reduce((e,t)=>e.length<t.length?e:t);let n="";for(let r=0;r<t.length;r++){const i=t[r];if(!e.every(e=>e[r]===i))break;n+=i}return n}function Ie(e,t){return new RegExp(`\\b${t}\\b`).test(e)}function ke(e,t,n=[]){let r="";for(;t<e.length&&(se(e[t])||n.includes(e[t]));)r+=e[t++];return r}function Te(e,t,n,r="$",i=":"){if(""===n)return e;let o=e.indexOf(`${r}${t}`);for(;-1!==o;){if(e[o+t.length+1]===i)if(e[o+t.length+2]===i)e=e.replace(`${r}${t}${i}${i}`,n);else{const a=ke(e,o+t.length+2,["_"]);e=e.replace(`${r}${t}${i}${a}`,n)}else e=e.replace(`${r}${t}`,n);o=e.indexOf(`${r}${t}`,o+n.length)}return e}function Be(e,t="$",n=":"){let r=e.indexOf(t);for(;-1!==r;){const i=ke(e,r+1);if(e[r+i.length+1]===n)if(e[r+i.length+2]===n)e=e.replace(`${t}${i}${n}${n}`,"");else{const o=ke(e,r+i.length+2);e=e.replace(`${t}${i}${n}${o}`,o)}r=e.indexOf(t,r+1)}return e}function Oe(e,t=!0){const n=Object.entries(e).filter(([e,t])=>null!=t).map(([e,t])=>`${e}=${encodeURIComponent(t)}`).join("&");return n?(t?"?":"")+n:""}function De(e){return String(Math.floor(e)).padStart(2,"0")}function Ce(e){const t=Math.floor(e/36e5);e%=36e5;const n=Math.floor(e/6e4);e%=6e4;const r=Math.floor(e/1e3);return t?`${De(t)}:${De(n)}:${De(r)}`:`${De(n)}:${De(r)}`}function $e(e){return Math.floor((A(e)?e.getTime():e)/864e5)}const ze={today:(e,t)=>De(e)+":"+De(t),yesterday:()=>"Yesterday",monday:()=>"Mon",tuesday:()=>"Tue",wednesday:()=>"Wed",thursday:()=>"Thu",friday:()=>"Fri",saturday:()=>"Sat",sunday:()=>"Sun",weeks:e=>`${e}w`},Fe={now:()=>"A few seconds",seconds:e=>`${e} seconds`,minutes:e=>`${e} minutes`,hours:e=>`${e} hours`,days:e=>`${e} days`,weeks:e=>`${e} weeks`};function Pe(t,n){const r=n?.now??Date.now(),i=n?.labels||Fe;let o=(r-(e.Types.isDate(t)?t.getTime():t))/1e3;return o<10?i.now():o<120?i.seconds(Math.floor(o)):(o/=60,o<120?i.minutes(Math.floor(o)):(o/=60,o<48?i.hours(Math.floor(o)):(o/=24,o<14?i.days(Math.floor(o)):(o/=7,i.weeks(Math.floor(o))))))}const Ue={},qe={s:1e3,m:6e4,h:36e5,d:864e5},Ne={0:"sunday",1:"monday",2:"tuesday",3:"wednesday",4:"thursday",5:"friday",6:"saturday"};function Me(e){return{zeroBasedIndex:e,day:Ne[e]}}function _e(e){return Me(e.getDay())}const Ve={ms:1,milli:1,millis:1,millisecond:1,milliseconds:1,s:1e3,sec:1e3,second:1e3,seconds:1e3,m:6e4,min:6e4,minute:6e4,minutes:6e4,h:36e5,hour:36e5,hours:36e5,d:864e5,day:864e5,days:864e5,w:6048e5,week:6048e5,weeks:6048e5,month:2592e6,months:2592e6,y:31536e6,year:31536e6,years:31536e6},Le={b:0,byte:0,bytes:0,kb:1,kilobyte:1,kilobytes:1,mb:2,megabyte:2,megabytes:2,gb:3,gigabyte:3,gigabytes:3,tb:4,terabyte:4,terabytes:4},je=new Map;function Ge(e,t=!1){e=e.filter(e=>e),t&&v(e[1])&&(e[1]="../"+e[1]);let n="";v(e[0])&&e[0].includes("://")&&(n=W(e[0],"://")??"",e[0]=Z(e[0],"://")??"");const r=e.map(e=>String(e)).flatMap(e=>e.split("/")),i=[];for(let e=0;e<r.length;e++)"."!==r[e]&&(".."===r[e]?(!n||i.length>1)&&i.pop():i.push(r[e]));return(n?n+"://":"")+i.join("/").replaceAll(/\/{2,}/g,"/")}function Ke(e){const t=Object.keys(e).sort((e,t)=>e.localeCompare(t)),n={};for(const r of t)n[r]=We(e[r]);return n}function He(e){const t=[];return e.sort((e,t)=>JSON.stringify(We(e)).localeCompare(JSON.stringify(We(t)))).forEach(e=>t.push(We(e))),t}function We(e){return Array.isArray(e)?He(e):m(e)?Ke(e):e}function Ze(e,t){return JSON.stringify(We(e))===JSON.stringify(We(t))}function Je(e){const t=Object.keys(e);return t[Math.floor(Math.random()*t.length)]}const Xe=[1e3,1e6,1e9,1e12,1e15,1e18,1e21,1e24,1e27,1e30,1e9,1e16,1e18,1e18,1e18,1e33],Ye=["thousand","million","billion","trillion","quadrillion","quintillion","sextillion","septillion","octillion","nonillion","gwei","bzz","btc","eth","dai","decillion"],Qe=["K","M","B","T","Qa","Qi","Sx","Sp","O","N","gwei","bzz","eth","btc","dai","D"];function et(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeNumber got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim(),r=Qe.findIndex(e=>e.toLowerCase()===n.toLowerCase());return-1===r?t:t*Xe[r]}function tt(e,t,n){return e<t?t:e>n?n:e}function nt(e,t,n){return e+(n?"["+t+"]":(e.length?".":"")+t)}function rt(e,t,n,r,i){if(!m(t))return t;for(const[o,a]of Object.entries(t)){const t=nt(n,o,r);Array.isArray(a)?i?rt(e,a,t,!0,i):e[t]=a.map(e=>rt(Array.isArray(e)?[]:{},e,"",!1,i)):m(a)?rt(e,a,t,!1,i):e[t]=a}return e}function it(e,t){const n={};for(const r of e)n[t(r)]=r;return n}function ot(e,t){const n=Math.ceil(e.length/t),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r}function at(e,t){const n=[],r=Math.ceil(e.length/t);for(let i=0;i<r;i++)n.push(e.slice(i*t,i*t+t));return n}function st(e,t){return Object.fromEntries(Object.entries(e).sort(t))}function ct(e,t){const n=[];let r=[];return e.forEach((i,o)=>{(0===o||!t(i,e[o-1]))&&(r=[],n.push(r)),r.push(i)}),n}function ut(e,t,n,r=100){if(e.map.has(t)){const n=e.keys.indexOf(t);e.keys.splice(n,1)}if(e.map.set(t,n),e.keys.push(t),e.keys.length>r){const t=e.keys.shift();t&&e.map.delete(t)}}class lt{constructor(e){this.value=e}static of(e){return new lt(e)}static empty(){return new lt(null)}map(e){return new lt(null!==this.value&&void 0!==this.value?e(this.value):null)}mapAsync(e){return null!==this.value&&void 0!==this.value?e(this.value).then(e=>lt.of(e)):Promise.resolve(lt.empty())}ifPresent(e){return null!==this.value&&void 0!==this.value&&e(this.value),this}ifPresentAsync(e){return null!==this.value&&void 0!==this.value?e(this.value).then(()=>this):Promise.resolve(this)}ifAbsent(e){return(null===this.value||void 0===this.value)&&e(),this}ifAbsentAsync(e){return null===this.value||void 0===this.value?e().then(()=>this):Promise.resolve(this)}getOrFallback(e){return this.value??e()}getOrFallbackAsync(e){return null!==this.value&&void 0!==this.value?Promise.resolve(this.value):e()}getOrThrow(){if(null===this.value||void 0===this.value)throw Error("Optional.value is empty");return this.value}}e.Optional=lt,e.Lazy=class{constructor(e){this.supplier=e,this.value=null}get(){return this.value||(this.value=this.supplier()),this.value}},e.AsyncLazy=class{constructor(e){this.supplier=e,this.value=null}async get(){return this.value||(this.value=await this.supplier()),this.value}};class dt{constructor(e){this.value=e,this.children=[]}}function ht(e,t){if(Math.log2(e.length)%1!=0)throw new Error("Array length must be a power of 2");let n=[...e];for(;n.length>1;){const e=[];for(let r=0;r<n.length;r+=2){const i=n[r+1];e.push(t(n[r],i))}n=e}return n[0]}function ft(...e){const t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t);let r=0;return e.forEach(e=>{n.set(e,r),r+=e.length}),n}function pt(e){return 137===e[0]&&80===e[1]&&78===e[2]&&71===e[3]}function mt(e){return 255===e[0]&&216===e[1]}function gt(e){return 87===e[8]&&69===e[9]&&66===e[10]&&80===e[11]}function yt(e,t){const n=new ArrayBuffer(8);return new DataView(n).setBigUint64(0,BigInt(e),"LE"===t),new Uint8Array(n)}function wt(e,t){const n=new Uint8Array(32);let r=e;if("LE"===t){for(let e=0;e<32;e++)n[e]=Number(0xffn&r),r>>=8n;return n}for(let e=31;e>=0;e--)n[e]=Number(0xffn&r),r>>=8n;return n}function bt(e,t){let n=0n;if("LE"===t){for(let t=31;t>=0;t--)n=n<<8n|BigInt(e[t]);return n}for(let t=0;t<32;t++)n=n<<8n|BigInt(e[t]);return n}function vt(e,t){const n=[];for(let r=0;r<e.length;r+=t)n.push(e.subarray(r,r+t));return n}const xt=[0,1,0,32898,2147483648,32906,2147483648,2147516416,0,32907,0,2147483649,2147483648,2147516545,2147483648,32777,0,138,0,136,0,2147516425,0,2147483658,0,2147516555,2147483648,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,0,32778,2147483648,2147483658,2147483648,2147516545,2147483648,32896,0,2147483649,2147483648,2147516424];function Et(e){for(let t=0;t<24;t++){const n=e[0]^e[10]^e[20]^e[30]^e[40],r=e[1]^e[11]^e[21]^e[31]^e[41],i=e[2]^e[12]^e[22]^e[32]^e[42],o=e[3]^e[13]^e[23]^e[33]^e[43],a=e[4]^e[14]^e[24]^e[34]^e[44],s=e[5]^e[15]^e[25]^e[35]^e[45],c=e[6]^e[16]^e[26]^e[36]^e[46],u=e[7]^e[17]^e[27]^e[37]^e[47],l=e[8]^e[18]^e[28]^e[38]^e[48],d=e[9]^e[19]^e[29]^e[39]^e[49],h=l^(i<<1|o>>>31),f=d^(o<<1|i>>>31),p=n^(a<<1|s>>>31),m=r^(s<<1|a>>>31),g=i^(c<<1|u>>>31),y=o^(u<<1|c>>>31),w=a^(l<<1|d>>>31),b=s^(d<<1|l>>>31),v=c^(n<<1|r>>>31),x=u^(r<<1|n>>>31);e[0]^=h,e[1]^=f,e[2]^=p,e[3]^=m,e[4]^=g,e[5]^=y,e[6]^=w,e[7]^=b,e[8]^=v,e[9]^=x,e[10]^=h,e[11]^=f,e[12]^=p,e[13]^=m,e[14]^=g,e[15]^=y,e[16]^=w,e[17]^=b,e[18]^=v,e[19]^=x,e[20]^=h,e[21]^=f,e[22]^=p,e[23]^=m,e[24]^=g,e[25]^=y,e[26]^=w,e[27]^=b,e[28]^=v,e[29]^=x,e[30]^=h,e[31]^=f,e[32]^=p,e[33]^=m,e[34]^=g,e[35]^=y,e[36]^=w,e[37]^=b,e[38]^=v,e[39]^=x,e[40]^=h,e[41]^=f,e[42]^=p,e[43]^=m,e[44]^=g,e[45]^=y,e[46]^=w,e[47]^=b,e[48]^=v,e[49]^=x;const E=e[0],A=e[1],R=e[2]<<1|e[3]>>>31,S=e[3]<<1|e[2]>>>31,I=e[5]<<30|e[4]>>>2,k=e[4]<<30|e[5]>>>2,T=e[6]<<28|e[7]>>>4,B=e[7]<<28|e[6]>>>4,O=e[8]<<27|e[9]>>>5,D=e[9]<<27|e[8]>>>5,C=e[11]<<4|e[10]>>>28,$=e[10]<<4|e[11]>>>28,z=e[13]<<12|e[12]>>>20,F=e[12]<<12|e[13]>>>20,P=e[14]<<6|e[15]>>>26,U=e[15]<<6|e[14]>>>26,q=e[17]<<23|e[16]>>>9,N=e[16]<<23|e[17]>>>9,M=e[18]<<20|e[19]>>>12,_=e[19]<<20|e[18]>>>12,V=e[20]<<3|e[21]>>>29,L=e[21]<<3|e[20]>>>29,j=e[22]<<10|e[23]>>>22,G=e[23]<<10|e[22]>>>22,K=e[25]<<11|e[24]>>>21,H=e[24]<<11|e[25]>>>21,W=e[26]<<25|e[27]>>>7,Z=e[27]<<25|e[26]>>>7,J=e[29]<<7|e[28]>>>25,X=e[28]<<7|e[29]>>>25,Y=e[31]<<9|e[30]>>>23,Q=e[30]<<9|e[31]>>>23,ee=e[33]<<13|e[32]>>>19,te=e[32]<<13|e[33]>>>19,ne=e[34]<<15|e[35]>>>17,re=e[35]<<15|e[34]>>>17,ie=e[36]<<21|e[37]>>>11,oe=e[37]<<21|e[36]>>>11,ae=e[38]<<8|e[39]>>>24,se=e[39]<<8|e[38]>>>24,ce=e[40]<<18|e[41]>>>14,ue=e[41]<<18|e[40]>>>14,le=e[42]<<2|e[43]>>>30,de=e[43]<<2|e[42]>>>30,he=e[45]<<29|e[44]>>>3,fe=e[44]<<29|e[45]>>>3,pe=e[47]<<24|e[46]>>>8,me=e[46]<<24|e[47]>>>8,ge=e[48]<<14|e[49]>>>18,ye=e[49]<<14|e[48]>>>18;e[0]=E^~z&K,e[1]=A^~F&H,e[2]=z^~K&ie,e[3]=F^~H&oe,e[4]=K^~ie&ge,e[5]=H^~oe&ye,e[6]=ie^~ge&E,e[7]=oe^~ye&A,e[8]=ge^~E&z,e[9]=ye^~A&F,e[10]=T^~M&V,e[11]=B^~_&L,e[12]=M^~V&ee,e[13]=_^~L&te,e[14]=V^~ee&he,e[15]=L^~te&fe,e[16]=ee^~he&T,e[17]=te^~fe&B,e[18]=he^~T&M,e[19]=fe^~B&_,e[20]=R^~P&W,e[21]=S^~U&Z,e[22]=P^~W&ae,e[23]=U^~Z&se,e[24]=W^~ae&ce,e[25]=Z^~se&ue,e[26]=ae^~ce&R,e[27]=se^~ue&S,e[28]=ce^~R&P,e[29]=ue^~S&U,e[30]=O^~C&j,e[31]=D^~$&G,e[32]=C^~j&ne,e[33]=$^~G&re,e[34]=j^~ne&pe,e[35]=G^~re&me,e[36]=ne^~pe&O,e[37]=re^~me&D,e[38]=pe^~O&C,e[39]=me^~D&$,e[40]=I^~q&J,e[41]=k^~N&X,e[42]=q^~J&Y,e[43]=N^~X&Q,e[44]=J^~Y&le,e[45]=X^~Q&de,e[46]=Y^~le&I,e[47]=Q^~de&k,e[48]=le^~I&q,e[49]=de^~k&N,e[0]^=xt[2*t],e[1]^=xt[2*t+1]}}function At(e){const t=[];for(let n=0;n<e.length;n+=4)t.push(e[n]|e[n+1]<<8|e[n+2]<<16|e[n+3]<<24);return t}function Rt(e,t){if(!e.length){const e=new Uint8Array(136);return e[0]=t,e[135]=128,[At(e)]}const n=vt(e,136),r=n[n.length-1];if(r.length<136){const e=new Uint8Array(136);e.set(r),e[r.length]=t,e[135]|=128,n[n.length-1]=e}if(136===r.length){const e=new Uint8Array(136);e[0]=t,e[135]=128,n.push(e)}return n.map(At)}function St(e,t){for(const n of t){for(let t=0;t<34;t+=2)e[t]^=n[t+1],e[t+1]^=n[t];Et(e)}return e}function It(e){return new Uint8Array([e[1],e[1]>>-24,e[1]>>-16,e[1]>>-8,e[0],e[0]>>8,e[0]>>16,e[0]>>24,e[3],e[3]>>-24,e[3]>>-16,e[3]>>-8,e[2],e[2]>>8,e[2]>>16,e[2]>>24,e[5],e[5]>>-24,e[5]>>-16,e[5]>>-8,e[4],e[4]>>8,e[4]>>16,e[4]>>24,e[7],e[7]>>-24,e[7]>>-16,e[7]>>-8,e[6],e[6]>>8,e[6]>>16,e[6]>>24])}function kt(e){return It(St(new Array(50).fill(0),Rt(e,1)))}function Tt(e,t,n=0){if(e.length>=t)return e;const r=new Uint8Array(t);return r.fill(n),r.set(e,t-e.length),r}function Bt(e,t,n=0){if(e.length>=t)return e;const r=new Uint8Array(t);return r.fill(n),r.set(e,0),r}function Ot(e,t){return(e%t+t)%t}function Dt(e,t){e=Ot(e,t);let[n,r]=[0n,1n],[i,o]=[t,e];for(;0n!==o;){const e=i/o;[n,r]=[r,n-e*r],[i,o]=[o,i-e*o]}if(i>1n)throw new Error("a is not invertible");return n<0n&&(n+=t),n}function Ct(e,t){return 0n===Ot(e,t)?0n:t%4n==3n?function(e,t,n){let r=1n;for(e=Ot(e,n);t>0;)t%2n==1n&&(r=Ot(r*e,n)),e=Ot(e*e,n),t/=2n;return r}(e,(t+1n)/4n,t):null}const $t=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,zt=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,Ft=0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,Pt=0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n;function Ut(e,t,n){if(0n===t)return[0n,0n];const r=Ot(3n*e*e*Dt(2n*t,n),n),i=Ot(r*r-2n*e,n);return[i,Ot(r*(e-i)-t,n)]}function qt(e,t,n,r,i){if(0n===e&&0n===t)return[n,r];if(0n===n&&0n===r)return[e,t];if(e===n&&t===Ot(-r,i))return[0n,0n];if(e===n&&t===r)return Ut(e,t,i);const o=Ot((r-t)*Dt(n-e,i),i),a=Ot(o*o-e-n,i);return[a,Ot(o*(e-a)-t,i)]}function Nt(e,t,n,r){let i=[0n,0n],o=[e,t];const a=n.toString(2);for(const e of a)"0"===e?(o=qt(i[0],i[1],o[0],o[1],r),i=Ut(i[0],i[1],r)):(i=qt(i[0],i[1],o[0],o[1],r),o=Ut(o[0],o[1],r));return i}function Mt(e,t,n){if(t<=0n||t>=zt)throw new Error("Invalid private key");if(n||(n=Ot(bt(kt(ft(kt(wt(t,"BE")),wt(e,"BE"))),"BE"),zt)),n<=0n||n>=zt)throw new Error("Invalid nonce");const r=Ot(e,zt),i=Nt(Ft,Pt,n,$t),o=Ot(i[0],zt);let a=Ot((r+Ot(o,zt)*t)*Dt(n,zt),zt);if(0n===o||0n===a)throw new Error("Invalid r or s value");let s=i[1]%2n==0n?27n:28n;return a>zt/2n&&(a=zt-a,s=27n===s?28n:27n),[o,a,s]}class _t{constructor(e){this.cursor=0,this.buffer=e}read(e){const t=this.buffer.subarray(this.cursor,this.cursor+e);return this.cursor+=e,t}max(){return this.buffer.length-this.cursor}}e.Uint8ArrayReader=_t;class Vt{constructor(e){this.buffer=e,this.cursor=0}write(e){const t=Math.min(this.max(),e.max());return this.buffer.set(e.read(t),this.cursor),this.cursor+=t,t}max(){return this.buffer.length-this.cursor}}e.Uint8ArrayWriter=Vt;class Lt{constructor(e,t=0n){this.span=t,this.writer=new Vt(new Uint8Array(e))}build(){return ft(yt(this.span,"LE"),this.writer.buffer)}hash(){const e=ht(vt(this.writer.buffer,32),(e,t)=>Lt.hashFunction(ft(e,t)));return Lt.hashFunction(ft(yt(this.span,"LE"),e))}}e.Chunk=Lt,Lt.hashFunction=kt;class jt{constructor(e,t=4096){this.counters=[1],this.capacity=t,this.chunks=[new Lt(t)],this.onChunk=e}static async root(e,n=4096){const r=new t(t.NOOP,n);return await r.append(e),r.finalize()}async append(e,t=0,n=0n){const r=new _t(e);for(;r.max()>0;){0===this.chunks[t].writer.max()&&await this.elevate(t);const e=this.chunks[t].writer.write(r);n?this.chunks[t].span+=n:this.chunks[0].span+=BigInt(e)}}async elevate(e){this.counters[e]=++this.counters[e]%(this.capacity/32),this.chunks[e+1]||(this.chunks.push(new Lt(this.capacity)),this.counters.push(1)),await this.append(this.chunks[e].hash(),e+1,this.chunks[e].span),await this.onChunk(this.chunks[e]),this.chunks[e]=new Lt(this.capacity)}async finalize(e=0){return this.chunks[e+1]?1===this.counters[e]?(await this.elevate(e+1),this.chunks[e+1]=this.chunks[e],this.finalize(e+1)):(await this.elevate(e),this.finalize(e+1)):(await this.onChunk(this.chunks[e]),this.chunks[e])}}e.MerkleTree=jt,t=jt,jt.NOOP=async e=>{};class Gt{constructor(e,t){if(t<0)throw Error("Scale must be non-negative");this.value=BigInt(e),this.scale=t}static fromDecimalString(e,t){let[n,r]=e.split(".");return r=(r||"").padEnd(t,"0").slice(0,t),new Gt(BigInt(n+r),t)}add(e){return this.assertSameScale(e),new Gt(this.value+e.value,this.scale)}subtract(e){return this.assertSameScale(e),new Gt(this.value-e.value,this.scale)}multiply(e){return new Gt(this.value*e,this.scale)}divmod(e){if(0n===e)throw new Error("Division by zero is not allowed");const t=this.value/e,n=this.value%e;return[new Gt(t,this.scale),new Gt(n,this.scale)]}exchange(e,t,n){if("*"===e){const e=this.value*t.value/10n**BigInt(this.scale);return new Gt(e,n)}this.assertSameScale(t);const r=this.value*10n**BigInt(n)/t.value;return new Gt(r,n)}compare(e){return this.assertSameScale(e),this.value>e.value?1:this.value<e.value?-1:0}toDecimalString(){if(0===this.scale)return this.value.toString();const e=this.value.toString();return`${e.slice(0,-this.scale)||"0"}.${e.slice(-this.scale).padStart(this.scale,"0")}`}toString(){return this.value.toString()}toJSON(){return this.toString()}assertSameScale(e){if(this.scale!==e.scale)throw new Error(`Scale mismatch: expected ${this.scale}, but got ${e.scale}`)}}function Kt(e,t,n,r){const i=e.findIndex(e=>e===`--${t}`||e.startsWith(`--${t}=`)),o=e[i];if(!o)return(n||{})[r||t||""]||null;if(o.includes("="))return o.split("=")[1];const a=e[i+1];return a&&!a.startsWith("-")?a:(n||{})[r||t||""]||null}function Ht(e,t,n,r){const i=Kt(e,t,n,r);if(!i)throw new Error(`Missing argument ${t}`);return i}function Wt(e,t){const n=e[t];e.splice(t,1),e.unshift(n)}function Zt(e,t){return{x:e.x+t.x,y:e.y+t.y}}function Jt(e,t){return{x:e.x*t,y:e.y*t}}function Xt(e,t,n){return{x:e.x+Math.cos(t)*n,y:e.y+Math.sin(t)*n}}function Yt(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function Qt(e,t,n="row-first"){const r=[];if("column-first"===n)for(let n=0;n<e.length;n++)for(let i=0;i<e[0].length;i++)t(n,i)&&r.push({x:n,y:i});else for(let n=0;n<e[0].length;n++)for(let i=0;i<e.length;i++)t(i,n)&&r.push({x:i,y:n});return r}function en(e,t,n){return!e[t-1]?.[n]}function tn(e,t,n){return!e[t+1]?.[n]}function nn(e,t,n){return!e[t][n-1]}function rn(e,t,n){return!e[t][n+1]}function on(e,t,n){const r=[];return e[t][n]?function(e,t,n){return e[t+1]?.[n]&&e[t-1]?.[n]&&!e[t][n-1]&&!e[t][n+1]}(e,t,n)||function(e,t,n){return e[t][n+1]&&e[t][n-1]&&!e[t-1]?.[n]&&!e[t+1]?.[n]}(e,t,n)?[]:(!e[t-1]?.[n-1]&&en(e,t,n)&&nn(e,t,n)&&r.push({x:t,y:n}),!e[t+1]?.[n-1]&&tn(e,t,n)&&nn(e,t,n)&&r.push({x:t+1,y:n}),!e[t-1]?.[n+1]&&en(e,t,n)&&rn(e,t,n)&&r.push({x:t,y:n+1}),!e[t+1]?.[n+1]&&tn(e,t,n)&&rn(e,t,n)&&r.push({x:t+1,y:n+1}),r):(e[t-1]?.[n]&&e[t][n-1]&&r.push({x:t,y:n}),e[t+1]?.[n]&&e[t][n-1]&&r.push({x:t+1,y:n}),e[t-1]?.[n]&&e[t][n+1]&&r.push({x:t,y:n+1}),e[t+1]?.[n]&&e[t][n+1]&&r.push({x:t+1,y:n+1}),r)}function an(e,t){return t.map(t=>function(e,t){return Math.atan2(t.y-e.y,t.x-e.x)}(e,t)).sort((e,t)=>e-t)}function sn(e,t,n,r){const i=(r.y-n.y)*(t.x-e.x)-(r.x-n.x)*(t.y-e.y);if(0===i)return null;let o=e.y-n.y,a=e.x-n.x;const s=(r.x-n.x)*o-(r.y-n.y)*a,c=(t.x-e.x)*o-(t.y-e.y)*a;return o=s/i,a=c/i,o>0&&o<1&&a>0&&a<1?{x:e.x+o*(t.x-e.x),y:e.y+o*(t.y-e.y)}:null}function cn(e,t,n){const r=[],i=Xt(e,n,1e4);for(const n of t){const t=sn(e,i,n.start,n.end);t&&r.push(t)}return r.length?r.reduce((t,n)=>Yt(e,n)<Yt(e,t)?n:t):null}e.FixedPointNumber=Gt;class un{constructor(){this.subscribers=[]}subscribe(e){return this.subscribers.push(e),()=>{this.subscribers=this.subscribers.filter(t=>t!==e)}}publish(e){this.subscribers.forEach(t=>t(e))}clear(){this.subscribers=[]}getSubscriberCount(){return this.subscribers.length}}e.PubSubChannel=un,e.AsyncQueue=class{constructor(e,t){this.queue=[],this.running=0,this.onProcessed=new un,this.onDrained=new un,this.concurrency=e,this.capacity=t}process(){if(this.running>=this.concurrency)return;const e=this.queue.shift();e&&(this.running++,e().finally(()=>{this.running--,this.process(),this.onProcessed.publish(),0===this.running&&this.onDrained.publish()}))}enqueue(e){if(this.queue.length<this.capacity)return this.queue.push(e),this.process(),Promise.resolve();if(this.onProcessed.getSubscriberCount())throw Error("Queue capacity is full");return new Promise(t=>{this.onProcessed.subscribe(()=>{this.queue.length<this.capacity&&(this.queue.push(e),this.process(),this.onProcessed.clear(),t())})})}drain(){if(0===this.running)return Promise.resolve();if(this.onDrained.getSubscriberCount())throw Error("Already draining");return new Promise(e=>{this.onDrained.subscribe(()=>{this.onDrained.clear(),e()})})}};class ln{constructor(){this.forks=new Map}insert(e,t){if(0===e.length)return void(this.handler=t);const n=e[0];let r,i=n;if(n.startsWith(":")&&(i=":",r=n.slice(1)),!this.forks.has(i)){const e=new ln;r&&(e.variableName=r),this.forks.set(i,e)}this.forks.get(i).insert(e.slice(1),t)}async handle(e,t,n,r){if(0===e.length)return!!this.handler&&(await this.handler(t,n,r),!0);const i=e[0],o=this.forks.get(i);if(o)return o.handle(e.slice(1),t,n,r);const a=this.forks.get(":");if(a)return a.variableName&&r.set(a.variableName,decodeURIComponent(i)),a.handle(e.slice(1),t,n,r);const s=this.forks.get("*");return!!s&&(r.set("wildcard",e.join("/")),!!s.handler&&(await s.handler(t,n,r),!0))}}e.TrieRouter=ln,e.RollingValueProvider=class{constructor(e){this.index=0,this.values=e}current(){return this.values[this.index]}next(){return this.index=(this.index+1)%this.values.length,this.values[this.index]}},e.Binary={hexToUint8Array:function(e){(e.startsWith("0x")||e.startsWith("0X"))&&(e=e.slice(2));const t=e.length/2,n=new Uint8Array(t);for(let r=0;r<t;r++){const t=parseInt(e.slice(2*r,2*r+2),16);n[r]=t}return n},uint8ArrayToHex:function(e){return Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")},binaryToUint8Array:function(e){const t=Math.ceil(e.length/8),n=new Uint8Array(t);for(let r=0;r<t;r++){const t=parseInt(e.slice(8*r,8*r+8),2);n[r]=t}return n},uint8ArrayToBinary:function(e){return Array.from(e).map(e=>e.toString(2).padStart(8,"0")).join("")},base64ToUint8Array:function(e){return xe(e,be)},uint8ArrayToBase64:function(e){return Ee(e,be)},base32ToUint8Array:function(e){return xe(e,ve)},uint8ArrayToBase32:function(e){return Ee(e,ve)},log2Reduce:ht,partition:vt,concatBytes:ft,numberToUint8:function(e){return new Uint8Array([e])},uint8ToNumber:function(e){return e[0]},numberToUint16:function(e,t){const n=new ArrayBuffer(2);return new DataView(n).setUint16(0,e,"LE"===t),new Uint8Array(n)},uint16ToNumber:function(e,t){return new DataView(e.buffer).getUint16(e.byteOffset,"LE"===t)},numberToUint32:function(e,t){const n=new ArrayBuffer(4);return new DataView(n).setUint32(0,e,"LE"===t),new Uint8Array(n)},uint32ToNumber:function(e,t){return new DataView(e.buffer).getUint32(e.byteOffset,"LE"===t)},numberToUint64:yt,uint64ToNumber:function(e,t){return new DataView(e.buffer).getBigUint64(e.byteOffset,"LE"===t)},numberToUint256:wt,uint256ToNumber:bt,sliceBytes:function(e,t){const n=[];let r=0;for(const i of t)n.push(e.subarray(r,r+i)),r+=i;return n},keccak256:kt,sha3_256:function(e){return It(St(new Array(50).fill(0),Rt(e,6)))},proximity:function(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e[r]^t[r];for(let e=0;e<8;e++)if(n>>7-e&1)return 8*r+e}return 8*Math.min(e.length,t.length)},commonPrefix:function(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++)if(e[r]!==t[r])return e.subarray(0,r);return e.subarray(0,n)},setBit:function(e,t,n,r){const i=Math.floor(t/8),o=t%8;1===n?e[i]|=1<<("BE"===r?7-o:o):e[i]&=~(1<<("BE"===r?7-o:o))},getBit:function(e,t,n){const r=t%8;return e[Math.floor(t/8)]>>("BE"===n?7-r:r)&1},indexOf:function(e,t,n=0){for(let r=n;r<e.length;r++)for(let n=0;n<t.length&&e[r+n]===t[n];n++)if(n===t.length-1)return r;return-1},equals:function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},padStart:Tt,padStartToMultiple:function(e,t,n=0){const r=e.length%t;return 0===r?e:Tt(e,e.length+t-r,n)},padEnd:Bt,padEndToMultiple:function(e,t,n=0){const r=e.length%t;return 0===r?e:Bt(e,e.length+t-r,n)},xorCypher:function(e,t){const n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r%t.length];return n},isUtf8:function(e){for(let t=0;t<e.length;t++){const n=e[t];if(!(n<128))if(192==(224&n)){if(t+1>=e.length||128!=(192&e[t+1]))return!1;t+=1}else if(224==(240&n)){if(t+2>=e.length||128!=(192&e[t+1])||128!=(192&e[t+2]))return!1;t+=2}else{if(240!=(248&n))return!1;if(t+3>=e.length||128!=(192&e[t+1])||128!=(192&e[t+2])||128!=(192&e[t+3]))return!1;t+=3}}return!0}},e.Elliptic={privateKeyToPublicKey:function(e){if(e<=0n||e>=zt)throw new Error("Invalid private key");return Nt(Ft,Pt,e,$t)},compressPublicKey:function(e){const t=e[1]%2n==0n?2:3;return new Uint8Array([t,...wt(e[0],"BE")])},publicKeyFromCompressed:function(e){if(33!==e.length||2!==e[0]&&3!==e[0])throw new Error("Invalid compressed public key");const t=bt(e.slice(1),"BE"),n=Ct(Ot(t**3n+7n,$t),$t);if(!n)throw Error("Invalid x: does not correspond to a valid curve point");const r=Ot(-n,$t),i=n%2n==0n;return[t,2===e[0]?i?n:r:i?r:n]},publicKeyToAddress:function(e){const t=new Uint8Array(20),n=kt(ft(wt(e[0],"BE"),wt(e[1],"BE")));return t.set(n.subarray(12)),t},signMessage:function(e,t,n){return Mt(bt(kt(e),"BE"),t,n)},signHash:Mt,verifySignature:function(e,t,n,r){const i=Ot(bt(kt(e),"BE"),zt),o=Dt(r,zt),a=Ot(i*o,zt),s=Ot(n*o,zt),c=Nt(Ft,Pt,a,$t),u=Nt(t[0],t[1],s,$t);return n===Ot(qt(c[0],c[1],u[0],u[1],$t)[0],zt)},recoverPublicKey:function(e,t,n,r){const i=Ct(Ot(t**3n+7n,$t),$t);if(!i)throw new Error("Invalid r: does not correspond to a valid curve point");const o=i%2n==(27n===r?0n:1n)?i:$t-i,a=Ot(bt(kt(e),"BE"),zt),s=Nt(t,o,n,$t),c=Nt(Ft,Pt,a,$t),u=qt(s[0],s[1],c[0],Ot(-c[1],$t),$t);return Nt(u[0],u[1],Dt(t,zt),$t)},checksumEncode:function(t){const n=e.Binary.uint8ArrayToHex(t),r=e.Binary.uint8ArrayToHex(e.Binary.keccak256(new Uint8Array([...n].map(e=>e.charCodeAt(0)))));let i="0x";for(let e=0;e<n.length;e++)parseInt(r[e],16)>7?i+=n[e].toUpperCase():i+=n[e];return i}},e.Random={intBetween:a,floatBetween:function(e,t,n=Math.random){return n()*(t-e)+e},chance:c,signed:function(){return 2*Math.random()-1},makeSeededRng:function(e){let t=e,n=3405648695,r=3735928559;return function(){return t+=n,n^=t<<7,t*=r,r^=t<<13,t^=n^r,(t>>>0)/4294967296}},point:function(e,t,n,r=Math.random){let i,o;do{i=a(0,e-1,r),o=a(0,t-1,r)}while(n&&s(n,i,o));return[i,o]},procs:function(e,t=Math.random){const n=Math.floor(e);return c(e-n,t)?n+1:n}},e.Arrays={countUnique:function(e,t,n,r,i){const o=t?e.map(t):e,a={};for(const e of o)a[e]=(a[e]||0)+1;const s=r?st(a,i?(e,t)=>e[1]-t[1]:(e,t)=>t[1]-e[1]):a;return n?Object.keys(s):s},makeUnique:function(e,t){return Object.values(it(e,t))},splitBySize:function(e,t){const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n},splitByCount:ot,index:it,indexCollection:function(e,t){const n={};for(const r of e){const e=t(r);n[e]||(n[e]=[]),n[e].push(r)}return n},onlyOrThrow:function(e){if(1===e.length)return e[0];throw Error(`Expected exactly one element, actual: ${e.length}`)},onlyOrNull:function(e){return 1===e.length?e[0]:null},firstOrThrow:function(e){if(!e.length)throw Error("Received empty array");return e[0]},firstOrNull:function(e){return e.length>0?e[0]:null},shuffle:i,initialize:function(e,t){const n=[];for(let r=0;r<e;r++)n.push(t(r));return n},initialize2D:function(e,t,n){const r=[];for(let i=0;i<e;i++){r.push([]);for(let e=0;e<t;e++)r[i].push(n)}return r},rotate2D:function(e){const t=[];for(let n=0;n<e[0].length;n++){t.push([]);for(let r=0;r<e.length;r++)t[n].push(e[r][n])}return t},containsShape:function(e,t,n,r){if(n<0||r<0||r+t[0].length>e[0].length||n+t.length>e.length)return!1;for(let i=0;i<t.length;i++)for(let o=0;o<t[i].length;o++)if(void 0!==t[i][o]&&e[n+i][r+o]!==t[i][o])return!1;return!0},glue:function(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e[r]),r<e.length-1&&(b(t)?n.push(t()):n.push(t));return n},pluck:function(e,t){return e.map(e=>e[t])},pick:u,pickMany:function(e,t,n=Math.random){if(t>e.length)throw new Error(`Count (${t}) is greater than array length (${e.length})`);return o(e,t,n).map(t=>e[t])},pickManyUnique:function(e,t,n,r=Math.random){if(t>e.length)throw new Error(`Count (${t}) is greater than array length (${e.length})`);const i=[];for(;i.length<t;){const t=u(e,r);i.some(e=>n(e,t))||i.push(t)}return i},pickWeighted:function(e,t,n){if(void 0===n&&(n=Math.random()),e.length!==t.length)throw new Error("Array length mismatch");let r=t.reduce((e,t)=>e+t,0);const i=n*r;for(let n=0;n<e.length-1;n++)if(r-=t[n],i>=r)return e[n];return l(e)},pickRandomIndices:o,pickGuaranteed:function(t,n,r,o,a,s=Math.random){const c=t.filter(e=>e!==n&&e!==r),u=[];for(null!==n&&u.push(n);c.length&&u.length<o;){const t=e.Random.intBetween(0,c.length-1,s);a(c[t],u)&&u.push(c[t]),c.splice(t,1)}return i(u,s),{values:u,indexOfGuaranteed:null!==n?u.indexOf(n):-1}},last:l,pipe:d,makePipe:function(e,t){return n=>d(n,e,t)},sortWeighted:function(e,t,n=Math.random){const r=t.map(e=>n()*e),i=[];for(let t=0;t<e.length;t++)i.push([e[t],r[t]]);return i.sort((e,t)=>t[1]-e[1]).map(e=>e[0])},pushAll:L,unshiftAll:function(e,t){Array.prototype.unshift.apply(e,t)},filterAndRemove:function(e,t){const n=[];for(let r=e.length-1;r>=0;r--)t(e[r])&&n.push(e.splice(r,1)[0]);return n},merge:function(e,t){const n=Object.keys(t);for(const r of n)Array.isArray(t[r])&&Array.isArray(e[r])&&L(e[r],t[r])},empty:function(e){return e.splice(0,e.length),e},pushToBucket:function(e,t,n){e[t]||(e[t]=[]),e[t].push(n)},unshiftAndLimit:function(e,t,n){for(e.unshift(t);e.length>n;)e.pop()},atRolling:function(e,t){let n=t%e.length;return n<0&&(n+=e.length),e[n]},group:ct,createOscillator:function(e){let t=0;return{next:()=>e[t++%e.length]}},organiseWithLimits:function(e,t,n,r,i){const o={};for(const e of Object.keys(t))o[e]=[];o[r]=[],i&&(e=e.sort(i));for(const i of e){const e=i[n],a=t[e]?e:r;o[a].length>=t[a]?o[r].push(i):o[a].push(i)}return o},tickPlaybook:function(e){if(0===e.length)return null;const t=e[0];return t.ttlMax?--t.ttl<=0&&e.shift():t.ttlMax=t.ttl,{progress:(t.ttlMax-t.ttl)/t.ttlMax,data:t.data}},getArgument:Kt,getBooleanArgument:function(e,t,n,r){const i=e.some(e=>e.endsWith("-"+t)),o=Kt(e,t,n,r);if(!o&&i)return!0;if(!o&&!i)return null;if(["true","1","yes","y","on"].includes(o.toLowerCase()))return!0;if(["false","0","no","n","off"].includes(o.toLowerCase()))return!1;throw Error(`Invalid boolean argument ${t}: ${o}`)},getNumberArgument:function(e,t,n,r){const i=Kt(e,t,n,r);if(!i)return null;try{return et(i)}catch{throw new Error(`Invalid number argument ${t}: ${i}`)}},requireStringArgument:Ht,requireNumberArgument:function(e,t,n,r){const i=Ht(e,t,n,r);try{return et(i)}catch{throw new Error(`Invalid argument ${t}: ${i}`)}},bringToFront:function(e,t){const n=[...e];return Wt(n,t),n},bringToFrontInPlace:Wt,findInstance:function(e,t){const n=e.find(e=>e instanceof t);return lt.of(n)},filterInstances:function(e,t){return e.filter(e=>e instanceof t)},interleave:function(e,t){const n=[],r=Math.max(e.length,t.length);for(let i=0;i<r;i++)e[i]&&n.push(e[i]),t[i]&&n.push(t[i]);return n},toggle:function(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]},createHierarchy:function(e,t,n,r,i=!1){const o=new Map,a=[];e.forEach(e=>{const n=new dt(e);o.set(e[t],n)}),e.forEach(e=>{const r=o.get(e[t]);if(!r)return;const i=e[n];if(i){const e=o.get(i);e&&e.children.push(r)}else a.push(r)});const s=e=>{e.children.sort((e,t)=>{const n=e.value[r],o=t.value[r];return i?o-n:n-o}),e.children.forEach(s)};return a.forEach(s),a},multicall:function(e){return()=>e.forEach(e=>e())},maxBy:function(e,t){return e.reduce((e,n)=>t(e)>t(n)?e:n)}},e.System={sleepMillis:r,forever:async function(e,t,n){for(;;){try{await e()}catch(e){n&&n("Error in forever",e)}await r(t)}},scheduleMany:function(e,t){for(let n=0;n<e.length;n++){const r=e[n],i=t[n],o=Math.max(0,i.getTime()-Date.now());setTimeout(r,o)}},waitFor:async function(e,t){let n=t.requiredConsecutivePasses||1,i=0;for(let o=0;o<t.attempts;o++){try{if(await e()){if(i++,i>=n)return}else i=0}catch{i=0}o<t.attempts-1&&await r(t.waitMillis)}throw Error("Timed out waiting for predicate")},expandError:function(e,t){if(v(e))return e;const n=Object.keys(e);e.message&&!n.includes("message")&&n.push("message");const r=n.map(t=>`${t}: ${e[t]}`).join("; ");return t&&e.stack?r+"\n"+e.stack:r},runAndSetInterval:function(e,t){e();const n=setInterval(()=>{e()},t);return()=>clearInterval(n)},whereAmI:function(){const e=globalThis.process;return e?!0===e.browser?"browser":"node":"browser"},withRetries:async function(e,t,n,i,o,a){let s=null;for(let c=0;c<=t;c++)try{return await e()}catch(e){if(s=e,c===t)break;const u=n+c/(t-1)*(i-n);o&&o("Error in withRetries, retrying",{attempt:c+1,allowedFailures:t,delayMillis:u,error:e}),a&&a(),await r(u)}throw s}},e.Numbers={make:et,sum:function(e){return e.reduce((e,t)=>e+t,0)},average:function(e){return e.reduce((e,t)=>e+t,0)/e.length},median:function(e){const t=[...e].sort((e,t)=>e-t),n=Math.floor(t.length/2);return t.length%2==0?(t[n]+t[n-1])/2:t[n]},getDistanceFromMidpoint:function(e,t){return e-(t-1)/2},clamp:tt,range:j,interpolate:function(e,t,n){return e+(t-e)*n},createSequence:function(){let e=0;return{next:()=>e++}},increment:function(e,t,n){const r=e+t;return r>n?n:r},decrement:function(e,t,n){const r=e-t;return r<n?n:r},format:function(e,t){const n=t?.longForm??!1,r=t?.unit?` ${t.unit}`:"",i=n?Ye:Qe,o=t?.precision??1;if(e<Xe[0])return`${e}${r}`;for(let t=0;t<Xe.length-1;t++)if(e<Xe[t+1])return`${(e/Xe[t]).toFixed(o)}${n?" ":""}${i[t]}${r}`;return`${(e/Xe[Xe.length-1]).toFixed(o)}${n?" ":""}${i[Xe.length-1]}${r}`},fromDecimals:function(e,t,n){let r=e.length-t;if(r<=0)return"0."+"0".repeat(-r)+e+(n?" "+n:"");let i=e.substring(0,r);return""===i&&(i="0"),i+"."+e.substring(r)+(n?" "+n:"")},makeStorage:function(e,t=1024){const n=parseFloat(e);if(isNaN(n))throw Error("makeStorage got NaN for input");const r=e.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),i=""===r?0:Le[r];if(null==i)throw Error(`Unknown unit: "${r}"`);return Math.ceil(n*t**i)},asMegabytes:function(e){return e/1024/1024},convertBytes:function(e,t=1024){return e>=t*t*t*t?(e/t/t/t/t).toFixed(3)+" TB":e>=t*t*t?(e/t/t/t).toFixed(3)+" GB":e>=t*t?(e/t/t).toFixed(3)+" MB":e>=t?(e/t).toFixed(3)+" KB":e+" B"},hexToRgb:function(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e.toLowerCase());if(!t)throw new Error("Invalid hex color: "+e);return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]},rgbToHex:function(e){return"#"+e.map(e=>e.toString(16).padStart(2,"0")).join("")},haversineDistanceToMeters:function(e,t,n,r){const i=e*Math.PI/180,o=n*Math.PI/180,a=(n-e)*Math.PI/180,s=(r-t)*Math.PI/180,c=Math.sin(a/2)*Math.sin(a/2)+Math.cos(i)*Math.cos(o)*Math.sin(s/2)*Math.sin(s/2);return 2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c))*6371e3},roundToNearest:p,formatDistance:function(e){return e>1e3?(e/1e3).toFixed(0)+" km":e>=500?p(e,100)+" m":e>=100?p(e,50)+" m":p(e,10)+" m"},triangularNumber:function(e){return e*(e+1)/2},searchFloat:function(e){const t=e.match(/-?\d+(\.\d+)?/);if(!t)throw Error("No float found in "+e);return parseFloat(t[0])},binomialSample:function(e,t,n=Math.random){const r=e*t,i=Math.sqrt(e*t*(1-t)),o=(n()+n()+n()+n()+n()+n()-3)*Math.SQRT2,a=Math.round(r+i*o);return Math.max(0,Math.min(e,a))},toSignificantDigits:function(e,t){if(!e.includes("."))return e;if(0===parseFloat(e))return"0";const[n,r]=e.split("."),i=n.replace("-",""),o=i.length;if(o>=t)return n;if("0"!==i){const e=t-o,i=r.slice(0,e);return/[1-9]/.test(i)?`${n}.${i.replace(/0+$/,"")}`:n}const a=t+(r.match(/^0*/)?.[0].length??0);return`${n}.${r.slice(0,a)}`}},e.Promises={raceFulfilled:async function(e){return n(Promise.all(e.map(n)))},invert:n,runInParallelBatches:async function(e,t=1){const n=ot(e,t),r=[],i=n.map(async e=>{for(const t of e)r.push(await t())});return await Promise.all(i),r}},e.Dates={getTimestamp:function(e,t){const n=new Date(t?.now||Date.now()),r=t?.labels||ze,i=A(e)?e:new Date(e);if($e(n)===$e(i))return r.today(i.getUTCHours(),i.getUTCMinutes(),i.getUTCHours()>12);if($e(n)-$e(i)===1)return r.yesterday();const o=_e(i);return $e(n)-$e(i)<7?r[o.day]():r.weeks(Math.round((n.getTime()-i.getTime())/6048e5))},getTimeDelta:Pe,secondsToHumanTime:function(e,t=Fe){return Pe(0,{now:1e3*e,labels:t})},countCycles:function(e,t,n){const r=(n?.now??Date.now())-e;return{cycles:Math.floor(r/t),remaining:t/(n?.precision??1)-Math.ceil(r%t/(n?.precision??1))}},isoDate:function(e){return(e||new Date).toISOString().slice(0,10)},throttle:function(e,t){return(!Ue[e]||Date.now()>Ue[e])&&(Ue[e]=Date.now()+t,!0)},timeSince:function(e,t,n){return t=A(t)?t.getTime():t,((n=n?A(n)?n.getTime():n:Date.now())-t)/qe[e]},dateTimeSlug:function(e){return(e||new Date).toISOString().slice(0,19).replace(/T|:/g,"-")},unixTimestamp:function(e){return Math.ceil((e||Date.now())/1e3)},fromUtcString:function(e){const t=new Date(e);return new Date(t.getTime()-6e4*t.getTimezoneOffset())},fromMillis:function(e){return new Date(e)},getProgress:function(e,t,n,r){r||(r=Date.now());const i=r-e,o=i/t,a=o*n;return{deltaMs:i,progress:t/n,baseTimeMs:o,totalTimeMs:a,remainingTimeMs:a-i}},humanizeTime:Ce,humanizeProgress:function(e){return`[${Math.floor(100*e.progress)}%] ${Ce(e.deltaMs)} out of ${Ce(e.totalTimeMs)} (${Ce(e.remainingTimeMs)} left) [${Math.round(e.baseTimeMs)} ms each]`},createTimeDigits:De,mapDayNumber:Me,getDayInfoFromDate:_e,getDayInfoFromDateTimeString:function(e){return _e(new Date(e))},seconds:function(e){return 1e3*e},minutes:function(e){return 6e4*e},hours:function(e){return 36e5*e},days:function(e){return 864e5*e},make:function(e){const t=parseFloat(e);if(isNaN(t))throw Error("makeDate got NaN for input");const n=e.replace(/^-?[0-9.]+/,"").trim().toLowerCase(),r=""===n?1:Ve[n];if(!r)throw Error(`Unknown unit: "${n}"`);return Math.ceil(t*r)},normalizeTime:function(e){let[t,n]=e.split(":");x(parseInt(t,10))||(t="0"),x(parseInt(n,10))||(n="0");let r=tt(U(t),0,23),i=tt(U(n),0,59);return`${De(r)}:${De(i)}`},absoluteDays:$e},e.Objects={safeParse:function(e){try{return JSON.parse(e)}catch{return null}},deleteDeep:function(e,t){const n=J(t,"."),r=X(t,".");if(!n||!r)return;const i=h(e,n);i&&delete i[r]},getDeep:h,setDeep:f,incrementDeep:function(e,t,n=1){const r=h(e,t)||0;return f(e,t,r+n),r},ensureDeep:function(e,t,n){return h(e,t)||f(e,t,n)},replaceDeep:function(e,t,n){const r=h(e,t);if(!r)throw new Error("Key '"+t+"' does not exist.");return f(e,t,n),r},getFirstDeep:function(e,t,n){for(const n of t){const t=h(e,n);if(t)return t}if(n){const t=Object.values(e);if(t.length)return t[0]}return null},deepMergeInPlace:_,deepMerge2:function(e,t){const n={};return _(n,e),_(n,t),n},deepMerge3:function(e,t,n){const r={};return _(r,e),_(r,t),_(r,n),r},mapAllAsync:async function(e,t){const n=[];for(const r of e)n.push(await t(r));return n},cloneWithJson:function(e){return JSON.parse(JSON.stringify(e))},sortObject:Ke,sortArray:He,sortAny:We,deepEquals:Ze,deepEqualsEvery:function(...e){for(let t=1;t<e.length;t++)if(!Ze(e[t-1],e[t]))return!1;return!0},runOn:function(e,t){return t(e),e},ifPresent:function(e,t){e&&t(e)},zip:V,zipSum:function(e){return V(e,(e,t)=>e+t)},removeEmptyArrays:function(e){for(const t of Object.keys(e))(y(e[t])||Array.isArray(e[t])&&e[t].every(e=>null==e))&&delete e[t];return e},removeEmptyValues:function(e){for(const t of Object.entries(e))(null===t[1]||void 0===t[1]||v(t[1])&&R(t[1]))&&delete e[t[0]];return e},flatten:function(e,t=!1,n){return rt({},e,n||"",!1,t)},unflatten:function e(t){if(!m(t))return t;const n=Array.isArray(t)?[]:{};for(const[r,i]of Object.entries(t))Array.isArray(i)?f(n,r,i.map(t=>e(t))):f(n,r,i);return n},match:function(e,t,n){return t[e]?t[e]:n},sort:st,map:function(e,t){const n={};for(const r of Object.entries(e))n[r[0]]=t(r[1]);return n},mapIterable:function(e,t){const n=[];let r=0;for(const i of e)n.push(t(i,r++));return n},filterKeys:function(e,t){const n={};for(const[r,i]of Object.entries(e))t(r)&&(n[r]=i);return n},filterValues:function(e,t){const n={};for(const[r,i]of Object.entries(e))t(i)&&(n[r]=i);return n},rethrow:async function(e,t){try{return await e()}catch{throw t}},setSomeOnObject:function(e,t,n){null!=n&&(e[t]=n)},setSomeDeep:function(e,t,n,r){const i=h(n,r);null!=i&&f(e,t,i)},flip:function(e){const t={};for(const[n,r]of Object.entries(e))t[r]=n;return t},getAllPermutations:function(e){const t=Object.keys(e),n=t.map(t=>e[t].length),r=n.reduce((e,t)=>e*t);let i=1;const o=[1];for(let e=0;e<n.length-1;e++)i*=n[e],o.push(i);const a=[];for(let n=0;n<r;n++){const r={};for(let i=0;i<t.length;i++){const a=e[t[i]],s=Math.floor(n/o[i])%a.length;r[t[i]]=a[s]}a.push(r)}return a},countTruthyValues:function(e){return Object.values(e).filter(e=>e).length},transformToArray:function(e){const t=[],n=Object.keys(e),r=e[n[0]].length;for(let i=0;i<r;i++){const r={};for(const t of n)r[t]=e[t][i];t.push(r)}return t},setMulti:function(e,t,n){for(const r of e)r[t]=n},incrementMulti:function(e,t,n=1){for(const r of e)r[t]+=n},createBidirectionalMap:function(){return{map:new Map,keys:[]}},createTemporalBidirectionalMap:function(){return{map:new Map,keys:[]}},pushToBidirectionalMap:ut,unshiftToBidirectionalMap:function(e,t,n,r=100){if(e.map.has(t)){const n=e.keys.indexOf(t);e.keys.splice(n,1)}if(e.map.set(t,n),e.keys.unshift(t),e.keys.length>r){const t=e.keys.shift();t&&e.map.delete(t)}},addToTemporalBidirectionalMap:function(e,t,n,r,i=100){ut(e,t,{validUntil:Date.now()+r,data:n},i)},getFromTemporalBidirectionalMap:function(e,t){const n=e.map.get(t);return n&&n.validUntil>Date.now()?n.data:null},createStatefulToggle:function(e){let t;return n=>{const r=n===e&&t!==e;return t=n,r}},diffKeys:function(e,t){const n=Object.keys(e),r=Object.keys(t);return{uniqueToA:n.filter(e=>!r.includes(e)),uniqueToB:r.filter(e=>!n.includes(e))}},pickRandomKey:Je,mapRandomKey:function(e,t){const n=Je(e);return e[n]=t(e[n]),n},fromObjectString:function(e){return e=(e=(e=(e=(e=(e=(e=(e=(e=(e=(e=e.replace(/\r\n/g,"\n")).replace(/(\w+)\((.+)\)/g,(e,t,n)=>`${t}(${n.replaceAll(",",",")})`)).replace(/(,)(\s+})/g,"$2")).replace(/\.\.\..+?,/g,"")).replace(/({\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',")).replace(/(,\s+)([a-zA-Z]\w+),/g,"$1$2: '$2',")).replace(/:(.+)\?(.+):/g,(e,t,n)=>`: (${t.trim()} && ${n.trim()}) ||`)).replace(/([a-zA-Z0-9]+)( ?: ?{)/g,'"$1"$2')).replace(/([a-zA-Z0-9]+) ?: ?(.+?)(,|\n|})/g,(e,t,n,r)=>`"${t}":"${n.trim()}"${r}`)).replace(/("'|'")/g,'"')).replaceAll(",",","),JSON.parse(e)},toQueryString:Oe,parseQueryString:function(e){const t={},n=e.split("&");for(const e of n){const[n,r]=e.split("=");n&&r&&(t[n]=decodeURIComponent(r))}return t},hasKey:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},selectMax:function(e,t){let n=null,r=-1/0;for(const[i,o]of Object.entries(e)){const e=t(o);e>r&&(r=e,n=i)}return n?[n,e[n]]:null},reposition:function(e,t,n,r){const i=e.find(e=>e[t]===n),o=e.find(e=>e[t]===n+r);i&&o?(i[t]=n+r,o[t]=n):i&&(i[t]=n+r),e.sort((e,n)=>P(e[t])-P(n[t])),e.forEach((e,n)=>e[t]=n+1)},unwrapSingleKey:function(e){const t=Object.keys(e);if(1===t.length)return e[t[0]];throw new Error("Expected object to have a single key")},parseKeyValues:function(e,t=":"){return Object.fromEntries(e.map(e=>Y(e,t)).map(e=>e[0]&&e[1]?[ne(e[0]),ne(e[1])]:null).filter(e=>e))},errorMatches:function(e,t){if(!e)return!1;const n=e.message;return"string"==typeof n&&n.includes(t)}},e.Types={isFunction:b,isObject:m,isStrictlyObject:g,isEmptyArray:y,isEmptyObject:function(e){return g(e)&&0===Object.keys(e).length},isUndefined:w,isString:v,isNumber:x,isBoolean:E,isDate:A,isBlank:R,isId:S,isIntegerString:I,isHexString:k,isUrl:N,isNullable:function(e,t){return null==t||e(t)},asString:z,asHexString:function(e,t){if(!k(e))throw new TypeError(`Expected hex string${t?.name?` for ${t.name}`:""}, got: `+e);if(t?.strictPrefix&&!e.startsWith("0x"))throw new TypeError(`Expected hex string with 0x prefix${t?.name?` for ${t.name}`:""}, got: `+e);const n=e.replace(/^0x/,"");if(n.length%2!=0&&!t?.uneven)throw RangeError(`Expected even number of hex digits${t?.name?` for ${t.name}`:""}; got: `+e);if(t&&t.byteLength&&n.length!==2*t.byteLength)throw RangeError(`Expected hex string${t?.name?` for ${t.name}`:""} of byte length ${t.byteLength}; got: `+n);return`0x${n}`},asSafeString:function(e,t){if(!z(e,t).split("").every(e=>"_"===e||se(e)))throw new TypeError(`Expected safe string${t?.name?` for ${t.name}`:""}, got: `+e);return e},asIntegerString:function(e,t){if(!I(e))throw new TypeError(`Expected integer string${t?.name?` for ${t.name}`:""}, got: `+e);const n=BigInt(e);if(t&&(t.min&&n<t.min||t.max&&n>t.max))throw RangeError(`Expected integer string${t?.name?` for ${t.name}`:""} in range: ${t.min??"-inf"}..${t.max??"inf"}; got: `+n);return e},asNumber:P,asFunction:function(e,t){if(!b(e))throw new TypeError(`Expected function${t?.name?` for ${t.name}`:""}, got: `+e);return e},asInteger:U,asBoolean:function(e,t){if("true"===e)return!0;if("false"===e)return!1;if(!E(e))throw new TypeError(`Expected boolean${t?.name?` for ${t.name}`:""}, got: `+e);return e},asDate:function(e,t){if(!A(e))throw new TypeError(`Expected date${t?.name?` for ${t.name}`:""}, got: `+e);return e},asNullableString:function(e){return R(e)?null:e},asEmptiableString:function(e,t){if(!v(e))throw new TypeError(`Expected string${t?.name?` for ${t.name}`:""}, got: `+e);return e},asId:function(e,t){if(S(e))return e;const n=parseInt(e,10);if(!S(n))throw new TypeError(`Expected id${t?.name?` for ${t.name}`:""}, got: `+e);return n},asTime:function(e,t){if(!v(e))throw new TypeError(`Expected time${t?.name?` for ${t.name}`:""}, got: `+e);const n=e.split(":");if(2!==n.length)throw new TypeError(`Expected time${t?.name?` for ${t.name}`:""}, got: `+e);const r=parseInt(n[0],10),i=parseInt(n[1],10);if(!x(r)||!x(i)||r<0||r>23||i<0||i>59)throw new TypeError(`Expected time, got${t?.name?` for ${t.name}`:""}: `+e);return`${String(r).padStart(2,"0")}:${String(i).padStart(2,"0")}`},asArray:function(e,t){if(!Array.isArray(e))throw new TypeError(`Expected array${t?.name?` for ${t.name}`:""}, got: `+e);return e},asObject:q,asNullableObject:function(e,t){return null===e?null:q(e,t)},asStringMap:function(e,t){const n=q(e,t);for(const r of Object.keys(n))if(!v(n[r]))throw new TypeError(`Expected string map${t?.name?` for ${t.name}`:""}, got: `+e);return n},asNumericDictionary:function(e,t){const n=q(e),r=Object.keys(n),i=Object.values(n);if(!r.every(v)||!i.every(x))throw new TypeError(`Expected numeric dictionary${t?.name?` for ${t.name}`:""}, got: `+e);return n},asUrl:function(e,t){if(!N(e))throw new TypeError(`Expected url${t?.name?` for ${t.name}`:""}, got: `+e);return e},asEmptiable:function(e,t){return""===t?void 0:e(t)},asNullable:function(e,t){return null==t?null:e(t)},asOptional:function(e,t){return null==t?void 0:e(t)},enforceObjectShape:M,enforceArrayShape:function(e,t){return e.every(e=>M(e,t))},isPng:pt,isJpg:mt,isWebp:gt,isImage:function(e){return pt(e)||mt(e)||gt(e)}},e.Strings={tokenizeByCount:function(e,t){return at(e,Math.ceil(e.length/t))},tokenizeByLength:at,searchHex:function(e,t){const n=new RegExp(`[0-9a-f]{${t}}`,"i"),r=e.match(n);return r?r[0]:null},searchSubstring:function(e,t,n=T){const r=Q(e,n);for(const e of r)if(t(e))return e;return null},randomHex:function(e,t=Math.random){let n="";for(let r=0;r<e;r++)n+=$[Math.floor(16*t())];return n},randomLetter:function(e,t=Math.random){let n="";for(let r=0;r<e;r++)n+=B[Math.floor(26*t())];return n},randomAlphanumeric:function(e,t=Math.random){let n="";for(let r=0;r<e;r++)n+=O[Math.floor(62*t())];return n},randomRichAscii:function(e,t=Math.random){let n="";for(let r=0;r<e;r++)n+=D[Math.floor(89*t())];return n},randomUnicode:function(e,t=Math.random){let n="";for(let r=0;r<e;r++)n+=C[Math.floor(t()*C.length)];return n},includesAny:function(e,t){return t.some(t=>e.includes(t))},slugify:G,normalForm:function(e){return G(e).replaceAll("-","")},enumify:function(e){return G(e).replace(/-/g,"_").toUpperCase()},escapeHtml:function(e){return e.replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")},decodeHtmlEntities:function(e){let t=e.replace(/&#(\d+);/g,(e,t)=>String.fromCharCode(t)).replace(/&#x(\d+);/g,(e,t)=>String.fromCharCode(parseInt(t,16)));for(const[e,n]of Object.entries(H))t=t.replaceAll(e,n);return t},after:Z,afterLast:X,before:W,beforeLast:J,betweenWide:function(e,t,n){const r=J(e,n);return r?Z(r,t):null},betweenNarrow:function(e,t,n){const r=Z(e,t);return r?W(r,n):null},getPreLine:function(e){return e.replace(/ +/g," ").replace(/^ /gm,"")},containsWord:Ie,containsWords:function(e,t,n){return"any"===n?t.some(t=>Ie(e,t)):t.every(t=>Ie(e,t))},joinUrl:Ge,getFuzzyMatchScore:K,sortByFuzzyScore:function(e,t){return e.filter(e=>K(e,t)).sort((e,n)=>K(n,t)-K(e,t))},splitOnce:Y,splitAll:Q,randomize:function(e,t=Math.random){return e.replace(/\{(.+?)\}/g,(e,n)=>u(n.split("|"),t))},expand:function e(t){const n=t.match(/\{(.+?)\}/);if(!n||!n.index)return[t];const r=n[1].split(","),i=t.slice(0,n.index),o=t.slice(n.index+n[0].length);let a=[];for(const t of r){const n=e(i+t+o);a=a.concat(n)}return a},shrinkTrim:ne,capitalize:re,decapitalize:ie,csvEscape:function(e){return e.match(/"|,/)?`"${e.replace(/"/g,'""')}"`:e},parseCsv:function(e,t=",",n='"'){const r=[];let i="",o=!1;const a=e.split("");for(const e of a)e!==t||o?e!==n||(i||o)&&!o?i+=e:o=!o:(r.push(i),i="");return r.push(i),r},surroundInOut:function(e,t){return t+e.split("").join(t)+t},getExtension:ee,getBasename:te,normalizeEmail:function(e){let[t,n]=e.split("@");t=ne(t.replaceAll(".","").toLowerCase()).replaceAll(" ","");const[r]=t.split("+");if(!r||!n||-1===n.indexOf(".")||n.indexOf(".")===n.length-1)throw new Error("Invalid email");return n=ne(n.toLowerCase()).replaceAll(" ",""),`${r}@${n}`},normalizeFilename:function(e){const t=te(e),n=ee(e);return n?`${t}.${n}`:t},parseFilename:function(e){const t=te(e),n=ee(e);return{basename:t,extension:n,filename:n?`${t}.${n}`:t}},camelToTitle:function(e){return re(e.replace(/([A-Z])/g," $1"))},slugToTitle:function(e){return e.split("-").map(re).join(" ")},slugToCamel:function(e){return ie(e.split("-").map(re).join(""))},joinHumanly:function(e,t=", ",n=" and "){return e&&e.length?1===e.length?e[0]:2===e.length?`${e[0]}${n}${e[1]}`:`${e.slice(0,e.length-1).join(t)}${n}${e[e.length-1]}`:""},findWeightedPair:ye,extractBlock:we,extractAllBlocks:function(e,t){const n=[];let r=t.wordBoundary?fe(e,[`${t.opening} `,`${t.opening}\n`],t.start||0):e.indexOf(t.opening,t.start||0);for(;;){if(-1===r)return n;const i=we(e,{...t,start:r});if(!i)return n;n.push(i),r=t.wordBoundary?fe(e,[`${t.opening} `,`${t.opening}\n`],r+i.length):e.indexOf(t.opening,r+i.length)}},replaceBlocks:function(t,n,r){let i=0;for(;;){const o=e.Strings.extractBlock(t,{...r,start:i});if(!o)return t;const a=n(o);i=t.indexOf(o,i)+a.length,t=t.replace(o,a)}},indexOfEarliest:fe,lastIndexOfBefore:ge,parseHtmlAttributes:function(e){const t={},n=e.match(/([a-z\-]+)="([^"]+)"/g);if(n)for(const e of n){const[n,r]=Y(e,"=");t[n]=r.slice(1,r.length-1)}return t},readNextWord:ke,readWordsAfterAll:function(e,t,n=[]){const r=he(e,t),i=[];for(const o of r)i.push(ke(e,o+t.length,n));return i},resolveVariables:function(e,t,n="$",r=":"){for(const i in t)e=Te(e,i,t[i],n,r);return e=Be(e)},resolveVariableWithDefaultSyntax:Te,resolveRemainingVariablesWithDefaults:Be,isLetter:oe,isDigit:ae,isLetterOrDigit:se,isValidObjectPathCharacter:function(e){return se(e)||"."===e||"["===e||"]"===e||"_"===e},insert:function(e,t,n,r,i){return e.slice(0,t)+r+e.slice(t,t+n)+i+e.slice(t+n)},indexOfRegex:le,allIndexOf:he,lineMatches:de,linesMatchInOrder:function(e,t,n=!0){let r=0;for(const i of t){let t=!1;for(;!t&&r<e.length;)de(e[r],i,n)&&(t=!0),r++;if(!t)return!1}return!0},represent:function e(t,n="json",r=0){if(t&&b(t.represent)){const e=t.represent();if(v(e))return"json"===n&&0===r?JSON.stringify(e):e}if(m(t,!1)){if(r>1)return"[object Object]";if("json"===n){if(Array.isArray(t)){const n=t.map(t=>e(t,"json",r+1));return 0===r?JSON.stringify(n):n}const n={};t.message&&(n.message=e(t.message,"json",r+1));for(const[i,o]of Object.entries(t))n[i]=e(o,"json",r+1);return 0===r?JSON.stringify(n):n}if("key-value"===n){const n=Object.keys(t);return t.message&&!n.includes("message")&&n.unshift("message"),n.map(n=>`${n}=${JSON.stringify(e(t[n],"json",r+1))}`).join(" ")}}return w(t)&&(t="undefined"),0===r?JSON.stringify(t):t},resolveMarkdownLinks:function(e,t){let n=e.indexOf("](");for(;-1!==n;){const r=ge(e,"[",n),i=e.indexOf(")",n);if(-1!==r&&-1!==i){const[n,o]=e.slice(r+1,i).split("]("),a=t(n,o);e=e.slice(0,r)+a+e.slice(i+1)}n=e.indexOf("](",n+1)}return e},buildUrl:function(e,t,n){return Ge([e,t])+Oe(n||{})},isChinese:function(e){return/^[\u4E00-\u9FA5]+$/.test(e)},replaceBetweenStrings:function(e,t,n,r,i=!0){const o=e.indexOf(t),a=e.indexOf(n,o+t.length);if(-1===o||-1===a)throw Error("Start or end not found");return i?e.substring(0,o+t.length)+r+e.substring(a):e.substring(0,o)+r+e.substring(a+n.length)},describeMarkdown:function(e){let t="p";return e.startsWith("#")?(t="h1",e=e.slice(1).trim()):e.startsWith("-")&&(t="li",e=e.slice(1).trim()),{type:t,isCapitalized:e[0]===e[0].toUpperCase(),hasPunctuation:/[.?!]$/.test(e),endsWithColon:/:$/.test(e)}},isBalanced:function(e,t="(",n=")"){let r=0,i=0;for(;i<e.length;)if(e.startsWith(t,i)?(r++,i+=t.length):e.startsWith(n,i)?(r--,i+=n.length):i++,r<0)return!1;return t===n?r%2==0:0===r},textToFormat:function(e){let t=(e=e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")).length;for(;(e=e.replace(/(\w+)[\s,']+\w+/g,"$1")).length!==t;)t=e.length;return e=(e=(e=e.replaceAll(/[A-Z][a-zA-Z0-9]*/g,"A")).replaceAll(/[a-z][a-zA-Z0-9]*/g,"a")).replaceAll(/[\u4E00-\u9FA5]+/g,"Z")},splitFormatting:function(e,t){const n=[];let r=0;for(;r<e.length;){const i=e.indexOf(t,r);if(-1===i){n.push({string:e.slice(r),symbol:null});break}const o=e.indexOf(t,i+t.length);if(i>r&&-1!==o&&n.push({string:e.slice(r,i),symbol:null}),-1===o){n.push({string:e.slice(r),symbol:null});break}n.push({string:e.slice(i+t.length,o),symbol:t}),r=o+t.length}return n},splitHashtags:function(e){const t=[];let n=0;for(;n<e.length;){const r=me(e,n);if(-1===r){t.push({string:e.slice(n),symbol:null});break}const i=pe(e,r+1);if(-1===i){t.push({string:e.slice(n,r),symbol:null}),t.push({string:e.slice(r+1),symbol:"#"});break}r>n&&t.push({string:e.slice(n,r),symbol:null}),t.push({string:e.slice(r+1,i),symbol:"#"}),n=i}return t},splitUrls:function(e){const t=[];let n=0;for(;n<e.length;){const r=fe(e,["http://","https://"],n);if(-1===r){t.push({string:e.slice(n),symbol:null});break}const i=fe(e,[" ","\n"],r);if(-1===i){r>n&&t.push({string:e.slice(n,r),symbol:null}),t.push({string:e.slice(r),symbol:"http"});break}r>n&&t.push({string:e.slice(n,r),symbol:null}),t.push({string:e.slice(r,i),symbol:"http"}),n=i}return t},route:function(e,t){const n=e.split("/").filter(e=>e),r=t.split("/").filter(e=>e);if(n.length!==r.length)return null;const i={};for(let e=0;e<n.length;e++){const t=n[e];if(t.startsWith(":"))i[t.slice(1)]=r[e];else if(t!==r[e])return null}return i},explodeReplace:Ae,generateVariants:function(t,n,r,i=Math.random){const o=e.Arrays.shuffle(n.map(t=>({variants:e.Arrays.shuffle(t.variants.map(e=>e),i),avoid:t.avoid})),i),a=[];for(const e of o){const n=e.variants.filter(t=>t!==e.avoid),i=n.find(e=>t.includes(e));if(i&&(L(a,Ae(t,i,n)),a.length>=r))break}if(a.length<r)for(const e of o){const n=e.variants.find(e=>t.includes(e));if(n&&(L(a,Ae(t,n,e.variants)),a.length>=r))break}return a.slice(0,r)},replaceWord:function(e,t,n,r=!1){const i=new RegExp(r?`(?<=\\s|^)${t}(?=\\s|$)`:`\\b${t}\\b`,"g");return e.replace(i,n)},replacePascalCaseWords:function(e,t){return e.replace(/\b[A-Z][a-zA-Z0-9]*\b/g,e=>e.toUpperCase()===e?e:t(e))},stripHtml:function(e){return e.replace(/<[^>]*>/g,"")},breakLine:Re,measureTextWidth:function(e,t={}){return[...e].reduce((e,n)=>e+(t[n]||1),0)},toLines:function(e,t,n={}){const r=[];let i="",o=0;for(let a=0;a<e.length;a++){const s=e[a];if(i+=s,o+=n[s]||1,o>t){const{line:e,rest:t}=Re(i);r.push(e),i=t,o=t.split("").map(e=>n[e]||1).reduce((e,t)=>e+t,0)}}return i&&r.push(i),r},levenshteinDistance:function(e,t){const n=[];for(let t=0;t<=e.length;t++)n[t]=[t];for(let e=0;e<=t.length;e++)n[0][e]=e;for(let r=1;r<=e.length;r++)for(let i=1;i<=t.length;i++){const o=e[r-1]===t[i-1]?0:1;n[r][i]=Math.min(n[r-1][i]+1,n[r][i-1]+1,n[r-1][i-1]+o)}return n[e.length][t.length]},findCommonPrefix:Se,findCommonDirectory:function(e){const t=Se(e),n=t.lastIndexOf("/");return-1===n?"":t.slice(0,n+1)}},e.Assertions={asEqual:function(e,t){if(e!==t)throw Error(`Expected [${e}] to equal [${t}]`);return[e,t]},asTrue:function(e){if(!0!==e)throw Error(`Expected [true], got: [${e}]`);return e},asTruthy:function(e){if(!e)throw Error(`Expected truthy value, got: [${e}]`);return e},asFalse:function(e){if(!1!==e)throw Error(`Expected [false], got: [${e}]`);return e},asFalsy:function(e){if(e)throw Error(`Expected falsy value, got: [${e}]`);return e},asEither:function(e,t){if(!t.includes(e))throw Error(`Expected any of [${t.join(", ")}], got: [${e}]`);return e}},e.Cache={get:async function(e,t,n){const r=Date.now(),i=je.get(e);if(i&&i.validUntil>r)return i.value;const o=await n(),a=r+t;return je.set(e,{value:o,validUntil:a}),o},delete:function(e){je.delete(e)},deleteExpired:function(){const e=Date.now();for(const[t,n]of je.entries())n.validUntil<=e&&je.delete(t)},size:function(){return je.size}},e.Vector={addPoint:Zt,subtractPoint:function(e,t){return{x:e.x-t.x,y:e.y-t.y}},multiplyPoint:Jt,normalizePoint:function(e){const t=Math.sqrt(e.x*e.x+e.y*e.y);return{x:e.x/t,y:e.y/t}},pushPoint:Xt,filterCoordinates:Qt,findCorners:function(e,t,n,r){const i=[{x:0,y:0},{x:n,y:0},{x:0,y:r},{x:n,y:r}];for(let t=0;t<e.length;t++)for(let n=0;n<e[0].length;n++){const r=on(e,t,n);for(const e of r)i.some(t=>t.x===e.x&&t.y===e.y)||i.push(e)}return i.map(e=>({x:e.x*t,y:e.y*t}))},findLines:function(e,t){const n=Qt(e,(t,n)=>0===e[t][n]&&0!==e[t][n+1],"row-first").map(e=>({...e,dx:1,dy:0})),r=Qt(e,(t,n)=>0===e[t][n]&&0!==e[t][n-1],"row-first").map(e=>({...e,dx:1,dy:0})),i=Qt(e,(t,n)=>0===e[t][n]&&0!==e[t-1]?.[n],"column-first").map(e=>({...e,dx:0,dy:1})),o=Qt(e,(t,n)=>0===e[t][n]&&0!==e[t+1]?.[n],"column-first").map(e=>({...e,dx:0,dy:1}));return n.forEach(e=>e.y++),o.forEach(e=>e.x++),[...ct([...i,...o],(e,t)=>e.x===t.x&&e.y-1===t.y),...ct([...r,...n],(e,t)=>e.y===t.y&&e.x-1===t.x)].map(e=>({start:e[0],end:l(e)})).map(e=>({start:Jt(e.start,t),end:Jt(Zt(e.end,{x:e.start.dx,y:e.start.dy}),t)}))},raycast:cn,raycastCircle:function(e,t,n){const r=an(e,n),i=[];for(const n of r){const r=cn(e,t,n-.001),o=cn(e,t,n+.001);r&&i.push(r),o&&i.push(o)}return i},getLineIntersectionPoint:sn}}(th)),th),rh=Vr(nh);rh.Arrays,rh.Assertions;const ih=rh.Binary;rh.Cache,rh.Dates,rh.Elliptic,rh.Numbers,rh.Objects,rh.Pagination,rh.Promises,rh.Random,rh.Strings,rh.System,rh.Types,rh.Optional,rh.Vector,rh.PubSubChannel,rh.Chunk,rh.MerkleTree,rh.FixedPointNumber,rh.Lazy,rh.AsyncLazy,rh.AsyncQueue,rh.Uint8ArrayReader,rh.Uint8ArrayWriter,rh.TrieRouter,rh.RollingValueProvider;class oh{constructor(e,t,n){this.encryptionKey=e,this.keyLen=e.length,this.padding=t,this.initCtr=n,this.index=0}key(){return this.encryptionKey}encrypt(e){const t=e.length;let n=t;if(this.padding>0){if(t>this.padding)throw new Error(`data length ${t} longer than padding ${this.padding}`);n=this.padding}const r=new Uint8Array(n);return this.transform(e,r),r}decrypt(e){const t=e.length;if(this.padding>0&&t!==this.padding)throw new Error(`data length ${t} different than padding ${this.padding}`);const n=new Uint8Array(t);return this.transform(e,n),n}reset(){this.index=0}transform(e,t){const n=e.length;for(let r=0;r<n;r+=this.keyLen){const i=Math.min(this.keyLen,n-r);this.transcrypt(this.index,e.subarray(r,r+i),t.subarray(r,r+i)),this.index++}t.length>n&&ah(t.subarray(n),this.encryptionKey,n)}transcrypt(e,t,n){const r=new Uint8Array(4);new DataView(r.buffer).setUint32(0,e+this.initCtr,!0);const i=new Uint8Array(this.encryptionKey.length+4);i.set(this.encryptionKey),i.set(r,this.encryptionKey.length);const o=ih.keccak256(i),a=ih.keccak256(o),s=t.length;for(let e=0;e<s;e++)n[e]=t[e]^a[e];n.length>s&&ah(n.subarray(s),this.encryptionKey,e*this.keyLen+s)}}function ah(e,t,n){if(0===e.length)return;let r=0,i=n;for(;r<e.length;){const n=new Uint8Array(4);new DataView(n.buffer).setUint32(0,i,!0);const o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length);const a=ih.keccak256(o),s=Math.min(a.length,e.length-r);e.set(a.subarray(0,s),r),r+=s,i++}}function sh(e=32){const t=new Uint8Array(e);var n;return 0!==(n=t).length&&crypto.getRandomValues(n),t}function ch(e){return new oh(e,0,Math.floor(128))}function uh(e){return new oh(e,4096,0)}class lh{encryptChunk(e,t){const n=t||sh(32);return{key:n,encryptedSpan:ch(n).encrypt(e.subarray(0,8)),encryptedData:uh(n).encrypt(e.subarray(8))}}}function dh(){return new lh}function hh(e,t){const n=ch(e).decrypt(t.subarray(0,8)),r=uh(e).decrypt(t.subarray(8)),i=new Uint8Array(8+r.length);return i.set(n),i.set(r,8),i}const fh=4096;function ph(e){const t=e.slice(0,Oi.LENGTH),n=function(e){if(e.length>fh)throw new Error(`payload size ${e.length} exceeds maximum chunk payload size 4096`);const t=new Uint8Array(fh);t.set(e);let n=ih.partition(t,32);for(;n.length>1;){const e=[];for(let t=0;t<n.length;t+=2){const r=n[t],i=n[t+1],o=ih.concatBytes(r,i),a=ih.keccak256(o);e.push(a)}n=e}return n[0]}(e.slice(Oi.LENGTH)),r=ih.keccak256(ih.concatBytes(t,n));return new Ti(r)}const mh=new TextEncoder;function gh(e,t){if(e instanceof Uint8Array||(e=mh.encode(e)),e.length<1||e.length>Yd)throw new RangeError(`payload size ${e.length} exceeds limits [1, 4096]`);let n;n=t instanceof Oi?t:Oi.fromBigInt(BigInt(e.length));const r=ih.concatBytes(n.toUint8Array(),e),i=ph(r);return{data:r,span:n,payload:new wi(e),address:i}}const yh=new TextEncoder;function wh(e,t){if(e instanceof Uint8Array||(e=yh.encode(e)),e.length<1||e.length>Yd)throw new RangeError(`payload size ${e.length} exceeds limits [1, 4096]`);const n=Oi.fromBigInt(BigInt(e.length)),r=ih.concatBytes(n.toUint8Array(),e),i=dh(),{key:o,encryptedSpan:a,encryptedData:s}=i.encryptChunk(r,t),c=ih.concatBytes(a,s),u=ph(c),l=new Ti(ih.concatBytes(u.toUint8Array(),o));return{data:c,encryptionKey:o,span:n,payload:new wi(c.slice(Oi.LENGTH)),address:u,reference:l}}function bh(e){const t=[];for(let n=0;n<e.length;n+=4096)t.push(e.slice(n,Math.min(n+4096,e.length)));return t}async function vh(e,t){if(1===e.length)return new Ti(e[0].address);const n=[];for(let r=0;r<e.length;r+=64){const i=e.slice(r,Math.min(r+64,e.length)),o=new Uint8Array(32*i.length);i.forEach((e,t)=>{o.set(e.address,32*t)});const a=gh(o);n.push({address:a.address.toUint8Array()}),await t(a)}return n.length>1?vh(n,t):new Ti(n[0].address)}let xh=class{constructor(e){this.cursor=0,this.buffer=e}write(e){throw new Error("SimpleUint8ArrayWriter.write() not implemented")}max(){return this.buffer.length}};class Eh{constructor(e){this.chunk=e,this.span=e.span.toBigInt(),this.writer=new xh(e.data)}hash(){return this.chunk.address.toUint8Array()}build(){return this.chunk.data}}async function Ah(e,t,n,r,i){const{bee:o,stamper:a}=e;let s=n?.tag;if(!s){s=(await o.createTag()).uid}const c=bh(t);let u=c.length,l=0;const d=()=>{r&&r({total:u,processed:l})},h=[],f={...n,tag:s};for(const e of c){const t=gh(e);h.push({address:t.address.toUint8Array()}),await Rh(o,a,t,f,i),l++,d()}let p;return p=1===h.length?new Ti(h[0].address):await vh(h,async e=>{await Rh(o,a,e,f,i),u++,l++,d()}),{reference:p.toHex(),tagUid:s}}async function Rh(e,t,n,r,i){const o={deferred:!1,pin:!1,...r};if(t){const r=new Eh(n),a=t.stamp(r),s=await e.uploadChunk(a,n.data,o,i),c=n.address.toHex(),u=s.reference.toHex();return c!==u&&console.error(`[ADDRESS MISMATCH] local=${c} bee=${u}`),s}throw new Error("No stamper or batch ID available")}async function Sh(e,t){if(1===e.length){const t=new Uint8Array(64);return t.set(e[0].address,0),t.set(e[0].key,32),new Ti(t)}const n=[];for(let r=0;r<e.length;r+=64){const i=e.slice(r,Math.min(r+64,e.length)),o=i.reduce((e,t)=>e+t.span,0n),a=new Uint8Array(4096);i.forEach((e,t)=>{a.set(e.address,64*t),a.set(e.key,64*t+32)});const s=Oi.fromBigInt(o).toUint8Array(),c=ih.concatBytes(s,a),u=dh(),{key:l,encryptedSpan:d,encryptedData:h}=u.encryptChunk(c),f=ih.concatBytes(d,h),p=await ph(f);await t(f),n.push({address:p.toUint8Array(),key:l,span:o})}if(n.length>1)return Sh(n,t);const r=new Uint8Array(64);return r.set(n[0].address,0),r.set(n[0].key,32),new Ti(r)}class Ih{constructor(e){this.cursor=0,this.buffer=e}write(e){throw new Error("SimpleUint8ArrayWriter.write() not implemented")}max(){return this.buffer.length}}class kh{constructor(e){this.encryptedChunk=e,this.span=e.span.toBigInt(),this.writer=new Ih(e.data)}hash(){return this.encryptedChunk.address.toUint8Array()}build(){return this.encryptedChunk.data}}async function Th(e,t,n,r,i,o){const{bee:a,stamper:s}=e;if(!s)throw new Error("No authentication method available");let c=r?.tag;if(!c){c=(await a.createTag()).uid}const u=bh(t);let l=u.length,d=0;const h=()=>{i&&i({total:l,processed:d})},f=[],p=[],m={...r,tag:c};for(const e of u){const t=wh(e,n);f.push({address:t.address.toUint8Array(),key:t.encryptionKey,span:BigInt(e.length)}),await Bh(a,s,t,m,o),p.push(t.address.toUint8Array()),d++,h()}let g;if(1===f.length){const e=new Uint8Array(64);e.set(f[0].address,0),e.set(f[0].key,32),g=new Ti(e)}else g=await Sh(f,async e=>{const t=ph(e);p.push(t.toUint8Array());const n=s.stamp({hash:()=>t.toUint8Array(),build:()=>e,span:0n,writer:void 0});await a.uploadChunk(n,e,m,o),l++,d++,h()});return{reference:g.toHex(),tagUid:c,chunkAddresses:p}}async function Bh(e,t,n,r,i){const o=new kh(n),a=t.stamp(o);await async function(e,t,n,r,i){const o={deferred:!1,pin:!1,...r};await e.uploadChunk(t,n,o,i)}(e,a,n.data,r,i)}async function Oh(e,t,n,r){const i=ih.concatBytes(t.batchId.toUint8Array(),t.index,t.timestamp,t.signature),o={"content-type":"application/octet-stream","swarm-postage-stamp":ih.uint8ArrayToHex(i)};r?.tag&&(o["swarm-tag"]=r.tag.toString()),void 0!==r?.deferred&&(o["swarm-deferred-upload"]=r.deferred.toString()),void 0!==r?.pin&&(o["swarm-pin"]=r.pin.toString());const a=await fetch(`${e.url}/chunks`,{method:"POST",headers:o,body:n});if(!a.ok){const e=await a.text();throw new Error(`Chunk upload failed: ${a.status} ${a.statusText} - ${e}`)}const s=await a.json();return new Ti(s.reference)}function Dh(e,t){return new Ti(ih.keccak256(ih.concatBytes(e.toUint8Array(),t)))}async function Ch(e,t,n,r,i,o,a){if(i.length<1||i.length>4096)throw new Error(`Invalid data length: ${i.length} (expected 1-4096)`);const s=wh(i,o),c=n.publicKey().address(),u=ih.concatBytes(r.toUint8Array(),s.address.toUint8Array()),l=n.sign(u),d=ih.concatBytes(r.toUint8Array(),l.toUint8Array(),s.data),h=Dh(r,c.toUint8Array());let f=a?.tag;if(!f){f=(await e.createTag()).uid}const p=t.stamp({hash:()=>h.toUint8Array(),build:()=>d,span:0n,writer:void 0}),m={tag:f,deferred:!1,pin:!1,...a};return await Oh(e,p,d,m),{socAddress:h.toUint8Array(),encryptionKey:s.encryptionKey,tagUid:f}}async function $h(e,t,n,r,i,o){if(i.length<1||i.length>4096)throw new Error(`Invalid data length: ${i.length} (expected 1-4096)`);const a=gh(i),s=new Uint8Array(4104);s.set(a.data);const c=n.publicKey().address(),u=ih.concatBytes(r.toUint8Array(),a.address.toUint8Array()),l=n.sign(u),d=ih.concatBytes(r.toUint8Array(),l.toUint8Array(),s),h=Dh(r,c.toUint8Array());let f=o?.tag;if(!f){f=(await e.createTag()).uid}const p=t.stamp({hash:()=>h.toUint8Array(),build:()=>d,span:0n,writer:void 0}),m={tag:f,deferred:!1,pin:!1,...o};return await Oh(e,p,d,m),{socAddress:h.toUint8Array(),tagUid:f}}async function zh(e,t,n,r,i,o){if(i.length<1||i.length>4096)throw new Error(`Invalid data length: ${i.length} (expected 1-4096)`);const a=gh(i),s=a.data,c=n.publicKey().address(),u=ih.concatBytes(r.toUint8Array(),a.address.toUint8Array()),l=n.sign(u),d=Dh(r,c.toUint8Array());let h=o?.tag;if(!h){h=(await e.createTag()).uid}const f=t.stamp({hash:()=>d.toUint8Array(),build:()=>s,span:0n,writer:void 0}),p=ih.concatBytes(f.batchId.toUint8Array(),f.index,f.timestamp,f.signature),m=ih.uint8ArrayToHex(p),g=`${e.url}/soc/${c.toHex()}/${r.toHex()}?sig=${l.toHex()}`,y={"content-type":"application/octet-stream","swarm-postage-stamp":m};h&&(y["swarm-tag"]=h.toString()),void 0!==o?.deferred&&(y["swarm-deferred-upload"]=o.deferred.toString()),void 0!==o?.pin&&(y["swarm-pin"]=o.pin.toString());const w=await fetch(g,{method:"POST",headers:y,body:s});if(!w.ok){const e=await w.text();throw new Error(`SOC upload failed: ${w.status} ${w.statusText} - ${e}`)}return{socAddress:d.toUint8Array(),tagUid:h}}function Fh(e){const t=e.replace(/^0x/i,"").toLowerCase();if(!/^[0-9a-f]{40}$/.test(t))throw new Error(`Invalid hex address: expected 40 hex characters (with optional 0x prefix), got "${e}"`);return t}function Ph(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);return Number(t.getBigUint64(0,!0))}function Uh(e,t){return new Ti(ih.keccak256(ih.concatBytes(e.toUint8Array(),t.toUint8Array())))}function qh(e,t,n,r){const i=new ki(e.slice(0,32)),o=$i.fromSlice(e,32),a=e.slice(97),s=ph(a),c=ih.concatBytes(i.toUint8Array(),s.toUint8Array()),u=o.recoverPublicKey(c).address();if(!u.equals(n))throw new Error("SOC owner mismatch");const l=Uh(i,u);if(!ih.equals(t.toUint8Array(),l.toUint8Array()))throw new Error("SOC data does not match given address");let d,h,f;if(r){const e=hh(r,a);d=e.slice(0,8);const t=Ph(d);h=e.slice(8,8+t),f=ih.concatBytes(i.toUint8Array(),o.toUint8Array(),d,h)}else{d=e.slice(97,105);const t=Ph(d);if(t>4096)throw new Error("SOC payload length is invalid; this chunk likely requires decryption");h=e.slice(105,105+t),f=e}const p=Ph(d);return{data:f,identifier:i.toHex(),signature:o.toHex(),span:p,payload:h,address:t.toHex(),owner:u.toHex()}}function Nh(e,t,n){const r=[],i=n?64:Qd,o=Math.floor(e.length/i),a=Math.ceil(t/Yd),s=Math.min(o,a);for(let t=0;t<s;t++){const o=t*i;if(o+i>e.length)break;const a=e.slice(o,o+Qd);if(a.every(e=>0===e))break;if(n){const t=e.slice(o+Qd,o+64);r.push({address:a,encryptionKey:t})}else r.push({address:a})}return r}async function Mh(e,t,n){const r=ih.uint8ArrayToHex(t.address),i=await e.downloadChunk(r,void 0,n);let o;o=t.encryptionKey?hh(t.encryptionKey,i):i;return{span:Ph(o.slice(0,8)),payload:o.slice(8)}}async function _h(e,t,n,r,i,o){const{span:a,payload:s}=await Mh(e,t,o);if(i(),a<=Yd)return s.slice(0,a);const c=Nh(s,a,n);if(0===c.length)throw new Error("No valid references found in intermediate chunk");const u=new Array(c.length);for(let t=0;t<c.length;t+=r){const a=c.slice(t,Math.min(t+r,c.length)),s=await Promise.all(a.map(t=>_h(e,t,n,r,i,o)));for(let e=0;e<s.length;e++)u[t+e]=s[e]}const l=u.reduce((e,t)=>e+t.length,0),d=new Uint8Array(l);let h=0;for(const e of u)d.set(e,h),h+=e.length;return d}async function Vh(e,t,n,r,i){const o=function(e){const t=Ld(e);if(t.length===Qd)return{address:t};if(64===t.length)return{address:t.slice(0,Qd),encryptionKey:t.slice(Qd)};throw new Error(`Invalid reference length: ${t.length}, expected 32 or 64`)}(t),a=void 0!==o.encryptionKey,{span:s,payload:c}=await Mh(e,o,i);if(s<=Yd)return r&&r({total:1,processed:1}),c.slice(0,s);const u=function(e){if(e<=Yd)return 1;const t=Math.ceil(e/Yd);let n=0,r=t;for(;r>1;){const e=64;r=Math.ceil(r/e),n+=r}return t+n}(s);let l=1;const d=()=>{l++,r&&r({total:u,processed:l})};r&&r({total:u,processed:1});const h=Nh(c,s,a);if(0===h.length)throw new Error("No valid references found in root chunk");const f=new Array(h.length);for(let t=0;t<h.length;t+=64){const n=h.slice(t,Math.min(t+64,h.length)),r=await Promise.all(n.map(t=>_h(e,t,a,64,d,i)));for(let e=0;e<r.length;e++)f[t+e]=r[e]}const p=f.reduce((e,t)=>e+t.length,0),m=new Uint8Array(p);let g=0;for(const e of f)m.set(e,g),g+=e.length;return r&&r({total:l,processed:l}),m}async function Lh(e,t,n,r){const i=new Ii(t),o=Uh(new ki(n),i);return qh(await e.downloadChunk(o.toHex(),void 0,r),o,i)}async function jh(e,t,n,r,i){const o=new Ii(t),a=Uh(new ki(n),o),s="string"==typeof r?Ld(r):r;return qh(await e.downloadChunk(a.toHex(),void 0,i),a,o,s)}async function Gh(e,t){const n=await async function e(n,r){for(const t of n.forks.values())await e(t.node,!1);const i=await n.marshal(),o=await t(i,r);return n.selfAddress=Ld(o.reference),o}(e,!0);return{rootReference:n.reference,tagUid:n.tagUid}}async function Kh(e,t,n){const r=await Vh(e,t,0,void 0,n),i=mu.unmarshalFromData(r,Ld(t));return await async function t(r){for(const i of r.forks.values()){if(!i.node.selfAddress)throw new Error("Fork node selfAddress is not set");const o=jd(i.node.selfAddress),a=await Vh(e,o,0,void 0,n),s=mu.unmarshalFromData(a,i.node.selfAddress);i.node.targetAddress=s.targetAddress,i.node.forks=s.forks,i.node.obfuscationKey=s.obfuscationKey,i.node.path=i.prefix,i.node.parent=r;for(const e of i.node.forks.values())e.node.parent=i.node;await t(i.node)}}(i),i}async function Hh(e,t){const n=await async function e(n,r){for(const t of n.forks.values())await e(t.node,!1);const i=wh(await n.marshal()),o=await t(i.data,i.address.toUint8Array(),r),a=new Uint8Array(64);return a.set(i.address.toUint8Array(),0),a.set(i.encryptionKey,32),n.selfAddress=a,o}(e,!0);return{rootReference:jd(e.selfAddress),tagUid:n.tagUid}}const Wh="chunks",Zh="metadata";class Jh{async open(){if(!this.db)return new Promise((e,t)=>{const n=indexedDB.open("swarm-utilization-store",1);n.onerror=()=>{t(new Error(`Failed to open IndexedDB: ${n.error}`))},n.onsuccess=()=>{this.db=n.result,e()},n.onupgradeneeded=e=>{const t=e.target.result;if(!t.objectStoreNames.contains(Wh)){const e=t.createObjectStore(Wh,{keyPath:["batchId","chunkIndex"]});e.createIndex("batchId","batchId",{unique:!1}),e.createIndex("lastAccess","lastAccess",{unique:!1})}t.objectStoreNames.contains(Zh)||t.createObjectStore(Zh,{keyPath:"batchId"})}})}async getChunk(e,t){return await this.open(),new Promise((n,r)=>{const i=this.db.transaction([Wh],"readonly").objectStore(Wh).get([e,t]);i.onsuccess=()=>{const r=i.result;r&&this.touchChunk(e,t).catch(e=>{console.warn("[UtilizationStore] Failed to update lastAccess:",e)}),n(r)},i.onerror=()=>{r(new Error(`Failed to get chunk: ${i.error}`))}})}async putChunk(e){return await this.open(),new Promise((t,n)=>{const r=this.db.transaction([Wh],"readwrite").objectStore(Wh),i={...e,lastAccess:Date.now()},o=r.put(i);o.onsuccess=()=>t(),o.onerror=()=>{n(new Error(`Failed to put chunk: ${o.error}`))}})}async getAllChunks(e){return await this.open(),new Promise((t,n)=>{const r=this.db.transaction([Wh],"readonly").objectStore(Wh).index("batchId").getAll(e);r.onsuccess=()=>{const e=r.result;e.sort((e,t)=>e.chunkIndex-t.chunkIndex),t(e)},r.onerror=()=>{n(new Error(`Failed to get all chunks: ${r.error}`))}})}async clearBatch(e){return await this.open(),new Promise((t,n)=>{const r=this.db.transaction([Wh,Zh],"readwrite"),i=r.objectStore(Wh),o=r.objectStore(Zh),a=i.index("batchId").openCursor(e);a.onsuccess=()=>{const e=a.result;e&&(e.delete(),e.continue())},o.delete(e),r.oncomplete=()=>t(),r.onerror=()=>{n(new Error(`Failed to clear batch: ${r.error}`))}})}async touchChunk(e,t){return await this.open(),new Promise((n,r)=>{const i=this.db.transaction([Wh],"readwrite"),o=i.objectStore(Wh),a=o.get([e,t]);a.onsuccess=()=>{const e=a.result;e&&(e.lastAccess=Date.now(),o.put(e))},i.oncomplete=()=>n(),i.onerror=()=>{r(new Error(`Failed to touch chunk: ${i.error}`))}})}async getMetadata(e){return await this.open(),new Promise((t,n)=>{const r=this.db.transaction([Zh],"readonly").objectStore(Zh).get(e);r.onsuccess=()=>t(r.result),r.onerror=()=>{n(new Error(`Failed to get metadata: ${r.error}`))}})}async putMetadata(e){return await this.open(),new Promise((t,n)=>{const r=this.db.transaction([Zh],"readwrite").objectStore(Zh).put(e);r.onsuccess=()=>t(),r.onerror=()=>{n(new Error(`Failed to put metadata: ${r.error}`))}})}close(){this.db&&(this.db.close(),this.db=void 0)}}async function Xh(e,t={}){const n=t.maxAge??6048e5,r=t.maxChunks??640;await e.open();const i=e.db;return new Promise((e,t)=>{const o=i.transaction([Wh],"readwrite"),a=o.objectStore(Wh),s=a.index("lastAccess"),c=Date.now()-n,u=[],l=s.openCursor();l.onsuccess=()=>{const e=l.result;if(e){const t=e.value;u.push({key:e.primaryKey,lastAccess:t.lastAccess}),e.continue()}else{for(const e of u)e.lastAccess<c&&a.delete(e.key);if(u.length>r){u.sort((e,t)=>e.lastAccess-t.lastAccess);const e=u.slice(0,u.length-r);for(const t of e)a.delete(t.key)}}},o.oncomplete=()=>e(),o.onerror=()=>{t(new Error(`Failed to evict entries: ${o.error}`))}})}function Yh(e){const t=ih.keccak256(e);return ih.uint8ArrayToHex(t)}const Qh=65536,ef=16,tf=4,nf=4,rf=4096,of=24;function af(e){if(e.length<2)throw new Error("Chunk address must be at least 2 bytes");return e[0]<<8|e[1]}function sf(e){return e.map(e=>{const t=e.address.toUint8Array();return{chunk:e,bucket:af(t),slot:0}})}const cf=64,uf=1024;function lf(e){if(e<0||e>=Qh)throw new Error(`Invalid bucket index: ${e} (must be 0-65535)`);return Math.floor(e/uf)}function df(e,t){if(t<0||t>=cf)throw new Error(`Invalid chunk index: ${t} (must be 0-63)`);const n=t*uf,r=n+uf;return gf(e.slice(n,r))}function hf(e,t,n){if(t<0||t>=cf)throw new Error(`Invalid chunk index: ${t} (must be 0-63)`);if(n.length!==rf)throw new Error(`Invalid chunk data length: ${n.length} (expected 4096)`);const r=yf(n);if(r.length!==uf)throw new Error(`Invalid chunk counters length: ${r.length} (expected 1024)`);const i=t*uf;e.set(r,i)}class ff{constructor(){this.dirtyChunks=new Set}markDirty(e){const t=lf(e);this.dirtyChunks.add(t)}markClean(e){this.dirtyChunks.delete(e)}getDirtyChunks(){return Array.from(this.dirtyChunks).sort((e,t)=>e-t)}hasDirtyChunks(){return this.dirtyChunks.size>0}clear(){this.dirtyChunks.clear()}get count(){return this.dirtyChunks.size}}function pf(e){const t=`batch-utilization:${e.toHex()}`,n=new TextEncoder,r=ih.keccak256(n.encode(t));return new zi(r)}async function mf(e,t,n,r,i){const o=wh(r,i).address.toUint8Array(),a=(await e.createTag()).uid;return await async function(e,t,n,r,i){if(n.length<1||n.length>4096)throw new Error(`Invalid payload length: ${n.length} (expected 1-4096)`);if(32!==r.length)throw new Error(`Invalid encryption key length: ${r.length} (expected 32)`);const o=wh(n,r);await Bh(e,t,o,i)}(e,t,r,i,{deferred:!1,tag:a}),o}function gf(e){const t=new ArrayBuffer(4*e.length),n=new DataView(t);for(let t=0;t<e.length;t++)n.setUint32(4*t,e[t],!0);return new Uint8Array(t)}function yf(e){if(e.length%4!=0)throw new Error("Byte array length must be a multiple of 4");const t=new Uint32Array(e.length/4),n=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let e=0;e<t.length;e++)t[e]=n.getUint32(4*e,!0);return t}function wf(e){const t=[];for(let n=0;n<e.length;n+=rf){const r=Math.min(n+rf,e.length),i=e.slice(n,r),o=new Uint8Array(rf);o.set(i),t.push(gh(o))}return t}function bf(e,t){const n=new Uint8Array(t);let r=0;for(const i of e){const e=i.data,o=Math.min(e.length,t-r);if(n.set(e.slice(0,o),r),r+=o,r>=t)break}return n}function vf(e){const t=new Uint32Array(Qh);t.fill(4);const n=[];for(let e=0;e<cf;e++)n.push({index:e,contentHash:"",lastUpload:0,dirty:!0});return{batchId:e,dataCounters:t,chunks:n,topic:pf(e),lastSync:Date.now()}}function xf(e){return Math.pow(2,e-16)}function Ef(e,t){return e<xf(t)}function Af(e,t,n){const r=new Uint32Array(e.dataCounters);for(const e of t){const t=af(e.address.toUint8Array()),i=r[t];if(!Ef(i,n))throw new Error(`Bucket ${t} is full (slot ${i})`);r[t]++}const i=wf(gf(r)),o=new Uint32Array(Qh),a=[];for(const e of i){const t=af(e.address.toUint8Array()),n=o[t];a.push({chunk:e,bucket:t,slot:n}),o[t]++}return{dataCounters:r,utilizationChunks:a}}function Rf(e,t,n,r){return Eu.fromState(e,t,n,r)}function Sf(e){const t=new Uint32Array(Qh);for(const{bucket:n,slot:r}of e)t[n]=Math.max(t[n],r);return t}function If(e){const t=new Uint32Array(Qh);for(let n=0;n<Qh;n++)t[n]=e[n];return t}async function kf(e,t){const{cache:n}=t,{bee:r,owner:i,encryptionKey:o}=t,a=await n.getAllChunks(e.toHex());if(a.length===cf)try{const t=new Uint32Array(Qh),n=[];for(const e of a)hf(t,e.chunkIndex,e.data),n.push({index:e.chunkIndex,contentHash:e.contentHash,lastUpload:e.lastAccess,dirty:!1});return{batchId:e,dataCounters:t,chunks:n,topic:pf(e),lastSync:Date.now()}}catch(e){console.warn("[BatchUtil] Failed to reconstruct from cache:",e)}const s=new Uint32Array(Qh),c=[];for(let e=0;e<cf;e++){const t=a.find(t=>t.chunkIndex===e);if(t){hf(s,e,t.data),c.push({index:e,contentHash:t.contentHash,lastUpload:t.lastAccess,dirty:!1});continue}const n=new Uint32Array(uf);n.fill(4);const r=gf(n);hf(s,e,r),c.push({index:e,contentHash:"",lastUpload:0,dirty:!0})}return{batchId:e,dataCounters:s,chunks:c,topic:pf(e),lastSync:Date.now()}}async function Tf(e,t){const{bee:n,stamper:r,encryptionKey:i,cache:o,tracker:a}=t,s=a.getDirtyChunks();if(0!==s.length){for(const t of s){const s=e.chunks[t],c=df(e.dataCounters,t);try{const u=await mf(n,r,0,c,i),l=ih.uint8ArrayToHex(u);if(s.contentHash===l){a.markClean(t);continue}s.contentHash=l,s.lastUpload=Date.now(),s.dirty=!1,await o.putChunk({batchId:e.batchId.toHex(),chunkIndex:t,data:c,contentHash:l,lastAccess:Date.now()}),a.markClean(t)}catch(e){throw console.error(`[BatchUtil] Failed to upload chunk ${t}:`,e),e}}e.lastSync=Date.now()}}async function Bf(e,t,n,r){const i=await kf(e,r),o=new ff;for(const e of t){const t=af(e.address.toUint8Array()),r=i.dataCounters[t];if(!Ef(r,n))throw new Error(`Bucket ${t} is full (slot ${r})`);i.dataCounters[t]++,o.markDirty(t)}const a=o.getDirtyChunks();for(const e of a)i.chunks[e].dirty=!0;return{state:i,tracker:o}}function Of(e,t){const n=xf(t),r=Math.max(...Array.from(e.dataCounters));return Math.min(1,r/n)}class Df{get signer(){return this.stamper.signer}get buckets(){return this.stamper.buckets}get maxSlot(){return this.stamper.maxSlot}constructor(e,t,n,r,i){this.dirty=!1,this.dirtyBuckets=new Set,this.stamper=e,this.batchId=t,this.depth=n,this.cache=r,this.utilizationState=i}static async create(e,t,n,r,i,o){const a=vf(t);let s;try{const e=await r.getAllChunks(t.toHex());if(e.length>0)for(const t of e)hf(a.dataCounters,t.chunkIndex,t.data)}catch(e){console.warn("[UtilizationAwareStamper] Failed to load state from cache, starting with fresh state:",e)}s=If(a.dataCounters);const c=Eu.fromState(e,t,s,n);return new Df(c,t,n,r,a)}stamp(e){const t=this.stamper.stamp(e),n=new DataView(t.index.buffer,t.index.byteOffset,t.index.byteLength).getUint32(0,!1);return this.utilizationState.dataCounters[n]++,this.dirtyBuckets.add(n),this.dirty=!0,t}getState(){return this.stamper.getState()}async flush(){if(!this.dirty)return;const e=new Set;for(const t of this.dirtyBuckets){const n=lf(t);e.add(n),this.utilizationState.chunks[n].dirty=!0}const t=new ff;for(const n of e){const e=n*uf;t.markDirty(e)}try{for(const t of e){const e=df(this.utilizationState.dataCounters,t);await this.cache.putChunk({batchId:this.batchId.toHex(),chunkIndex:t,data:e,contentHash:Yh(e),lastAccess:Date.now()}),this.utilizationState.chunks[t].dirty=!1}this.utilizationState.lastSync=Date.now()}catch(e){throw console.error("[UtilizationAwareStamper] Failed to flush to cache:",e),e}this.dirtyBuckets.clear(),this.dirty=!1}getUtilizationState(){return this.utilizationState}applyUtilizationUpdate(e){for(const{index:t,value:n}of e)t>=0&&t<Qh&&n>this.utilizationState.dataCounters[t]&&(this.utilizationState.dataCounters[t]=n);const t=If(this.utilizationState.dataCounters);this.stamper=Eu.fromState(this.stamper.signer,this.batchId,t,this.depth)}getBucketUpdatesForBroadcast(){return Array.from(this.dirtyBuckets).map(e=>({index:e,value:this.utilizationState.dataCounters[e]}))}}const Cf=pr({version:nr().int().nonnegative(),data:cr()});class $f{getItem(e){if("undefined"!=typeof window&&window.localStorage)return window.localStorage.getItem(e)??void 0}setItem(e,t){"undefined"!=typeof window&&window.localStorage&&window.localStorage.setItem(e,t)}removeItem(e){"undefined"!=typeof window&&window.localStorage&&window.localStorage.removeItem(e)}}class zf{constructor(){this.storage=new Map}getItem(e){return this.storage.get(e)}setItem(e,t){this.storage.set(e,t)}removeItem(e){this.storage.delete(e)}clear(){this.storage.clear()}}class Ff{constructor(e){this.listeners=new Set,this.options=e}subscribe(e){return this.listeners.add(e),this.boundStorageHandler||this.setupStorageEventListener(),()=>{this.listeners.delete(e),0===this.listeners.size&&this.cleanupStorageEventListener()}}setupStorageEventListener(){"undefined"!=typeof window&&(this.boundStorageHandler=e=>{if(e.key!==this.options.key)return;const t=this.load();this.notifyListeners(t)},window.addEventListener("storage",this.boundStorageHandler))}cleanupStorageEventListener(){this.boundStorageHandler&&"undefined"!=typeof window&&(window.removeEventListener("storage",this.boundStorageHandler),this.boundStorageHandler=void 0)}notifyListeners(e){for(const t of this.listeners)try{t(e)}catch(e){console.error(`[${this.options.loggerName??"Storage"}] Listener error:`,e)}}load(){const e=this.options.storage.getItem(this.options.key);if(!e)return[];try{const t=JSON.parse(e);return this.parse(t)}catch(e){return console.error(`[${this.options.loggerName??"Storage"}] Load failed:`,e),[]}}parse(e){const t=Cf.safeParse(e),n=t.success?t.data.version:0,r=t.success?t.data.data:e,i=this.options.parsers[n];return i?i(r,n):(console.error(`[${this.options.loggerName??"Storage"}] No parser for version ${n}`),[])}save(e){try{const t=this.options.serializer?e.map(this.options.serializer):e,n={version:this.options.currentVersion,data:t};this.options.storage.setItem(this.options.key,JSON.stringify(n))}catch(e){console.error(`[${this.options.loggerName??"Storage"}] Save failed:`,e)}}clear(){this.options.storage.removeItem(this.options.key)}}function Pf(e){return new Ff({...e,storage:new $f})}function Uf(e){return new Ff({...e,storage:new zf})}function qf(e){return t=>{const n=e.safeParse(t);return n.success?n.data:(console.error("Parse failed:",n.error.format()),[])}}const Nf=e=>{const t=hr(Mu).safeParse(e);return t.success?t.data:(console.error("Parse failed:",t.error.format()),[])},Mf=e=>{const t=hr(_u).safeParse(e);return t.success?t.data:(console.error("Parse failed:",t.error.format()),[])},_f=e=>{const t=hr(Vu).safeParse(e);return t.success?t.data:(console.error("Parse failed:",t.error.format()),[])},Vf=e=>{const t=hr(Lu).safeParse(e);return t.success?t.data:(console.error("Parse failed:",t.error.format()),[])};function Lf(e){return"passkey"===e.type?{id:e.id.toString(),name:e.name,createdAt:e.createdAt,type:e.type,credentialId:e.credentialId,swarmEncryptionKey:e.swarmEncryptionKey,defaultPostageStampBatchID:e.defaultPostageStampBatchID?.toString()}:"agent"===e.type?{id:e.id.toString(),name:e.name,createdAt:e.createdAt,type:e.type,swarmEncryptionKey:e.swarmEncryptionKey,defaultPostageStampBatchID:e.defaultPostageStampBatchID?.toString()}:{id:e.id.toString(),name:e.name,createdAt:e.createdAt,type:e.type,ethereumAddress:e.ethereumAddress.toString(),encryptedMasterKey:Array.from(e.encryptedMasterKey.toUint8Array()),encryptionSalt:Array.from(e.encryptionSalt.toUint8Array()),encryptedSecretSeed:Array.from(e.encryptedSecretSeed.toUint8Array()),swarmEncryptionKey:e.swarmEncryptionKey,defaultPostageStampBatchID:e.defaultPostageStampBatchID?.toString()}}function jf(e){return{id:e.id,accountId:e.accountId.toString(),name:e.name,defaultPostageStampBatchID:e.defaultPostageStampBatchID?.toString(),createdAt:e.createdAt,settings:e.settings}}function Gf(e){return{appUrl:e.appUrl,appName:e.appName,lastConnectedAt:e.lastConnectedAt,identityId:e.identityId,appIcon:e.appIcon,appDescription:e.appDescription,connectedUntil:e.connectedUntil,appSecret:e.appSecret}}function Kf(e){return{accountId:e.accountId,batchID:e.batchID.toString(),signerKey:e.signerKey.toString(),utilization:e.utilization,usable:e.usable,depth:e.depth,amount:e.amount.toString(),bucketDepth:e.bucketDepth,blockNumber:e.blockNumber,immutableFlag:e.immutableFlag,exists:e.exists,batchTTL:e.batchTTL,createdAt:e.createdAt}}function Hf(){return Pf({key:"swarm-id-accounts",currentVersion:1,parsers:{1:Nf},serializer:Lf,loggerName:"AccountsStorage"})}function Wf(){return Pf({key:"swarm-id-identities",currentVersion:1,parsers:{1:Mf},serializer:jf,loggerName:"IdentitiesStorage"})}function Zf(){return Pf({key:"swarm-id-connected-apps",currentVersion:1,parsers:{1:_f},serializer:Gf,loggerName:"ConnectedAppsStorage"})}function Jf(e){const t=Zf(),n=t.load().map(t=>t.appUrl===e?{...t,lastConnectedAt:0,connectedUntil:void 0}:t);t.save(n)}function Xf(){return Pf({key:"swarm-id-postage-stamps",currentVersion:1,parsers:{1:Vf},serializer:Kf,loggerName:"PostageStampsStorage"})}function Yf(e){return{beeNodeUrl:e.beeNodeUrl,gnosisRpcUrl:e.gnosisRpcUrl}}function Qf(){return{load(){if("undefined"==typeof localStorage)return;const e=localStorage.getItem(Ju);if(e)try{return function(e){const t=Ku.safeParse(e);if(t.success)return t.data;console.error("[NetworkSettingsStorage] Parse failed:",t.error.format())}(JSON.parse(e))}catch(e){return void console.error("[NetworkSettingsStorage] Failed to parse stored data:",e)}},save(e){if("undefined"==typeof localStorage)return void console.warn("[NetworkSettingsStorage] localStorage not available");const t=Yf(e);localStorage.setItem(Ju,JSON.stringify(t))},clear(){"undefined"!=typeof localStorage&&localStorage.removeItem(Ju)}}}const ep=32;class tp{constructor(e,t){if(this.start=e,this.level=t,t<0||t>ep)throw new Error(`Epoch level must be between 0 and 32, got ${t}`)}async marshalBinary(){const e=new Uint8Array(9);return new DataView(e.buffer).setBigUint64(0,this.start,!1),e[8]=this.level,ih.keccak256(e)}next(e,t){return this.start+this.length()>t?this.childAt(t):np(t,e).childAt(t)}length(){return 1n<<BigInt(this.level)}parent(){const e=this.length()<<1n,t=this.start/e*e;return new tp(t,this.level+1)}left(){return new tp(this.start-this.length(),this.level)}childAt(e){const t=this.level-1,n=1n<<BigInt(t);let r=this.start;return(e&n)>0n&&(r|=n),new tp(r,t)}isLeft(){return 0n===(this.start&this.length())}toString(){return`${this.start}/${this.level}`}}function np(e,t){if(0n===t)return new tp(0n,ep);const n=e-t;let r=1n,i=0;for(;i<ep&&(r<n||e/r!==t/r);)r<<=1n,i++;return new tp(t/r*r,i)}function rp(e,t,n){return e?e.next(t,n):new tp(0n,ep)}async function ip(e,t,n){if(0n===e)return;const r=t>0n?t:0n,i=e>128n&&e-128n>r?e-128n:r;let o=e-1n;for(;o>=i;){try{const t=await n(e,new tp(o,0));if(t)return t}catch{}if(0n===o)break;o--}}class op{constructor(e,t,n){this.bee=e,this.topic=t,this.owner=n}async findAt(e,t=0n){const n=new tp(e,0);try{const t=await this.getEpochChunk(e,n);if(t)return t}catch{}const{epoch:r,chunk:i}=await this.common(e,t);if(!i&&r.level===ep)return;const o=await this.atEpoch(e,r,i);if(o)return o;try{if(void 0===await this.getEpochChunk(e,new tp(0n,ep)))return this.findPreviousLeaf(e,t)}catch{}}async common(e,t){let n=np(e,t);for(;;){try{const t=await this.getEpochChunk(e,n);if(t)return{epoch:n,chunk:t}}catch(e){}if(n.level===ep)return{epoch:n};n=n.parent()}}async atEpoch(e,t,n){let r;try{r=await this.getEpochChunk(e,t)}catch(e){return t.isLeft()?n:this.atEpoch(t.start-1n,t.left(),n)}if(!r){if(t.level>0){const r=await this.atEpoch(e,t.childAt(e),n);if(r)return r}return t.isLeft()?n:this.atEpoch(t.start-1n,t.left(),n)}return 0===t.level?r:this.atEpoch(e,t.childAt(e),r)}async getEpochChunk(e,t){const n={timeout:2e3},r=await t.marshalBinary(),i=ih.keccak256(ih.concatBytes(this.topic.toUint8Array(),r)),o=new Ti(ih.keccak256(ih.concatBytes(i,this.owner.toUint8Array()))),a=await this.bee.downloadChunk(o.toHex(),void 0,n),s=a.slice(97,105),c=new DataView(s.buffer,s.byteOffset,s.byteLength),u=Number(c.getBigUint64(0,!0)),l=a.slice(105,105+u);if(![40,48,72,80].includes(l.length))return void console.warn(`Unexpected feed payload length: ${l.length}. Expected 40, 48, 72, or 80 bytes.`);const d=48===l.length||80===l.length?8:0,h=l.slice(d,d+8);return new DataView(h.buffer,h.byteOffset,h.byteLength).getBigUint64(0,!1)>e?void 0:l.slice(d+8)}findPreviousLeaf(e,t){return ip(e,t,(e,t)=>this.getEpochChunk(e,t))}}class ap{constructor(e,t,n,r){this.bee=e,this.topic=t,this.owner=n,this.encryptionKey=r}async findAt(e,t=0n){const n=new tp(e,0);try{const t=await this.getEpochChunk(e,n);if(t)return t}catch{}const r=await this.findAtEpoch(e,new tp(0n,ep),void 0);if(r)return r;try{if(void 0===await this.getEpochChunk(e,new tp(0n,ep)))return this.findPreviousLeaf(e,t)}catch{}}async findAtEpoch(e,t,n){let r;try{r=await this.getEpochChunk(e,t)}catch(e){return t.isLeft()?n:this.findAtEpoch(t.start-1n,t.left(),n)}if(r)return 0===t.level?r:this.findAtEpoch(e,t.childAt(e),r);if(t.level>0){const r=await this.findAtEpoch(e,t.childAt(e),n);if(r)return r}return t.isLeft()?n:this.findAtEpoch(t.start-1n,t.left(),n)}async getEpochChunk(e,t){const n=await this.getEpochChunkWithMetadata(e,t);return n?.reference}async findAtWithMetadata(e){const t=new tp(e,0);try{const n=await this.getEpochChunkWithMetadata(e,t);if(n)return{reference:n.reference,epoch:t,timestamp:n.timestamp}}catch{}return this.findAtEpochWithMetadata(e,new tp(0n,ep),void 0)}async findAtEpochWithMetadata(e,t,n){let r;try{r=await this.getEpochChunkWithMetadata(e,t)}catch(e){return t.isLeft()?n:this.findAtEpochWithMetadata(t.start-1n,t.left(),n)}if(r){const n={reference:r.reference,epoch:t,timestamp:r.timestamp};return 0===t.level?n:this.findAtEpochWithMetadata(e,t.childAt(e),n)}if(t.level>0){const r=await this.findAtEpochWithMetadata(e,t.childAt(e),n);if(r)return r}return t.isLeft()?n:this.findAtEpochWithMetadata(t.start-1n,t.left(),n)}async getEpochChunkWithMetadata(e,t){const n={timeout:2e3},r=await t.marshalBinary(),i=ih.keccak256(ih.concatBytes(this.topic.toUint8Array(),r));let o;if(this.encryptionKey){o=(await jh(this.bee,this.owner,i,this.encryptionKey,n)).payload}else{const e=new Ti(ih.keccak256(ih.concatBytes(i,this.owner.toUint8Array()))),t=await this.bee.downloadChunk(e.toHex(),void 0,n),r=8,a=32+65,s=t.slice(a,a+r),c=new DataView(s.buffer,s.byteOffset,s.byteLength),u=Number(c.getBigUint64(0,!0)),l=a+r;o=t.slice(l,l+u)}if(![40,48,72,80].includes(o.length))return void console.warn(`Unexpected feed payload length: ${o.length}. Expected 40, 48, 72, or 80 bytes.`);const a=48===o.length||80===o.length?8:0,s=o.slice(a,a+8),c=new DataView(s.buffer,s.byteOffset,s.byteLength).getBigUint64(0,!1);return c>e?void 0:{reference:o.slice(a+8),timestamp:c}}findPreviousLeaf(e,t){return ip(e,t,(e,t)=>this.getEpochChunk(e,t))}}class sp{constructor(e,t,n){this.bee=e,this.topic=t,this.signer=n}async update(e,t,n,r,i){if(32!==t.length&&64!==t.length)throw new Error(`Reference must be 32 or 64 bytes, got ${t.length}`);const o=await this.calculateEpoch(e,i,r);return{socAddress:await this.uploadEpochChunk(o,e,t,n,r),epoch:{start:o.start,level:o.level},timestamp:e}}async calculateEpoch(e,t,n){if(t?.lastEpoch&&void 0!==t.lastTimestamp){return new tp(t.lastEpoch.start,t.lastEpoch.level).next(t.lastTimestamp,e)}const r=this.signer.publicKey().address(),i=new ap(this.bee,this.topic,r,n),o=await i.findAtWithMetadata(e);return o?o.epoch.next(o.timestamp,e):new tp(0n,ep)}getOwner(){return this.signer.publicKey().address()}async uploadEpochChunk(e,t,n,r,i){const o=await e.marshalBinary(),a=new ki(ih.keccak256(ih.concatBytes(this.topic.toUint8Array(),o))),s=new Uint8Array(8);new DataView(s.buffer).setBigUint64(0,t,!1);const c=ih.concatBytes(s,n);return(i?await Ch(this.bee,r,this.signer,a,c,i,{deferred:!1}):await zh(this.bee,r,this.signer,a,c,{deferred:!1})).socAddress}}function cp(e){return new op(e.bee,e.topic,e.owner)}function up(e){return new ap(e.bee,e.topic,e.owner,e.encryptionKey)}function lp(e){return new sp(e.bee,e.topic,e.signer)}const dp=cp;class hp{constructor(e,t,n){this.bee=e,this.topic=t,this.owner=n}async findAt(e,t=0n,n){for(let e=0n;;e++){if(!await this.indexExists(e,n))return{current:e>0n?e-1n:void 0,next:e}}}async indexExists(e,t){const n=function(e,t){const n=ih.numberToUint64(t,"BE");return ih.keccak256(ih.concatBytes(e.toUint8Array(),n))}(this.topic,e),r=function(e,t){return new Ti(ih.keccak256(ih.concatBytes(e,t.toUint8Array())))}(n,this.owner);try{return await this.bee.downloadChunk(ih.uint8ArrayToHex(r.toUint8Array()),void 0,t),!0}catch{return!1}}}class fp{constructor(e,t,n){this.syncFinder=new hp(e,t,n)}async findAt(e,t=0n,n){return this.syncFinder.findAt(e,t,n)}}const pp=5,mp=86400,gp=Math.floor(262144),yp="https://api.swarmscan.io/v1/postage-stamps/stats";async function wp(){const e=await fetch(yp);if(!e.ok)throw new Error(`Failed to fetch Swarmscan stats: ${e.status}`);return(await e.json()).pricePerGBPerMonth}function bp(e,t){const n=BigInt(e),r=1e16*t/gp;return 2592e3*(Number(n)/r)}function vp(e){if(void 0===e||e<=0)return"N/A";return`${Math.floor(e/mp)}d ${Math.floor(e%mp/3600)}h`}async function xp(e,t){const n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",method:"eth_getBlockByNumber",params:[`0x${t.toString(16)}`,!1],id:1})}),r=await n.json();if(r.error)throw new Error(`RPC error: ${r.error.message}`);if(!r.result)throw new Error(`Block ${t} not found`);return parseInt(r.result.timestamp,16)}function Ep(e,t){return e+t}function Ap(e,t,n,r){const i=new URLSearchParams;return i.set("origin",t),n&&(i.set("appName",n.name),n.description&&i.set("appDescription",n.description),n.icon&&i.set("appIcon",n.icon)),r?.challenge&&i.set("challenge",r.challenge),r?.agent&&i.set("agent",""),`${e}/connect#${i.toString()}`}const Rp=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),Sp=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),Ip=BigInt("0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"),kp=BigInt("0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8"),Tp=32,Bp=32;function Op(e,t){const n=e%t;return n>=0n?n:n+t}function Dp(e,t){let[n,r]=[Op(e,t),t],[i,o]=[1n,0n];for(;0n!==r;){const e=n/r;[n,r]=[r,n-e*r],[i,o]=[o,i-e*o]}if(1n!==n)throw new Error("Modular inverse does not exist");return Op(i,t)}function Cp(e,t,n,r){if(0n===e&&0n===t)return[n,r];if(0n===n&&0n===r)return[e,t];if(e===n&&0n===Op(t+r,Rp))return null;let i;if(e===n&&t===r){const n=Op(3n*e*e,Rp),r=Op(2n*t,Rp);i=Op(n*Dp(r,Rp),Rp)}else{const o=Op(r-t,Rp),a=Op(n-e,Rp);i=Op(o*Dp(a,Rp),Rp)}const o=Op(i*i-e-n,Rp);return[o,Op(i*(e-o)-t,Rp)]}function $p(e,t){return Cp(e,t,e,t)}function zp(e,t,n){if(0n===n)return null;let r=null,i=[e,t],o=Op(n,Sp);for(;o>0n;)1n&o&&(null===r?r=i:null!==i&&(r=Cp(r[0],r[1],i[0],i[1]))),null!==i&&(i=$p(i[0],i[1])),o>>=1n;return r}function Fp(e){let t=0n;for(const n of e)t=t<<8n|BigInt(n);return t}function Pp(e,t){const n=new Uint8Array(t);let r=e;for(let e=t-1;e>=0;e--)n[e]=Number(0xffn&r),r>>=8n;return n}function Up(e){if(32!==e.length)throw new Error("Private key must be 32 bytes");const t=Fp(e),n=zp(Ip,kp,t);if(null===n)throw new Error("Invalid private key");return{x:Pp(n[0],Tp),y:Pp(n[1],Tp)}}function qp(e,t,n){const r=function(e,t,n){if(32!==e.length)throw new Error("Private key must be 32 bytes");if(t.length!==Tp||n.length!==Tp)throw new Error("Public key coordinates must be 32 bytes each");const r=Fp(e),i=zp(Fp(t),Fp(n),r);if(null===i)throw new Error("ECDH computation resulted in point at infinity");return Pp(i[0],Tp)}(e,t,n),i=new Uint8Array(r.length+1);i.set(r),i[r.length]=0;const o=ih.keccak256(i),a=new Uint8Array(r.length+1);a.set(r),a[r.length]=1;return{lookupKey:o,accessKeyDecryptionKey:ih.keccak256(a)}}function Np(e,t){if(t.length!==Bp)throw new Error("Key must be 32 bytes");const n=new Uint8Array(e.length),r=Math.ceil(e.length/Bp);for(let i=0;i<r;i++){const r=new Uint8Array(t.length+4);r.set(t),r[t.length]=255&i,r[t.length+1]=i>>8&255,r[t.length+2]=i>>16&255,r[t.length+3]=i>>24&255;const o=ih.keccak256(r),a=ih.keccak256(o),s=i*Bp,c=Math.min(s+Bp,e.length);for(let t=s;t<c;t++)n[t]=e[t]^a[t-s]}return n}const Mp=Np;function _p(e){if(33!==e.length)throw new Error("Compressed public key must be 33 bytes");const t=e[0];if(2!==t&&3!==t)throw new Error("Invalid compressed public key prefix");const n=Fp(e.slice(1));let r=function(e,t,n){let r=1n;e=Op(e,n);for(;t>0n;)1n&t&&(r=Op(r*e,n)),t>>=1n,e=Op(e*e,n);return r}(Op(n*n*n+7n,Rp),(Rp+1n)/4n,Rp);return 0n==(1n&r)!==(2===t)&&(r=Rp-r),{x:Pp(n,Tp),y:Pp(r,Tp)}}function Vp(e,t){if(e.length!==Tp||t.length!==Tp)throw new Error("Public key coordinates must be 32 bytes each");const n=0n==(1n&Fp(t))?2:3,r=new Uint8Array(33);return r[0]=n,r.set(e,1),r}function Lp(){const e=new Uint8Array(Bp);return crypto.getRandomValues(e),e}function jp(e){const t={entries:{}};for(const n of e){const e=jd(n.lookupKey);t.entries[e]={reference:jd(n.encryptedAccessKey),metadata:{}}}const n=JSON.stringify(t);return(new TextEncoder).encode(n)}function Gp(e){const t=(new TextDecoder).decode(e),n=JSON.parse(t),r=[];for(const[e,t]of Object.entries(n.entries))r.push({lookupKey:Ld(e),encryptedAccessKey:Ld(t.reference)});return r}function Kp(e,t){return e.find(e=>{if(e.lookupKey.length!==t.length)return!1;for(let n=0;n<t.length;n++)if(e.lookupKey[n]!==t[n])return!1;return!0})}const Hp=65,Wp=(new TextEncoder).encode("act-grantee-list");function Zp(e){const t=ih.concatBytes(e,Wp);return ih.keccak256(t)}function Jp(e,t){const n=function(e){const t=new Uint8Array(e.length*Hp);for(let n=0;n<e.length;n++){const r=n*Hp;t[r]=4,t.set(e[n].x,r+1),t.set(e[n].y,r+1+32)}return t}(e);return function(e,t){return Np(e,Zp(t))}(n,t)}function Xp(e,t){const n=function(e,t){const n=Zp(t);return Mp(e,n)}(e,t);return function(e){if(0===e.length)return[];if(e.length%Hp!==0)throw new Error(`Invalid grantee list length: ${e.length} is not a multiple of 65`);const t=e.length/Hp,n=[];for(let r=0;r<t;r++){const t=r*Hp;if(4!==e[t])throw new Error(`Invalid public key prefix at index ${r}: expected 0x04, got 0x${e[t].toString(16)}`);const i=e.slice(t+1,t+1+32),o=e.slice(t+1+32,t+Hp);n.push({x:i,y:o})}return n}(n)}const Yp=BigInt("9223372036854775807"),Qp=new TextEncoder,em="encryptedglref";let tm=0;function nm(e){return(Yp-BigInt(e)).toString()}function rm(e){const t=BigInt(e);return Number(Yp-t)}function im(e,t,n,r){const i=nm(t),o=Ld(n),a=r?{[em]:r}:void 0;e.addFork(Qp.encode(i),o,a)}function om(e){const t=e.collect();if(0===t.length)return;t.sort((e,t)=>e.fullPathString.localeCompare(t.fullPathString));const n=t[0];return{timestamp:rm(n.fullPathString),metadata:{actReference:jd(n.targetAddress),encryptedGranteeListRef:n.metadata?.[em]}}}async function am(e,t){const n=await async function e(n,r){for(const t of n.forks.values())await e(t.node,!1);const i=await n.marshal(),o=await t(i,r);return n.selfAddress=Ld(o.reference),o}(e,!0);return{rootReference:n.reference,tagUid:n.tagUid}}function sm(e,t){return mu.unmarshalFromData(e,t)}async function cm(e,t){await async function e(n){for(const r of n.forks.values()){if(!r.node.selfAddress)throw new Error("Fork node selfAddress is not set");const n=jd(r.node.selfAddress),i=await t(n),o=mu.unmarshalFromData(i,r.node.selfAddress);r.node.targetAddress=o.targetAddress,r.node.forks=o.forks,r.node.obfuscationKey=o.obfuscationKey;for(const e of r.node.forks.values())e.node.parent=r.node;await e(r.node)}}(e)}function um(){const e=Math.floor(Date.now()/1e3);return e<=tm?(tm+=1,tm):(tm=e,e)}function lm(e){let t=!0;for(let n=32;n<e.length;n++)if(0!==e[n]){t=!1;break}return jd(t?e.slice(0,32):e)}async function dm(e,t,n,r,i,o,a){const s=Lp(),c=Np(t,s),u=Up(n),l=[],d=qp(n,u.x,u.y);l.push({lookupKey:d.lookupKey,encryptedAccessKey:Np(s,d.accessKeyDecryptionKey)});for(const e of r){const t=qp(n,e.x,e.y);l.push({lookupKey:t.lookupKey,encryptedAccessKey:Np(s,t.accessKeyDecryptionKey)})}const h=jp(l),f=!0===i?.beeCompatible,p=f?await Ah(e,h,i,void 0,o):await Th(e,h,void 0,i,void 0,o),m=Jp(r,n),g=await Th(e,m,void 0,i,void 0,o),y=um(),w=new mu;im(w,y,p.reference,g.reference);const b=await am(w,async(t,n)=>f?await Ah(e,t,i,n?a:void 0,o):await Th(e,t,void 0,i,n?a:void 0,o)),v=b.rootReference,x=b.tagUid,E=Vp(u.x,u.y);return{encryptedReference:jd(c),historyReference:v,granteeListReference:g.reference,publisherPubKey:jd(E),actReference:p.reference,tagUid:x}}async function hm(e,t,n,r,i,o,a){const s=_p(Ld(r)),c=sm(await Vh(e,n,0,void 0,a),Ld(n));await cm(c,async t=>Vh(e,t,0,void 0,a));const u=o?function(e,t){const n=nm(t),r=e.collect();if(0===r.length)return;r.sort((e,t)=>e.fullPathString.localeCompare(t.fullPathString));for(const e of r)if(e.fullPathString>=n)return{timestamp:rm(e.fullPathString),metadata:{actReference:jd(e.targetAddress),encryptedGranteeListRef:e.metadata?.[em]}};const i=r[r.length-1];return{timestamp:rm(i.fullPathString),metadata:{actReference:jd(i.targetAddress),encryptedGranteeListRef:i.metadata?.[em]}}}(c,o):om(c);if(!u)throw new Error("No ACT entry found in history");const l=u.metadata.actReference,d=Gp(await Vh(e,l,0,void 0,a)),h=qp(i,s.x,s.y);let f=Kp(d,h.lookupKey);if(!f){const e=Up(i),n=qp(i,e.x,e.y);if(f=Kp(d,n.lookupKey),!f)throw new Error("Access denied: no ACT entry found for this key");const r=Mp(f.encryptedAccessKey,n.accessKeyDecryptionKey),o=Ld(t);return lm(Mp(o,r))}const p=Mp(f.encryptedAccessKey,h.accessKeyDecryptionKey),m=Ld(t);return lm(Mp(m,p))}async function fm(e,t,n,r,i,o,a){const{bee:s}=e,c=64===t.length,u=sm(await Vh(s,t,0,void 0,o),Ld(t));await cm(u,async e=>Vh(s,e,0,void 0,o));const l=om(u);if(!l)throw new Error("History manifest is empty");const d=Gp(await Vh(s,l.metadata.actReference,0,void 0,o)),h=Up(n),f=qp(n,h.x,h.y),p=Kp(d,f.lookupKey);if(!p)throw new Error("Cannot find publisher entry in ACT");const m=Mp(p.encryptedAccessKey,f.accessKeyDecryptionKey),g=[...d];for(const e of r){const t=qp(n,e.x,e.y);g.push({lookupKey:t.lookupKey,encryptedAccessKey:Np(m,t.accessKeyDecryptionKey)})}let y=[];if(l.metadata.encryptedGranteeListRef){y=Xp(await Vh(s,l.metadata.encryptedGranteeListRef,0,void 0,o),n)}const w=[...y,...r],b=jp(g),v=c?await Ah(e,b,i,void 0,o):await Th(e,b,void 0,i,void 0,o),x=Jp(w,n),E=await Th(e,x,void 0,i,void 0,o);im(u,um(),v.reference,E.reference);const A=await am(u,async(t,n)=>c?await Ah(e,t,i,n?a:void 0,o):await Th(e,t,void 0,i,n?a:void 0,o)),R=A.rootReference,S=A.tagUid;return{historyReference:R,granteeListReference:E.reference,actReference:v.reference,tagUid:S}}async function pm(e,t,n,r,i,o,a,s){const{bee:c}=e,u=64===t.length,l=sm(await Vh(c,t,0,void 0,a),Ld(t));await cm(l,async e=>Vh(c,e,0,void 0,a));const d=om(l);if(!d)throw new Error("History manifest is empty");const h=Gp(await Vh(c,d.metadata.actReference,0,void 0,a)),f=Up(r),p=qp(r,f.x,f.y),m=Kp(h,p.lookupKey);if(!m)throw new Error("Cannot find publisher entry in ACT");const g=Mp(m.encryptedAccessKey,p.accessKeyDecryptionKey),y=Ld(n),w=Mp(y,g),b=Lp(),v=Np(w,b);let x=[];if(d.metadata.encryptedGranteeListRef){x=Xp(await Vh(c,d.metadata.encryptedGranteeListRef,0,void 0,a),r)}const E=x.filter(e=>!i.some(t=>function(e,t){if(e.x.length!==t.x.length||e.y.length!==t.y.length)return!1;for(let n=0;n<e.x.length;n++)if(e.x[n]!==t.x[n])return!1;for(let n=0;n<e.y.length;n++)if(e.y[n]!==t.y[n])return!1;return!0}(e,t))),A=[];A.push({lookupKey:p.lookupKey,encryptedAccessKey:Np(b,p.accessKeyDecryptionKey)});for(const e of E){const t=qp(r,e.x,e.y);A.push({lookupKey:t.lookupKey,encryptedAccessKey:Np(b,t.accessKeyDecryptionKey)})}const R=jp(A),S=u?await Ah(e,R,o,void 0,a):await Th(e,R,void 0,o,void 0,a),I=Jp(E,r),k=await Th(e,I,void 0,o,void 0,a);im(l,um(),S.reference,k.reference);const T=await am(l,async(t,n)=>u?await Ah(e,t,o,n?s:void 0,a):await Th(e,t,void 0,o,n?s:void 0,a)),B=T.rootReference,O=T.tagUid;return{encryptedReference:jd(v),historyReference:B,granteeListReference:k.reference,actReference:S.reference,tagUid:O}}async function mm(e,t,n,r){const i=sm(await Vh(e,t,0,void 0,r),Ld(t));await cm(i,async t=>Vh(e,t,0,void 0,r));const o=om(i);if(!o||!o.metadata.encryptedGranteeListRef)return[];return Xp(await Vh(e,o.metadata.encryptedGranteeListRef,0,void 0,r),n).map(e=>jd(Vp(e.x,e.y)))}function gm(e){return _p(Ld(e))}const ym="index.bin";class wm{constructor(){this.parentIdentified=!1,this.authenticated=!1,this.authLoading=!0,this.stamperDepth=23,this.storagePartitioned=!1,this.popupMode="window",this.isConnecting=!1;const e=Qf().load();this.beeApiUrl=e?.beeNodeUrl||Ru,this.bee=new xu(this.beeApiUrl),this.setupMessageListener(),this.setupConnectedAppsListener(),this.utilizationChannel=new BroadcastChannel("swarm-id-utilization"),this.setupUtilizationListener(),this.announceReady()}setupConnectedAppsListener(){if(this.unsubscribeConnectedApps)return;const e=Zf();this.unsubscribeConnectedApps=e.subscribe(e=>{this.handleConnectedAppsChange(e)})}async handleConnectedAppsChange(e){if(!this.parentOrigin)return;const t=this.findMostRecentConnection(e);t?this.authenticated?t.appSecret!==this.appSecret&&await this.authenticateFromStorage(t):await this.authenticateFromStorage(t):this.authenticated&&!this.storagePartitioned&&(this.clearAuthData(),this.sendToParent({type:"disconnectResponse",requestId:"storage-event",success:!0}))}async authenticateFromStorage(e){this.appSecret=e.appSecret,this.authenticated=!0,this.storagePartitioned=!1,this.storagePartitionedIdentity=void 0,this.authLoading=!1,this.isConnecting=!1;const t=this.lookupPostageStampForApp();t&&(this.postageBatchId=t.batchID.toHex(),this.signerKey=t.signerKey.toHex(),this.stamperDepth=t.depth,await this.initializeStamper()),this.showAuthButton(),this.sendToParent({type:"authSuccess",origin:this.parentOrigin})}async handlePopupMessage(e){if("setSecret"===e.type){if(e.appOrigin!==this.parentOrigin)return void console.warn("[Proxy] setSecret appOrigin mismatch:",e.appOrigin,"!==",this.parentOrigin);if(!this.pendingChallenge||e.challenge!==this.pendingChallenge)return void console.warn("[Proxy] setSecret challenge mismatch — ignoring");this.pendingChallenge=void 0,localStorage.removeItem(Xu),this.appSecret=e.data.secret,this.authenticated=!0,this.storagePartitioned=!0,this.authLoading=!1,this.isConnecting=!1,e.data.identityId&&e.data.identityName&&e.data.identityAddress&&(this.storagePartitionedIdentity={id:e.data.identityId,name:e.data.identityName,address:e.data.identityAddress}),this.postageBatchId=void 0,this.signerKey=void 0,this.showAuthButton(),this.sendToParent({type:"authSuccess",origin:this.parentOrigin})}}destroy(){this.unsubscribeConnectedApps&&(this.unsubscribeConnectedApps(),this.unsubscribeConnectedApps=void 0),this.utilizationChannel.close()}setupUtilizationListener(){this.utilizationChannel.onmessage=e=>{try{const t=Wu.safeParse(e.data);t.success&&t.data.batchId===this.postageBatchId&&this.stamper&&this.stamper.applyUtilizationUpdate(t.data.buckets)}catch(e){console.error("[Proxy] Failed to apply utilization update:",e)}}}async withWriteLock(e){const t=`swarm-write-${this.postageBatchId}`;return navigator.locks.request(t,{mode:"exclusive"},async()=>{try{return await e()}finally{}})}announceReady(){window.parent&&window.parent!==window&&window.parent.postMessage({type:"proxyInitialized"},"*")}getPostageBatchId(){return this.postageBatchId}getSignerKey(){return this.signerKey}async initializeStamper(){if(!this.signerKey||!this.postageBatchId)return void console.warn("[Proxy] Cannot initialize stamper: missing signer key or batch ID");const e=this.lookupAccountForApp();if(e)try{this.utilizationStore||(this.utilizationStore=new Jh),this.stamper=await Df.create(this.signerKey,new Ci(this.postageBatchId),this.stamperDepth,this.utilizationStore,e.owner,e.encryptionKey)}catch(e){console.error("[Proxy] Failed to initialize stamper:",e),this.stamper=void 0}else console.warn("[Proxy] Cannot initialize stamper: account not found")}async saveStamperState(){if(this.stamper)try{const e=this.stamper.getBucketUpdatesForBroadcast();await this.stamper.flush(),this.postageBatchId&&e.length>0&&this.utilizationChannel.postMessage({type:"utilization-updated",batchId:this.postageBatchId,buckets:e})}catch(e){console.error("[Proxy] Failed to save stamper state:",e)}}setupMessageListener(){window.addEventListener("message",async e=>{const{type:t}=e.data;if("parentIdentify"===t)return void await this.handleParentIdentify(e);if(!this.parentIdentified)return void console.warn("[Proxy] Ignoring message - parent not identified yet");if(e.origin===window.location.origin&&"setSecret"===t){const t=Md.safeParse(e.data);if(t.success)return void await this.handlePopupMessage(t.data)}if(e.origin!==this.parentOrigin)return void console.warn("[Proxy] Rejected message from unauthorized origin:",e.origin);if("setButtonStyles"===t)return this.currentStyles=e.data.styles,void(!this.authenticated&&this.authButtonContainer&&this.showAuthButton());let n;try{n=Jl.parse(e.data)}catch(e){return void console.warn("[Proxy] Invalid parent message:",e)}try{await this.handleParentMessage(n,e)}catch(t){console.error("[Proxy] Error handling parent message:",t),this.sendErrorToParent(e,n.requestId,t instanceof Error?t.message:"Unknown error")}})}async handleParentIdentify(e){if(this.parentIdentified)return void console.error("[Proxy] Parent already identified! Ignoring duplicate.");const t=e.data,n=t.popupMode,r=t.metadata,i=t.buttonConfig;this.parentOrigin=e.origin,this.parentIdentified=!0,e.source&&(this.parentWindow=e.source),n&&(this.popupMode=n),r&&(this.appMetadata=r),i&&(this.buttonConfig=i),await this.loadAuthData(),e.source&&e.source.postMessage({type:"proxyReady",authenticated:this.authenticated,parentOrigin:this.parentOrigin},{targetOrigin:e.origin})}async handleParentMessage(e,t){switch(e.type){case"parentIdentify":break;case"checkAuth":this.handleCheckAuth(e,t);break;case"disconnect":this.handleDisconnect(e,t);break;case"requestAuth":this.handleRequestAuth(e,t);break;case"uploadData":await this.handleUploadData(e,t);break;case"downloadData":await this.handleDownloadData(e,t);break;case"uploadFile":await this.handleUploadFile(e,t);break;case"downloadFile":await this.handleDownloadFile(e,t);break;case"uploadChunk":await this.handleUploadChunk(e,t);break;case"downloadChunk":await this.handleDownloadChunk(e,t);break;case"getConnectionInfo":this.handleGetConnectionInfo(e,t);break;case"isConnected":await this.handleIsConnected(e,t);break;case"getNodeInfo":await this.handleGetNodeInfo(e,t);break;case"gsocMine":this.handleGsocMine(e,t);break;case"gsocSend":await this.handleGsocSend(e,t);break;case"socUpload":await this.handleSocUpload(e,t);break;case"socRawUpload":await this.handleSocRawUpload(e,t);break;case"socDownload":await this.handleSocDownload(e,t);break;case"socRawDownload":await this.handleSocRawDownload(e,t);break;case"socGetOwner":await this.handleSocGetOwner(e,t);break;case"epochFeedDownloadReference":await this.handleEpochFeedDownloadReference(e,t);break;case"epochFeedUploadReference":await this.handleEpochFeedUploadReference(e,t);break;case"feedGetOwner":await this.handleFeedGetOwner(e,t);break;case"seqFeedGetOwner":await this.handleSequentialFeedGetOwner(e,t);break;case"seqFeedDownloadPayload":await this.handleSequentialFeedDownloadPayload(e,t);break;case"seqFeedDownloadRawPayload":await this.handleSequentialFeedDownloadRawPayload(e,t);break;case"seqFeedDownloadReference":await this.handleSequentialFeedDownloadReference(e,t);break;case"seqFeedUploadPayload":await this.handleSequentialFeedUploadPayload(e,t);break;case"seqFeedUploadRawPayload":await this.handleSequentialFeedUploadRawPayload(e,t);break;case"seqFeedUploadReference":await this.handleSequentialFeedUploadReference(e,t);break;case"actUploadData":await this.handleActUploadData(e,t);break;case"actDownloadData":await this.handleActDownloadData(e,t);break;case"actAddGrantees":await this.handleActAddGrantees(e,t);break;case"actRevokeGrantees":await this.handleActRevokeGrantees(e,t);break;case"actGetGrantees":await this.handleActGetGrantees(e,t);break;case"getPostageBatch":await this.handleGetPostageBatch(e,t);break;case"createFeedManifest":await this.handleCreateFeedManifest(e,t);break;case"connect":this.handleConnect(e,t);break;default:const n=e;console.warn("[Proxy] Unhandled message type:",n)}}async loadAuthData(){if(!this.parentOrigin)return void(this.authLoading=!1);const e=this.lookupAppSecretFromSharedStorage();if(e){this.appSecret=e.secret,this.authenticated=!0,this.authLoading=!1,this.showAuthButton();const t=this.lookupPostageStampForApp();t?(this.postageBatchId=t.batchID.toHex(),this.signerKey=t.signerKey.toHex(),this.stamperDepth=t.depth,await this.initializeStamper()):(this.postageBatchId=void 0,this.signerKey=void 0)}else this.authLoading=!1,this.showAuthButton()}lookupPostageStampForApp(){if(this.parentOrigin)try{const e=Zf().load(),t=this.findMostRecentConnection(e);if(!t)return;const n=Wf(),r=n.load().find(e=>e.id===t.identityId);if(!r)return;const i=Xf().load();let o;return r.defaultPostageStampBatchID&&(o=i.find(e=>e.batchID.equals(r.defaultPostageStampBatchID))),o||(o=i.find(e=>e.accountId===r.accountId.toHex())),o}catch(e){return void console.error("[Proxy] Error looking up postage stamp:",e)}}lookupAccountForApp(){if(this.parentOrigin)try{const e=Zf().load(),t=this.findMostRecentConnection(e);if(!t)return;const n=Wf(),r=n.load().find(e=>e.id===t.identityId);if(!r)return;const i=Hf(),o=i.load().find(e=>e.id.equals(r.accountId));if(!o)return;return{owner:o.id,encryptionKey:Ld(o.swarmEncryptionKey)}}catch(e){return void console.error("[Proxy] Error looking up account:",e)}}isConnectionValid(e){return!!e.connectedUntil&&e.connectedUntil>Date.now()}findMostRecentConnection(e){return e.filter(e=>e.appUrl===this.parentOrigin&&this.isConnectionValid(e)).sort((e,t)=>t.lastConnectedAt-e.lastConnectedAt)[0]}lookupAppSecretFromSharedStorage(){if(this.parentOrigin)try{const e=Zf().load(),t=this.findMostRecentConnection(e);if(!t)return;if(!t.appSecret)return;return{secret:t.appSecret,identityId:t.identityId}}catch(e){return void console.error("[Proxy] Error looking up app secret from shared storage:",e)}}clearAuthData(){if(!this.parentOrigin)return;const e=`swarm-stamper-${this.parentOrigin}-${this.postageBatchId}`;localStorage.removeItem(e);try{Jf(this.parentOrigin)}catch(e){console.error("[Proxy] Error invalidating connected app in shared storage:",e)}this.authenticated=!1,this.authLoading=!1,this.appSecret=void 0,this.postageBatchId=void 0,this.signerKey=void 0,this.stamper=void 0,this.storagePartitioned=!1,this.storagePartitionedIdentity=void 0,this.pendingChallenge=void 0,this.showAuthButton()}sendErrorToParent(e,t,n){e.source&&t&&e.source.postMessage({type:"error",requestId:t,error:n},{targetOrigin:e.origin})}ensureCanUpload(){if(this.storagePartitioned)throw new Error("Uploads are unavailable in download-only mode due to browser storage partitioning.")}sendToParent(e){this.parentOrigin&&this.parentWindow?this.parentWindow.postMessage(e,this.parentOrigin):console.warn("[Proxy] Cannot send message to parent - no parent window reference")}handleCheckAuth(e,t){t.source&&t.source.postMessage({type:"authStatusResponse",requestId:e.requestId,authenticated:this.authenticated,origin:this.authenticated?this.parentOrigin:void 0},{targetOrigin:t.origin})}handleGetConnectionInfo(e,t){let n;if(this.authenticated&&this.parentOrigin)if(this.storagePartitioned&&this.storagePartitionedIdentity)n=this.storagePartitionedIdentity;else try{const e=Zf().load(),t=this.findMostRecentConnection(e);if(t){const e=Wf(),r=e.load().find(e=>e.id===t.identityId);r&&(n={id:r.id,name:r.name,address:r.id})}}catch(e){console.error("[Proxy] Error looking up identity:",e)}const r=!(!this.postageBatchId||!this.signerKey||this.storagePartitioned);t.source&&t.source.postMessage({type:"connectionInfoResponse",requestId:e.requestId,canUpload:r,storagePartitioned:this.storagePartitioned||void 0,identity:n},{targetOrigin:t.origin})}async handleIsConnected(e,t){const n=await this.bee.isConnected();t.source&&t.source.postMessage({type:"isConnectedResponse",requestId:e.requestId,connected:n},{targetOrigin:t.origin})}async handleGetNodeInfo(e,t){try{const n=await this.bee.getNodeInfo();t.source&&t.source.postMessage({type:"getNodeInfoResponse",requestId:e.requestId,beeMode:n.beeMode,chequebookEnabled:n.chequebookEnabled,swapEnabled:n.swapEnabled},{targetOrigin:t.origin})}catch(n){this.sendErrorToParent(t,e.requestId,n instanceof Error?n.message:"Failed to get node info")}}handleDisconnect(e,t){this.clearAuthData(),t.source&&t.source.postMessage({type:"disconnectResponse",requestId:e.requestId,success:!0},{targetOrigin:t.origin})}handleRequestAuth(e,t){this.currentStyles=e.styles,this.authButtonContainer&&this.showAuthButton()}showAuthButton(){if(!this.authButtonContainer||this.isConnecting)return;this.authButtonContainer.innerHTML="";const e=document.createElement("button"),t=this.authenticated,n=this.authLoading,r=this.buttonConfig||{},i=r.loadingText||"⏳ Loading...",o=r.disconnectText||"🔓 Disconnect from Swarm ID",a=r.connectText||"🔐 Login with Swarm ID";n?(e.textContent=i,e.disabled=!0):e.textContent=t?o:a;const s=this.currentStyles||{};e.style.width="100%",e.style.height="100%",e.style.display="flex",e.style.alignItems="center",e.style.justifyContent="center",n?(e.style.backgroundColor="#999",e.style.cursor="default"):t?(e.style.backgroundColor="#666",e.style.cursor=s.cursor||"pointer"):(e.style.backgroundColor=r.backgroundColor||s.backgroundColor||"#dd7200",e.style.cursor=s.cursor||"pointer"),e.style.color=r.color||s.color||"white",e.style.border=s.border||"none",e.style.borderRadius=r.borderRadius||s.borderRadius||"0",e.style.padding=s.padding||"0",e.style.fontSize=s.fontSize||"14px",e.style.fontWeight=s.fontWeight||"600",e.addEventListener("click",()=>{t?this.handleDisconnectClick():this.handleLoginClick(e)}),this.authButtonContainer.appendChild(e)}handleConnect(e,t){const n=this.openAuthPopup({agent:e.agent,popupMode:e.popupMode});t.source.postMessage({type:"connectResponse",requestId:e.requestId,success:n},{targetOrigin:t.origin})}openAuthPopup(e){if(!this.parentOrigin)return console.error("[Proxy] Cannot open auth window - parent origin not set"),!1;const t=crypto.randomUUID();this.pendingChallenge=t,localStorage.setItem(Xu,t);const n=window.location.pathname.replace(/\/proxy$/,""),r=Ap(window.location.origin+n,this.parentOrigin,this.appMetadata,{challenge:t,agent:e?.agent}),i=e?.popupMode??this.popupMode;let o=null;if(o="popup"===i?window.open(r,"_blank","width=500,height=600"):window.open(r,"_blank"),!o)return console.warn("[Proxy] Popup was blocked or failed to open"),this.isConnecting=!1,this.showAuthButton(),!1;return setTimeout(()=>{const e=setInterval(()=>{o?.closed&&(clearInterval(e),this.isConnecting&&!this.authenticated&&(this.isConnecting=!1,this.showAuthButton()))},500);setTimeout(()=>{clearInterval(e)},3e5)},2e3),!0}handleLoginClick(e){if(this.isConnecting=!0,e.disabled=!0,e.innerHTML='<span style="display: inline-block; width: 16px; height: 16px; border: 2px solid rgba(255,255,255,.3); border-radius: 50%; border-top-color: white; animation: spin 1s linear infinite;"></span>',!document.getElementById("swarm-id-spinner-style")){const e=document.createElement("style");e.id="swarm-id-spinner-style",e.textContent="@keyframes spin { to { transform: rotate(360deg); } }",document.head.appendChild(e)}this.openAuthPopup()}handleDisconnectClick(){this.clearAuthData(),this.sendToParent({type:"authStatusResponse",requestId:"disconnect",authenticated:!1,origin:void 0})}setAuthButtonContainer(e){this.authButtonContainer=e,this.showAuthButton()}async handleUploadData(e,t){const{requestId:n,data:r,options:i,requestOptions:o,enableProgress:a}=e;try{if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");if(this.ensureCanUpload(),!this.signerKey||!this.postageBatchId)throw new Error("Signer key and postage batch ID required. Please login first.");if(!this.stamper)throw new Error("Stamper not initialized. Please login first.");const e=a?e=>{t.source&&t.source.postMessage({type:"uploadProgress",requestId:n,total:e.total,processed:e.processed},{targetOrigin:t.origin})}:void 0,s=await this.withWriteLock(async()=>{const t={bee:this.bee,stamper:this.stamper};let n;return n=i?.encrypt?await Th(t,r,void 0,i,e,o):await Ah(t,r,i,e,o),await this.saveStamperState(),n});t.source&&t.source.postMessage({type:"uploadDataResponse",requestId:n,reference:s.reference,tagUid:s.tagUid},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"Upload failed")}}async handleDownloadData(e,t){const{requestId:n,reference:r,options:i,requestOptions:o}=e;if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");try{const e=await Vh(this.bee,r,0,void 0,o);t.source&&t.source.postMessage({type:"downloadDataResponse",requestId:n,data:e},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"Download failed")}}async handleUploadFile(e,t){const{requestId:n,data:r,name:i,options:o,requestOptions:a}=e,s=i||"index.bin";try{if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");if(this.ensureCanUpload(),!this.postageBatchId)throw new Error("No postage batch ID available. Please authenticate with a valid batch ID.");if(!this.stamper)throw new Error("Stamper not initialized. Please login first.");const e=await this.withWriteLock(async()=>{const e={bee:this.bee,stamper:this.stamper};let t;t=!1!==o?.encrypt?await Th(e,r,void 0,o,void 0,a):await Ah(e,r,o,void 0,a);const n=new mu,i=Ld(t.reference);n.addFork(s,i,{"Content-Type":"application/octet-stream",Filename:s}),n.addFork("/",Au,{"website-index-document":s});let c=o?.tag;if(!c){const t=await e.bee.createTag();c=t.uid}let u;return u=!0===o?.encryptManifest?await Hh(n,async(t,n,r)=>{const i=e.stamper.stamp({hash:()=>n,build:()=>t,span:0n,writer:void 0});return await e.bee.uploadChunk(i,t,{...o,tag:c,deferred:!1},a),{tagUid:r?c:void 0}}):await Gh(n,async(t,n)=>{const r=gh(t),i=e.stamper.stamp({hash:()=>r.address.toUint8Array(),build:()=>r.data,span:r.span.toBigInt(),writer:void 0});return{reference:(await e.bee.uploadChunk(i,r.data,{...o,tag:c,deferred:!1},a)).reference.toHex(),tagUid:n?c:void 0}}),await this.saveStamperState(),u});t.source&&t.source.postMessage({type:"uploadFileResponse",requestId:n,reference:e.rootReference,tagUid:e.tagUid},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"Upload failed")}}async handleDownloadFile(e,t){const{requestId:n,reference:r,path:i,options:o,requestOptions:a}=e;if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");try{const e=await Kh(this.bee,r,a);let o;if(i)o=i;else{const{indexDocument:t}=e.getDocsMetadata();if(!t)throw new Error("Manifest does not contain an index document reference");o=t}const s=e.find(o);if(!s)throw new Error(`Path not found in manifest: ${o}`);if(!s.targetAddress)throw new Error(`Path "${o}" does not have a target address`);const c=s.metadata?.Filename||o.split("/").pop()||"file",u=jd(s.targetAddress),l=await Vh(this.bee,u,0,void 0,a);t.source&&t.source.postMessage({type:"downloadFileResponse",requestId:n,name:c,data:l},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"Download failed")}}async handleUploadChunk(e,t){const{requestId:n,data:r,options:i,requestOptions:o}=e;try{if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");if(this.ensureCanUpload(),!this.signerKey||!this.postageBatchId)throw new Error("Signer key and postage batch ID required. Please authenticate.");if(r.length<1||r.length>4096)throw new Error(`Invalid chunk size: ${r.length} bytes. Chunks must be between 1 and 4096 bytes.`);if(this.stamper||await this.initializeStamper(),!this.stamper)throw new Error("Failed to initialize stamper for signing");const e=await this.withWriteLock(async()=>{const e=gh(r),t={hash:()=>e.address.toUint8Array(),build:()=>e.data,span:0n,writer:void 0},n=this.stamper.stamp(t);let a=i?.tag;if(!a){a=(await this.bee.createTag()).uid}const s={...i,tag:a,deferred:!1,pin:!1},c=await this.bee.uploadChunk(n,e.data,s,o);return await this.saveStamperState(),c});t.source&&t.source.postMessage({type:"uploadChunkResponse",requestId:n,reference:e.reference.toHex()},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"Upload failed")}}async handleDownloadChunk(e,t){const{requestId:n,reference:r,options:i,requestOptions:o}=e;if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");try{const e=await this.bee.downloadChunk(r,i,o);t.source&&t.source.postMessage({type:"downloadChunkResponse",requestId:n,data:e},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"Download failed")}}handleGsocMine(e,t){const{requestId:n,targetOverlay:r,identifier:i,proximity:o}=e;try{const e=this.bee.gsocMine(r,i,o);t.source&&t.source.postMessage({type:"gsocMineResponse",requestId:n,signer:e.toHex()},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"GSOC mine failed")}}async handleGsocSend(e,t){const{requestId:n,signer:r,identifier:i,data:o,options:a}=e;try{if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");if(this.ensureCanUpload(),!this.postageBatchId||!this.stamper)throw new Error("Postage batch ID and stamper required. Please login first.");const e=new Ri(r),s=new ki(i),c=await this.withWriteLock(async()=>{const t=await $h(this.bee,this.stamper,e,s,o,a);return await this.saveStamperState(),t});t.source&&t.source.postMessage({type:"gsocSendResponse",requestId:n,reference:jd(c.socAddress),tagUid:c.tagUid},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"GSOC send failed")}}async handleSocUpload(e,t){const{requestId:n,identifier:r,data:i,signer:o,options:a}=e;try{if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");if(this.ensureCanUpload(),!this.postageBatchId||!this.stamper)throw new Error("Postage batch ID and stamper required. Please login first.");const e=o??this.appSecret,s=new Ri(e),c=new ki(r),u=await this.withWriteLock(async()=>{const e=await Ch(this.bee,this.stamper,s,c,i,void 0,a);return await this.saveStamperState(),e});t.source&&t.source.postMessage({type:"socUploadResponse",requestId:n,reference:jd(u.socAddress),tagUid:u.tagUid,encryptionKey:jd(u.encryptionKey),owner:s.publicKey().address().toHex()},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"SOC upload failed")}}async handleSocRawUpload(e,t){const{requestId:n,identifier:r,data:i,signer:o,options:a}=e;try{if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");if(this.ensureCanUpload(),!this.postageBatchId||!this.stamper)throw new Error("Postage batch ID and stamper required. Please login first.");const e=o??this.appSecret,s=new Ri(e),c=new ki(r),u=await this.withWriteLock(async()=>{const e=await $h(this.bee,this.stamper,s,c,i,a);return await this.saveStamperState(),e});t.source&&t.source.postMessage({type:"socRawUploadResponse",requestId:n,reference:jd(u.socAddress),tagUid:u.tagUid,encryptionKey:void 0,owner:s.publicKey().address().toHex()},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"SOC raw upload failed")}}async handleSocDownload(e,t){const{requestId:n,owner:r,identifier:i,encryptionKey:o,requestOptions:a}=e;try{let e=r;if(!e){if(!this.appSecret)throw new Error("Not authenticated. Please login first.");e=new Ri(this.appSecret).publicKey().address().toHex()}const s=await jh(this.bee,e,i,o,a);t.source&&t.source.postMessage({type:"socDownloadResponse",requestId:n,data:s.data,identifier:s.identifier,signature:s.signature,span:s.span,payload:s.payload,address:s.address,owner:s.owner},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"SOC download failed")}}async handleSocRawDownload(e,t){const{requestId:n,owner:r,identifier:i,encryptionKey:o,requestOptions:a}=e;try{let e=r;if(!e){if(!this.appSecret)throw new Error("Not authenticated. Please login first.");e=new Ri(this.appSecret).publicKey().address().toHex()}const s=o?await jh(this.bee,e,i,o,a):await Lh(this.bee,e,i,a);t.source&&t.source.postMessage({type:"socRawDownloadResponse",requestId:n,data:s.data,identifier:s.identifier,signature:s.signature,span:s.span,payload:s.payload,address:s.address,owner:s.owner},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"SOC raw download failed")}}async handleSocGetOwner(e,t){const{requestId:n}=e;try{if(!this.appSecret)throw new Error("Not authenticated. Please login first.");const e=new Ri(this.appSecret).publicKey().address().toHex();t.source&&t.source.postMessage({type:"socGetOwnerResponse",requestId:n,owner:e},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"SOC get owner failed")}}parseFeedTimestamp(e){if("number"==typeof e)return BigInt(Math.floor(e));if(!/^-?\d+$/.test(e))throw new Error(`Invalid timestamp format: "${e}" (expected decimal integer)`);return BigInt(e)}parseFeedIndex(e){if("number"==typeof e)return BigInt(Math.floor(e));if(!/^-?\d+$/.test(e))throw new Error(`Invalid index format: "${e}" (expected decimal integer)`);return BigInt(e)}makeSequentialFeedIdentifier(e,t){const n=ih.numberToUint64(t,"BE");return ih.keccak256(ih.concatBytes(e,n))}async findLatestSequentialIndex(e,t,n,r){const i={...n,timeout:r??2e3},o=(a={bee:this.bee,topic:new zi(e),owner:t},new fp(a.bee,a.topic,a.owner));var a;return(await o.findAt(0n,0n,i)).current}sequentialNextIndex(e){return e===(1n<<64n)-1n?0n:e+1n}async handleFeedGetOwner(e,t){const{requestId:n}=e;try{if(!this.appSecret)throw new Error("Not authenticated. Please login first.");const e=new Ri(this.appSecret).publicKey().address().toHex();t.source&&t.source.postMessage({type:"feedGetOwnerResponse",requestId:n,owner:e},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"Feed get owner failed")}}async handleEpochFeedDownloadReference(e,t){const{requestId:n,topic:r,owner:i,at:o,after:a,encryptionKey:s}=e;try{let e=i;if(!e){if(!this.appSecret)throw new Error("Not authenticated. Please login first.");e=new Ri(this.appSecret).publicKey().address().toHex()}const c=new zi(Ld(r)),u=new Ii(e),l=this.parseFeedTimestamp(o),d=void 0!==a?this.parseFeedTimestamp(a):0n,h=s?Ld(s):void 0;let f;if(h){const e=up({bee:this.bee,topic:c,owner:u,encryptionKey:h});f=await e.findAt(l,d)}else{const e=up({bee:this.bee,topic:c,owner:u});f=await e.findAt(l,d)}t.source&&t.source.postMessage({type:"epochFeedDownloadReferenceResponse",requestId:n,reference:f?jd(f):void 0},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"Epoch feed download reference failed")}}async handleEpochFeedUploadReference(e,t){const{requestId:n,topic:r,signer:i,at:o,reference:a,encryptionKey:s,hints:c}=e;try{if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");if(this.ensureCanUpload(),!this.postageBatchId||!this.stamper)throw new Error("Postage batch ID and stamper required. Please login first.");const e=i??this.appSecret,u=new Ri(e),l=new zi(Ld(r)),d=u.publicKey().address().toHex(),h=new Ii(d),f=lp({bee:this.bee,topic:l,owner:h,signer:u}),p=this.parseFeedTimestamp(o),m=s?Ld(s):void 0,g=c?.lastEpoch?{lastEpoch:{start:BigInt(c.lastEpoch.start),level:c.lastEpoch.level},lastTimestamp:c.lastTimestamp?BigInt(c.lastTimestamp):void 0}:void 0,y=await this.withWriteLock(async()=>{const e=Ld(a),t=await f.update(p,e,this.stamper,m,g),n=up({bee:this.bee,topic:l,owner:h,encryptionKey:m});return await n.findAt(p,p),await this.saveStamperState(),t});t.source&&t.source.postMessage({type:"epochFeedUploadReferenceResponse",requestId:n,socAddress:jd(y.socAddress),encryptionKey:s||void 0,epoch:{start:y.epoch.start.toString(),level:y.epoch.level},timestamp:y.timestamp.toString()},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"Epoch feed upload reference failed")}}async handleSequentialFeedGetOwner(e,t){const{requestId:n}=e;try{if(!this.appSecret)throw new Error("Not authenticated. Please login first.");const e=new Ri(this.appSecret).publicKey().address().toHex();t.source&&t.source.postMessage({type:"seqFeedGetOwnerResponse",requestId:n,owner:e},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"Sequential feed get owner failed")}}async resolveSequentialOwner(e){if(e)return e;if(!this.appSecret)throw new Error("Not authenticated. Please login first.");return new Ri(this.appSecret).publicKey().address().toHex()}parseSequentialPayload(e,t){if(!t)return{payload:e};if(e.length<8)return{payload:e,timestamp:void 0};const n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=Number(n.getBigUint64(0,!1));return{payload:e.slice(8),timestamp:r}}async resolveSequentialIndex(e,t,n,r,i=!0,o,a,s=!1,c){if(!s&&!a)throw new Error("Encryption key is required for encrypted feed lookup");if(void 0!==n)return this.parseFeedIndex(n);const u=await this.findLatestSequentialIndex(e,t,o,c);if(void 0===u)throw new Error("Sequential feed has no updates");if(void 0===r)return u;if(!i)throw new Error("Cannot use 'at' without timestamps");const l=this.parseFeedTimestamp(r);for(let n=u;n>=0n;n--){const r=this.makeSequentialFeedIdentifier(e,n),i=new ki(r),c=s?a?await jh(this.bee,t,i,a,o):await Lh(this.bee,t,i,o):await jh(this.bee,t,i,a??"",o),u=this.parseSequentialPayload(c.payload,!0);if(void 0!==u.timestamp&&BigInt(u.timestamp)<=l)return n;if(0n===n)break}return u}async handleSequentialFeedDownloadPayload(e,t){const{requestId:n,topic:r,owner:i,index:o,at:a,hasTimestamp:s,encryptionKey:c,lookupTimeoutMs:u,requestOptions:l}=e;try{if(!c)throw new Error("Encryption key is required for downloadPayload");const e=await this.resolveSequentialOwner(i),d=new Ii(e),h=Ld(r),f=!1!==s,p=await this.resolveSequentialIndex(h,d,o,a,f,l,c,!1,u),m=this.makeSequentialFeedIdentifier(h,p),g=new ki(m),y=await jh(this.bee,d,g,c,l),w=this.parseSequentialPayload(y.payload,f),b=this.sequentialNextIndex(p);t.source&&t.source.postMessage({type:"seqFeedDownloadPayloadResponse",requestId:n,payload:w.payload,timestamp:w.timestamp,feedIndex:p.toString(),feedIndexNext:b.toString()},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"Sequential feed download payload failed")}}async handleSequentialFeedDownloadRawPayload(e,t){const{requestId:n,topic:r,owner:i,index:o,at:a,hasTimestamp:s,encryptionKey:c,lookupTimeoutMs:u,requestOptions:l}=e;try{const e=await this.resolveSequentialOwner(i),d=new Ii(e),h=Ld(r),f=!1!==s,p=await this.resolveSequentialIndex(h,d,o,a,f,l,c,!0,u),m=this.makeSequentialFeedIdentifier(h,p),g=new ki(m),y=c?await jh(this.bee,d,g,c,l):await Lh(this.bee,d,g,l),w=this.parseSequentialPayload(y.payload,f),b=this.sequentialNextIndex(p);t.source&&t.source.postMessage({type:"seqFeedDownloadRawPayloadResponse",requestId:n,payload:w.payload,timestamp:w.timestamp,feedIndex:p.toString(),feedIndexNext:b.toString()},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"Sequential feed download raw payload failed")}}async handleSequentialFeedDownloadReference(e,t){const{requestId:n,topic:r,owner:i,index:o,at:a,hasTimestamp:s,encryptionKey:c,lookupTimeoutMs:u,requestOptions:l}=e;try{if(!c)throw new Error("Encryption key is required for downloadReference");const e=await this.resolveSequentialOwner(i),d=new Ii(e),h=Ld(r),f=!1!==s,p=await this.resolveSequentialIndex(h,d,o,a,f,l,c,!1,u),m=this.makeSequentialFeedIdentifier(h,p),g=new ki(m),y=await jh(this.bee,d,g,c,l),w=this.parseSequentialPayload(y.payload,f);if(32!==w.payload.length&&64!==w.payload.length)throw new Error("Sequential feed update does not contain a reference; use downloadPayload");const b=jd(w.payload),v=this.sequentialNextIndex(p);t.source&&t.source.postMessage({type:"seqFeedDownloadReferenceResponse",requestId:n,reference:b,feedIndex:p.toString(),feedIndexNext:v.toString()},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"Sequential feed download reference failed")}}buildSequentialPayload(e,t,n){if(!t)return e;const r=new Uint8Array(8);return new DataView(r.buffer).setBigUint64(0,n,!1),ih.concatBytes(r,e)}async handleSequentialFeedUploadPayload(e,t){const{requestId:n,topic:r,signer:i,data:o,index:a,at:s,hasTimestamp:c,lookupTimeoutMs:u,options:l,requestOptions:d}=e;try{if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");if(this.ensureCanUpload(),!this.postageBatchId||!this.stamper)throw new Error("Postage batch ID and stamper required. Please login first.");const e=i??this.appSecret,h=new Ri(e),f=h.publicKey().address(),p=Ld(r),m=!1!==c,g=void 0!==s?this.parseFeedTimestamp(s):BigInt(Math.floor(Date.now()/1e3));let y;if(void 0!==a)y=this.parseFeedIndex(a);else{const e=await this.findLatestSequentialIndex(p,f,d,u);y=void 0===e?0n:this.sequentialNextIndex(e)}const w=this.buildSequentialPayload(o,m,g);if(w.length<1||w.length>4096)throw new Error(`Invalid payload length: ${w.length} (expected 1-4096)`);const b=await this.withWriteLock(async()=>{const e=this.makeSequentialFeedIdentifier(p,y),t=new ki(e),n=await Ch(this.bee,this.stamper,h,t,w,void 0,l);return await this.saveStamperState(),n});t.source&&t.source.postMessage({type:"seqFeedUploadPayloadResponse",requestId:n,reference:jd(b.socAddress),feedIndex:y.toString(),owner:f.toHex(),encryptionKey:jd(b.encryptionKey),tagUid:b.tagUid},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"Sequential feed upload payload failed")}}async handleSequentialFeedUploadRawPayload(e,t){const{requestId:n,topic:r,signer:i,data:o,index:a,at:s,hasTimestamp:c,encryptionKey:u,lookupTimeoutMs:l,options:d,requestOptions:h}=e;try{if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");if(this.ensureCanUpload(),!this.postageBatchId||!this.stamper)throw new Error("Postage batch ID and stamper required. Please login first.");const e=i??this.appSecret,f=new Ri(e),p=f.publicKey().address(),m=Ld(r),g=!1!==c,y=void 0!==s?this.parseFeedTimestamp(s):BigInt(Math.floor(Date.now()/1e3));let w;if(void 0!==a)w=this.parseFeedIndex(a);else{const e=await this.findLatestSequentialIndex(m,p,h,l);w=void 0===e?0n:this.sequentialNextIndex(e)}const b=this.buildSequentialPayload(o,g,y);if(b.length<1||b.length>4096)throw new Error(`Invalid payload length: ${b.length} (expected 1-4096)`);const v=this.makeSequentialFeedIdentifier(m,w),x=new ki(v),E=await this.withWriteLock(async()=>{let e;return e=u?await Ch(this.bee,this.stamper,f,x,b,Ld(u),d):await zh(this.bee,this.stamper,f,x,b,d),await this.saveStamperState(),e});t.source&&t.source.postMessage({type:"seqFeedUploadRawPayloadResponse",requestId:n,reference:jd(E.socAddress),feedIndex:w.toString(),owner:p.toHex(),encryptionKey:u||void 0,tagUid:E.tagUid},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"Sequential feed upload raw payload failed")}}async handleSequentialFeedUploadReference(e,t){const{requestId:n,topic:r,signer:i,reference:o,index:a,at:s,hasTimestamp:c,lookupTimeoutMs:u,options:l,requestOptions:d}=e;try{if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");if(this.ensureCanUpload(),!this.postageBatchId||!this.stamper)throw new Error("Postage batch ID and stamper required. Please login first.");const e=i??this.appSecret,h=new Ri(e),f=h.publicKey().address(),p=Ld(r),m=!1!==c,g=void 0!==s?this.parseFeedTimestamp(s):BigInt(Math.floor(Date.now()/1e3));let y;if(void 0!==a)y=this.parseFeedIndex(a);else{const e=await this.findLatestSequentialIndex(p,f,d,u);y=void 0===e?0n:this.sequentialNextIndex(e)}const w=Ld(o),b=this.buildSequentialPayload(w,m,g);if(b.length<1||b.length>4096)throw new Error(`Invalid payload length: ${b.length} (expected 1-4096)`);const{result:v,encryptionKeyResult:x}=await this.withWriteLock(async()=>{const e=this.makeSequentialFeedIdentifier(p,y),t=new ki(e),n=await Ch(this.bee,this.stamper,h,t,b,void 0,l);return await this.saveStamperState(),{result:n,encryptionKeyResult:jd(n.encryptionKey)}});t.source&&t.source.postMessage({type:"seqFeedUploadReferenceResponse",requestId:n,reference:jd(v.socAddress),feedIndex:y.toString(),owner:f.toHex(),encryptionKey:x,tagUid:v.tagUid},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"Sequential feed upload reference failed")}}async handleActUploadData(e,t){const{requestId:n,data:r,grantees:i,options:o,requestOptions:a,enableProgress:s}=e;try{if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");if(this.ensureCanUpload(),!this.signerKey||!this.postageBatchId)throw new Error("Signer key and postage batch ID required. Please login first.");if(!this.stamper)throw new Error("Stamper not initialized. Please login first.");const e={bee:this.bee,stamper:this.stamper},c=i.map(e=>gm(e)),u=s?e=>{t.source&&t.source.postMessage({type:"uploadProgress",requestId:n,total:e.total,processed:e.processed},{targetOrigin:t.origin})}:void 0,l=Ld(this.appSecret),{actResult:d,contentUpload:h}=await this.withWriteLock(async()=>{const t=await Th(e,r,void 0,o,u,a),n=new mu,i=Ld(t.reference);n.addFork(ym,i,{"Content-Type":"application/octet-stream",Filename:ym}),n.addFork("/",Au,{"website-index-document":ym});let s=o?.tag;if(!s){const t=await e.bee.createTag();s=t.uid}const d=Ld((!0===o?.beeCompatible?await Gh(n,async(t,n)=>{const r=gh(t),i=e.stamper.stamp({hash:()=>r.address.toUint8Array(),build:()=>r.data,span:0n,writer:void 0});return await e.bee.uploadChunk(i,r.data,{...o,tag:s,deferred:!1},a),{reference:r.address.toHex(),tagUid:n?s:void 0}}):await Hh(n,async(t,n,r)=>{const i=e.stamper.stamp({hash:()=>n,build:()=>t,span:0n,writer:void 0});return await e.bee.uploadChunk(i,t,{...o,tag:s,deferred:!1},a),{tagUid:r?s:void 0}})).rootReference),h=await dm(e,d,l,c,o,a);return await this.saveStamperState(),{actResult:h,contentUpload:t}});t.source&&t.source.postMessage({type:"actUploadDataResponse",requestId:n,encryptedReference:d.encryptedReference,historyReference:d.historyReference,granteeListReference:d.granteeListReference,publisherPubKey:d.publisherPubKey,actReference:d.actReference,tagUid:h.tagUid},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"ACT upload failed")}}async handleActDownloadData(e,t){const{requestId:n,encryptedReference:r,historyReference:i,publisherPubKey:o,timestamp:a,requestOptions:s}=e;try{if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");const e=Ld(this.appSecret),c=await hm(this.bee,r,i,o,e,a,s),u=await Kh(this.bee,c,s),{indexDocument:l}=u.getDocsMetadata();if(!l)throw new Error("Manifest does not contain an index document reference");const d=u.find(l);if(!d)throw new Error(`Content node "${l}" not found in manifest`);if(!d.targetAddress)throw new Error(`Content node "${l}" does not have a target address`);const h=jd(d.targetAddress),f=await Vh(this.bee,h,0,void 0,s);t.source&&t.source.postMessage({type:"actDownloadDataResponse",requestId:n,data:f},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"ACT download failed")}}async handleActAddGrantees(e,t){const{requestId:n,historyReference:r,grantees:i,requestOptions:o}=e;try{if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");if(this.ensureCanUpload(),!this.signerKey||!this.postageBatchId)throw new Error("Signer key and postage batch ID required. Please login first.");if(!this.stamper)throw new Error("Stamper not initialized. Please login first.");const e={bee:this.bee,stamper:this.stamper},a=Ld(this.appSecret),s=i.map(e=>gm(e)),c=await this.withWriteLock(async()=>{const t=await fm(e,r,a,s,void 0,o);return await this.saveStamperState(),t});t.source&&t.source.postMessage({type:"actAddGranteesResponse",requestId:n,historyReference:c.historyReference,granteeListReference:c.granteeListReference,actReference:c.actReference},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"ACT add grantees failed")}}async handleActRevokeGrantees(e,t){const{requestId:n,historyReference:r,encryptedReference:i,revokeGrantees:o,requestOptions:a}=e;try{if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");if(this.ensureCanUpload(),!this.signerKey||!this.postageBatchId)throw new Error("Signer key and postage batch ID required. Please login first.");if(!this.stamper)throw new Error("Stamper not initialized. Please login first.");const e={bee:this.bee,stamper:this.stamper},s=Ld(this.appSecret),c=o.map(e=>gm(e)),u=await this.withWriteLock(async()=>{const t=await pm(e,r,i,s,c,void 0,a);return await this.saveStamperState(),t});t.source&&t.source.postMessage({type:"actRevokeGranteesResponse",requestId:n,encryptedReference:u.encryptedReference,historyReference:u.historyReference,granteeListReference:u.granteeListReference,actReference:u.actReference},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"ACT revoke grantees failed")}}async handleActGetGrantees(e,t){const{requestId:n,historyReference:r,requestOptions:i}=e;try{if(!this.authenticated||!this.appSecret)throw new Error("Not authenticated. Please login first.");const e=Ld(this.appSecret),o=await mm(this.bee,r,e,i);t.source&&t.source.postMessage({type:"actGetGranteesResponse",requestId:n,grantees:o},{targetOrigin:t.origin})}catch(e){this.sendErrorToParent(t,n,e instanceof Error?e.message:"ACT get grantees failed")}}async handleGetPostageBatch(e,t){const n=this.lookupPostageStampForApp();if(!n)return void(t.source&&t.source.postMessage({type:"getPostageBatchResponse",requestId:e.requestId,postageBatch:void 0},{targetOrigin:t.origin}));let r=n.batchTTL;try{const e=await wp();r=bp(n.amount,e)}catch(e){console.warn("[Proxy] Failed to calculate TTL:",e)}const i={batchID:n.batchID.toHex(),utilization:n.utilization,usable:n.usable,label:"",depth:n.depth,amount:n.amount.toString(),bucketDepth:n.bucketDepth,blockNumber:n.blockNumber,immutableFlag:n.immutableFlag,exists:n.exists,batchTTL:r};t.source&&t.source.postMessage({type:"getPostageBatchResponse",requestId:e.requestId,postageBatch:i},{targetOrigin:t.origin})}async handleCreateFeedManifest(e,t){const{topic:n,owner:r,feedType:i,uploadOptions:o,requestOptions:a}=e;let s=r;if(!s&&this.appSecret){const e=new Ri(this.appSecret);s=e.publicKey().address().toHex()}if(s)try{if(this.ensureCanUpload(),!this.postageBatchId)throw new Error("No postage batch configured");if(!this.stamper)throw new Error("Stamper not initialized. Please login first.");const r=await this.withWriteLock(async()=>{const e=await async function(e,t,n,r,i,o,a){const s=r.startsWith("0x")?r.slice(2):r;let c=o?.tag;c||(c=(await e.createTag()).uid);const u={...o,tag:c},l=new mu;l.addFork("/",Au,{"swarm-feed-owner":s,"swarm-feed-topic":n,"swarm-feed-type":i?.feedType??"Sequence"});const d=l.forks.get(47);if(!d)throw new Error("[FeedManifest] Failed to create '/' fork");const h=d.node,f=gh(await h.marshal());await Rh(e,t,f,u,a),h.selfAddress=f.address.toUint8Array();const p=await l.marshal();if(!1!==i?.encrypt){const n=wh(p);await Bh(e,t,n,u,a);const r=new Uint8Array(64);return r.set(n.address.toUint8Array(),0),r.set(n.encryptionKey,32),{reference:jd(r),tagUid:c}}{const n=gh(p);return await Rh(e,t,n,u,a),{reference:n.address.toHex(),tagUid:c}}}(this.bee,this.stamper,n,s,{encrypt:!1!==o?.encrypt,feedType:i},o,a);return await this.saveStamperState(),e});t.source&&t.source.postMessage({type:"createFeedManifestResponse",requestId:e.requestId,reference:r.reference},{targetOrigin:t.origin})}catch(n){this.sendErrorToParent(t,e.requestId,n instanceof Error?n.message:"Create feed manifest failed")}else this.sendErrorToParent(t,e.requestId,"No owner provided and no app signer available")}}function bm(){return new wm}class vm{constructor(e=1e3){this.pendingUploads=new Map,this.defaultDelay=e}scheduleUpload(e,t,n,r){const i=r??this.defaultDelay,o=this.pendingUploads.get(e);o?.timerId&&(clearTimeout(o.timerId),o.promise.reject(new Error("Upload cancelled by new request")));const a=o?.tracker??t;if(o&&o.tracker!==t)for(const e of t.getDirtyChunks())a.markDirty(1024*e);return new Promise((t,r)=>{const o=setTimeout(async()=>{try{await n(),t()}catch(t){console.error(`[DebouncedUploader] Upload failed for batch ${e}:`,t),r(t instanceof Error?t:new Error(String(t)))}finally{this.pendingUploads.delete(e)}},i);this.pendingUploads.set(e,{tracker:a,timerId:o,uploadFn:n,promise:{resolve:t,reject:r}})})}async flush(e){const t=this.pendingUploads.get(e);if(t){t.timerId&&clearTimeout(t.timerId);try{await t.uploadFn()}finally{this.pendingUploads.delete(e)}}}async flushAll(){const e=Array.from(this.pendingUploads.keys());await Promise.all(e.map(e=>this.flush(e)))}cancel(e){const t=this.pendingUploads.get(e);t&&(t.timerId&&clearTimeout(t.timerId),this.pendingUploads.delete(e))}cancelAll(){for(const e of this.pendingUploads.values())e.timerId&&clearTimeout(e.timerId);this.pendingUploads.clear()}getPendingCount(){return this.pendingUploads.size}hasPending(e){return this.pendingUploads.has(e)}}function xm(e){return{version:1,timestamp:e.timestamp,accountId:e.accountId,metadata:{accountName:e.metadata.accountName,defaultPostageStampBatchID:e.metadata.defaultPostageStampBatchID,createdAt:e.metadata.createdAt,lastModified:e.metadata.lastModified},identities:e.identities.map(jf),connectedApps:e.connectedApps.map(Gf),postageStamps:e.postageStamps.map(Kf)}}function Em(e){const t=Gu.safeParse(e);return t.success?{success:!0,data:t.data}:{success:!1,error:t.error}}const Am=pr({version:Rr(1),accountName:zn(),exportedAt:nr(),ciphertext:zn()}),Rm=Am.extend({accountType:Rr("passkey"),credentialId:zn()}),Sm=Am.extend({accountType:Rr("ethereum"),ethereumAddress:zn()}),Im=Am.extend({accountType:Rr("agent")}),km=wr("accountType",[Rm,Sm,Im]);async function Tm(e){const t=Ld(await _d(e,"swarm-id-backup-encryption-v1"));return crypto.subtle.importKey("raw",t,"AES-GCM",!1,["encrypt","decrypt"])}async function Bm(e,t){const n=crypto.getRandomValues(new Uint8Array(12)),r=(new TextEncoder).encode(e),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},t,r),o=new Uint8Array(n.length+i.byteLength);return o.set(n,0),o.set(new Uint8Array(i),n.length),function(e){let t="";for(const n of e)t+=String.fromCharCode(n);return btoa(t)}(o)}async function Om(e,t){const n=function(e){const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(e),r=n.slice(0,12),i=n.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},t,i);return(new TextDecoder).decode(o)}function Dm(e){const t={version:1,accountName:e.name,exportedAt:Date.now()};return"passkey"===e.type?{...t,accountType:"passkey",credentialId:e.credentialId}:"ethereum"===e.type?{...t,accountType:"ethereum",ethereumAddress:e.ethereumAddress.toHex()}:{...t,accountType:"agent"}}async function Cm(e,t,n,r,i){const o=Date.now(),a=xm({accountId:e.id.toHex(),metadata:{accountName:e.name,defaultPostageStampBatchID:e.defaultPostageStampBatchID?.toHex(),createdAt:e.createdAt,lastModified:o},identities:t,connectedApps:n,postageStamps:r,timestamp:o}),s=JSON.stringify(a),c=await Tm(i),u=await Bm(s,c),l=Dm(e);return km.parse({...l,ciphertext:u})}async function $m(e,t){const n=zm(e);if(!n.success)return{success:!1,error:new yn([{code:"custom",message:n.error,path:[]}])};const r=await Tm(t);let i,o;try{i=await Om(n.header.ciphertext,r)}catch{return{success:!1,error:new yn([{code:"custom",message:"Decryption failed: wrong key or corrupted data",path:["ciphertext"]}])}}try{o=JSON.parse(i)}catch{return{success:!1,error:new yn([{code:"custom",message:"Decrypted data is not valid JSON",path:["ciphertext"]}])}}return Em(o)}function zm(e){if("object"!=typeof e||null===e)return{success:!1,error:"Input must be a non-null object"};const t=km.safeParse(e);return t.success?{success:!0,header:t.data}:{success:!1,error:t.error.issues.map(e=>e.message).join("; ")}}function Fm(e){const t=JSON.stringify(xm(e));return(new TextEncoder).encode(t)}function Pm(e){const t=(new TextDecoder).decode(e),n=Em(JSON.parse(t));if(!n.success)throw new Error(`Failed to deserialize account state: ${n.error.message}`);return n.data}const Um="swarm-id-backup-v1:account";function qm(e){const{bee:t,accountsStore:n,identitiesStore:r,connectedAppsStore:i,postageStampsStore:o,utilizationStore:a,utilizationUploader:s}=e;async function c(e,i){const c=n.getAccount(new Ii(e));if(!c)return void console.warn("[SyncCoordinator] Account not found for utilization update");const u=c.defaultPostageStampBatchID??r.getIdentitiesByAccount(c.id)[0]?.defaultPostageStampBatchID;if(!u)return void console.warn("[SyncCoordinator] No default stamp, skipping utilization");const l=new Ci(u),d=o.getStamp(l);if(!d)return void console.warn("[SyncCoordinator] Stamp not found, skipping utilization");const h=i.map(e=>({address:{toUint8Array:()=>e,toHex:()=>Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("")},data:new Uint8Array(0)}));const f=await _d(c.swarmEncryptionKey,"backup-key"),p=new Ri(f).publicKey().address(),{state:m,tracker:g}=await Bf(l,h,d.depth,{bee:t,owner:p,encryptionKey:Ld(c.swarmEncryptionKey),cache:a}),y=Of(m,d.depth);if(o.updateStampUtilization(l,y),g.hasDirtyChunks()){const e=await o.getStamper(l,{owner:p,encryptionKey:Ld(c.swarmEncryptionKey)});if(!e)return void console.warn("[SyncCoordinator] Cannot create stamper, skipping upload");const n=s.scheduleUpload(l.toHex(),g,async()=>{await Tf(m,{bee:t,stamper:e,encryptionKey:Ld(c.swarmEncryptionKey),cache:a,tracker:g}),e.flush&&await e.flush()}),r=new Promise((e,t)=>{setTimeout(()=>t(new Error("Utilization upload timeout (30000ms)")),3e4)});return Promise.race([n,r])}}return async function(e){const a=performance.now(),s=()=>(new Date).toISOString(),u=function(e){const t=n.getAccount(new Ii(e));if(!t)return void console.warn("[SyncCoordinator] Account not found",e);const a=t.defaultPostageStampBatchID??r.getIdentitiesByAccount(t.id)[0]?.defaultPostageStampBatchID;if(!a)return void console.warn("[SyncCoordinator] No default stamp for account",e);const s=o.getStamp(a);if(!s)return void console.warn("[SyncCoordinator] Default stamp not found");const c=r.getIdentitiesByAccount(t.id),u=c.flatMap(e=>i.getAppsByIdentityId(e.id)),l=o.getStampsByAccount(e);return{snapshot:{version:1,timestamp:Date.now(),accountId:e,metadata:{accountName:t.name,defaultPostageStampBatchID:a.toHex(),createdAt:t.createdAt,lastModified:Date.now()},identities:c,connectedApps:u,postageStamps:l},encryptionKey:t.swarmEncryptionKey,defaultStamp:s}}(e);if(!u)return;const{snapshot:l,encryptionKey:d,defaultStamp:h}=u;try{const n=await _d(d,"backup-key"),r=new Ri(n),i=r.publicKey().address(),u=Fm(l),f=await o.getStamper(h.batchID,{owner:i,encryptionKey:Ld(d)});if(!f)throw new Error(`Cannot create stamper for batch ${h.batchID.toHex()}`);const p=await Th({bee:t,stamper:f},u,Ld(d),void 0),m=p.chunkAddresses;try{await c(e,m)}catch(e){console.error(`[SyncCoordinator ${s()}] Utilization upload failed (+${(performance.now()-a).toFixed(2)}ms):`,e)}const g=zi.fromString(`${Um}:${e}`),y=new sp(t,g,r),w=BigInt(Math.floor(Date.now()/1e3)),b=new Ti(p.reference).toUint8Array(),v=await y.update(w,b,f);return m.push(v.socAddress),{status:"success",reference:p.reference,timestamp:w,chunkAddresses:m}}catch(e){return console.error(`[SyncCoordinator ${s()}] Sync failed (+${(performance.now()-a).toFixed(2)}ms):`,e),{status:"error",error:e instanceof Error?e.message:String(e)}}}}async function Nm(e,t,n,r){const i=n.toHex(),o=await Wd(t.toHex()),a=await _d(o,"backup-key"),s=new Ri(a).publicKey().address(),c=zi.fromString(`${Um}:${i}`),u=new ap(e,c,s),l=BigInt(Math.floor(Date.now()/1e3)),d=await u.findAt(l);if(!d)return;const h=new Ti(d);return{snapshot:Pm(await Vh(e,h.toHex())),swarmEncryptionKey:o,credentialId:r}}const Mm=new Uint8Array([87,104,179,182,167,219,86,210,29,26,191,244,13,65,206,191,200,52,72,254,216,215,233,176,110,192,211,176,115,242,143]);async function _m(e){const t=e instanceof Uint8Array?e:new Ti(e).toUint8Array();if(32!==t.length)throw new Error(`Invalid content reference length: ${t.length} (expected 32 bytes)`);const n=JSON.stringify({"website-index-document":"index.bin"})+"\n",r=JSON.stringify({"Content-Type":"application/octet-stream",Filename:"index.bin"})+"\n",i=(new TextEncoder).encode(n),o=(new TextEncoder).encode(r),a=194+i.length+66+o.length,s=new Uint8Array(a);let c=0;c+=32,s.set(Mm,c),c+=31,s[c]=32,c+=1,c+=32,s[c+5]=128,s[c+13]=2,c+=32,s[c]=16,c+=1,s[c]=1,c+=1,s[c]=47,c+=30,c+=32,s[c]=i.length>>8&255,s[c+1]=255&i.length,c+=2,s.set(i,c),c+=i.length,s[c]=18,c+=1,s[c]=9,c+=1;const u=(new TextEncoder).encode("index.bin");s.set(u,c),c+=30,s.set(t,c),c+=32,s[c]=o.length>>8&255,s[c+1]=255&o.length,c+=2,s.set(o,c),c+=o.length;return{manifestChunk:{data:s,address:gh(s).address.toHex()}}}function Vm(e){const t=e instanceof Uint8Array?e:Ld(e);if(32!==t.length)throw new Error(`Invalid content reference length: ${t.length} (expected 32 bytes)`);const n=new mu;return n.addFork("/",Au,{"website-index-document":"index.bin"}),n.addFork("index.bin",t,{"Content-Type":"application/octet-stream",Filename:"index.bin"}),{manifestNode:n}}function Lm(e){const t=e instanceof Uint8Array?e:new Ti(e).toUint8Array();if(32!==t.length)throw new Error(`Invalid content reference length: ${t.length} (expected 32 bytes)`);const n=new Uint8Array(192);let r=0;return r+=32,n.set(Mm,r),r+=31,n[r]=32,r+=1,r+=32,n[r+5]=128,r+=32,n[r]=2,r+=1,n[r]=1,r+=1,n[r]=47,r+=30,n.set(t,r),r+=32,n}const jm=4096;function Gm(e){if(e.length>jm)throw new Error(`Payload too large to pad: ${e.length} > 4096`);if(e.length===jm)return e;const t=new Uint8Array(jm);return t.set(e,0),t}function Km(e){if(e.length<192)throw new Error(`Manifest too small: ${e.length} bytes (expected at least 192)`);const t=e[63];32!==t&&console.warn(`[ManifestBuilder] Unexpected refBytesCount: ${t} (expected 32)`);const n=e.slice(96,128),r=Math.floor(47/8);if(!(128&n[r]))throw new Error('Manifest does not contain "/" fork');let i=0;for(let e=0;e<r;e++)i+=Hm(n[e]);for(let e=0;e<7;e++)n[r]&1<<e&&i++;let o=128;for(let t=0;t<i;t++){const t=e[o];if(o+=64,!!(16&t)){o+=2+(e[o]<<8|e[o+1])}}const a=e[o+1];if(1!==a||47!==e[o+2])throw new Error(`Expected "/" prefix, got length ${a} and byte 0x${e[o+2].toString(16)}`);const s=o+32,c=e.slice(s,s+32);if(Wm(c))throw new Error('Manifest "/" fork has zero reference');return new Ti(c).toHex()}function Hm(e){let t=0;for(;e;)t+=1&e,e>>>=1;return t}function Wm(e){for(let t=0;t<e.length;t++)if(0!==e[t])return!1;return!0}function Zm(e){if(e.length<96)throw new Error(`Manifest too small: ${e.length} bytes (expected at least 96)`);const t=e.slice(64,96);if(Wm(t))throw new Error("Manifest entry is zero");return new Ti(t).toHex()}function Jm(e){if(e.length<192)throw new Error(`Manifest too small: ${e.length} bytes (expected at least 192)`);const t=e.slice(96,128),n=Math.floor(105/8);if(!(2&t[n]))throw new Error('Manifest does not contain "index.bin" fork');let r=0;for(let e=0;e<n;e++)r+=Hm(t[e]);for(let e=0;e<1;e++)t[n]&1<<e&&r++;let i=128;for(let t=0;t<r;t++){const t=e[i];if(i+=64,!!(16&t)){i+=2+(e[i]<<8|e[i+1])}}const o=e[i],a=e[i+1];if(105!==e[i+2])throw new Error(`Expected "index.bin" prefix, got byte 0x${e[i+2].toString(16)}`);if(a>=9){const t=e.slice(i+2,i+2+9),n=(new TextEncoder).encode("index.bin");t.every((e,t)=>e===n[t])||console.warn('[ManifestBuilder] Prefix does not fully match "index.bin"')}if(!!!(2&o))throw new Error('"index.bin" fork is not a VALUE type');const s=i+32,c=e.slice(s,s+32);if(Wm(c))throw new Error('Manifest "index.bin" fork has zero reference');return new Ti(c).toHex()}const Xm=1e3,Ym=6e4,Qm=36e5,eg=24*Qm,tg=30*eg;export{Um as ACCOUNT_SYNC_TOPIC_PREFIX,Gu as AccountStateSnapshotSchemaV1,Hl as ActAddGranteesMessageSchema,zd as ActAddGranteesResponseMessageSchema,Kl as ActDownloadDataMessageSchema,$d as ActDownloadDataResponseMessageSchema,Zl as ActGetGranteesMessageSchema,Pd as ActGetGranteesResponseMessageSchema,Wl as ActRevokeGranteesMessageSchema,Fd as ActRevokeGranteesResponseMessageSchema,Gl as ActUploadDataMessageSchema,Cd as ActUploadDataResponseMessageSchema,el as ActUploadOptionsSchema,Bu as AddressSchema,Im as AgentBackupHeaderSchemaV1,ap as AsyncEpochFinder,qd as AuthDataSchema,ul as AuthStatusSchema,ef as BUCKET_DEPTH,sp as BasicEpochUpdater,Tu as BatchIdSchema,ll as ButtonStylesSchema,rf as CHUNK_SIZE,nf as DATA_COUNTER_START,eg as DAY,of as DEFAULT_BATCH_DEPTH,Ru as DEFAULT_BEE_NODE_URL,Su as DEFAULT_GNOSIS_RPC_URL,tg as DEFAULT_SESSION_DURATION,vm as DebouncedUtilizationUploader,ol as DownloadOptionsSchema,km as EncryptedSwarmIdExportSchemaV1,Du as EncryptionKeySchema,tp as EpochIndex,Sm as EthereumBackupHeaderSchemaV1,Fu as FeedIndexSchema,sl as FileDataSchema,pp as GNOSIS_BLOCK_TIME,Qm as HOUR,Cu as IdentifierSchema,Ud as IframeToParentMessageSchema,$f as LocalStorageAdapter,ep as MAX_LEVEL,jm as MAX_PADDED_PAYLOAD_SIZE,Ym as MINUTE,zf as MemoryStorageAdapter,Qh as NUM_BUCKETS,Ku as NetworkSettingsSchemaV1,Jl as ParentToIframeMessageSchema,Rm as PasskeyBackupHeaderSchemaV1,Md as PopupToIframeMessageSchema,cl as PostageBatchSchema,Ou as PrivateKeySchema,ku as ReferenceSchema,tl as RequestOptionsSchema,Xm as SECOND,Xu as STORAGE_CHALLENGE_KEY,yp as SWARMSCAN_STATS_URL,Zu as SWARM_SECRET_PREFIX,Nd as SetSecretMessageSchema,$u as SignatureSchema,Xd as SwarmIdClient,wm as SwarmIdProxy,op as SyncEpochFinder,zu as TimestampSchema,tf as UTILIZATION_SLOTS_PER_BUCKET,Qu as UploadOptionsSchema,al as UploadResultSchema,Df as UtilizationAwareStamper,Jh as UtilizationStoreDB,Ff as VersionedStorageManager,Cf as VersionedStorageSchema,fm as addGranteesToAct,sf as assignChunksToBuckets,Zd as backupKeyToPrivateKey,Ap as buildAuthUrl,Dm as buildBackupHeader,_m as buildBzzCompatibleManifest,Vm as buildBzzManifestNode,Lm as buildMinimalManifest,Yh as calculateContentHash,Ep as calculateExpiryTimestamp,xf as calculateMaxSlotsPerBucket,bp as calculateTTLSeconds,Of as calculateUtilization,Af as calculateUtilizationUpdate,Vp as compressPublicKey,Hf as createAccountsStorageManager,dm as createActForContent,up as createAsyncEpochFinder,Zf as createConnectedAppsStorageManager,Cm as createEncryptedExport,dp as createEpochFinder,lp as createEpochUpdater,Wf as createIdentitiesStorageManager,Pf as createLocalStorageManager,Uf as createMemoryStorageManager,Qf as createNetworkSettingsStorageManager,Xf as createPostageStampsStorageManager,Rf as createStamper,qm as createSyncAccount,cp as createSyncEpochFinder,qf as createZodParser,hm as decryptActReference,Om as decryptBackupPayload,$m as decryptEncryptedExport,Hd as deriveAccountBackupKey,Wd as deriveAccountSwarmEncryptionKey,Tm as deriveBackupEncryptionKey,Kd as deriveIdentityKey,_d as deriveSecret,Pm as deserializeAccountState,Em as deserializeAccountStateSnapshot,yf as deserializeUint32Array,Jf as disconnectApp,Vh as downloadDataWithChunkAPI,Bm as encryptBackupPayload,Xh as evictOldEntries,Jm as extractContentFromFlatManifest,Zm as extractEntryFromManifest,Km as extractReferenceFromManifest,wp as fetchSwarmPrice,vp as formatTTL,Vd as generateMasterKey,xp as getBlockTimestamp,mm as getGranteesFromAct,Ef as hasBucketCapacity,Fh as hexAddress,Ld as hexToUint8Array,bm as initProxy,vf as initializeBatchUtilization,np as lca,Kh as loadMantarayTreeWithChunkAPI,kf as loadUtilizationState,rp as next,Gm as padPayloadForSOCDetection,gm as parseCompressedPublicKey,zm as parseEncryptedExportHeader,Sf as prepareBucketState,_p as publicKeyFromCompressed,Up as publicKeyFromPrivate,bf as reconstructFromChunks,Nm as restoreAccountFromSwarm,pm as revokeGranteesFromAct,Gh as saveMantarayTreeRecursively,Tf as saveUtilizationState,Lf as serializeAccount,Fm as serializeAccountState,xm as serializeAccountStateSnapshot,Gf as serializeConnectedApp,jf as serializeIdentity,Yf as serializeNetworkSettings,Kf as serializePostageStamp,gf as serializeUint32Array,wf as splitIntoChunks,af as toBucket,jd as uint8ArrayToHex,Bf as updateAfterWrite,Jd as utils,Gd as verifySecret};
|
|
2
|
+
//# sourceMappingURL=swarm-id.esm.js.map
|