@junobuild/core-standalone 2.0.0 → 2.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.
@@ -12,7 +12,7 @@ import{A as je,B as Ke,C as jr,D as Me,E as Rr,F as ye,G as wr,H as Ot,a as ln,b
12
12
  Request ID: ${V(t)}
13
13
  `)}throw new Error("unreachable")}var qn=({IDL:e})=>{let r=e.Variant({mainnet:e.Null,testnet:e.Null}),t=e.Text,n=e.Record({network:r,address:t,min_confirmations:e.Opt(e.Nat32)}),i=e.Nat64,a=i,o=e.Nat32,s=e.Record({start_height:o,end_height:e.Opt(o),network:r}),c=e.Vec(e.Nat8),u=e.Record({tip_height:o,block_headers:e.Vec(c)}),p=e.Record({network:r}),d=e.Nat64,m=e.Vec(d),h=e.Record({network:r,filter:e.Opt(e.Variant({page:e.Vec(e.Nat8),min_confirmations:e.Nat32})),address:t}),g=e.Vec(e.Nat8),I=e.Record({txid:e.Vec(e.Nat8),vout:e.Nat32}),S=e.Record({height:e.Nat32,value:i,outpoint:I}),B=e.Record({next_page:e.Opt(e.Vec(e.Nat8)),tip_height:o,tip_block_hash:g,utxos:e.Vec(S)}),O=e.Record({transaction:e.Vec(e.Nat8),network:r}),y=e.Principal,v=e.Record({canister_id:y,num_requested_changes:e.Opt(e.Nat64)}),R=e.Variant({from_user:e.Record({user_id:e.Principal}),from_canister:e.Record({canister_version:e.Opt(e.Nat64),canister_id:e.Principal})}),w=e.Vec(e.Nat8),k=e.Variant({creation:e.Record({controllers:e.Vec(e.Principal)}),code_deployment:e.Record({mode:e.Variant({reinstall:e.Null,upgrade:e.Null,install:e.Null}),module_hash:e.Vec(e.Nat8)}),load_snapshot:e.Record({canister_version:e.Nat64,taken_at_timestamp:e.Nat64,snapshot_id:w}),controllers_change:e.Record({controllers:e.Vec(e.Principal)}),code_uninstall:e.Null}),K=e.Record({timestamp_nanos:e.Nat64,canister_version:e.Nat64,origin:R,details:k}),D=e.Record({controllers:e.Vec(e.Principal),module_hash:e.Opt(e.Vec(e.Nat8)),recent_changes:e.Vec(K),total_num_changes:e.Nat64}),E=e.Record({canister_id:y}),G=e.Variant({controllers:e.Null,public:e.Null,allowed_viewers:e.Vec(e.Principal)}),$=e.Record({freezing_threshold:e.Nat,controllers:e.Vec(e.Principal),reserved_cycles_limit:e.Nat,log_visibility:G,wasm_memory_limit:e.Nat,memory_allocation:e.Nat,compute_allocation:e.Nat}),xe=e.Record({status:e.Variant({stopped:e.Null,stopping:e.Null,running:e.Null}),memory_size:e.Nat,cycles:e.Nat,settings:$,query_stats:e.Record({response_payload_bytes_total:e.Nat,num_instructions_total:e.Nat,num_calls_total:e.Nat,request_payload_bytes_total:e.Nat}),idle_cycles_burned_per_day:e.Nat,module_hash:e.Opt(e.Vec(e.Nat8)),reserved_cycles:e.Nat}),P=e.Record({canister_id:y}),ne=e.Record({freezing_threshold:e.Opt(e.Nat),controllers:e.Opt(e.Vec(e.Principal)),reserved_cycles_limit:e.Opt(e.Nat),log_visibility:e.Opt(G),wasm_memory_limit:e.Opt(e.Nat),memory_allocation:e.Opt(e.Nat),compute_allocation:e.Opt(e.Nat)}),nr=e.Record({settings:e.Opt(ne),sender_canister_version:e.Opt(e.Nat64)}),ir=e.Record({canister_id:y}),Oe=e.Record({canister_id:y}),Y=e.Record({canister_id:y,snapshot_id:w}),ie=e.Record({canister_id:y}),M=e.Variant({secp256k1:e.Null}),Re=e.Record({key_id:e.Record({name:e.Text,curve:M}),canister_id:e.Opt(y),derivation_path:e.Vec(e.Vec(e.Nat8))}),ae=e.Record({public_key:e.Vec(e.Nat8),chain_code:e.Vec(e.Nat8)}),ar=e.Record({canister_id:y}),oe=e.Record({idx:e.Nat64,timestamp_nanos:e.Nat64,content:e.Vec(e.Nat8)}),or=e.Record({canister_log_records:e.Vec(oe)}),Be=e.Record({value:e.Text,name:e.Text}),we=e.Record({status:e.Nat,body:e.Vec(e.Nat8),headers:e.Vec(Be)}),se=e.Record({url:e.Text,method:e.Variant({get:e.Null,head:e.Null,post:e.Null}),max_response_bytes:e.Opt(e.Nat64),body:e.Opt(e.Vec(e.Nat8)),transform:e.Opt(e.Record({function:e.Func([e.Record({context:e.Vec(e.Nat8),response:we})],[we],["query"]),context:e.Vec(e.Nat8)})),headers:e.Vec(Be)}),L=e.Variant({reinstall:e.Null,upgrade:e.Opt(e.Record({wasm_memory_persistence:e.Opt(e.Variant({keep:e.Null,replace:e.Null})),skip_pre_upgrade:e.Opt(e.Bool)})),install:e.Null}),be=e.Record({hash:e.Vec(e.Nat8)}),sr=e.Record({arg:e.Vec(e.Nat8),wasm_module_hash:e.Vec(e.Nat8),mode:L,chunk_hashes_list:e.Vec(be),target_canister:y,store_canister:e.Opt(y),sender_canister_version:e.Opt(e.Nat64)}),cr=e.Vec(e.Nat8),lr=e.Record({arg:e.Vec(e.Nat8),wasm_module:cr,mode:L,canister_id:y,sender_canister_version:e.Opt(e.Nat64)}),ur=e.Record({canister_id:y}),De=e.Record({id:w,total_size:e.Nat64,taken_at_timestamp:e.Nat64}),dr=e.Vec(De),pr=e.Record({canister_id:y,sender_canister_version:e.Opt(e.Nat64),snapshot_id:w}),_r=e.Record({start_at_timestamp_nanos:e.Nat64,subnet_id:e.Principal}),mr=e.Record({num_block_failures_total:e.Nat64,node_id:e.Principal,num_blocks_proposed_total:e.Nat64}),yr=e.Vec(e.Record({timestamp_nanos:e.Nat64,node_metrics:e.Vec(mr)})),hr=e.Record({settings:e.Opt(ne),specified_id:e.Opt(y),amount:e.Opt(e.Nat),sender_canister_version:e.Opt(e.Nat64)}),fr=e.Record({canister_id:y}),Tr=e.Record({canister_id:y,amount:e.Nat}),gr=e.Vec(e.Nat8),qe=e.Variant({ed25519:e.Null,bip340secp256k1:e.Null}),Ee=e.Record({key_id:e.Record({algorithm:qe,name:e.Text}),canister_id:e.Opt(y),derivation_path:e.Vec(e.Vec(e.Nat8))}),Nr=e.Record({public_key:e.Vec(e.Nat8),chain_code:e.Vec(e.Nat8)}),xr=e.Record({key_id:e.Record({name:e.Text,curve:M}),derivation_path:e.Vec(e.Vec(e.Nat8)),message_hash:e.Vec(e.Nat8)}),Fe=e.Record({signature:e.Vec(e.Nat8)}),Ae=e.Variant({bip341:e.Record({merkle_root_hash:e.Vec(e.Nat8)})}),ya=e.Record({aux:e.Opt(Ae),key_id:e.Record({algorithm:qe,name:e.Text}),derivation_path:e.Vec(e.Vec(e.Nat8)),message:e.Vec(e.Nat8)}),ha=e.Record({signature:e.Vec(e.Nat8)}),fa=e.Record({canister_id:y}),Ta=e.Record({canister_id:y}),ga=e.Record({canister_id:y}),Na=e.Vec(be),xa=e.Record({subnet_id:e.Principal}),Oa=e.Record({replica_version:e.Text}),Ra=e.Record({replace_snapshot:e.Opt(w),canister_id:y}),wa=De,ba=e.Record({canister_id:y,sender_canister_version:e.Opt(e.Nat64)}),Ea=e.Record({canister_id:e.Principal,settings:ne,sender_canister_version:e.Opt(e.Nat64)}),Fa=e.Record({chunk:e.Vec(e.Nat8),canister_id:e.Principal}),Aa=be;return e.Service({bitcoin_get_balance:e.Func([n],[a],[]),bitcoin_get_block_headers:e.Func([s],[u],[]),bitcoin_get_current_fee_percentiles:e.Func([p],[m],[]),bitcoin_get_utxos:e.Func([h],[B],[]),bitcoin_send_transaction:e.Func([O],[],[]),canister_info:e.Func([v],[D],[]),canister_status:e.Func([E],[xe],[]),clear_chunk_store:e.Func([P],[],[]),create_canister:e.Func([nr],[ir],[]),delete_canister:e.Func([Oe],[],[]),delete_canister_snapshot:e.Func([Y],[],[]),deposit_cycles:e.Func([ie],[],[]),ecdsa_public_key:e.Func([Re],[ae],[]),fetch_canister_logs:e.Func([ar],[or],["query"]),http_request:e.Func([se],[we],[]),install_chunked_code:e.Func([sr],[],[]),install_code:e.Func([lr],[],[]),list_canister_snapshots:e.Func([ur],[dr],[]),load_canister_snapshot:e.Func([pr],[],[]),node_metrics_history:e.Func([_r],[yr],[]),provisional_create_canister_with_cycles:e.Func([hr],[fr],[]),provisional_top_up_canister:e.Func([Tr],[],[]),raw_rand:e.Func([],[gr],[]),schnorr_public_key:e.Func([Ee],[Nr],[]),sign_with_ecdsa:e.Func([xr],[Fe],[]),sign_with_schnorr:e.Func([ya],[ha],[]),start_canister:e.Func([fa],[],[]),stop_canister:e.Func([Ta],[],[]),stored_chunks:e.Func([ga],[Na],[]),subnet_info:e.Func([xa],[Oa],[]),take_canister_snapshot:e.Func([Ra],[wa],[]),uninstall_code:e.Func([ba],[],[]),update_settings:e.Func([Ea],[],[]),upload_chunk:e.Func([Fa],[Aa],[])})};var zr=class extends Br{constructor(r,t,n,i){super(["Call failed:",` Canister: ${r.toText()}`,` Method: ${t} (${n})`,...Object.getOwnPropertyNames(i).map(a=>` "${a}": ${JSON.stringify(i[a])}`)].join(`
14
14
  `)),this.canisterId=r,this.methodName=t,this.type=n,this.props=i}},Ct=class extends zr{constructor(r,t,n){var i;super(r,t,"query",{Status:n.status,Code:(i=un[n.reject_code])!==null&&i!==void 0?i:`Unknown Code "${n.reject_code}"`,Message:n.reject_message}),this.result=n}},Gr=class extends zr{constructor(r,t,n,i,a,o,s){super(r,t,"update",Object.assign({"Request ID":V(n)},i.body?Object.assign(Object.assign({},s?{"Error code":s}:{}),{"Reject code":String(a),"Reject message":o}):{"HTTP status code":i.status.toString(),"HTTP status text":i.statusText})),this.requestId=n,this.response=i,this.reject_code=a,this.reject_message=o,this.error_code=s}},W=Symbol.for("ic-agent-metadata"),ue=class e{constructor(r){this[W]=Object.freeze(r)}static agentOf(r){return r[W].config.agent}static interfaceOf(r){return r[W].service}static canisterIdOf(r){return T.from(r[W].config.canisterId)}static async install(r,t){let n=r.mode===void 0?{install:null}:r.mode,i=r.arg?[...new Uint8Array(r.arg)]:[],a=[...new Uint8Array(r.module)],o=typeof t.canisterId=="string"?T.fromText(t.canisterId):t.canisterId;await jn(t).install_code({mode:n,arg:i,wasm_module:a,canister_id:o,sender_canister_version:[]})}static async createCanister(r,t){function n(a){return[{controllers:a.controllers?[a.controllers]:[],compute_allocation:a.compute_allocation?[a.compute_allocation]:[],freezing_threshold:a.freezing_threshold?[a.freezing_threshold]:[],memory_allocation:a.memory_allocation?[a.memory_allocation]:[],reserved_cycles_limit:[],log_visibility:[],wasm_memory_limit:[]}]}let{canister_id:i}=await jn(r||{}).provisional_create_canister_with_cycles({amount:[],settings:n(t||{}),specified_id:[],sender_canister_version:[]});return i}static async createAndInstallCanister(r,t,n){let i=await this.createCanister(n);return await this.install(Object.assign({},t),Object.assign(Object.assign({},n),{canisterId:i})),this.createActor(r,Object.assign(Object.assign({},n),{canisterId:i}))}static createActorClass(r,t){let n=r({IDL:Or});class i extends e{constructor(o){if(!o.canisterId)throw new Br(`Canister ID is required, but received ${typeof o.canisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`);let s=typeof o.canisterId=="string"?T.fromText(o.canisterId):o.canisterId;super({config:Object.assign(Object.assign(Object.assign({},Mn),o),{canisterId:s}),service:n});for(let[c,u]of n._fields)t?.httpDetails&&u.annotations.push(It),t?.certificate&&u.annotations.push(Jn),this[c]=ho(this,c,u,o.blsVerify)}}return i}static createActor(r,t){if(!t.canisterId)throw new Br(`Canister ID is required, but received ${typeof t.canisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`);return new(this.createActorClass(r))(t)}static createActorWithHttpDetails(r,t){return new(this.createActorClass(r,{httpDetails:!0}))(t)}static createActorWithExtendedDetails(r,t,n={httpDetails:!0,certificate:!0}){return new(this.createActorClass(r,n))(t)}};function Ge(e,r){let t=Or.decode(e,Kn.Buffer.from(r));switch(t.length){case 0:return;case 1:return t[0];default:return t}}var Mn={pollingStrategyFactory:Hr.defaultStrategy},It="http-details",Jn="certificate";function ho(e,r,t,n){let i;t.annotations.includes("query")||t.annotations.includes("composite_query")?i=async(o,...s)=>{var c,u;o=Object.assign(Object.assign({},o),(u=(c=e[W].config).queryTransform)===null||u===void 0?void 0:u.call(c,r,s,Object.assign(Object.assign({},e[W].config),o)));let p=o.agent||e[W].config.agent||Ot(),d=T.from(o.canisterId||e[W].config.canisterId),m=Or.encode(t.argTypes,s),h=await p.query(d,{methodName:r,arg:m,effectiveCanisterId:o.effectiveCanisterId}),g=Object.assign(Object.assign({},h.httpDetails),{requestDetails:h.requestDetails});switch(h.status){case"rejected":throw new Ct(d,r,h);case"replied":return t.annotations.includes(It)?{httpDetails:g,result:Ge(t.retTypes,h.reply.arg)}:Ge(t.retTypes,h.reply.arg)}}:i=async(o,...s)=>{var c,u;o=Object.assign(Object.assign({},o),(u=(c=e[W].config).callTransform)===null||u===void 0?void 0:u.call(c,r,s,Object.assign(Object.assign({},e[W].config),o)));let p=o.agent||e[W].config.agent||Ot(),{canisterId:d,effectiveCanisterId:m,pollingStrategyFactory:h}=Object.assign(Object.assign(Object.assign({},Mn),e[W].config),o),g=T.from(d),I=m!==void 0?T.from(m):g,S=Or.encode(t.argTypes,s),{requestId:B,response:O,requestDetails:y}=await p.call(g,{methodName:r,arg:S,effectiveCanisterId:I}),v,R;if(O.body&&O.body.certificate){if(p.rootKey==null)throw new Error("Agent is missing root key");let D=O.body.certificate;R=await qr.create({certificate:Nt(D),rootKey:p.rootKey,canisterId:T.from(d),blsVerify:n});let E=[new TextEncoder().encode("request_status"),B];switch(new TextDecoder().decode(X(R.lookup([...E,"status"])))){case"replied":v=X(R.lookup([...E,"reply"]));break;case"rejected":{let $=new Uint8Array(X(R.lookup([...E,"reject_code"])))[0],xe=new TextDecoder().decode(X(R.lookup([...E,"reject_message"]))),P=X(R.lookup([...E,"error_code"])),ne=P?new TextDecoder().decode(P):void 0;throw new Gr(g,r,B,O,$,xe,ne)}}}else if(O.body&&"reject_message"in O.body){let{reject_code:D,reject_message:E,error_code:G}=O.body;throw new Gr(g,r,B,O,D,E,G)}if(O.status===202){let D=h(),E=await St(p,I,B,D,n);R=E.certificate,v=E.reply}let w=t.annotations.includes(It),k=t.annotations.includes(Jn),K=Object.assign(Object.assign({},O),{requestDetails:y});if(v!==void 0)return w&&k?{httpDetails:K,certificate:R,result:Ge(t.retTypes,v)}:k?{certificate:R,result:Ge(t.retTypes,v)}:w?{httpDetails:K,result:Ge(t.retTypes,v)}:Ge(t.retTypes,v);if(t.retTypes.length===0)return w?{httpDetails:O,result:void 0}:void 0;throw new Error(`Call was returned undefined, but type [${t.retTypes.join(",")}].`)};let a=(...o)=>i({},...o);return a.withOptions=o=>(...s)=>i(o,...s),a}function jn(e){function r(t,n){if(e.effectiveCanisterId)return{effectiveCanisterId:T.from(e.effectiveCanisterId)};let i=n[0],a=T.fromHex("");return i&&typeof i=="object"&&i.target_canister&&t==="install_chunked_code"&&(a=T.from(i.target_canister)),i&&typeof i=="object"&&i.canister_id&&(a=T.from(i.canister_id)),{effectiveCanisterId:a}}return ue.createActor(qn,Object.assign(Object.assign(Object.assign({},e),{canisterId:T.fromHex("")}),{callTransform:r,queryTransform:r}))}var To=(e=>(e[e.FractionalMoreThan8Decimals=0]="FractionalMoreThan8Decimals",e[e.InvalidFormat=1]="InvalidFormat",e[e.FractionalTooManyDecimals=2]="FractionalTooManyDecimals",e))(To||{}),Ac=BigInt(1e8);var _=e=>e==null,f=e=>!_(e);var go=class extends Error{},Fr=(e,r)=>{if(e==null)throw new go(r)};var de=e=>new Uint8Array(e),$r=e=>Array.from(e);var Hn=({a:e,b:r})=>e.length===r.length&&e.every((t,n)=>t===r[n]);var Wn="abcdefghijklmnopqrstuvwxyz234567",Er=Object.create(null);for(let e=0;e<Wn.length;e++)Er[Wn[e]]=e;Er[0]=Er.o;Er[1]=Er.i;var Yr=e=>btoa(String.fromCharCode(...new Uint8Array(e)));var Pc=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);var kt="__bigint__",Ut="__principal__",Bt="__uint8array__",zn=(e,r)=>typeof r=="bigint"?{[kt]:`${r}`}:f(r)&&r instanceof T?{[Ut]:r.toText()}:f(r)&&r instanceof Uint8Array?{[Bt]:Array.from(r)}:r,Gn=(e,r)=>{let t=n=>r[n];return f(r)&&typeof r=="object"&&kt in r?BigInt(t(kt)):f(r)&&typeof r=="object"&&Ut in r?T.fromText(t(Ut)):f(r)&&typeof r=="object"&&Bt in r?Uint8Array.from(t(Bt)):r};var N=e=>f(e)?[e]:[],A=e=>e?.[0];var No=({authData:e})=>{if(e.byteLength<37)return{invalidAuthData:null};if(e.byteLength<53)return{invalidAuthData:null};let r=e.slice(37,53),t=xo({bytes:r});return"aaguid"in t?{aaguidBytes:r,aaguidText:t.aaguid}:{unknownProvider:null}},xo=({bytes:e})=>{if(e.length!==16)return{invalidBytes:null};let r=(e instanceof Uint8Array?$r(e):e).map(t=>t.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5");return r==="00000000-0000-0000-0000-000000000000"?{unknownProvider:null}:{aaguid:r}};function Oo(e){let r=new DataView(new ArrayBuffer(2)),t=e.slice(53,55);[...new Uint8Array(t)].forEach((i,a)=>r.setUint8(a,i));let n=r.getUint16(0);return e.slice(55+n)}function Ro(e){return Me(e.buffer,Ke).buffer}var wo=class{constructor(e){this._cose=e,this._encodedKey=Ro(e)}_encodedKey;toDer(){return this._encodedKey}},Zn=class{#e;#r;constructor({rawId:e,cose:r}){this.#e=e,this.#r=new wo(r)}getPublicKey(){return this.#r}getCredentialId(){return this.#e}getCredentialIdText(){return Yr(this.#e)}},bo=class extends Zn{#e;#r;constructor({authData:e,...r}){super(r);let t=No({authData:e});this.#e="aaguidText"in t?t.aaguidText:void 0,this.#r="aaguidBytes"in t?t.aaguidBytes:void 0}getAAGUID(){return this.#r}getAAGUIDText(){return this.#e}},Eo=class extends Zn{},Fo=class extends Error{},Ao=class extends Error{},vo=class extends Error{},Vo=class extends Error{},Po=class extends Error{},So=class extends Error{},Co=class extends Error{},$n=class extends Error{};var Io={ECDSA_WITH_SHA256:-7,RSA_WITH_SHA256:-257},ko=6e4,Qn=()=>window.crypto.getRandomValues(new Uint8Array(16)),Uo=()=>Qn(),Bo=()=>Qn(),Do=()=>{let{location:{href:e}}=window,r=URL.parse(e);if(_(r))throw new Fo;let{hostname:t}=r;return t},ei=({appId:e})=>e?.id??Do(),qo=({appId:e,user:r}={})=>{let{document:{title:t}}=window,n=()=>({rp:{name:e?.name??t,id:ei({appId:e})}}),i=()=>({user:{id:Bo(),name:r?.name??r?.displayName??t,displayName:r?.displayName??t}});return{attestation:"direct",challenge:Uo(),...n(),...i(),pubKeyCredParams:Object.values(Io).map(a=>({type:"public-key",alg:a})),excludeCredentials:[],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"preferred",residentKey:"required",requireResidentKey:!0}}},jo=(e={})=>({rpId:ei(e),allowCredentials:[],userVerification:"required"}),Dt=async({fn:e,step:r,onProgress:t})=>{t?.({step:r,state:"in_progress"});try{let n=await e();return t?.({step:r,state:"success"}),n}catch(n){throw t?.({step:r,state:"error"}),n}},fe=(e=>(e[e.RequestingUserCredential=0]="RequestingUserCredential",e[e.FinalizingCredential=1]="FinalizingCredential",e[e.Signing=2]="Signing",e))(fe||{}),ri=({timeout:e})=>AbortSignal.timeout(e??ko),Ko=async({challenge:e,credentialIds:r,passkeyOptions:t,timeout:n})=>await navigator.credentials.get({publicKey:{...jo(t),challenge:e.buffer,allowCredentials:(r??[]).map(i=>({id:i.buffer,type:"public-key"}))},signal:ri({timeout:n})}),Yn=e=>{if(e.status!=="initialized")throw new Ao},Xn=e=>{if(_(e))throw new vo},Ln=({type:e})=>{if(e!=="public-key")throw new Vo},qt=class Ar extends ce{#e;#r;constructor({onProgress:r,...t}){if(super(),this.#e=r,"retrievePublicKey"in t){let{retrievePublicKey:n}=t;this.#r={status:"pending",retrievePublicKey:n};return}this.#r=Ar.#t({credential:new bo(t)})}static#t({credential:r}){return{status:"initialized",credential:r}}static async createWithNewCredential({passkeyOptions:r,timeout:t,...n}={}){let i=await navigator.credentials.create({publicKey:qo(r),signal:ri({timeout:t})});Xn(i),Ln(i);let{response:{attestationObject:a},rawId:o}=i;if(_(a))throw new Po;let{authData:s}=Dr.decode(a),c=Oo(s);return new Ar({...n,rawId:de(o),cose:c,authData:s})}static async createWithExistingCredential(r){return new Ar(r)}getPublicKey(){Yn(this.#r);let{credential:r}=this.#r;return r.getPublicKey()}getCredential(){Yn(this.#r);let{credential:r}=this.#r;return r}async sign(r){let t=await Dt({fn:async()=>{let n=await Ko({challenge:de(r),...this.#r.status==="initialized"&&{credentialIds:[this.#r.credential.getCredentialId()]}});return Xn(n),Ln(n),n},step:0,onProgress:this.#e});return await Dt({fn:async()=>{let{rawId:n}=t;if(this.#r.status==="initialized"){if(!Hn({a:this.#r.credential.getCredentialId(),b:de(n)}))throw new So;return}let{retrievePublicKey:i}=this.#r,a=await i({credentialId:de(n)});this.#r=Ar.#t({credential:new Eo({rawId:de(n),cose:a})})},step:1,onProgress:this.#e}),await Dt({fn:async()=>{let{response:n}=t,{clientDataJSON:i}=n,{authenticatorData:a,signature:o}="authenticatorData"in n&&"signature"in n?n:{};if(_(a))throw new $n;if(_(o))throw new $n;let s=Dr.encode({authenticator_data:a,client_data_json:new TextDecoder().decode(i),signature:de(o)});if(_(s))throw new Co;return Object.assign(s,{__signature__:void 0}),s},step:2,onProgress:this.#e})}},Mo=async()=>f(window.PublicKeyCredential)&&"isUserVerifyingPlatformAuthenticatorAvailable"in PublicKeyCredential?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1;var $e=class{callbacks=[];populate(r){this.callbacks.forEach(({callback:t})=>t(r))}subscribe(r){let t=Symbol();return this.callbacks.push({id:t,callback:r}),()=>this.callbacks=this.callbacks.filter(({id:n})=>n!==t)}};var H=class e extends $e{static instance;authUser=null;constructor(){super()}static getInstance(){return e.instance||(e.instance=new e),e.instance}set(r){this.authUser=r,this.populate(r)}get(){return this.authUser}subscribe(r){let t=super.subscribe(r);return r(this.authUser),t}reset(){this.authUser=null,this.populate(this.authUser)}};var jt=({message:e,detail:r})=>{let t=new CustomEvent(e,{detail:r,bubbles:!0});document.dispatchEvent(t)};var Ye="http://127.0.0.1:5987",ti="rdmx6-jaaaa-aaaaa-aaadq-cai";var ni=async({identity:e,container:r})=>{let n=f(r)&&r!==!1?r===!0?Ye:r:"https://icp-api.io",i=f(r);return await wr.create({identity:e,shouldFetchRootKey:i,host:n})};var Xe=class e{static instance;#e=void 0;constructor(){}static getInstance(){return _(e.instance)&&(e.instance=new e),e.instance}async getAgent({identity:r,...t}){let n=r.getPrincipal().toText();if(_(this.#e)||_(this.#e[n])){let i=await ni({identity:r,...t});return this.#e={...this.#e??{},[n]:i},i}return this.#e[n]}reset(){this.#e=null}};var Le=class e{static instance;#e=void 0;constructor(){}static getInstance(){return _(e.instance)&&(e.instance=new e),e.instance}async getActor({satelliteId:r,identity:t,actorKey:n,...i}){let a=`${n}#${t.getPrincipal().toText()}#${r};`;if(_(this.#e)||_(this.#e[a])){let o=await this.createActor({satelliteId:r,identity:t,...i});return this.#e={...this.#e??{},[a]:o},o}return this.#e[a]}reset(){this.#e=null}async createActor({idlFactory:r,satelliteId:t,...n}){let i=await Xe.getInstance().getAgent(n);return ue.createActor(r,{agent:i,canisterId:t})}};var ii=e=>(e.preventDefault(),e.returnValue="Are you sure you want to exit?"),Jo=()=>{window.addEventListener("beforeunload",ii,{capture:!0})},Wo=()=>{window.removeEventListener("beforeunload",ii,{capture:!0})},Kt=async({fn:e})=>{try{return Jo(),await e()}finally{Wo()}};var q=class e extends $e{static instance;env;constructor(){super()}static getInstance(){return e.instance||(e.instance=new e),e.instance}set(r){this.env=r,this.populate(r)}get(){return this.env}reset(){this.env=null}subscribe(r){let t=super.subscribe(r);return r(this.env),t}};var ai=BigInt(144e11),oi=!1,si={width:576,height:576},ci={width:505,height:705},li="internetcomputer.org";var ui=async e=>{let r=new Blob([JSON.stringify(e,zn)],{type:"application/json; charset=utf-8"});return new Uint8Array(await r.arrayBuffer())},Xr=async e=>{let r=new Blob([e instanceof Uint8Array?e:new Uint8Array(e)],{type:"application/json; charset=utf-8"});return JSON.parse(await r.text(),Gn)},Lr=()=>typeof window<"u";var Zr=({width:e,height:r})=>{if(!Lr()||_(window)||_(window.top))return;let{top:{innerWidth:t,innerHeight:n}}=window,i=n/2+screenY-r/2,a=t/2+screenX-e/2;return`toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=${e}, height=${r}, top=${i}, left=${a}`};var rt=function(e,r,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof r=="function"?e!==r||!i:!r.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,t):i?i.value=t:r.set(e,t),t},Te=function(e,r,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof r=="function"?e!==r||!n:!r.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(e):n?n.value:r.get(e)},Qr,et,Ze,Qe;function di(e){return e!==null&&typeof e=="object"}var Pe=class e{constructor(r){if(Qr.set(this,void 0),et.set(this,void 0),r.byteLength!==e.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");rt(this,Qr,r,"f"),rt(this,et,e.derEncode(r),"f")}static from(r){if(typeof r=="string"){let t=_e(r);return this.fromRaw(t)}else if(di(r)){let t=r;if(di(t)&&Object.hasOwnProperty.call(t,"__derEncodedPublicKey__"))return this.fromDer(t);if(ArrayBuffer.isView(t)){let n=t;return this.fromRaw(_n(n.buffer))}else{if(t instanceof ArrayBuffer)return this.fromRaw(t);if("rawKey"in t)return this.fromRaw(t.rawKey);if("derKey"in t)return this.fromDer(t.derKey);if("toDer"in t)return this.fromDer(t.toDer())}}throw new Error("Cannot construct Ed25519PublicKey from the provided key.")}static fromRaw(r){return new e(r)}static fromDer(r){return new e(this.derDecode(r))}static derEncode(r){let t=Me(r,jr).buffer;return t.__derEncodedPublicKey__=void 0,t}static derDecode(r){let t=Rr(r,jr);if(t.length!==this.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");return t}get rawKey(){return Te(this,Qr,"f")}get derKey(){return Te(this,et,"f")}toDer(){return this.derKey}toRaw(){return this.rawKey}};Qr=new WeakMap,et=new WeakMap;Pe.RAW_KEY_LENGTH=32;var Se=class e extends ce{constructor(r,t){super(),Ze.set(this,void 0),Qe.set(this,void 0),rt(this,Ze,Pe.from(r),"f"),rt(this,Qe,new Uint8Array(t),"f")}static generate(r){if(r&&r.length!==32)throw new Error("Ed25519 Seed needs to be 32 bytes long.");r||(r=je.utils.randomPrivateKey()),dn(r,new Uint8Array(new Array(32).fill(0)))&&console.warn("Seed is all zeros. This is not a secure seed. Please provide a seed with sufficient entropy if this is a production environment.");let t=new Uint8Array(32);for(let i=0;i<32;i++)t[i]=new Uint8Array(r)[i];let n=je.getPublicKey(t);return e.fromKeyPair(n,t)}static fromParsedJson(r){let[t,n]=r;return new e(Pe.fromDer(_e(t)),_e(n))}static fromJSON(r){let t=JSON.parse(r);if(Array.isArray(t)){if(typeof t[0]=="string"&&typeof t[1]=="string")return this.fromParsedJson([t[0],t[1]]);throw new Error("Deserialization error: JSON must have at least 2 items.")}throw new Error(`Deserialization error: Invalid JSON type for string: ${JSON.stringify(r)}`)}static fromKeyPair(r,t){return new e(Pe.fromRaw(r),t)}static fromSecretKey(r){let t=je.getPublicKey(new Uint8Array(r));return e.fromKeyPair(t,r)}toJSON(){return[V(Te(this,Ze,"f").toDer()),V(Te(this,Qe,"f"))]}getKeyPair(){return{secretKey:Te(this,Qe,"f"),publicKey:Te(this,Ze,"f")}}getPublicKey(){return Te(this,Ze,"f")}async sign(r){let t=new Uint8Array(r),n=pn(je.sign(t,Te(this,Qe,"f").slice(0,32)));return Object.defineProperty(n,"__signature__",{enumerable:!1,value:void 0}),n}static verify(r,t,n){let[i,a,o]=[r,t,n].map(s=>(typeof s=="string"&&(s=_e(s)),s instanceof Uint8Array&&(s=s.buffer),new Uint8Array(s)));return je.verify(a,i,o)}};Ze=new WeakMap,Qe=new WeakMap;var Mt=class e extends Error{constructor(r){super(r),this.message=r,Object.setPrototypeOf(this,e.prototype)}};function pi(e){if(typeof globalThis<"u"&&globalThis.crypto&&globalThis.crypto.subtle)return globalThis.crypto.subtle;if(e)return e;if(typeof crypto<"u"&&crypto.subtle)return crypto.subtle;throw new Mt("Global crypto was not available and none was provided. Please inlcude a SubtleCrypto implementation. See https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto")}var Ce=class e extends ce{constructor(r,t,n){super(),this._keyPair=r,this._derKey=t,this._subtleCrypto=n}static async generate(r){let{extractable:t=!1,keyUsages:n=["sign","verify"],subtleCrypto:i}=r??{},a=pi(i),o=await a.generateKey({name:"ECDSA",namedCurve:"P-256"},t,n),s=await a.exportKey("spki",o.publicKey);return new this(o,s,a)}static async fromKeyPair(r,t){let n=pi(t),i=await n.exportKey("spki",r.publicKey);return new e(r,i,n)}getKeyPair(){return this._keyPair}getPublicKey(){let r=this._derKey,t=Object.create(this._keyPair.publicKey);return t.toDer=function(){return r},t}async sign(r){let t={name:"ECDSA",hash:{name:"SHA-256"}};return await this._subtleCrypto.sign(t,this._keyPair.privateKey,r)}};var er=gt(Sa());var Ho=function(e,r,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof r=="function"?e!==r||!i:!r.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,t):i?i.value=t:r.set(e,t),t},vr=function(e,r,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof r=="function"?e!==r||!n:!r.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(e):n?n.value:r.get(e)},ge,tt=class{constructor(r){ge.set(this,void 0),Ho(this,ge,r,"f")}get rawKey(){return vr(this,ge,"f").rawKey}get derKey(){return vr(this,ge,"f").derKey}toDer(){return vr(this,ge,"f").toDer()}getPublicKey(){return vr(this,ge,"f")}getPrincipal(){return T.from(vr(this,ge,"f").rawKey)}transformRequest(){return Promise.reject("Not implemented. You are attempting to use a partial identity to sign calls, but this identity only has access to the public key.To sign calls, use a DelegationIdentity instead.")}};ge=new WeakMap;var zo=function(e,r,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof r=="function"?e!==r||!i:!r.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,t):i?i.value=t:r.set(e,t),t},Go=function(e,r,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof r=="function"?e!==r||!n:!r.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(e):n?n.value:r.get(e)},$o=function(e,r){var t={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&r.indexOf(n)<0&&(t[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(e);i<n.length;i++)r.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(t[n[i]]=e[n[i]]);return t},nt,Yo=new TextEncoder().encode("ic-request-auth-delegation"),Xo=new TextEncoder().encode(`
15
- ic-request`);function Jt(e){if(typeof e!="string"||e.length<64)throw new Error("Invalid public key.");return _e(e)}var rr=class{constructor(r,t,n){this.pubkey=r,this.expiration=t,this.targets=n}toCBOR(){return er.value.map(Object.assign({pubkey:er.value.bytes(this.pubkey),expiration:er.value.u64(this.expiration.toString(16),16)},this.targets&&{targets:er.value.array(this.targets.map(r=>er.value.bytes(r.toUint8Array())))}))}toJSON(){return Object.assign({expiration:this.expiration.toString(16),pubkey:V(this.pubkey)},this.targets&&{targets:this.targets.map(r=>r.toHex())})}};async function Lo(e,r,t,n){let i=new rr(r.toDer(),BigInt(+t)*BigInt(1e6),n),a=new Uint8Array([...Yo,...new Uint8Array(xt(Object.assign({},i)))]),o=await e.sign(a);return{delegation:i,signature:o}}var Ie=class e{constructor(r,t){this.delegations=r,this.publicKey=t}static async create(r,t,n=new Date(Date.now()+900*1e3),i={}){var a,o;let s=await Lo(r,t,n,i.targets);return new e([...((a=i.previous)===null||a===void 0?void 0:a.delegations)||[],s],((o=i.previous)===null||o===void 0?void 0:o.publicKey)||r.getPublicKey().toDer())}static fromJSON(r){let{publicKey:t,delegations:n}=typeof r=="string"?JSON.parse(r):r;if(!Array.isArray(n))throw new Error("Invalid delegations.");let i=n.map(a=>{let{delegation:o,signature:s}=a,{pubkey:c,expiration:u,targets:p}=o;if(p!==void 0&&!Array.isArray(p))throw new Error("Invalid targets.");return{delegation:new rr(Jt(c),BigInt("0x"+u),p&&p.map(d=>{if(typeof d!="string")throw new Error("Invalid target.");return T.fromHex(d)})),signature:Jt(s)}});return new this(i,Jt(t))}static fromDelegations(r,t){return new this(r,t)}toJSON(){return{delegations:this.delegations.map(r=>{let{delegation:t,signature:n}=r,{targets:i}=t;return{delegation:Object.assign({expiration:t.expiration.toString(16),pubkey:V(t.pubkey)},i&&{targets:i.map(a=>a.toHex())}),signature:V(n)}}),publicKey:V(this.publicKey)}}},ke=class extends ce{constructor(r,t){super(),this._inner=r,this._delegation=t}static fromDelegation(r,t){return new this(r,t)}getDelegation(){return this._delegation}getPublicKey(){return{derKey:this._delegation.publicKey,toDer:()=>this._delegation.publicKey}}sign(r){return this._inner.sign(r)}async transformRequest(r){let{body:t}=r,n=$o(r,["body"]),i=await xt(t);return Object.assign(Object.assign({},n),{body:{content:t,sender_sig:await this.sign(new Uint8Array([...Xo,...new Uint8Array(i)])),sender_delegation:this._delegation.delegations,sender_pubkey:this._delegation.publicKey}})}},Vr=class e extends tt{constructor(r,t){super(r),nt.set(this,void 0),zo(this,nt,t,"f")}get delegation(){return Go(this,nt,"f")}static fromDelegation(r,t){return new e(r,t)}};nt=new WeakMap;function _i(e,r){for(let{delegation:i}of e.delegations)if(+new Date(Number(i.expiration/BigInt(1e6)))<=+Date.now())return!1;let t=[],n=r?.scope;n&&(Array.isArray(n)?t.push(...n.map(i=>typeof i=="string"?T.fromText(i):i)):t.push(typeof n=="string"?T.fromText(n):n));for(let i of t){let a=i.toText();for(let{delegation:o}of e.delegations){if(o.targets===void 0)continue;let s=!0;for(let c of o.targets)if(c.toText()===a){s=!1;break}if(s)return!1}}return!0}var Zo=gt(Pa());var mi;(function(e){e[e.ECDSA_WITH_SHA256=-7]="ECDSA_WITH_SHA256"})(mi||(mi={}));var yi=["mousedown","mousemove","keydown","touchstart","wheel"],Pr=class{constructor(r={}){var t;this.callbacks=[],this.idleTimeout=600*1e3,this.timeoutID=void 0;let{onIdle:n,idleTimeout:i=600*1e3}=r||{};this.callbacks=n?[n]:[],this.idleTimeout=i;let a=this._resetTimer.bind(this);window.addEventListener("load",a,!0),yi.forEach(function(s){document.addEventListener(s,a,!0)});let o=(s,c)=>{let u;return(...p)=>{let d=this,m=function(){u=void 0,s.apply(d,p)};clearTimeout(u),u=window.setTimeout(m,c)}};if(r?.captureScroll){let s=o(a,(t=r?.scrollDebounce)!==null&&t!==void 0?t:100);window.addEventListener("scroll",s,!0)}a()}static create(r={}){return new this(r)}registerCallback(r){this.callbacks.push(r)}exit(){clearTimeout(this.timeoutID),window.removeEventListener("load",this._resetTimer,!0);let r=this._resetTimer.bind(this);yi.forEach(function(t){document.removeEventListener(t,r,!0)}),this.callbacks.forEach(t=>t())}_resetTimer(){let r=this.exit.bind(this);window.clearTimeout(this.timeoutID),this.timeoutID=window.setTimeout(r,this.idleTimeout)}};var Qo=(e,r)=>r.some(t=>e instanceof t),hi,fi;function es(){return hi||(hi=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function rs(){return fi||(fi=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Ti=new WeakMap,Ht=new WeakMap,gi=new WeakMap,Wt=new WeakMap,Gt=new WeakMap;function ts(e){let r=new Promise((t,n)=>{let i=()=>{e.removeEventListener("success",a),e.removeEventListener("error",o)},a=()=>{t(ee(e.result)),i()},o=()=>{n(e.error),i()};e.addEventListener("success",a),e.addEventListener("error",o)});return r.then(t=>{t instanceof IDBCursor&&Ti.set(t,e)}).catch(()=>{}),Gt.set(r,e),r}function ns(e){if(Ht.has(e))return;let r=new Promise((t,n)=>{let i=()=>{e.removeEventListener("complete",a),e.removeEventListener("error",o),e.removeEventListener("abort",o)},a=()=>{t(),i()},o=()=>{n(e.error||new DOMException("AbortError","AbortError")),i()};e.addEventListener("complete",a),e.addEventListener("error",o),e.addEventListener("abort",o)});Ht.set(e,r)}var zt={get(e,r,t){if(e instanceof IDBTransaction){if(r==="done")return Ht.get(e);if(r==="objectStoreNames")return e.objectStoreNames||gi.get(e);if(r==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return ee(e[r])},set(e,r,t){return e[r]=t,!0},has(e,r){return e instanceof IDBTransaction&&(r==="done"||r==="store")?!0:r in e}};function Ni(e){zt=e(zt)}function is(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(r,...t){let n=e.call(it(this),r,...t);return gi.set(n,r.sort?r.sort():[r]),ee(n)}:rs().includes(e)?function(...r){return e.apply(it(this),r),ee(Ti.get(this))}:function(...r){return ee(e.apply(it(this),r))}}function as(e){return typeof e=="function"?is(e):(e instanceof IDBTransaction&&ns(e),Qo(e,es())?new Proxy(e,zt):e)}function ee(e){if(e instanceof IDBRequest)return ts(e);if(Wt.has(e))return Wt.get(e);let r=as(e);return r!==e&&(Wt.set(e,r),Gt.set(r,e)),r}var it=e=>Gt.get(e);function Oi(e,r,{blocked:t,upgrade:n,blocking:i,terminated:a}={}){let o=indexedDB.open(e,r),s=ee(o);return n&&o.addEventListener("upgradeneeded",c=>{n(ee(o.result),c.oldVersion,c.newVersion,ee(o.transaction),c)}),t&&o.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),s.then(c=>{a&&c.addEventListener("close",()=>a()),i&&c.addEventListener("versionchange",u=>i(u.oldVersion,u.newVersion,u))}).catch(()=>{}),s}var os=["get","getKey","getAll","getAllKeys","count"],ss=["put","add","delete","clear"],$t=new Map;function xi(e,r){if(!(e instanceof IDBDatabase&&!(r in e)&&typeof r=="string"))return;if($t.get(r))return $t.get(r);let t=r.replace(/FromIndex$/,""),n=r!==t,i=ss.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(i||os.includes(t)))return;let a=async function(o,...s){let c=this.transaction(o,i?"readwrite":"readonly"),u=c.store;return n&&(u=u.index(s.shift())),(await Promise.all([u[t](...s),i&&c.done]))[0]};return $t.set(r,a),a}Ni(e=>({...e,get:(r,t,n)=>xi(r,t)||e.get(r,t,n),has:(r,t)=>!!xi(r,t)||e.has(r,t)}));var Ri="auth-client-db",wi="ic-keyval",cs=async(e=Ri,r=wi,t)=>(at&&(localStorage!=null&&localStorage.getItem(j))&&(localStorage.removeItem(j),localStorage.removeItem(C)),await Oi(e,t,{upgrade:n=>{n.objectStoreNames.contains(r)&&n.clear(r),n.createObjectStore(r)}}));async function ls(e,r,t){return await e.get(r,t)}async function us(e,r,t,n){return await e.put(r,n,t)}async function ds(e,r,t){return await e.delete(r,t)}var Sr=class e{constructor(r,t){this._db=r,this._storeName=t}static async create(r){let{dbName:t=Ri,storeName:n=wi,version:i=bi}=r??{},a=await cs(t,n,i);return new e(a,n)}async set(r,t){return await us(this._db,this._storeName,r,t)}async get(r){var t;return(t=await ls(this._db,this._storeName,r))!==null&&t!==void 0?t:null}async remove(r){return await ds(this._db,this._storeName,r)}};var ps=function(e,r,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof r=="function"?e!==r||!i:!r.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,t):i?i.value=t:r.set(e,t),t},_s=function(e,r,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof r=="function"?e!==r||!n:!r.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(e):n?n.value:r.get(e)},ot,C="identity",j="delegation",Ei="iv",bi=1,at=typeof window<"u",Cr=class{constructor(r="ic-",t){this.prefix=r,this._localStorage=t}get(r){return Promise.resolve(this._getLocalStorage().getItem(this.prefix+r))}set(r,t){return this._getLocalStorage().setItem(this.prefix+r,t),Promise.resolve()}remove(r){return this._getLocalStorage().removeItem(this.prefix+r),Promise.resolve()}_getLocalStorage(){if(this._localStorage)return this._localStorage;let r=typeof window>"u"?typeof globalThis>"u"?typeof self>"u"?void 0:self.localStorage:globalThis.localStorage:window.localStorage;if(!r)throw new Error("Could not find local storage.");return r}},pe=class{constructor(r){ot.set(this,void 0),ps(this,ot,r??{},"f")}get _db(){return new Promise(r=>{if(this.initializedDb){r(this.initializedDb);return}Sr.create(_s(this,ot,"f")).then(t=>{this.initializedDb=t,r(t)})})}async get(r){return await(await this._db).get(r)}async set(r,t){await(await this._db).set(r,t)}async remove(r){await(await this._db).remove(r)}};ot=new WeakMap;var ms="https://identity.ic0.app",ys="#authorize",Yt="ECDSA",Xt="Ed25519",hs=500,Zt="UserInterrupt",st=class{constructor(r,t,n,i,a,o,s,c){this._identity=r,this._key=t,this._chain=n,this._storage=i,this.idleManager=a,this._createOptions=o,this._idpWindow=s,this._eventHandler=c,this._registerDefaultIdleCallback()}static async create(r={}){var t,n,i;let a=(t=r.storage)!==null&&t!==void 0?t:new pe,o=(n=r.keyType)!==null&&n!==void 0?n:Yt,s=null;if(r.identity)s=r.identity;else{let d=await a.get(C);if(!d&&at)try{let m=new Cr,h=await m.get(j),g=await m.get(C);h&&g&&o===Yt&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await a.set(j,h),await a.set(C,g),d=h,await m.remove(j),await m.remove(C))}catch(m){console.error("error while attempting to recover localstorage: "+m)}if(d)try{typeof d=="object"?o===Xt&&typeof d=="string"?s=await Se.fromJSON(d):s=await Ce.fromKeyPair(d):typeof d=="string"&&(s=Se.fromJSON(d))}catch{}}let c=new me,u=null;if(s)try{let d=await a.get(j);if(typeof d=="object"&&d!==null)throw new Error("Delegation chain is incorrectly stored. A delegation chain should be stored as a string.");r.identity?c=r.identity:d&&(u=Ie.fromJSON(d),_i(u)?"toDer"in s?c=Vr.fromDelegation(s,u):c=ke.fromDelegation(s,u):(await Lt(a),s=null))}catch(d){console.error(d),await Lt(a),s=null}let p;return!((i=r.idleOptions)===null||i===void 0)&&i.disableIdle?p=void 0:(u||r.identity)&&(p=Pr.create(r.idleOptions)),s||(o===Xt?(s=await Se.generate(),await a.set(C,JSON.stringify(s.toJSON()))):(r.storage&&o===Yt&&console.warn(`You are using a custom storage provider that may not support CryptoKey storage. If you are using a custom storage provider that does not support CryptoKey storage, you should use '${Xt}' as the key type, as it can serialize to a string`),s=await Ce.generate(),await a.set(C,s.getKeyPair()))),new this(c,s,u,a,p,r)}_registerDefaultIdleCallback(){var r,t;let n=(r=this._createOptions)===null||r===void 0?void 0:r.idleOptions;!n?.onIdle&&!n?.disableDefaultIdleCallback&&((t=this.idleManager)===null||t===void 0||t.registerCallback(()=>{this.logout(),location.reload()}))}async _handleSuccess(r,t){var n,i;let a=r.delegations.map(u=>({delegation:new rr(u.delegation.pubkey,u.delegation.expiration,u.delegation.targets),signature:u.signature.buffer})),o=Ie.fromDelegations(a,r.userPublicKey.buffer),s=this._key;if(!s)return;this._chain=o,"toDer"in s?this._identity=Vr.fromDelegation(s,this._chain):this._identity=ke.fromDelegation(s,this._chain),(n=this._idpWindow)===null||n===void 0||n.close();let c=(i=this._createOptions)===null||i===void 0?void 0:i.idleOptions;!this.idleManager&&!c?.disableIdle&&(this.idleManager=Pr.create(c),this._registerDefaultIdleCallback()),this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(j,JSON.stringify(this._chain.toJSON())),t?.(r)}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null}async login(r){var t,n,i,a;let o=BigInt(8)*BigInt(36e11),s=new URL(((t=r?.identityProvider)===null||t===void 0?void 0:t.toString())||ms);s.hash=ys,(n=this._idpWindow)===null||n===void 0||n.close(),this._removeEventListener(),this._eventHandler=this._getEventHandler(s,Object.assign({maxTimeToLive:(i=r?.maxTimeToLive)!==null&&i!==void 0?i:o},r)),window.addEventListener("message",this._eventHandler),this._idpWindow=(a=window.open(s.toString(),"idpWindow",r?.windowOpenerFeatures))!==null&&a!==void 0?a:void 0;let c=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(Zt,r?.onError):setTimeout(c,hs))};c()}_getEventHandler(r,t){return async n=>{var i,a,o;if(n.origin!==r.origin)return;let s=n.data;switch(s.kind){case"authorize-ready":{let c=Object.assign({kind:"authorize-client",sessionPublicKey:new Uint8Array((i=this._key)===null||i===void 0?void 0:i.getPublicKey().toDer()),maxTimeToLive:t?.maxTimeToLive,allowPinAuthentication:t?.allowPinAuthentication,derivationOrigin:(a=t?.derivationOrigin)===null||a===void 0?void 0:a.toString()},t?.customValues);(o=this._idpWindow)===null||o===void 0||o.postMessage(c,r.origin);break}case"authorize-client-success":try{await this._handleSuccess(s,t?.onSuccess)}catch(c){this._handleFailure(c.message,t?.onError)}break;case"authorize-client-failure":this._handleFailure(s.text,t?.onError);break;default:break}}}_handleFailure(r,t){var n;(n=this._idpWindow)===null||n===void 0||n.close(),t?.(r),this._removeEventListener(),delete this._idpWindow}_removeEventListener(){this._eventHandler&&window.removeEventListener("message",this._eventHandler),this._eventHandler=void 0}async logout(r={}){if(await Lt(this._storage),this._identity=new me,this._chain=null,r.returnTo)try{window.history.pushState({},"",r.returnTo)}catch{window.location.href=r.returnTo}}};async function Lt(e){await e.remove(C),await e.remove(j),await e.remove(Ei)}var re=async({fn:e,step:r,onProgress:t})=>{t?.({step:r,state:"in_progress"});try{let n=await e();return t?.({step:r,state:"success"}),n}catch(n){throw t?.({step:r,state:"error"}),n}};var Fi=(t=>(t[t.AuthorizingWithProvider=0]="AuthorizingWithProvider",t[t.CreatingOrRetrievingUser=1]="CreatingOrRetrievingUser",t))(Fi||{});var ct=class extends Error{},Ue=class extends Error{},lt=class extends Error{},ut=class extends Error{},dt=class extends Error{},pt=class extends Error{},_t=class extends Error{},mt=class extends Error{};var tr=class{async signIn({options:r,authClient:t,initAuth:n}){await re({fn:async()=>await this.#e({options:r,authClient:t}),step:0,onProgress:r?.onProgress}),await re({fn:async()=>await n({provider:this.id}),step:1,onProgress:r?.onProgress})}#e({options:r,authClient:t}){return new Promise(async(n,i)=>{if(_(t)){i(new Ue("No client is ready to perform a sign-in. Have you initialized the Satellite?"));return}await t.login({onSuccess:n,onError:a=>{if(a===Zt){i(new lt(a));return}i(new ct(a))},maxTimeToLive:r?.maxTimeToLiveInNanoseconds??ai,allowPinAuthentication:r?.allowPin??oi,...r?.derivationOrigin!==void 0&&{derivationOrigin:r.derivationOrigin},...this.signInOptions({windowed:r?.windowed})})})}};var yt=class extends tr{#e;constructor({domain:r}){super(),this.#e=r}get id(){return"internet_identity"}signInOptions({windowed:r}){let t=()=>{let n=q.getInstance().get()?.container;if(_(n)||n===!1)return`https://identity.${this.#e??li}`;let i=q.getInstance().get(),a=f(i)&&f(i?.internetIdentityId)?i.internetIdentityId:ti,{host:o,protocol:s}=new URL(n===!0?Ye:n);return/apple/i.test(navigator?.vendor)?`${s}//${o}?canisterId=${a}`:`${s}//${a}.${o.replace("127.0.0.1","localhost")}`};return{...r!==!1&&{windowOpenerFeatures:Zr(si)},identityProvider:t()}}};var ht=class extends tr{#e;#r;constructor({appName:r,logoUrl:t}){super(),this.#e=r,this.#r=t}get id(){return"nfid"}signInOptions({windowed:r}){return{...r!==!1&&{windowOpenerFeatures:Zr(ci)},identityProvider:`https://nfid.one/authenticate/?applicationName=${encodeURI(this.#e)}&applicationLogo=${encodeURI(this.#r)}`}}};var te={certified:!1};var x=e=>f(e)?e:ft()??new me;var Ai=({IDL:e})=>{let r=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),t=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),n=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),i=e.Record({field:n,desc:e.Bool}),a=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),o=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(a),description:e.Opt(e.Text),created_at:e.Opt(a)}),s=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),c=e.Record({order:e.Opt(i),owner:e.Opt(e.Principal),matcher:e.Opt(o),paginate:e.Opt(s)}),u=e.Record({controllers:e.Vec(e.Principal)}),p=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),d=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:p,expires_at:e.Opt(e.Nat64)}),m=e.Record({version:e.Opt(e.Nat64)}),h=e.Variant({Db:e.Null,Storage:e.Null}),g=e.Record({version:e.Opt(e.Nat64)}),I=e.Record({proposal_ids:e.Vec(e.Nat)}),S=e.Record({cycles:e.Nat,destination_id:e.Principal}),B=e.Record({token:e.Opt(e.Text),collection:e.Text,owner:e.Principal,name:e.Text,description:e.Opt(e.Text),full_path:e.Text}),O=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),y=e.Record({key:B,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,O)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),v=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),R=e.Record({allowed_callers:e.Vec(e.Principal)}),w=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(v),rules:e.Opt(R)}),k=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),K=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(k)}),D=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),E=e.Variant({Deny:e.Null,Allow:e.Null}),G=e.Record({status_code:e.Nat16,location:e.Text}),$=e.Record({iframe:e.Opt(D),updated_at:e.Opt(e.Nat64),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(k),raw_access:e.Opt(E),redirects:e.Opt(e.Vec(e.Tuple(e.Text,G)))}),xe=e.Record({db:e.Opt(K),authentication:e.Opt(w),storage:$}),P=e.Record({updated_at:e.Nat64,owner:e.Principal,data:e.Vec(e.Nat8),description:e.Opt(e.Text),created_at:e.Nat64,version:e.Opt(e.Nat64)}),ne=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),nr=e.Record({clear_existing_assets:e.Opt(e.Bool)}),ir=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),Oe=e.Variant({AssetsUpgrade:nr,SegmentsDeployment:ir}),Y=e.Record({status:ne,updated_at:e.Nat64,sha256:e.Opt(e.Vec(e.Nat8)),executed_at:e.Opt(e.Nat64),owner:e.Principal,created_at:e.Nat64,version:e.Opt(e.Nat64),proposal_type:Oe}),ie=e.Variant({Heap:e.Null,Stable:e.Null}),M=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),Re=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),ae=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(ie),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:M,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(Re),write:M,max_changes_per_user:e.Opt(e.Nat32)}),ar=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),certificate_version:e.Opt(e.Nat16)}),oe=e.Record({memory:ie,token:e.Opt(e.Text),sha256:e.Opt(e.Vec(e.Nat8)),headers:e.Vec(e.Tuple(e.Text,e.Text)),index:e.Nat64,encoding_type:e.Text,full_path:e.Text}),or=e.Variant({Callback:e.Record({token:oe,callback:e.Func([],[],["query"])})}),Be=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(or),status_code:e.Nat16}),we=e.Record({token:e.Opt(oe),body:e.Vec(e.Nat8)}),se=e.Record({token:e.Opt(e.Text),collection:e.Text,name:e.Text,description:e.Opt(e.Text),encoding_type:e.Opt(e.Text),full_path:e.Text}),L=e.Record({batch_id:e.Nat}),be=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,y)),items_length:e.Nat64}),sr=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),cr=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,P)),items_length:e.Nat64}),lr=e.Record({desc:e.Bool}),ur=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),De=e.Record({order:e.Opt(lr),paginate:e.Opt(ur)}),dr=e.Record({proposal_id:e.Nat}),pr=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(dr,Y)),items_length:e.Nat64}),_r=e.Record({include_system:e.Bool}),mr=e.Record({matcher:e.Opt(_r)}),yr=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,ae)),items_length:e.Nat64}),hr=e.Record({stable:e.Nat64,heap:e.Nat64}),fr=e.Record({version:e.Opt(e.Nat64),internet_identity:e.Opt(v),rules:e.Opt(R)}),Tr=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:p,expires_at:e.Opt(e.Nat64)}),gr=e.Record({controller:Tr,controllers:e.Vec(e.Principal)}),qe=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(k)}),Ee=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),Nr=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(ie),max_size:e.Opt(e.Nat),read:M,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(Re),write:M,max_changes_per_user:e.Opt(e.Nat32)}),xr=e.Record({iframe:e.Opt(D),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),version:e.Opt(e.Nat64),max_memory_size:e.Opt(k),raw_access:e.Opt(E),redirects:e.Opt(e.Vec(e.Tuple(e.Text,G)))}),Fe=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Ae=e.Record({chunk_id:e.Nat});return e.Service({commit_asset_upload:e.Func([r],[],[]),commit_proposal:e.Func([t],[e.Null],[]),commit_proposal_asset_upload:e.Func([r],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(r)],[],[]),count_assets:e.Func([e.Text,c],[e.Nat64],["query"]),count_collection_assets:e.Func([e.Text],[e.Nat64],["query"]),count_collection_docs:e.Func([e.Text],[e.Nat64],["query"]),count_docs:e.Func([e.Text,c],[e.Nat64],["query"]),count_proposals:e.Func([],[e.Nat64],["query"]),del_asset:e.Func([e.Text,e.Text],[],[]),del_assets:e.Func([e.Text],[],[]),del_controllers:e.Func([u],[e.Vec(e.Tuple(e.Principal,d))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,m],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,c],[],[]),del_filtered_docs:e.Func([e.Text,c],[],[]),del_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[],[]),del_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,m))],[],[]),del_rule:e.Func([h,e.Text,g],[],[]),delete_proposal_assets:e.Func([I],[],[]),deposit_cycles:e.Func([S],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(y)],["query"]),get_auth_config:e.Func([],[e.Opt(w)],["query"]),get_config:e.Func([],[xe],[]),get_db_config:e.Func([],[e.Opt(K)],["query"]),get_doc:e.Func([e.Text,e.Text],[e.Opt(P)],["query"]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(y)))],["query"]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(P)))],["query"]),get_proposal:e.Func([e.Nat],[e.Opt(Y)],["query"]),get_rule:e.Func([h,e.Text],[e.Opt(ae)],["query"]),get_storage_config:e.Func([],[$],["query"]),http_request:e.Func([ar],[Be],["query"]),http_request_streaming_callback:e.Func([oe],[we],["query"]),init_asset_upload:e.Func([se],[L],[]),init_proposal:e.Func([Oe],[e.Nat,Y],[]),init_proposal_asset_upload:e.Func([se,e.Nat],[L],[]),init_proposal_many_assets_upload:e.Func([e.Vec(se),e.Nat],[e.Vec(e.Tuple(e.Text,L))],[]),list_assets:e.Func([e.Text,c],[be],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,d))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,sr))],["query"]),list_docs:e.Func([e.Text,c],[cr],["query"]),list_proposals:e.Func([De],[pr],["query"]),list_rules:e.Func([h,mr],[yr],["query"]),memory_size:e.Func([],[hr],["query"]),reject_proposal:e.Func([t],[e.Null],[]),set_auth_config:e.Func([fr],[w],[]),set_controllers:e.Func([gr],[e.Vec(e.Tuple(e.Principal,d))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([qe],[K],[]),set_doc:e.Func([e.Text,e.Text,Ee],[P],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,Ee))],[e.Vec(e.Tuple(e.Text,P))],[]),set_rule:e.Func([h,e.Text,Nr],[ae],[]),set_storage_config:e.Func([xr],[$],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Y],[]),upload_asset_chunk:e.Func([Fe],[Ae],[]),upload_proposal_asset_chunk:e.Func([Fe],[Ae],[])})},vi=({IDL:e})=>{let r=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),t=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),n=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),i=e.Record({field:n,desc:e.Bool}),a=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),o=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(a),description:e.Opt(e.Text),created_at:e.Opt(a)}),s=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),c=e.Record({order:e.Opt(i),owner:e.Opt(e.Principal),matcher:e.Opt(o),paginate:e.Opt(s)}),u=e.Record({controllers:e.Vec(e.Principal)}),p=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),d=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:p,expires_at:e.Opt(e.Nat64)}),m=e.Record({version:e.Opt(e.Nat64)}),h=e.Variant({Db:e.Null,Storage:e.Null}),g=e.Record({version:e.Opt(e.Nat64)}),I=e.Record({proposal_ids:e.Vec(e.Nat)}),S=e.Record({cycles:e.Nat,destination_id:e.Principal}),B=e.Record({token:e.Opt(e.Text),collection:e.Text,owner:e.Principal,name:e.Text,description:e.Opt(e.Text),full_path:e.Text}),O=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),y=e.Record({key:B,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,O)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),v=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),R=e.Record({allowed_callers:e.Vec(e.Principal)}),w=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(v),rules:e.Opt(R)}),k=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),K=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(k)}),D=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),E=e.Variant({Deny:e.Null,Allow:e.Null}),G=e.Record({status_code:e.Nat16,location:e.Text}),$=e.Record({iframe:e.Opt(D),updated_at:e.Opt(e.Nat64),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(k),raw_access:e.Opt(E),redirects:e.Opt(e.Vec(e.Tuple(e.Text,G)))}),xe=e.Record({db:e.Opt(K),authentication:e.Opt(w),storage:$}),P=e.Record({updated_at:e.Nat64,owner:e.Principal,data:e.Vec(e.Nat8),description:e.Opt(e.Text),created_at:e.Nat64,version:e.Opt(e.Nat64)}),ne=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),nr=e.Record({clear_existing_assets:e.Opt(e.Bool)}),ir=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),Oe=e.Variant({AssetsUpgrade:nr,SegmentsDeployment:ir}),Y=e.Record({status:ne,updated_at:e.Nat64,sha256:e.Opt(e.Vec(e.Nat8)),executed_at:e.Opt(e.Nat64),owner:e.Principal,created_at:e.Nat64,version:e.Opt(e.Nat64),proposal_type:Oe}),ie=e.Variant({Heap:e.Null,Stable:e.Null}),M=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),Re=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),ae=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(ie),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:M,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(Re),write:M,max_changes_per_user:e.Opt(e.Nat32)}),ar=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),certificate_version:e.Opt(e.Nat16)}),oe=e.Record({memory:ie,token:e.Opt(e.Text),sha256:e.Opt(e.Vec(e.Nat8)),headers:e.Vec(e.Tuple(e.Text,e.Text)),index:e.Nat64,encoding_type:e.Text,full_path:e.Text}),or=e.Variant({Callback:e.Record({token:oe,callback:e.Func([],[],[])})}),Be=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(or),status_code:e.Nat16}),we=e.Record({token:e.Opt(oe),body:e.Vec(e.Nat8)}),se=e.Record({token:e.Opt(e.Text),collection:e.Text,name:e.Text,description:e.Opt(e.Text),encoding_type:e.Opt(e.Text),full_path:e.Text}),L=e.Record({batch_id:e.Nat}),be=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,y)),items_length:e.Nat64}),sr=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),cr=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,P)),items_length:e.Nat64}),lr=e.Record({desc:e.Bool}),ur=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),De=e.Record({order:e.Opt(lr),paginate:e.Opt(ur)}),dr=e.Record({proposal_id:e.Nat}),pr=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(dr,Y)),items_length:e.Nat64}),_r=e.Record({include_system:e.Bool}),mr=e.Record({matcher:e.Opt(_r)}),yr=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,ae)),items_length:e.Nat64}),hr=e.Record({stable:e.Nat64,heap:e.Nat64}),fr=e.Record({version:e.Opt(e.Nat64),internet_identity:e.Opt(v),rules:e.Opt(R)}),Tr=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:p,expires_at:e.Opt(e.Nat64)}),gr=e.Record({controller:Tr,controllers:e.Vec(e.Principal)}),qe=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(k)}),Ee=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),Nr=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(ie),max_size:e.Opt(e.Nat),read:M,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(Re),write:M,max_changes_per_user:e.Opt(e.Nat32)}),xr=e.Record({iframe:e.Opt(D),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),version:e.Opt(e.Nat64),max_memory_size:e.Opt(k),raw_access:e.Opt(E),redirects:e.Opt(e.Vec(e.Tuple(e.Text,G)))}),Fe=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Ae=e.Record({chunk_id:e.Nat});return e.Service({commit_asset_upload:e.Func([r],[],[]),commit_proposal:e.Func([t],[e.Null],[]),commit_proposal_asset_upload:e.Func([r],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(r)],[],[]),count_assets:e.Func([e.Text,c],[e.Nat64],[]),count_collection_assets:e.Func([e.Text],[e.Nat64],[]),count_collection_docs:e.Func([e.Text],[e.Nat64],[]),count_docs:e.Func([e.Text,c],[e.Nat64],[]),count_proposals:e.Func([],[e.Nat64],[]),del_asset:e.Func([e.Text,e.Text],[],[]),del_assets:e.Func([e.Text],[],[]),del_controllers:e.Func([u],[e.Vec(e.Tuple(e.Principal,d))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,m],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,c],[],[]),del_filtered_docs:e.Func([e.Text,c],[],[]),del_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[],[]),del_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,m))],[],[]),del_rule:e.Func([h,e.Text,g],[],[]),delete_proposal_assets:e.Func([I],[],[]),deposit_cycles:e.Func([S],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(y)],[]),get_auth_config:e.Func([],[e.Opt(w)],[]),get_config:e.Func([],[xe],[]),get_db_config:e.Func([],[e.Opt(K)],[]),get_doc:e.Func([e.Text,e.Text],[e.Opt(P)],[]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(y)))],[]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(P)))],[]),get_proposal:e.Func([e.Nat],[e.Opt(Y)],[]),get_rule:e.Func([h,e.Text],[e.Opt(ae)],[]),get_storage_config:e.Func([],[$],[]),http_request:e.Func([ar],[Be],[]),http_request_streaming_callback:e.Func([oe],[we],[]),init_asset_upload:e.Func([se],[L],[]),init_proposal:e.Func([Oe],[e.Nat,Y],[]),init_proposal_asset_upload:e.Func([se,e.Nat],[L],[]),init_proposal_many_assets_upload:e.Func([e.Vec(se),e.Nat],[e.Vec(e.Tuple(e.Text,L))],[]),list_assets:e.Func([e.Text,c],[be],[]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,d))],[]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,sr))],[]),list_docs:e.Func([e.Text,c],[cr],[]),list_proposals:e.Func([De],[pr],[]),list_rules:e.Func([h,mr],[yr],[]),memory_size:e.Func([],[hr],[]),reject_proposal:e.Func([t],[e.Null],[]),set_auth_config:e.Func([fr],[w],[]),set_controllers:e.Func([gr],[e.Vec(e.Tuple(e.Principal,d))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([qe],[K],[]),set_doc:e.Func([e.Text,e.Text,Ee],[P],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,Ee))],[e.Vec(e.Tuple(e.Text,P))],[]),set_rule:e.Func([h,e.Text,Nr],[ae],[]),set_storage_config:e.Func([xr],[$],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Y],[]),upload_asset_chunk:e.Func([Fe],[Ae],[]),upload_proposal_asset_chunk:e.Func([Fe],[Ae],[])})};var Vi=({satelliteId:e,container:r})=>{let{satelliteId:t}=Qt({satelliteId:e}),{container:n}=en({container:r});if(f(n)&&n!==!1){let{host:i,protocol:a}=new URL(n===!0?Ye:n);return`${a}//${t??"unknown"}.${i.replace("127.0.0.1","localhost")}`}return`https://${t??"unknown"}.icp0.io`},Qt=({satelliteId:e})=>f(e)?{satelliteId:e}:q.getInstance().get()??{satelliteId:void 0},en=({container:e})=>f(e)?{container:e}:q.getInstance().get()??{container:void 0};var b=({satellite:e,options:{certified:r}})=>Si({idlFactory:r?vi:Ai,actorKey:`stock#${r?"update":"query"}`,...e}),Pi=({idlFactory:e,...r})=>Si({idlFactory:e,actorKey:"extended#query",...r}),Si=async({satelliteId:e,container:r,...t})=>{let{satelliteId:n}=Qt({satelliteId:e});Fr(n,"No satellite ID defined. Did you initialize Juno?");let{container:i}=en({container:r});return await Le.getInstance().getActor({satelliteId:n,container:i,...t})};var Ci=e=>{if(_(e))return N();switch(e.matcher){case"equal":return N({Equal:e.timestamp});case"greaterThan":return N({GreaterThan:e.timestamp});case"lessThan":return N({LessThan:e.timestamp});case"between":return N({Between:[e.timestamps.start,e.timestamps.end]});default:throw new mt("Invalid list matcher for timestamp",e)}},Ne=({matcher:e,paginate:r,order:t,owner:n})=>({matcher:_(e)?[]:[{key:N(e.key),description:N(e.description),created_at:Ci(e.createdAt),updated_at:Ci(e.updatedAt)}],paginate:N(_(r)?void 0:{start_after:N(r.startAfter),limit:N(_(r.limit)?void 0:BigInt(r.limit))}),order:N(_(t)?void 0:{desc:t.desc,field:t.field==="created_at"?{CreatedAt:null}:t.field==="updated_at"?{UpdatedAt:null}:{Keys:null}}),owner:N(_(n)?void 0:typeof n=="string"?T.fromText(n):n)});var Ii=async({data:e})=>{try{return await Xr(e)}catch(r){console.error("The data parsing has failed, mapping to undefined as a fallback.",r);return}};var rn=async e=>{let{data:r,version:t,description:n}=e;return{description:N(n),data:await ui(r),version:N(t)}},tn=e=>{let{version:r}=e;return{version:N(r)}},Ir=async({doc:e,key:r})=>{let{owner:t,version:n,description:i,data:a,...o}=e;return{key:r,description:A(i),owner:t.toText(),data:await Xr(a),version:A(n),...o}};var ki=async({collection:e,key:r,...t})=>{let{get_doc:n}=await b(t),i=A(await n(e,r));if(!_(i))return Ir({doc:i,key:r})},Ui=async({docs:e,...r})=>{let{get_many_docs:t}=await b(r),n=e.map(({collection:o,key:s})=>[o,s]),i=await t(n),a=[];for(let[o,s]of i){let c=A(s);a.push(f(c)?await Ir({key:o,doc:c}):void 0)}return a},Bi=async({collection:e,doc:r,...t})=>{let{set_doc:n}=await b(t),{key:i}=r,a=await rn(r),o=await n(e,i,a);return await Ir({key:i,doc:o})},Di=async({docs:e,...r})=>{let{set_many_docs:t}=await b(r),n=[];for(let{collection:o,doc:s}of e){let{key:c}=s;n.push([o,c,await rn(s)])}let i=await t(n),a=[];for(let[o,s]of i)a.push(await Ir({key:o,doc:s}));return a},qi=async({collection:e,doc:r,...t})=>{let{del_doc:n}=await b(t),{key:i}=r;return n(e,i,tn(r))},ji=async({docs:e,...r})=>{let{del_many_docs:t}=await b(r),n=e.map(({collection:i,doc:a})=>[i,a.key,tn(a)]);await t(n)},Ki=async({collection:e,filter:r,...t})=>{let{del_filtered_docs:n}=await b(t);return n(e,Ne(r))},Mi=async({collection:e,filter:r,...t})=>{let{list_docs:n}=await b(t),{items:i,items_page:a,items_length:o,matches_length:s,matches_pages:c}=await n(e,Ne(r)),u=[];for(let[p,d]of i){let{data:m,owner:h,description:g,version:I,...S}=d;u.push({key:p,description:A(g),owner:h.toText(),data:await Ii({data:m}),version:A(I),...S})}return{items:u,items_length:o,items_page:A(a),matches_length:s,matches_pages:A(c)}},Ji=async({collection:e,filter:r,...t})=>{let{count_docs:n}=await b(t);return n(e,Ne(r))};var Tt=async({satellite:e,options:r,...t})=>{let n=x(e?.identity);return await ki({...t,satellite:{...e,identity:n},options:r??te})},fd=async({satellite:e,options:r,...t})=>{let n=x(e?.identity);return await Ui({...t,satellite:{...e,identity:n},options:r??te})},Wi=async({satellite:e,...r})=>{let t=x(e?.identity);return await Bi({...r,satellite:{...e,identity:t},options:{certified:!0}})},Hi=async({satellite:e,...r})=>{let t=x(e?.identity);return await Di({...r,satellite:{...e,identity:t},options:{certified:!0}})},Td=async({satellite:e,...r})=>{let t=x(e?.identity);return await qi({...r,satellite:{...e,identity:t},options:{certified:!0}})},gd=async({satellite:e,...r})=>{let t=x(e?.identity);return await ji({...r,satellite:{...e,identity:t},options:{certified:!0}})},Nd=async({satellite:e,filter:r,...t})=>{let n=x(e?.identity);return await Ki({...t,filter:r??{},satellite:{...e,identity:n},options:{certified:!0}})},xd=async({satellite:e,options:r,filter:t,...n})=>{let i=x(e?.identity);return await Mi({...n,filter:t??{},satellite:{...e,identity:i},options:r??te})},Od=async({satellite:e,options:r,filter:t,...n})=>{let i=x(e?.identity);return await Ji({...n,filter:t??{},satellite:{...e,identity:i},options:r??te})};var zi=async({delegationIdentity:e,passkeyIdentity:r,satelliteId:t})=>{let n=r.getCredential().getAAGUID(),[i,a]=await Hi({docs:[{collection:"#user",doc:{key:e.getPrincipal().toText(),data:{provider:"webauthn",providerData:{webauthn:{...f(n)&&{aaguid:$r(n)}}}}}},{collection:"#user-webauthn",doc:{key:r.getCredential().getCredentialIdText(),data:{publicKey:de(r.getPublicKey().toDer())}}}],satellite:{identity:e,satelliteId:t}});return i};var Gi=(a=>(a[a.RequestingUserCredential=0]="RequestingUserCredential",a[a.FinalizingCredential=1]="FinalizingCredential",a[a.Signing=2]="Signing",a[a.FinalizingSession=3]="FinalizingSession",a[a.RetrievingUser=4]="RetrievingUser",a))(Gi||{}),$i=(o=>(o[o.CreatingUserCredential=0]="CreatingUserCredential",o[o.ValidatingUserCredential=1]="ValidatingUserCredential",o[o.FinalizingCredential=2]="FinalizingCredential",o[o.Signing=3]="Signing",o[o.FinalizingSession=4]="FinalizingSession",o[o.RegisteringUser=5]="RegisteringUser",o))($i||{});var kr=class{get id(){return"webauthn"}async signUp({options:{onProgress:r,maxTimeToLiveInMilliseconds:t,passkey:n}={},loadAuthWithUser:i}){let{satelliteId:a}=q.getInstance().get()??{satelliteId:void 0};if(_(a))throw new Ue("Satellite ID not set. Have you initialized the Satellite?");let o=({step:I,state:S})=>{switch(I){case fe.RequestingUserCredential:r?.({step:1,state:S});break;case fe.FinalizingCredential:r?.({step:2,state:S});break;case fe.Signing:r?.({step:3,state:S});break}},c=await re({fn:async()=>await qt.createWithNewCredential({onProgress:o,passkeyOptions:n}),step:0,onProgress:r}),{delegationIdentity:u,sessionKey:p}=await this.#e({identity:c,maxTimeToLiveInMilliseconds:t}),m=await re({fn:async()=>await zi({delegationIdentity:u,passkeyIdentity:c,satelliteId:a}),step:5,onProgress:r});await re({fn:async()=>await this.#r({delegationIdentity:u,sessionKey:p}),step:4,onProgress:r}),await re({fn:async()=>await i({user:m}),step:5,onProgress:r})}async signIn({options:{onProgress:r,maxTimeToLiveInMilliseconds:t}={},loadAuth:n}){let{satelliteId:i}=q.getInstance().get()??{satelliteId:void 0};if(_(i))throw new Ue("Satellite ID not set. Have you initialized the Satellite?");let a=async({credentialId:d})=>{let m=await Tt({collection:"#user-webauthn",key:Yr(d),options:{certified:!0},satellite:{identity:new me,satelliteId:i}});if(_(m))throw new dt("No public key found for the selected passkey.");let{data:h}=m,{publicKey:g}=h;return Rr(g.buffer,Ke)},o=({step:d,state:m})=>{switch(d){case fe.RequestingUserCredential:r?.({step:0,state:m});break;case fe.FinalizingCredential:r?.({step:1,state:m});break;case fe.Signing:r?.({step:2,state:m});break}},s=await qt.createWithExistingCredential({retrievePublicKey:a,onProgress:o}),{delegationIdentity:c,sessionKey:u}=await this.#e({identity:s,maxTimeToLiveInMilliseconds:t});await re({fn:async()=>await this.#r({delegationIdentity:c,sessionKey:u}),step:3,onProgress:r}),await re({fn:n,step:4,onProgress:r})}async#e({identity:r,maxTimeToLiveInMilliseconds:t}){let n=await Ce.generate({extractable:!1}),i=t??144e5,a=await Ie.create(r,n.getPublicKey(),new Date(Date.now()+i));return{delegationIdentity:ke.fromDelegation(n,a),sessionKey:n}}async#r({sessionKey:r,delegationIdentity:t}){let n=new pe;await Promise.all([n.set(C,r.getKeyPair()),n.set(j,JSON.stringify(t.getDelegation().toJSON()))])}};var Ur=()=>st.create({idleOptions:{disableIdle:!0,disableDefaultIdleCallback:!0}}),Yi=async()=>(await new pe().remove(C),await Ur());var nn=({error:e,type:r})=>typeof e=="string"?e.includes(r):e instanceof Error?e.message.includes(r):!1;var Xi="juno.datastore.error.user.cannot_update";var Li=async({provider:e})=>{let{user:r,userId:t}=await an();if(f(r))return r;try{return await Ts({userId:t,provider:e})}catch(n){if(nn({error:n,type:Xi})){let i=await Zi({userId:t});if(f(i))return i}throw n}},an=async()=>{let e=ft();if(_(e))throw new _t("No identity to initialize the user. Have you initialized Juno?");let r=e.getPrincipal().toText(),t=await Zi({userId:r});return{userId:r,user:t}},Zi=({userId:e})=>Tt({collection:"#user",key:e}),Ts=({userId:e,...r})=>Wi({collection:"#user",doc:{key:e,data:r}});var z,on=async()=>{await sn({fn:async()=>{let{user:r}=await an();H.getInstance().set(r??null)}})},gs=async({user:e})=>{await sn({fn:async()=>{H.getInstance().set(e)}})},Qi=async({provider:e})=>{await sn({fn:async()=>{let t=await Li({provider:e});H.getInstance().set(t)}})},sn=async({fn:e})=>{if(z=await Ur(),!await z.isAuthenticated()){z=await Yi();return}await e()},Ns=async e=>{let r=async()=>await Os(e);if(Object.values(e)[0].context?.windowGuard===!1){await r();return}await Kt({fn:r})},xs=async e=>{let r=async()=>await Rs(e);if(Object.values(e)?.[0].context?.windowGuard===!1){await r();return}await Kt({fn:r})},Os=async e=>{if("webauthn"in e){let{webauthn:{options:r}}=e;await new kr().signIn({options:r,loadAuth:on});return}if("nfid"in e){let{nfid:{options:r}}=e,{appName:t,logoUrl:n,...i}=r??{};await new ht({appName:t,logoUrl:n}).signIn({options:i,authClient:z,initAuth:Qi});return}if("internet_identity"in e){let{internet_identity:{options:r}}=e,{domain:t,...n}=r??{};await new yt({domain:t}).signIn({options:n,authClient:z,initAuth:Qi});return}throw new ut("An unknown or unsupported provider was provided for sign-in.")},Rs=async e=>{if("webauthn"in e){let{webauthn:{options:r}}=e;await new kr().signUp({options:r,loadAuthWithUser:gs});return}throw new pt("An unknown or unsupported provider was provided for sign-up.")},cn=async e=>{await ws(),z=await Ur(),e?.windowReload!==!1&&window.location.reload()},ws=async()=>{await z?.logout(),z=null,H.getInstance().reset(),Le.getInstance().reset(),Xe.getInstance().reset()},ft=()=>z?.getIdentity(),bs=async()=>(z??await Ur()).getIdentity(),Es=async()=>{let e=H.getInstance().get();return _(e)||!(await z?.isAuthenticated()??!1)?null:z?.getIdentity()??null};var ea=e=>{let r=e===!0?"./workers/auth.worker.js":e,t=new Worker(r),n=async()=>{jt({message:"junoSignOutAuthTimer"}),await cn()};return t.onmessage=async({data:i})=>{let{msg:a,data:o}=i;switch(a){case"junoSignOutAuthTimer":await n();return;case"junoDelegationRemainingTime":jt({message:"junoDelegationRemainingTime",detail:o?.authRemainingTime});return}},H.getInstance().subscribe(i=>{if(_(i)){t.postMessage({msg:"junoStopAuthTimer"});return}t.postMessage({msg:"junoStartAuthTimer"})})};var ra=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_SATELLITE_ID??import.meta.env?.PUBLIC_SATELLITE_ID:void 0;return typeof process<"u"?process.env?.NEXT_PUBLIC_SATELLITE_ID??e():e()},ta=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_CONTAINER??import.meta.env?.PUBLIC_CONTAINER:void 0;return typeof process<"u"?process.env?.NEXT_PUBLIC_CONTAINER??e():e()};var Tp=async({idlFactory:e,satellite:r})=>{let t=x(r?.identity);return await Pi({idlFactory:e,...r,identity:t})};var na=async({asset:{data:e,headers:r,...t},actor:n,progress:i})=>{let{init_asset_upload:a,upload_asset_chunk:o,commit_asset_upload:s}=n,{batch_id:c}=await a(Fs(t));i?.onInitiatedBatch();let{chunkIds:u}=await Vs({data:e,uploadFn:o,batchId:c});i?.onUploadedFileChunks(t.fullPath),await vs({commitFn:s,batchId:c,data:e,headers:r,chunkIds:u}),i?.onCommittedBatch()};var Fs=({filename:e,collection:r,token:t,fullPath:n,encoding:i,description:a})=>({collection:r,full_path:n,name:e,token:N(t),encoding_type:N(i),description:N(a)}),As=({batchId:e,chunkIds:r,headers:t,data:n})=>{let i=t.find(([a,o])=>a.toLowerCase()==="content-type")===void 0&&n.type!==void 0&&n.type!==""?[["Content-Type",n.type]]:void 0;return{batch_id:e,chunk_ids:r.map(({chunk_id:a})=>a),headers:[...t,...i??[]]}},vs=async({commitFn:e,...r})=>{let t=As(r);await e(t)},Vs=async({data:e,uploadFn:r,batchId:t})=>{let n=[],i=Lr()?new Blob([await e.arrayBuffer()]):e,a=0n;for(let s=0;s<i.size;s+=19e5){let c=i.slice(s,s+19e5);n.push({batchId:t,chunk:c,uploadFn:r,orderId:a}),a++}let o=[];for await(let s of Ps({uploadChunks:n}))o=[...o,...s];return{chunkIds:o}};async function*Ps({uploadChunks:e,limit:r=12}){for(let t=0;t<e.length;t=t+r){let n=e.slice(t,t+r);yield await Promise.all(n.map(i=>Ss(i)))}}var Ss=async({batchId:e,chunk:r,uploadFn:t,orderId:n})=>t({batch_id:e,content:new Uint8Array(await r.arrayBuffer()),order_id:N(n)});var ia=async({asset:e,...r})=>{let t=await b(r);await na({actor:t,asset:e})},aa=async({collection:e,filter:r,...t})=>{let{list_assets:n}=await b(t),{items:i,items_length:a,items_page:o,matches_length:s,matches_pages:c}=await n(e,Ne(r));return{items:i.map(([u,p])=>p),items_length:a,items_page:A(o),matches_length:s,matches_pages:A(c)}},oa=async({collection:e,filter:r,...t})=>{let{count_assets:n}=await b(t);return n(e,Ne(r))},sa=async({collection:e,fullPath:r,...t})=>(await b(t)).del_asset(e,r),ca=async({assets:e,satellite:r})=>{let{del_many_assets:t}=await b({satellite:r,options:{certified:!0}}),n=e.map(({collection:i,fullPath:a})=>[i,a]);await t(n)},la=async({collection:e,filter:r,...t})=>{let{del_filtered_assets:n}=await b(t);return n(e,Ne(r))},ua=async({collection:e,fullPath:r,...t})=>{let{get_asset:n}=await b(t);return A(await n(e,r))},da=async({assets:e,...r})=>{let{get_many_assets:t}=await b(r),n=e.map(({collection:a,fullPath:o})=>[a,o]);return(await t(n)).map(([a,o])=>A(o))};var pa=e=>btoa([...e].map(r=>String.fromCharCode(r)).join(""));var kp=e=>_a(e),Up=e=>_a({filename:e.data.name,...e}),_a=async({filename:e,data:r,collection:t,headers:n=[],fullPath:i,token:a,satellite:o,encoding:s,description:c})=>{let u=x(o?.identity),p=decodeURI(e),d=i??`/${t}/${p}`,m={...o,identity:u};return await ia({asset:{data:r,filename:p,collection:t,token:a,headers:n,fullPath:d,encoding:s,description:c},satellite:m,options:{certified:!0}}),{downloadUrl:ma({satellite:m,assetKey:{fullPath:d,token:a}}),fullPath:d,name:p}},Bp=async({collection:e,filter:r,satellite:t,options:n})=>{let i={...t,identity:x(t?.identity)},{items:a,...o}=await aa({collection:e,filter:r??{},satellite:i,options:n??te}),s=a.map(({key:{full_path:c,token:u,name:p,owner:d,description:m},headers:h,encodings:g,created_at:I,updated_at:S})=>{let B=A(u);return{fullPath:c,description:A(m),name:p,downloadUrl:ma({satellite:i,assetKey:{fullPath:c,token:B}}),token:B,headers:h,encodings:g.reduce((O,[y,{modified:v,sha256:R,total_length:w}])=>({...O,[y]:{modified:v,sha256:pa(R),total_length:w}}),{}),owner:d.toText(),created_at:I,updated_at:S}});return{items:s,assets:s,...o}},Dp=async({collection:e,filter:r,satellite:t,options:n})=>{let i={...t,identity:x(t?.identity)};return await oa({collection:e,satellite:i,filter:r??{},options:n??te})},qp=({collection:e,fullPath:r,satellite:t})=>sa({collection:e,fullPath:r,satellite:{...t,identity:x(t?.identity)},options:{certified:!0}}),jp=({assets:e,satellite:r})=>ca({assets:e,satellite:{...r,identity:x(r?.identity)},options:{certified:!0}}),Kp=async({collection:e,satellite:r,filter:t})=>{let n={...r,identity:x(r?.identity)};return await la({collection:e,satellite:n,filter:t??{},options:{certified:!0}})},Mp=async({satellite:e,options:r,...t})=>{let n=x(e?.identity);return await ua({...t,satellite:{...e,identity:n},options:r??te})},Jp=async({satellite:e,options:r,...t})=>{let n=x(e?.identity);return await da({...t,satellite:{...e,identity:n},options:r??te})},ma=({assetKey:{fullPath:e,token:r},satellite:t})=>{let n={...t,identity:x(t?.identity)};return`${Vi(n)}${e}${f(r)?`?token=${r}`:""}`};var Cs=e=>{let r=e?.satelliteId??ra();Fr(r,"Satellite ID is not configured. Juno cannot be initialized.");let t=e?.container??ta();return{satelliteId:r,internetIdentityId:e?.internetIdentityId,workers:e?.workers,container:t}},Zp=e=>Is(e),Is=async e=>{let r=Cs(e);q.getInstance().set(r),await on();let t=r.workers?.auth!==void 0?ea(r.workers.auth):void 0;return[...t?[t]:[]]},ks=e=>H.getInstance().subscribe(e),Qp=ks;export{Fi as AuthClientSignInProgressStep,_t as InitError,yt as InternetIdentityProvider,mt as ListError,ht as NFIDProvider,ct as SignInError,Ue as SignInInitError,ut as SignInProviderNotSupportedError,lt as SignInUserInterruptError,pt as SignUpProviderNotSupportedError,Gi as WebAuthnSignInProgressStep,dt as WebAuthnSignInRetrievePublicKeyError,$i as WebAuthnSignUpProgressStep,Qp as authSubscribe,Dp as countAssets,Od as countDocs,qp as deleteAsset,Td as deleteDoc,Kp as deleteFilteredAssets,Nd as deleteFilteredDocs,jp as deleteManyAssets,gd as deleteManyDocs,ma as downloadUrl,Mp as getAsset,Tt as getDoc,Es as getIdentityOnce,Jp as getManyAssets,fd as getManyDocs,Tp as getSatelliteExtendedActor,Zp as initJuno,Is as initSatellite,Mo as isWebAuthnAvailable,Bp as listAssets,xd as listDocs,ks as onAuthStateChange,Wi as setDoc,Hi as setManyDocs,Ns as signIn,cn as signOut,xs as signUp,bs as unsafeIdentity,kp as uploadBlob,Up as uploadFile};
15
+ ic-request`);function Jt(e){if(typeof e!="string"||e.length<64)throw new Error("Invalid public key.");return _e(e)}var rr=class{constructor(r,t,n){this.pubkey=r,this.expiration=t,this.targets=n}toCBOR(){return er.value.map(Object.assign({pubkey:er.value.bytes(this.pubkey),expiration:er.value.u64(this.expiration.toString(16),16)},this.targets&&{targets:er.value.array(this.targets.map(r=>er.value.bytes(r.toUint8Array())))}))}toJSON(){return Object.assign({expiration:this.expiration.toString(16),pubkey:V(this.pubkey)},this.targets&&{targets:this.targets.map(r=>r.toHex())})}};async function Lo(e,r,t,n){let i=new rr(r.toDer(),BigInt(+t)*BigInt(1e6),n),a=new Uint8Array([...Yo,...new Uint8Array(xt(Object.assign({},i)))]),o=await e.sign(a);return{delegation:i,signature:o}}var Ie=class e{constructor(r,t){this.delegations=r,this.publicKey=t}static async create(r,t,n=new Date(Date.now()+900*1e3),i={}){var a,o;let s=await Lo(r,t,n,i.targets);return new e([...((a=i.previous)===null||a===void 0?void 0:a.delegations)||[],s],((o=i.previous)===null||o===void 0?void 0:o.publicKey)||r.getPublicKey().toDer())}static fromJSON(r){let{publicKey:t,delegations:n}=typeof r=="string"?JSON.parse(r):r;if(!Array.isArray(n))throw new Error("Invalid delegations.");let i=n.map(a=>{let{delegation:o,signature:s}=a,{pubkey:c,expiration:u,targets:p}=o;if(p!==void 0&&!Array.isArray(p))throw new Error("Invalid targets.");return{delegation:new rr(Jt(c),BigInt("0x"+u),p&&p.map(d=>{if(typeof d!="string")throw new Error("Invalid target.");return T.fromHex(d)})),signature:Jt(s)}});return new this(i,Jt(t))}static fromDelegations(r,t){return new this(r,t)}toJSON(){return{delegations:this.delegations.map(r=>{let{delegation:t,signature:n}=r,{targets:i}=t;return{delegation:Object.assign({expiration:t.expiration.toString(16),pubkey:V(t.pubkey)},i&&{targets:i.map(a=>a.toHex())}),signature:V(n)}}),publicKey:V(this.publicKey)}}},ke=class extends ce{constructor(r,t){super(),this._inner=r,this._delegation=t}static fromDelegation(r,t){return new this(r,t)}getDelegation(){return this._delegation}getPublicKey(){return{derKey:this._delegation.publicKey,toDer:()=>this._delegation.publicKey}}sign(r){return this._inner.sign(r)}async transformRequest(r){let{body:t}=r,n=$o(r,["body"]),i=await xt(t);return Object.assign(Object.assign({},n),{body:{content:t,sender_sig:await this.sign(new Uint8Array([...Xo,...new Uint8Array(i)])),sender_delegation:this._delegation.delegations,sender_pubkey:this._delegation.publicKey}})}},Vr=class e extends tt{constructor(r,t){super(r),nt.set(this,void 0),zo(this,nt,t,"f")}get delegation(){return Go(this,nt,"f")}static fromDelegation(r,t){return new e(r,t)}};nt=new WeakMap;function _i(e,r){for(let{delegation:i}of e.delegations)if(+new Date(Number(i.expiration/BigInt(1e6)))<=+Date.now())return!1;let t=[],n=r?.scope;n&&(Array.isArray(n)?t.push(...n.map(i=>typeof i=="string"?T.fromText(i):i)):t.push(typeof n=="string"?T.fromText(n):n));for(let i of t){let a=i.toText();for(let{delegation:o}of e.delegations){if(o.targets===void 0)continue;let s=!0;for(let c of o.targets)if(c.toText()===a){s=!1;break}if(s)return!1}}return!0}var Zo=gt(Pa());var mi;(function(e){e[e.ECDSA_WITH_SHA256=-7]="ECDSA_WITH_SHA256"})(mi||(mi={}));var yi=["mousedown","mousemove","keydown","touchstart","wheel"],Pr=class{constructor(r={}){var t;this.callbacks=[],this.idleTimeout=600*1e3,this.timeoutID=void 0;let{onIdle:n,idleTimeout:i=600*1e3}=r||{};this.callbacks=n?[n]:[],this.idleTimeout=i;let a=this._resetTimer.bind(this);window.addEventListener("load",a,!0),yi.forEach(function(s){document.addEventListener(s,a,!0)});let o=(s,c)=>{let u;return(...p)=>{let d=this,m=function(){u=void 0,s.apply(d,p)};clearTimeout(u),u=window.setTimeout(m,c)}};if(r?.captureScroll){let s=o(a,(t=r?.scrollDebounce)!==null&&t!==void 0?t:100);window.addEventListener("scroll",s,!0)}a()}static create(r={}){return new this(r)}registerCallback(r){this.callbacks.push(r)}exit(){clearTimeout(this.timeoutID),window.removeEventListener("load",this._resetTimer,!0);let r=this._resetTimer.bind(this);yi.forEach(function(t){document.removeEventListener(t,r,!0)}),this.callbacks.forEach(t=>t())}_resetTimer(){let r=this.exit.bind(this);window.clearTimeout(this.timeoutID),this.timeoutID=window.setTimeout(r,this.idleTimeout)}};var Qo=(e,r)=>r.some(t=>e instanceof t),hi,fi;function es(){return hi||(hi=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function rs(){return fi||(fi=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Ti=new WeakMap,Ht=new WeakMap,gi=new WeakMap,Wt=new WeakMap,Gt=new WeakMap;function ts(e){let r=new Promise((t,n)=>{let i=()=>{e.removeEventListener("success",a),e.removeEventListener("error",o)},a=()=>{t(ee(e.result)),i()},o=()=>{n(e.error),i()};e.addEventListener("success",a),e.addEventListener("error",o)});return r.then(t=>{t instanceof IDBCursor&&Ti.set(t,e)}).catch(()=>{}),Gt.set(r,e),r}function ns(e){if(Ht.has(e))return;let r=new Promise((t,n)=>{let i=()=>{e.removeEventListener("complete",a),e.removeEventListener("error",o),e.removeEventListener("abort",o)},a=()=>{t(),i()},o=()=>{n(e.error||new DOMException("AbortError","AbortError")),i()};e.addEventListener("complete",a),e.addEventListener("error",o),e.addEventListener("abort",o)});Ht.set(e,r)}var zt={get(e,r,t){if(e instanceof IDBTransaction){if(r==="done")return Ht.get(e);if(r==="objectStoreNames")return e.objectStoreNames||gi.get(e);if(r==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return ee(e[r])},set(e,r,t){return e[r]=t,!0},has(e,r){return e instanceof IDBTransaction&&(r==="done"||r==="store")?!0:r in e}};function Ni(e){zt=e(zt)}function is(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(r,...t){let n=e.call(it(this),r,...t);return gi.set(n,r.sort?r.sort():[r]),ee(n)}:rs().includes(e)?function(...r){return e.apply(it(this),r),ee(Ti.get(this))}:function(...r){return ee(e.apply(it(this),r))}}function as(e){return typeof e=="function"?is(e):(e instanceof IDBTransaction&&ns(e),Qo(e,es())?new Proxy(e,zt):e)}function ee(e){if(e instanceof IDBRequest)return ts(e);if(Wt.has(e))return Wt.get(e);let r=as(e);return r!==e&&(Wt.set(e,r),Gt.set(r,e)),r}var it=e=>Gt.get(e);function Oi(e,r,{blocked:t,upgrade:n,blocking:i,terminated:a}={}){let o=indexedDB.open(e,r),s=ee(o);return n&&o.addEventListener("upgradeneeded",c=>{n(ee(o.result),c.oldVersion,c.newVersion,ee(o.transaction),c)}),t&&o.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),s.then(c=>{a&&c.addEventListener("close",()=>a()),i&&c.addEventListener("versionchange",u=>i(u.oldVersion,u.newVersion,u))}).catch(()=>{}),s}var os=["get","getKey","getAll","getAllKeys","count"],ss=["put","add","delete","clear"],$t=new Map;function xi(e,r){if(!(e instanceof IDBDatabase&&!(r in e)&&typeof r=="string"))return;if($t.get(r))return $t.get(r);let t=r.replace(/FromIndex$/,""),n=r!==t,i=ss.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(i||os.includes(t)))return;let a=async function(o,...s){let c=this.transaction(o,i?"readwrite":"readonly"),u=c.store;return n&&(u=u.index(s.shift())),(await Promise.all([u[t](...s),i&&c.done]))[0]};return $t.set(r,a),a}Ni(e=>({...e,get:(r,t,n)=>xi(r,t)||e.get(r,t,n),has:(r,t)=>!!xi(r,t)||e.has(r,t)}));var Ri="auth-client-db",wi="ic-keyval",cs=async(e=Ri,r=wi,t)=>(at&&(localStorage!=null&&localStorage.getItem(j))&&(localStorage.removeItem(j),localStorage.removeItem(C)),await Oi(e,t,{upgrade:n=>{n.objectStoreNames.contains(r)&&n.clear(r),n.createObjectStore(r)}}));async function ls(e,r,t){return await e.get(r,t)}async function us(e,r,t,n){return await e.put(r,n,t)}async function ds(e,r,t){return await e.delete(r,t)}var Sr=class e{constructor(r,t){this._db=r,this._storeName=t}static async create(r){let{dbName:t=Ri,storeName:n=wi,version:i=bi}=r??{},a=await cs(t,n,i);return new e(a,n)}async set(r,t){return await us(this._db,this._storeName,r,t)}async get(r){var t;return(t=await ls(this._db,this._storeName,r))!==null&&t!==void 0?t:null}async remove(r){return await ds(this._db,this._storeName,r)}};var ps=function(e,r,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof r=="function"?e!==r||!i:!r.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,t):i?i.value=t:r.set(e,t),t},_s=function(e,r,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof r=="function"?e!==r||!n:!r.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(e):n?n.value:r.get(e)},ot,C="identity",j="delegation",Ei="iv",bi=1,at=typeof window<"u",Cr=class{constructor(r="ic-",t){this.prefix=r,this._localStorage=t}get(r){return Promise.resolve(this._getLocalStorage().getItem(this.prefix+r))}set(r,t){return this._getLocalStorage().setItem(this.prefix+r,t),Promise.resolve()}remove(r){return this._getLocalStorage().removeItem(this.prefix+r),Promise.resolve()}_getLocalStorage(){if(this._localStorage)return this._localStorage;let r=typeof window>"u"?typeof globalThis>"u"?typeof self>"u"?void 0:self.localStorage:globalThis.localStorage:window.localStorage;if(!r)throw new Error("Could not find local storage.");return r}},pe=class{constructor(r){ot.set(this,void 0),ps(this,ot,r??{},"f")}get _db(){return new Promise(r=>{if(this.initializedDb){r(this.initializedDb);return}Sr.create(_s(this,ot,"f")).then(t=>{this.initializedDb=t,r(t)})})}async get(r){return await(await this._db).get(r)}async set(r,t){await(await this._db).set(r,t)}async remove(r){await(await this._db).remove(r)}};ot=new WeakMap;var ms="https://identity.ic0.app",ys="#authorize",Yt="ECDSA",Xt="Ed25519",hs=500,Zt="UserInterrupt",st=class{constructor(r,t,n,i,a,o,s,c){this._identity=r,this._key=t,this._chain=n,this._storage=i,this.idleManager=a,this._createOptions=o,this._idpWindow=s,this._eventHandler=c,this._registerDefaultIdleCallback()}static async create(r={}){var t,n,i;let a=(t=r.storage)!==null&&t!==void 0?t:new pe,o=(n=r.keyType)!==null&&n!==void 0?n:Yt,s=null;if(r.identity)s=r.identity;else{let d=await a.get(C);if(!d&&at)try{let m=new Cr,h=await m.get(j),g=await m.get(C);h&&g&&o===Yt&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await a.set(j,h),await a.set(C,g),d=h,await m.remove(j),await m.remove(C))}catch(m){console.error("error while attempting to recover localstorage: "+m)}if(d)try{typeof d=="object"?o===Xt&&typeof d=="string"?s=await Se.fromJSON(d):s=await Ce.fromKeyPair(d):typeof d=="string"&&(s=Se.fromJSON(d))}catch{}}let c=new me,u=null;if(s)try{let d=await a.get(j);if(typeof d=="object"&&d!==null)throw new Error("Delegation chain is incorrectly stored. A delegation chain should be stored as a string.");r.identity?c=r.identity:d&&(u=Ie.fromJSON(d),_i(u)?"toDer"in s?c=Vr.fromDelegation(s,u):c=ke.fromDelegation(s,u):(await Lt(a),s=null))}catch(d){console.error(d),await Lt(a),s=null}let p;return!((i=r.idleOptions)===null||i===void 0)&&i.disableIdle?p=void 0:(u||r.identity)&&(p=Pr.create(r.idleOptions)),s||(o===Xt?(s=await Se.generate(),await a.set(C,JSON.stringify(s.toJSON()))):(r.storage&&o===Yt&&console.warn(`You are using a custom storage provider that may not support CryptoKey storage. If you are using a custom storage provider that does not support CryptoKey storage, you should use '${Xt}' as the key type, as it can serialize to a string`),s=await Ce.generate(),await a.set(C,s.getKeyPair()))),new this(c,s,u,a,p,r)}_registerDefaultIdleCallback(){var r,t;let n=(r=this._createOptions)===null||r===void 0?void 0:r.idleOptions;!n?.onIdle&&!n?.disableDefaultIdleCallback&&((t=this.idleManager)===null||t===void 0||t.registerCallback(()=>{this.logout(),location.reload()}))}async _handleSuccess(r,t){var n,i;let a=r.delegations.map(u=>({delegation:new rr(u.delegation.pubkey,u.delegation.expiration,u.delegation.targets),signature:u.signature.buffer})),o=Ie.fromDelegations(a,r.userPublicKey.buffer),s=this._key;if(!s)return;this._chain=o,"toDer"in s?this._identity=Vr.fromDelegation(s,this._chain):this._identity=ke.fromDelegation(s,this._chain),(n=this._idpWindow)===null||n===void 0||n.close();let c=(i=this._createOptions)===null||i===void 0?void 0:i.idleOptions;!this.idleManager&&!c?.disableIdle&&(this.idleManager=Pr.create(c),this._registerDefaultIdleCallback()),this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(j,JSON.stringify(this._chain.toJSON())),t?.(r)}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null}async login(r){var t,n,i,a;let o=BigInt(8)*BigInt(36e11),s=new URL(((t=r?.identityProvider)===null||t===void 0?void 0:t.toString())||ms);s.hash=ys,(n=this._idpWindow)===null||n===void 0||n.close(),this._removeEventListener(),this._eventHandler=this._getEventHandler(s,Object.assign({maxTimeToLive:(i=r?.maxTimeToLive)!==null&&i!==void 0?i:o},r)),window.addEventListener("message",this._eventHandler),this._idpWindow=(a=window.open(s.toString(),"idpWindow",r?.windowOpenerFeatures))!==null&&a!==void 0?a:void 0;let c=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(Zt,r?.onError):setTimeout(c,hs))};c()}_getEventHandler(r,t){return async n=>{var i,a,o;if(n.origin!==r.origin)return;let s=n.data;switch(s.kind){case"authorize-ready":{let c=Object.assign({kind:"authorize-client",sessionPublicKey:new Uint8Array((i=this._key)===null||i===void 0?void 0:i.getPublicKey().toDer()),maxTimeToLive:t?.maxTimeToLive,allowPinAuthentication:t?.allowPinAuthentication,derivationOrigin:(a=t?.derivationOrigin)===null||a===void 0?void 0:a.toString()},t?.customValues);(o=this._idpWindow)===null||o===void 0||o.postMessage(c,r.origin);break}case"authorize-client-success":try{await this._handleSuccess(s,t?.onSuccess)}catch(c){this._handleFailure(c.message,t?.onError)}break;case"authorize-client-failure":this._handleFailure(s.text,t?.onError);break;default:break}}}_handleFailure(r,t){var n;(n=this._idpWindow)===null||n===void 0||n.close(),t?.(r),this._removeEventListener(),delete this._idpWindow}_removeEventListener(){this._eventHandler&&window.removeEventListener("message",this._eventHandler),this._eventHandler=void 0}async logout(r={}){if(await Lt(this._storage),this._identity=new me,this._chain=null,r.returnTo)try{window.history.pushState({},"",r.returnTo)}catch{window.location.href=r.returnTo}}};async function Lt(e){await e.remove(C),await e.remove(j),await e.remove(Ei)}var re=async({fn:e,step:r,onProgress:t})=>{t?.({step:r,state:"in_progress"});try{let n=await e();return t?.({step:r,state:"success"}),n}catch(n){throw t?.({step:r,state:"error"}),n}};var Fi=(t=>(t[t.AuthorizingWithProvider=0]="AuthorizingWithProvider",t[t.CreatingOrRetrievingUser=1]="CreatingOrRetrievingUser",t))(Fi||{});var ct=class extends Error{},Ue=class extends Error{},lt=class extends Error{},ut=class extends Error{},dt=class extends Error{},pt=class extends Error{},_t=class extends Error{},mt=class extends Error{};var tr=class{async signIn({options:r,authClient:t,initAuth:n}){await re({fn:async()=>await this.#e({options:r,authClient:t}),step:0,onProgress:r?.onProgress}),await re({fn:async()=>await n({provider:this.id}),step:1,onProgress:r?.onProgress})}#e({options:r,authClient:t}){return new Promise(async(n,i)=>{if(_(t)){i(new Ue("No client is ready to perform a sign-in. Have you initialized the Satellite?"));return}await t.login({onSuccess:n,onError:a=>{if(a===Zt){i(new lt(a));return}i(new ct(a))},maxTimeToLive:r?.maxTimeToLiveInNanoseconds??ai,allowPinAuthentication:r?.allowPin??oi,...r?.derivationOrigin!==void 0&&{derivationOrigin:r.derivationOrigin},...this.signInOptions({windowed:r?.windowed})})})}};var yt=class extends tr{#e;constructor({domain:r}){super(),this.#e=r}get id(){return"internet_identity"}signInOptions({windowed:r}){let t=()=>{let n=q.getInstance().get()?.container;if(_(n)||n===!1)return`https://identity.${this.#e??li}`;let i=q.getInstance().get(),a=f(i)&&f(i?.internetIdentityId)?i.internetIdentityId:ti,{host:o,protocol:s}=new URL(n===!0?Ye:n);return/apple/i.test(navigator?.vendor)?`${s}//${o}?canisterId=${a}`:`${s}//${a}.${o.replace("127.0.0.1","localhost")}`};return{...r!==!1&&{windowOpenerFeatures:Zr(si)},identityProvider:t()}}};var ht=class extends tr{#e;#r;constructor({appName:r,logoUrl:t}){super(),this.#e=r,this.#r=t}get id(){return"nfid"}signInOptions({windowed:r}){return{...r!==!1&&{windowOpenerFeatures:Zr(ci)},identityProvider:`https://nfid.one/authenticate/?applicationName=${encodeURI(this.#e)}&applicationLogo=${encodeURI(this.#r)}`}}};var te={certified:!1};var x=e=>f(e)?e:ft()??new me;var Ai=({IDL:e})=>{let r=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),t=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),n=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),i=e.Record({field:n,desc:e.Bool}),a=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),o=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(a),description:e.Opt(e.Text),created_at:e.Opt(a)}),s=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),c=e.Record({order:e.Opt(i),owner:e.Opt(e.Principal),matcher:e.Opt(o),paginate:e.Opt(s)}),u=e.Record({controllers:e.Vec(e.Principal)}),p=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),d=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:p,expires_at:e.Opt(e.Nat64)}),m=e.Record({version:e.Opt(e.Nat64)}),h=e.Variant({Db:e.Null,Storage:e.Null}),g=e.Record({version:e.Opt(e.Nat64)}),I=e.Record({proposal_ids:e.Vec(e.Nat)}),S=e.Record({cycles:e.Nat,destination_id:e.Principal}),B=e.Record({token:e.Opt(e.Text),collection:e.Text,owner:e.Principal,name:e.Text,description:e.Opt(e.Text),full_path:e.Text}),O=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),y=e.Record({key:B,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,O)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),v=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),R=e.Record({allowed_callers:e.Vec(e.Principal)}),w=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(v),rules:e.Opt(R)}),k=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),K=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(k)}),D=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),E=e.Variant({Deny:e.Null,Allow:e.Null}),G=e.Record({status_code:e.Nat16,location:e.Text}),$=e.Record({iframe:e.Opt(D),updated_at:e.Opt(e.Nat64),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(k),raw_access:e.Opt(E),redirects:e.Opt(e.Vec(e.Tuple(e.Text,G)))}),xe=e.Record({db:e.Opt(K),authentication:e.Opt(w),storage:$}),P=e.Record({updated_at:e.Nat64,owner:e.Principal,data:e.Vec(e.Nat8),description:e.Opt(e.Text),created_at:e.Nat64,version:e.Opt(e.Nat64)}),ne=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),nr=e.Record({clear_existing_assets:e.Opt(e.Bool)}),ir=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),Oe=e.Variant({AssetsUpgrade:nr,SegmentsDeployment:ir}),Y=e.Record({status:ne,updated_at:e.Nat64,sha256:e.Opt(e.Vec(e.Nat8)),executed_at:e.Opt(e.Nat64),owner:e.Principal,created_at:e.Nat64,version:e.Opt(e.Nat64),proposal_type:Oe}),ie=e.Variant({Heap:e.Null,Stable:e.Null}),M=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),Re=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),ae=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(ie),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:M,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(Re),write:M,max_changes_per_user:e.Opt(e.Nat32)}),ar=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),certificate_version:e.Opt(e.Nat16)}),oe=e.Record({memory:ie,token:e.Opt(e.Text),sha256:e.Opt(e.Vec(e.Nat8)),headers:e.Vec(e.Tuple(e.Text,e.Text)),index:e.Nat64,encoding_type:e.Text,full_path:e.Text}),or=e.Variant({Callback:e.Record({token:oe,callback:e.Func([],[],["query"])})}),Be=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(or),status_code:e.Nat16}),we=e.Record({token:e.Opt(oe),body:e.Vec(e.Nat8)}),se=e.Record({token:e.Opt(e.Text),collection:e.Text,name:e.Text,description:e.Opt(e.Text),encoding_type:e.Opt(e.Text),full_path:e.Text}),L=e.Record({batch_id:e.Nat}),be=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,y)),items_length:e.Nat64}),sr=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),cr=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,P)),items_length:e.Nat64}),lr=e.Record({desc:e.Bool}),ur=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),De=e.Record({order:e.Opt(lr),paginate:e.Opt(ur)}),dr=e.Record({proposal_id:e.Nat}),pr=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(dr,Y)),items_length:e.Nat64}),_r=e.Record({include_system:e.Bool}),mr=e.Record({matcher:e.Opt(_r)}),yr=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,ae)),items_length:e.Nat64}),hr=e.Record({stable:e.Nat64,heap:e.Nat64}),fr=e.Record({version:e.Opt(e.Nat64),internet_identity:e.Opt(v),rules:e.Opt(R)}),Tr=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:p,expires_at:e.Opt(e.Nat64)}),gr=e.Record({controller:Tr,controllers:e.Vec(e.Principal)}),qe=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(k)}),Ee=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),Nr=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(ie),max_size:e.Opt(e.Nat),read:M,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(Re),write:M,max_changes_per_user:e.Opt(e.Nat32)}),xr=e.Record({iframe:e.Opt(D),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),version:e.Opt(e.Nat64),max_memory_size:e.Opt(k),raw_access:e.Opt(E),redirects:e.Opt(e.Vec(e.Tuple(e.Text,G)))}),Fe=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Ae=e.Record({chunk_id:e.Nat});return e.Service({commit_asset_upload:e.Func([r],[],[]),commit_proposal:e.Func([t],[e.Null],[]),commit_proposal_asset_upload:e.Func([r],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(r)],[],[]),count_assets:e.Func([e.Text,c],[e.Nat64],["query"]),count_collection_assets:e.Func([e.Text],[e.Nat64],["query"]),count_collection_docs:e.Func([e.Text],[e.Nat64],["query"]),count_docs:e.Func([e.Text,c],[e.Nat64],["query"]),count_proposals:e.Func([],[e.Nat64],["query"]),del_asset:e.Func([e.Text,e.Text],[],[]),del_assets:e.Func([e.Text],[],[]),del_controllers:e.Func([u],[e.Vec(e.Tuple(e.Principal,d))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,m],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,c],[],[]),del_filtered_docs:e.Func([e.Text,c],[],[]),del_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[],[]),del_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,m))],[],[]),del_rule:e.Func([h,e.Text,g],[],[]),delete_proposal_assets:e.Func([I],[],[]),deposit_cycles:e.Func([S],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(y)],["query"]),get_auth_config:e.Func([],[e.Opt(w)],["query"]),get_config:e.Func([],[xe],[]),get_db_config:e.Func([],[e.Opt(K)],["query"]),get_doc:e.Func([e.Text,e.Text],[e.Opt(P)],["query"]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(y)))],["query"]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(P)))],["query"]),get_proposal:e.Func([e.Nat],[e.Opt(Y)],["query"]),get_rule:e.Func([h,e.Text],[e.Opt(ae)],["query"]),get_storage_config:e.Func([],[$],["query"]),http_request:e.Func([ar],[Be],["query"]),http_request_streaming_callback:e.Func([oe],[we],["query"]),init_asset_upload:e.Func([se],[L],[]),init_proposal:e.Func([Oe],[e.Nat,Y],[]),init_proposal_asset_upload:e.Func([se,e.Nat],[L],[]),init_proposal_many_assets_upload:e.Func([e.Vec(se),e.Nat],[e.Vec(e.Tuple(e.Text,L))],[]),list_assets:e.Func([e.Text,c],[be],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,d))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,sr))],["query"]),list_docs:e.Func([e.Text,c],[cr],["query"]),list_proposals:e.Func([De],[pr],["query"]),list_rules:e.Func([h,mr],[yr],["query"]),memory_size:e.Func([],[hr],["query"]),reject_proposal:e.Func([t],[e.Null],[]),set_auth_config:e.Func([fr],[w],[]),set_controllers:e.Func([gr],[e.Vec(e.Tuple(e.Principal,d))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([qe],[K],[]),set_doc:e.Func([e.Text,e.Text,Ee],[P],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,Ee))],[e.Vec(e.Tuple(e.Text,P))],[]),set_rule:e.Func([h,e.Text,Nr],[ae],[]),set_storage_config:e.Func([xr],[$],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Y],[]),upload_asset_chunk:e.Func([Fe],[Ae],[]),upload_proposal_asset_chunk:e.Func([Fe],[Ae],[])})},vi=({IDL:e})=>{let r=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),t=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),n=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),i=e.Record({field:n,desc:e.Bool}),a=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),o=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(a),description:e.Opt(e.Text),created_at:e.Opt(a)}),s=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),c=e.Record({order:e.Opt(i),owner:e.Opt(e.Principal),matcher:e.Opt(o),paginate:e.Opt(s)}),u=e.Record({controllers:e.Vec(e.Principal)}),p=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),d=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:p,expires_at:e.Opt(e.Nat64)}),m=e.Record({version:e.Opt(e.Nat64)}),h=e.Variant({Db:e.Null,Storage:e.Null}),g=e.Record({version:e.Opt(e.Nat64)}),I=e.Record({proposal_ids:e.Vec(e.Nat)}),S=e.Record({cycles:e.Nat,destination_id:e.Principal}),B=e.Record({token:e.Opt(e.Text),collection:e.Text,owner:e.Principal,name:e.Text,description:e.Opt(e.Text),full_path:e.Text}),O=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),y=e.Record({key:B,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,O)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),v=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),R=e.Record({allowed_callers:e.Vec(e.Principal)}),w=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(v),rules:e.Opt(R)}),k=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),K=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(k)}),D=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),E=e.Variant({Deny:e.Null,Allow:e.Null}),G=e.Record({status_code:e.Nat16,location:e.Text}),$=e.Record({iframe:e.Opt(D),updated_at:e.Opt(e.Nat64),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(k),raw_access:e.Opt(E),redirects:e.Opt(e.Vec(e.Tuple(e.Text,G)))}),xe=e.Record({db:e.Opt(K),authentication:e.Opt(w),storage:$}),P=e.Record({updated_at:e.Nat64,owner:e.Principal,data:e.Vec(e.Nat8),description:e.Opt(e.Text),created_at:e.Nat64,version:e.Opt(e.Nat64)}),ne=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),nr=e.Record({clear_existing_assets:e.Opt(e.Bool)}),ir=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),Oe=e.Variant({AssetsUpgrade:nr,SegmentsDeployment:ir}),Y=e.Record({status:ne,updated_at:e.Nat64,sha256:e.Opt(e.Vec(e.Nat8)),executed_at:e.Opt(e.Nat64),owner:e.Principal,created_at:e.Nat64,version:e.Opt(e.Nat64),proposal_type:Oe}),ie=e.Variant({Heap:e.Null,Stable:e.Null}),M=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),Re=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),ae=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(ie),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:M,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(Re),write:M,max_changes_per_user:e.Opt(e.Nat32)}),ar=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),certificate_version:e.Opt(e.Nat16)}),oe=e.Record({memory:ie,token:e.Opt(e.Text),sha256:e.Opt(e.Vec(e.Nat8)),headers:e.Vec(e.Tuple(e.Text,e.Text)),index:e.Nat64,encoding_type:e.Text,full_path:e.Text}),or=e.Variant({Callback:e.Record({token:oe,callback:e.Func([],[],[])})}),Be=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(or),status_code:e.Nat16}),we=e.Record({token:e.Opt(oe),body:e.Vec(e.Nat8)}),se=e.Record({token:e.Opt(e.Text),collection:e.Text,name:e.Text,description:e.Opt(e.Text),encoding_type:e.Opt(e.Text),full_path:e.Text}),L=e.Record({batch_id:e.Nat}),be=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,y)),items_length:e.Nat64}),sr=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),cr=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,P)),items_length:e.Nat64}),lr=e.Record({desc:e.Bool}),ur=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),De=e.Record({order:e.Opt(lr),paginate:e.Opt(ur)}),dr=e.Record({proposal_id:e.Nat}),pr=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(dr,Y)),items_length:e.Nat64}),_r=e.Record({include_system:e.Bool}),mr=e.Record({matcher:e.Opt(_r)}),yr=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,ae)),items_length:e.Nat64}),hr=e.Record({stable:e.Nat64,heap:e.Nat64}),fr=e.Record({version:e.Opt(e.Nat64),internet_identity:e.Opt(v),rules:e.Opt(R)}),Tr=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:p,expires_at:e.Opt(e.Nat64)}),gr=e.Record({controller:Tr,controllers:e.Vec(e.Principal)}),qe=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(k)}),Ee=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),Nr=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(ie),max_size:e.Opt(e.Nat),read:M,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(Re),write:M,max_changes_per_user:e.Opt(e.Nat32)}),xr=e.Record({iframe:e.Opt(D),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),version:e.Opt(e.Nat64),max_memory_size:e.Opt(k),raw_access:e.Opt(E),redirects:e.Opt(e.Vec(e.Tuple(e.Text,G)))}),Fe=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Ae=e.Record({chunk_id:e.Nat});return e.Service({commit_asset_upload:e.Func([r],[],[]),commit_proposal:e.Func([t],[e.Null],[]),commit_proposal_asset_upload:e.Func([r],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(r)],[],[]),count_assets:e.Func([e.Text,c],[e.Nat64],[]),count_collection_assets:e.Func([e.Text],[e.Nat64],[]),count_collection_docs:e.Func([e.Text],[e.Nat64],[]),count_docs:e.Func([e.Text,c],[e.Nat64],[]),count_proposals:e.Func([],[e.Nat64],[]),del_asset:e.Func([e.Text,e.Text],[],[]),del_assets:e.Func([e.Text],[],[]),del_controllers:e.Func([u],[e.Vec(e.Tuple(e.Principal,d))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,m],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,c],[],[]),del_filtered_docs:e.Func([e.Text,c],[],[]),del_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[],[]),del_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,m))],[],[]),del_rule:e.Func([h,e.Text,g],[],[]),delete_proposal_assets:e.Func([I],[],[]),deposit_cycles:e.Func([S],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(y)],[]),get_auth_config:e.Func([],[e.Opt(w)],[]),get_config:e.Func([],[xe],[]),get_db_config:e.Func([],[e.Opt(K)],[]),get_doc:e.Func([e.Text,e.Text],[e.Opt(P)],[]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(y)))],[]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(P)))],[]),get_proposal:e.Func([e.Nat],[e.Opt(Y)],[]),get_rule:e.Func([h,e.Text],[e.Opt(ae)],[]),get_storage_config:e.Func([],[$],[]),http_request:e.Func([ar],[Be],[]),http_request_streaming_callback:e.Func([oe],[we],[]),init_asset_upload:e.Func([se],[L],[]),init_proposal:e.Func([Oe],[e.Nat,Y],[]),init_proposal_asset_upload:e.Func([se,e.Nat],[L],[]),init_proposal_many_assets_upload:e.Func([e.Vec(se),e.Nat],[e.Vec(e.Tuple(e.Text,L))],[]),list_assets:e.Func([e.Text,c],[be],[]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,d))],[]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,sr))],[]),list_docs:e.Func([e.Text,c],[cr],[]),list_proposals:e.Func([De],[pr],[]),list_rules:e.Func([h,mr],[yr],[]),memory_size:e.Func([],[hr],[]),reject_proposal:e.Func([t],[e.Null],[]),set_auth_config:e.Func([fr],[w],[]),set_controllers:e.Func([gr],[e.Vec(e.Tuple(e.Principal,d))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([qe],[K],[]),set_doc:e.Func([e.Text,e.Text,Ee],[P],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,Ee))],[e.Vec(e.Tuple(e.Text,P))],[]),set_rule:e.Func([h,e.Text,Nr],[ae],[]),set_storage_config:e.Func([xr],[$],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Y],[]),upload_asset_chunk:e.Func([Fe],[Ae],[]),upload_proposal_asset_chunk:e.Func([Fe],[Ae],[])})};var Vi=({satelliteId:e,container:r})=>{let{satelliteId:t}=Qt({satelliteId:e}),{container:n}=en({container:r});if(f(n)&&n!==!1){let{host:i,protocol:a}=new URL(n===!0?Ye:n);return`${a}//${t??"unknown"}.${i.replace("127.0.0.1","localhost")}`}return`https://${t??"unknown"}.icp0.io`},Qt=({satelliteId:e})=>f(e)?{satelliteId:e}:q.getInstance().get()??{satelliteId:void 0},en=({container:e})=>f(e)?{container:e}:q.getInstance().get()??{container:void 0};var b=({satellite:e,options:{certified:r}})=>Si({idlFactory:r?vi:Ai,actorKey:`stock#${r?"update":"query"}`,...e}),Pi=({idlFactory:e,...r})=>Si({idlFactory:e,actorKey:"extended#query",...r}),Si=async({satelliteId:e,container:r,...t})=>{let{satelliteId:n}=Qt({satelliteId:e});Fr(n,"No satellite ID defined. Did you initialize Juno?");let{container:i}=en({container:r});return await Le.getInstance().getActor({satelliteId:n,container:i,...t})};var Ci=e=>{if(_(e))return N();switch(e.matcher){case"equal":return N({Equal:e.timestamp});case"greaterThan":return N({GreaterThan:e.timestamp});case"lessThan":return N({LessThan:e.timestamp});case"between":return N({Between:[e.timestamps.start,e.timestamps.end]});default:throw new mt("Invalid list matcher for timestamp",e)}},Ne=({matcher:e,paginate:r,order:t,owner:n})=>({matcher:_(e)?[]:[{key:N(e.key),description:N(e.description),created_at:Ci(e.createdAt),updated_at:Ci(e.updatedAt)}],paginate:N(_(r)?void 0:{start_after:N(r.startAfter),limit:N(_(r.limit)?void 0:BigInt(r.limit))}),order:N(_(t)?void 0:{desc:t.desc,field:t.field==="created_at"?{CreatedAt:null}:t.field==="updated_at"?{UpdatedAt:null}:{Keys:null}}),owner:N(_(n)?void 0:typeof n=="string"?T.fromText(n):n)});var Ii=async({data:e})=>{try{return await Xr(e)}catch(r){console.error("The data parsing has failed, mapping to undefined as a fallback.",r);return}};var rn=async e=>{let{data:r,version:t,description:n}=e;return{description:N(n),data:await ui(r),version:N(t)}},tn=e=>{let{version:r}=e;return{version:N(r)}},Ir=async({doc:e,key:r})=>{let{owner:t,version:n,description:i,data:a,...o}=e;return{key:r,description:A(i),owner:t.toText(),data:await Xr(a),version:A(n),...o}};var ki=async({collection:e,key:r,...t})=>{let{get_doc:n}=await b(t),i=A(await n(e,r));if(!_(i))return Ir({doc:i,key:r})},Ui=async({docs:e,...r})=>{let{get_many_docs:t}=await b(r),n=e.map(({collection:o,key:s})=>[o,s]),i=await t(n),a=[];for(let[o,s]of i){let c=A(s);a.push(f(c)?await Ir({key:o,doc:c}):void 0)}return a},Bi=async({collection:e,doc:r,...t})=>{let{set_doc:n}=await b(t),{key:i}=r,a=await rn(r),o=await n(e,i,a);return await Ir({key:i,doc:o})},Di=async({docs:e,...r})=>{let{set_many_docs:t}=await b(r),n=[];for(let{collection:o,doc:s}of e){let{key:c}=s;n.push([o,c,await rn(s)])}let i=await t(n),a=[];for(let[o,s]of i)a.push(await Ir({key:o,doc:s}));return a},qi=async({collection:e,doc:r,...t})=>{let{del_doc:n}=await b(t),{key:i}=r;return n(e,i,tn(r))},ji=async({docs:e,...r})=>{let{del_many_docs:t}=await b(r),n=e.map(({collection:i,doc:a})=>[i,a.key,tn(a)]);await t(n)},Ki=async({collection:e,filter:r,...t})=>{let{del_filtered_docs:n}=await b(t);return n(e,Ne(r))},Mi=async({collection:e,filter:r,...t})=>{let{list_docs:n}=await b(t),{items:i,items_page:a,items_length:o,matches_length:s,matches_pages:c}=await n(e,Ne(r)),u=[];for(let[p,d]of i){let{data:m,owner:h,description:g,version:I,...S}=d;u.push({key:p,description:A(g),owner:h.toText(),data:await Ii({data:m}),version:A(I),...S})}return{items:u,items_length:o,items_page:A(a),matches_length:s,matches_pages:A(c)}},Ji=async({collection:e,filter:r,...t})=>{let{count_docs:n}=await b(t);return n(e,Ne(r))};var Tt=async({satellite:e,options:r,...t})=>{let n=x(e?.identity);return await ki({...t,satellite:{...e,identity:n},options:r??te})},fd=async({satellite:e,options:r,...t})=>{let n=x(e?.identity);return await Ui({...t,satellite:{...e,identity:n},options:r??te})},Wi=async({satellite:e,...r})=>{let t=x(e?.identity);return await Bi({...r,satellite:{...e,identity:t},options:{certified:!0}})},Hi=async({satellite:e,...r})=>{let t=x(e?.identity);return await Di({...r,satellite:{...e,identity:t},options:{certified:!0}})},Td=async({satellite:e,...r})=>{let t=x(e?.identity);return await qi({...r,satellite:{...e,identity:t},options:{certified:!0}})},gd=async({satellite:e,...r})=>{let t=x(e?.identity);return await ji({...r,satellite:{...e,identity:t},options:{certified:!0}})},Nd=async({satellite:e,filter:r,...t})=>{let n=x(e?.identity);return await Ki({...t,filter:r??{},satellite:{...e,identity:n},options:{certified:!0}})},xd=async({satellite:e,options:r,filter:t,...n})=>{let i=x(e?.identity);return await Mi({...n,filter:t??{},satellite:{...e,identity:i},options:r??te})},Od=async({satellite:e,options:r,filter:t,...n})=>{let i=x(e?.identity);return await Ji({...n,filter:t??{},satellite:{...e,identity:i},options:r??te})};var zi=async({delegationIdentity:e,passkeyIdentity:r,satelliteId:t})=>{let n=r.getCredential().getAAGUID(),[i,a]=await Hi({docs:[{collection:"#user",doc:{key:e.getPrincipal().toText(),data:{provider:"webauthn",providerData:{webauthn:{...f(n)&&{aaguid:$r(n)}}}}}},{collection:"#user-webauthn",doc:{key:r.getCredential().getCredentialIdText(),data:{publicKey:de(r.getPublicKey().toDer())}}}],satellite:{identity:e,satelliteId:t}});return i};var Gi=(a=>(a[a.RequestingUserCredential=0]="RequestingUserCredential",a[a.FinalizingCredential=1]="FinalizingCredential",a[a.Signing=2]="Signing",a[a.FinalizingSession=3]="FinalizingSession",a[a.RetrievingUser=4]="RetrievingUser",a))(Gi||{}),$i=(o=>(o[o.CreatingUserCredential=0]="CreatingUserCredential",o[o.ValidatingUserCredential=1]="ValidatingUserCredential",o[o.FinalizingCredential=2]="FinalizingCredential",o[o.Signing=3]="Signing",o[o.FinalizingSession=4]="FinalizingSession",o[o.RegisteringUser=5]="RegisteringUser",o))($i||{});var kr=class{get id(){return"webauthn"}async signUp({options:{onProgress:r,maxTimeToLiveInMilliseconds:t,passkey:n}={},loadAuthWithUser:i}){let{satelliteId:a}=q.getInstance().get()??{satelliteId:void 0};if(_(a))throw new Ue("Satellite ID not set. Have you initialized the Satellite?");let o=({step:I,state:S})=>{switch(I){case fe.RequestingUserCredential:r?.({step:1,state:S});break;case fe.FinalizingCredential:r?.({step:2,state:S});break;case fe.Signing:r?.({step:3,state:S});break}},c=await re({fn:async()=>await qt.createWithNewCredential({onProgress:o,passkeyOptions:n}),step:0,onProgress:r}),{delegationIdentity:u,sessionKey:p}=await this.#e({identity:c,maxTimeToLiveInMilliseconds:t}),m=await re({fn:async()=>await zi({delegationIdentity:u,passkeyIdentity:c,satelliteId:a}),step:5,onProgress:r});await re({fn:async()=>await this.#r({delegationIdentity:u,sessionKey:p}),step:4,onProgress:r}),await re({fn:async()=>await i({user:m}),step:5,onProgress:r})}async signIn({options:{onProgress:r,maxTimeToLiveInMilliseconds:t}={},loadAuth:n}){let{satelliteId:i}=q.getInstance().get()??{satelliteId:void 0};if(_(i))throw new Ue("Satellite ID not set. Have you initialized the Satellite?");let a=async({credentialId:d})=>{let m=await Tt({collection:"#user-webauthn",key:Yr(d),options:{certified:!0},satellite:{identity:new me,satelliteId:i}});if(_(m))throw new dt("No public key found for the selected passkey.");let{data:h}=m,{publicKey:g}=h;return Rr(g.buffer,Ke)},o=({step:d,state:m})=>{switch(d){case fe.RequestingUserCredential:r?.({step:0,state:m});break;case fe.FinalizingCredential:r?.({step:1,state:m});break;case fe.Signing:r?.({step:2,state:m});break}},s=await qt.createWithExistingCredential({retrievePublicKey:a,onProgress:o}),{delegationIdentity:c,sessionKey:u}=await this.#e({identity:s,maxTimeToLiveInMilliseconds:t});await re({fn:async()=>await this.#r({delegationIdentity:c,sessionKey:u}),step:3,onProgress:r}),await re({fn:n,step:4,onProgress:r})}async#e({identity:r,maxTimeToLiveInMilliseconds:t}){let n=await Ce.generate({extractable:!1}),i=t??144e5,a=await Ie.create(r,n.getPublicKey(),new Date(Date.now()+i));return{delegationIdentity:ke.fromDelegation(n,a),sessionKey:n}}async#r({sessionKey:r,delegationIdentity:t}){let n=new pe;await Promise.all([n.set(C,r.getKeyPair()),n.set(j,JSON.stringify(t.getDelegation().toJSON()))])}};var Ur=()=>st.create({idleOptions:{disableIdle:!0,disableDefaultIdleCallback:!0}}),Yi=async()=>(await new pe().remove(C),await Ur());var nn=({error:e,type:r})=>typeof e=="string"?e.includes(r):e instanceof Error?e.message.includes(r):!1;var Xi="juno.datastore.error.user.cannot_update";var Li=async({provider:e})=>{let{user:r,userId:t}=await an();if(f(r))return r;try{return await Ts({userId:t,provider:e})}catch(n){if(nn({error:n,type:Xi})){let i=await Zi({userId:t});if(f(i))return i}throw n}},an=async()=>{let e=ft();if(_(e))throw new _t("No identity to initialize the user. Have you initialized Juno?");let r=e.getPrincipal().toText(),t=await Zi({userId:r});return{userId:r,user:t}},Zi=({userId:e})=>Tt({collection:"#user",key:e}),Ts=({userId:e,...r})=>Wi({collection:"#user",doc:{key:e,data:r}});var z,on=async()=>{await sn({fn:async()=>{let{user:r}=await an();H.getInstance().set(r??null)}})},gs=async({user:e})=>{await sn({fn:async()=>{H.getInstance().set(e)}})},Qi=async({provider:e})=>{await sn({fn:async()=>{let t=await Li({provider:e});H.getInstance().set(t)}})},sn=async({fn:e})=>{if(z=await Ur(),!await z.isAuthenticated()){z=await Yi();return}await e()},Ns=async e=>{let r=async()=>await Os(e);if(Object.values(e)[0].context?.windowGuard===!1){await r();return}await Kt({fn:r})},xs=async e=>{let r=async()=>await Rs(e);if(Object.values(e)?.[0].context?.windowGuard===!1){await r();return}await Kt({fn:r})},Os=async e=>{if("webauthn"in e){let{webauthn:{options:r}}=e;await new kr().signIn({options:r,loadAuth:on});return}if("nfid"in e){let{nfid:{options:r}}=e,{appName:t,logoUrl:n,...i}=r??{};await new ht({appName:t,logoUrl:n}).signIn({options:i,authClient:z,initAuth:Qi});return}if("internet_identity"in e){let{internet_identity:{options:r}}=e,{domain:t,...n}=r??{};await new yt({domain:t}).signIn({options:n,authClient:z,initAuth:Qi});return}throw new ut("An unknown or unsupported provider was provided for sign-in.")},Rs=async e=>{if("webauthn"in e){let{webauthn:{options:r}}=e;await new kr().signUp({options:r,loadAuthWithUser:gs});return}throw new pt("An unknown or unsupported provider was provided for sign-up.")},cn=async e=>{await ws(),z=await Ur(),e?.windowReload!==!1&&window.location.reload()},ws=async()=>{await z?.logout(),z=null,H.getInstance().reset(),Le.getInstance().reset(),Xe.getInstance().reset()},ft=()=>z?.getIdentity(),bs=async()=>(z??await Ur()).getIdentity(),Es=async()=>{let e=H.getInstance().get();return _(e)||!(await z?.isAuthenticated()??!1)?null:z?.getIdentity()??null};var ea=e=>{let r=e===!0?"./workers/auth.worker.js":e,t=new Worker(r),n=async()=>{jt({message:"junoSignOutAuthTimer"}),await cn()};return t.onmessage=async({data:i})=>{let{msg:a,data:o}=i;switch(a){case"junoSignOutAuthTimer":await n();return;case"junoDelegationRemainingTime":jt({message:"junoDelegationRemainingTime",detail:o?.authRemainingTime});return}},H.getInstance().subscribe(i=>{if(_(i)){t.postMessage({msg:"junoStopAuthTimer"});return}t.postMessage({msg:"junoStartAuthTimer"})})};var ra=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_SATELLITE_ID??import.meta.env?.PUBLIC_SATELLITE_ID:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SATELLITE_ID??e():e()},ta=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_CONTAINER??import.meta.env?.PUBLIC_CONTAINER:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_CONTAINER??e():e()};var Tp=async({idlFactory:e,satellite:r})=>{let t=x(r?.identity);return await Pi({idlFactory:e,...r,identity:t})};var na=async({asset:{data:e,headers:r,...t},actor:n,progress:i})=>{let{init_asset_upload:a,upload_asset_chunk:o,commit_asset_upload:s}=n,{batch_id:c}=await a(Fs(t));i?.onInitiatedBatch();let{chunkIds:u}=await Vs({data:e,uploadFn:o,batchId:c});i?.onUploadedFileChunks(t.fullPath),await vs({commitFn:s,batchId:c,data:e,headers:r,chunkIds:u}),i?.onCommittedBatch()};var Fs=({filename:e,collection:r,token:t,fullPath:n,encoding:i,description:a})=>({collection:r,full_path:n,name:e,token:N(t),encoding_type:N(i),description:N(a)}),As=({batchId:e,chunkIds:r,headers:t,data:n})=>{let i=t.find(([a,o])=>a.toLowerCase()==="content-type")===void 0&&n.type!==void 0&&n.type!==""?[["Content-Type",n.type]]:void 0;return{batch_id:e,chunk_ids:r.map(({chunk_id:a})=>a),headers:[...t,...i??[]]}},vs=async({commitFn:e,...r})=>{let t=As(r);await e(t)},Vs=async({data:e,uploadFn:r,batchId:t})=>{let n=[],i=Lr()?new Blob([await e.arrayBuffer()]):e,a=0n;for(let s=0;s<i.size;s+=19e5){let c=i.slice(s,s+19e5);n.push({batchId:t,chunk:c,uploadFn:r,orderId:a}),a++}let o=[];for await(let s of Ps({uploadChunks:n}))o=[...o,...s];return{chunkIds:o}};async function*Ps({uploadChunks:e,limit:r=12}){for(let t=0;t<e.length;t=t+r){let n=e.slice(t,t+r);yield await Promise.all(n.map(i=>Ss(i)))}}var Ss=async({batchId:e,chunk:r,uploadFn:t,orderId:n})=>t({batch_id:e,content:new Uint8Array(await r.arrayBuffer()),order_id:N(n)});var ia=async({asset:e,...r})=>{let t=await b(r);await na({actor:t,asset:e})},aa=async({collection:e,filter:r,...t})=>{let{list_assets:n}=await b(t),{items:i,items_length:a,items_page:o,matches_length:s,matches_pages:c}=await n(e,Ne(r));return{items:i.map(([u,p])=>p),items_length:a,items_page:A(o),matches_length:s,matches_pages:A(c)}},oa=async({collection:e,filter:r,...t})=>{let{count_assets:n}=await b(t);return n(e,Ne(r))},sa=async({collection:e,fullPath:r,...t})=>(await b(t)).del_asset(e,r),ca=async({assets:e,satellite:r})=>{let{del_many_assets:t}=await b({satellite:r,options:{certified:!0}}),n=e.map(({collection:i,fullPath:a})=>[i,a]);await t(n)},la=async({collection:e,filter:r,...t})=>{let{del_filtered_assets:n}=await b(t);return n(e,Ne(r))},ua=async({collection:e,fullPath:r,...t})=>{let{get_asset:n}=await b(t);return A(await n(e,r))},da=async({assets:e,...r})=>{let{get_many_assets:t}=await b(r),n=e.map(({collection:a,fullPath:o})=>[a,o]);return(await t(n)).map(([a,o])=>A(o))};var pa=e=>btoa([...e].map(r=>String.fromCharCode(r)).join(""));var kp=e=>_a(e),Up=e=>_a({filename:e.data.name,...e}),_a=async({filename:e,data:r,collection:t,headers:n=[],fullPath:i,token:a,satellite:o,encoding:s,description:c})=>{let u=x(o?.identity),p=decodeURI(e),d=i??`/${t}/${p}`,m={...o,identity:u};return await ia({asset:{data:r,filename:p,collection:t,token:a,headers:n,fullPath:d,encoding:s,description:c},satellite:m,options:{certified:!0}}),{downloadUrl:ma({satellite:m,assetKey:{fullPath:d,token:a}}),fullPath:d,name:p}},Bp=async({collection:e,filter:r,satellite:t,options:n})=>{let i={...t,identity:x(t?.identity)},{items:a,...o}=await aa({collection:e,filter:r??{},satellite:i,options:n??te}),s=a.map(({key:{full_path:c,token:u,name:p,owner:d,description:m},headers:h,encodings:g,created_at:I,updated_at:S})=>{let B=A(u);return{fullPath:c,description:A(m),name:p,downloadUrl:ma({satellite:i,assetKey:{fullPath:c,token:B}}),token:B,headers:h,encodings:g.reduce((O,[y,{modified:v,sha256:R,total_length:w}])=>({...O,[y]:{modified:v,sha256:pa(R),total_length:w}}),{}),owner:d.toText(),created_at:I,updated_at:S}});return{items:s,assets:s,...o}},Dp=async({collection:e,filter:r,satellite:t,options:n})=>{let i={...t,identity:x(t?.identity)};return await oa({collection:e,satellite:i,filter:r??{},options:n??te})},qp=({collection:e,fullPath:r,satellite:t})=>sa({collection:e,fullPath:r,satellite:{...t,identity:x(t?.identity)},options:{certified:!0}}),jp=({assets:e,satellite:r})=>ca({assets:e,satellite:{...r,identity:x(r?.identity)},options:{certified:!0}}),Kp=async({collection:e,satellite:r,filter:t})=>{let n={...r,identity:x(r?.identity)};return await la({collection:e,satellite:n,filter:t??{},options:{certified:!0}})},Mp=async({satellite:e,options:r,...t})=>{let n=x(e?.identity);return await ua({...t,satellite:{...e,identity:n},options:r??te})},Jp=async({satellite:e,options:r,...t})=>{let n=x(e?.identity);return await da({...t,satellite:{...e,identity:n},options:r??te})},ma=({assetKey:{fullPath:e,token:r},satellite:t})=>{let n={...t,identity:x(t?.identity)};return`${Vi(n)}${e}${f(r)?`?token=${r}`:""}`};var Cs=e=>{let r=e?.satelliteId??ra();Fr(r,"Satellite ID is not configured. Juno cannot be initialized.");let t=e?.container??ta();return{satelliteId:r,internetIdentityId:e?.internetIdentityId,workers:e?.workers,container:t}},Zp=e=>Is(e),Is=async e=>{let r=Cs(e);q.getInstance().set(r),await on();let t=r.workers?.auth!==void 0?ea(r.workers.auth):void 0;return[...t?[t]:[]]},ks=e=>H.getInstance().subscribe(e),Qp=ks;export{Fi as AuthClientSignInProgressStep,_t as InitError,yt as InternetIdentityProvider,mt as ListError,ht as NFIDProvider,ct as SignInError,Ue as SignInInitError,ut as SignInProviderNotSupportedError,lt as SignInUserInterruptError,pt as SignUpProviderNotSupportedError,Gi as WebAuthnSignInProgressStep,dt as WebAuthnSignInRetrievePublicKeyError,$i as WebAuthnSignUpProgressStep,Qp as authSubscribe,Dp as countAssets,Od as countDocs,qp as deleteAsset,Td as deleteDoc,Kp as deleteFilteredAssets,Nd as deleteFilteredDocs,jp as deleteManyAssets,gd as deleteManyDocs,ma as downloadUrl,Mp as getAsset,Tt as getDoc,Es as getIdentityOnce,Jp as getManyAssets,fd as getManyDocs,Tp as getSatelliteExtendedActor,Zp as initJuno,Is as initSatellite,Mo as isWebAuthnAvailable,Bp as listAssets,xd as listDocs,ks as onAuthStateChange,Wi as setDoc,Hi as setManyDocs,Ns as signIn,cn as signOut,xs as signUp,bs as unsafeIdentity,kp as uploadBlob,Up as uploadFile};
16
16
  /*! Bundled license information:
17
17
 
18
18
  buffer/index.js: