@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.
@@ -54,7 +54,7 @@ ${t(i)}
54
54
  Request ID: ${(0,m_.toHex)(r)}
55
55
  `)}throw new Error("unreachable")}Zt.pollForResponse=g_});var b_=ee(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});md.default=({IDL:e})=>{let t=e.Variant({mainnet:e.Null,testnet:e.Null}),r=e.Text,n=e.Record({network:t,address:r,min_confirmations:e.Opt(e.Nat32)}),i=e.Nat64,s=i,a=e.Nat32,o=e.Record({start_height:a,end_height:e.Opt(a),network:t}),c=e.Vec(e.Nat8),d=e.Record({tip_height:a,block_headers:e.Vec(c)}),f=e.Record({network:t}),p=e.Nat64,m=e.Vec(p),b=e.Record({network:t,filter:e.Opt(e.Variant({page:e.Vec(e.Nat8),min_confirmations:e.Nat32})),address:r}),l=e.Vec(e.Nat8),A=e.Record({txid:e.Vec(e.Nat8),vout:e.Nat32}),v=e.Record({height:e.Nat32,value:i,outpoint:A}),F=e.Record({next_page:e.Opt(e.Vec(e.Nat8)),tip_height:a,tip_block_hash:l,utxos:e.Vec(v)}),C=e.Record({transaction:e.Vec(e.Nat8),network:t}),E=e.Principal,H=e.Record({canister_id:E,num_requested_changes:e.Opt(e.Nat64)}),x=e.Variant({from_user:e.Record({user_id:e.Principal}),from_canister:e.Record({canister_version:e.Opt(e.Nat64),canister_id:e.Principal})}),q=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:q}),controllers_change:e.Record({controllers:e.Vec(e.Principal)}),code_uninstall:e.Null}),G=e.Record({timestamp_nanos:e.Nat64,canister_version:e.Nat64,origin:x,details:K}),D=e.Record({controllers:e.Vec(e.Principal),module_hash:e.Opt(e.Vec(e.Nat8)),recent_changes:e.Vec(G),total_num_changes:e.Nat64}),ae=e.Record({canister_id:E}),Q=e.Variant({controllers:e.Null,public:e.Null,allowed_viewers:e.Vec(e.Principal)}),ne=e.Record({freezing_threshold:e.Nat,controllers:e.Vec(e.Principal),reserved_cycles_limit:e.Nat,log_visibility:Q,wasm_memory_limit:e.Nat,memory_allocation:e.Nat,compute_allocation:e.Nat}),w=e.Record({status:e.Variant({stopped:e.Null,stopping:e.Null,running:e.Null}),memory_size:e.Nat,cycles:e.Nat,settings:ne,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}),g=e.Record({canister_id:E}),S=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(Q),wasm_memory_limit:e.Opt(e.Nat),memory_allocation:e.Opt(e.Nat),compute_allocation:e.Opt(e.Nat)}),R=e.Record({settings:e.Opt(S),sender_canister_version:e.Opt(e.Nat64)}),I=e.Record({canister_id:E}),j=e.Record({canister_id:E}),Y=e.Record({canister_id:E,snapshot_id:q}),oe=e.Record({canister_id:E}),se=e.Variant({secp256k1:e.Null}),z=e.Record({key_id:e.Record({name:e.Text,curve:se}),canister_id:e.Opt(E),derivation_path:e.Vec(e.Vec(e.Nat8))}),U=e.Record({public_key:e.Vec(e.Nat8),chain_code:e.Vec(e.Nat8)}),_=e.Record({canister_id:E}),Z=e.Record({idx:e.Nat64,timestamp_nanos:e.Nat64,content:e.Vec(e.Nat8)}),re=e.Record({canister_log_records:e.Vec(Z)}),le=e.Record({value:e.Text,name:e.Text}),X=e.Record({status:e.Nat,body:e.Vec(e.Nat8),headers:e.Vec(le)}),u=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:X})],[X],["query"]),context:e.Vec(e.Nat8)})),headers:e.Vec(le)}),h=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}),y=e.Record({hash:e.Vec(e.Nat8)}),P=e.Record({arg:e.Vec(e.Nat8),wasm_module_hash:e.Vec(e.Nat8),mode:h,chunk_hashes_list:e.Vec(y),target_canister:E,store_canister:e.Opt(E),sender_canister_version:e.Opt(e.Nat64)}),O=e.Vec(e.Nat8),B=e.Record({arg:e.Vec(e.Nat8),wasm_module:O,mode:h,canister_id:E,sender_canister_version:e.Opt(e.Nat64)}),M=e.Record({canister_id:E}),T=e.Record({id:q,total_size:e.Nat64,taken_at_timestamp:e.Nat64}),V=e.Vec(T),L=e.Record({canister_id:E,sender_canister_version:e.Opt(e.Nat64),snapshot_id:q}),k=e.Record({start_at_timestamp_nanos:e.Nat64,subnet_id:e.Principal}),J=e.Record({num_block_failures_total:e.Nat64,node_id:e.Principal,num_blocks_proposed_total:e.Nat64}),te=e.Vec(e.Record({timestamp_nanos:e.Nat64,node_metrics:e.Vec(J)})),de=e.Record({settings:e.Opt(S),specified_id:e.Opt(E),amount:e.Opt(e.Nat),sender_canister_version:e.Opt(e.Nat64)}),ge=e.Record({canister_id:E}),Ie=e.Record({canister_id:E,amount:e.Nat}),Ue=e.Vec(e.Nat8),_e=e.Variant({ed25519:e.Null,bip340secp256k1:e.Null}),fe=e.Record({key_id:e.Record({algorithm:_e,name:e.Text}),canister_id:e.Opt(E),derivation_path:e.Vec(e.Vec(e.Nat8))}),Ke=e.Record({public_key:e.Vec(e.Nat8),chain_code:e.Vec(e.Nat8)}),Ht=e.Record({key_id:e.Record({name:e.Text,curve:se}),derivation_path:e.Vec(e.Vec(e.Nat8)),message_hash:e.Vec(e.Nat8)}),Ut=e.Record({signature:e.Vec(e.Nat8)}),Vt=e.Variant({bip341:e.Record({merkle_root_hash:e.Vec(e.Nat8)})}),Kt=e.Record({aux:e.Opt(Vt),key_id:e.Record({algorithm:_e,name:e.Text}),derivation_path:e.Vec(e.Vec(e.Nat8)),message:e.Vec(e.Nat8)}),Be=e.Record({signature:e.Vec(e.Nat8)}),Ot=e.Record({canister_id:E}),at=e.Record({canister_id:E}),Ge=e.Record({canister_id:E}),Hc=e.Vec(y),Kc=e.Record({subnet_id:e.Principal}),$e=e.Record({replica_version:e.Text}),Gc=e.Record({replace_snapshot:e.Opt(q),canister_id:E}),$c=T,Wc=e.Record({canister_id:E,sender_canister_version:e.Opt(e.Nat64)}),zc=e.Record({canister_id:e.Principal,settings:S,sender_canister_version:e.Opt(e.Nat64)}),Yc=e.Record({chunk:e.Vec(e.Nat8),canister_id:e.Principal}),dn=y;return e.Service({bitcoin_get_balance:e.Func([n],[s],[]),bitcoin_get_block_headers:e.Func([o],[d],[]),bitcoin_get_current_fee_percentiles:e.Func([f],[m],[]),bitcoin_get_utxos:e.Func([b],[F],[]),bitcoin_send_transaction:e.Func([C],[],[]),canister_info:e.Func([H],[D],[]),canister_status:e.Func([ae],[w],[]),clear_chunk_store:e.Func([g],[],[]),create_canister:e.Func([R],[I],[]),delete_canister:e.Func([j],[],[]),delete_canister_snapshot:e.Func([Y],[],[]),deposit_cycles:e.Func([oe],[],[]),ecdsa_public_key:e.Func([z],[U],[]),fetch_canister_logs:e.Func([_],[re],["query"]),http_request:e.Func([u],[X],[]),install_chunked_code:e.Func([P],[],[]),install_code:e.Func([B],[],[]),list_canister_snapshots:e.Func([M],[V],[]),load_canister_snapshot:e.Func([L],[],[]),node_metrics_history:e.Func([k],[te],[]),provisional_create_canister_with_cycles:e.Func([de],[ge],[]),provisional_top_up_canister:e.Func([Ie],[],[]),raw_rand:e.Func([],[Ue],[]),schnorr_public_key:e.Func([fe],[Ke],[]),sign_with_ecdsa:e.Func([Ht],[Ut],[]),sign_with_schnorr:e.Func([Kt],[Be],[]),start_canister:e.Func([Ot],[],[]),stop_canister:e.Func([at],[],[]),stored_chunks:e.Func([Ge],[Hc],[]),subnet_info:e.Func([Kc],[$e],[]),take_canister_snapshot:e.Func([Gc],[$c],[]),uninstall_code:e.Func([Wc],[],[]),update_settings:e.Func([zc],[],[]),upload_chunk:e.Func([Yc],[dn],[])})}});var cc=ee(ze=>{"use strict";var uN=ze&&ze.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(ze,"__esModule",{value:!0});ze.AdvancedActor=ze.getManagementCanister=ze.ACTOR_METHOD_WITH_CERTIFICATE=ze.ACTOR_METHOD_WITH_HTTP_DETAILS=ze.Actor=ze.UpdateCallRejectedError=ze.QueryCallRejectedError=ze.ActorCallError=void 0;var lN=Hf(),gd=qs(),bd=wi(),Ws=Ri(),w_=ac(),pr=Ct(),dN=$t(),Gi=Fi(),fN=uN(b_()),zs=class extends bd.AgentError{constructor(t,r,n,i){super(["Call failed:",` Canister: ${t.toText()}`,` Method: ${r} (${n})`,...Object.getOwnPropertyNames(i).map(s=>` "${s}": ${JSON.stringify(i[s])}`)].join(`
56
56
  `)),this.canisterId=t,this.methodName=r,this.type=n,this.props=i}};ze.ActorCallError=zs;var oc=class extends zs{constructor(t,r,n){var i;super(t,r,"query",{Status:n.status,Code:(i=gd.ReplicaRejectCode[n.reject_code])!==null&&i!==void 0?i:`Unknown Code "${n.reject_code}"`,Message:n.reject_message}),this.result=n}};ze.QueryCallRejectedError=oc;var Ys=class extends zs{constructor(t,r,n,i,s,a,o){super(t,r,"update",Object.assign({"Request ID":(0,dN.toHex)(n)},i.body?Object.assign(Object.assign({},o?{"Error code":o}:{}),{"Reject code":String(s),"Reject message":a}):{"HTTP status code":i.status.toString(),"HTTP status text":i.statusText})),this.requestId=n,this.response=i,this.reject_code=s,this.reject_message=a,this.error_code=o}};ze.UpdateCallRejectedError=Ys;var fr=Symbol.for("ic-agent-metadata"),Js=class e{constructor(t){this[fr]=Object.freeze(t)}static agentOf(t){return t[fr].config.agent}static interfaceOf(t){return t[fr].service}static canisterIdOf(t){return pr.Principal.from(t[fr].config.canisterId)}static async install(t,r){let n=t.mode===void 0?{install:null}:t.mode,i=t.arg?[...new Uint8Array(t.arg)]:[],s=[...new Uint8Array(t.module)],a=typeof r.canisterId=="string"?pr.Principal.fromText(r.canisterId):r.canisterId;await wd(r).install_code({mode:n,arg:i,wasm_module:s,canister_id:a,sender_canister_version:[]})}static async createCanister(t,r){function n(s){return[{controllers:s.controllers?[s.controllers]:[],compute_allocation:s.compute_allocation?[s.compute_allocation]:[],freezing_threshold:s.freezing_threshold?[s.freezing_threshold]:[],memory_allocation:s.memory_allocation?[s.memory_allocation]:[],reserved_cycles_limit:[],log_visibility:[],wasm_memory_limit:[]}]}let{canister_id:i}=await wd(t||{}).provisional_create_canister_with_cycles({amount:[],settings:n(r||{}),specified_id:[],sender_canister_version:[]});return i}static async createAndInstallCanister(t,r,n){let i=await this.createCanister(n);return await this.install(Object.assign({},r),Object.assign(Object.assign({},n),{canisterId:i})),this.createActor(t,Object.assign(Object.assign({},n),{canisterId:i}))}static createActorClass(t,r){let n=t({IDL:Ws.IDL});class i extends e{constructor(a){if(!a.canisterId)throw new bd.AgentError(`Canister ID is required, but received ${typeof a.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 o=typeof a.canisterId=="string"?pr.Principal.fromText(a.canisterId):a.canisterId;super({config:Object.assign(Object.assign(Object.assign({},x_),a),{canisterId:o}),service:n});for(let[c,d]of n._fields)r?.httpDetails&&d.annotations.push(ze.ACTOR_METHOD_WITH_HTTP_DETAILS),r?.certificate&&d.annotations.push(ze.ACTOR_METHOD_WITH_CERTIFICATE),this[c]=pN(this,c,d,a.blsVerify)}}return i}static createActor(t,r){if(!r.canisterId)throw new bd.AgentError(`Canister ID is required, but received ${typeof r.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(t))(r)}static createActorWithHttpDetails(t,r){return new(this.createActorClass(t,{httpDetails:!0}))(r)}static createActorWithExtendedDetails(t,r,n={httpDetails:!0,certificate:!0}){return new(this.createActorClass(t,n))(r)}};ze.Actor=Js;function $i(e,t){let r=Ws.IDL.decode(e,lN.Buffer.from(t));switch(r.length){case 0:return;case 1:return r[0];default:return r}}var x_={pollingStrategyFactory:w_.strategy.defaultStrategy};ze.ACTOR_METHOD_WITH_HTTP_DETAILS="http-details";ze.ACTOR_METHOD_WITH_CERTIFICATE="certificate";function pN(e,t,r,n){let i;r.annotations.includes("query")||r.annotations.includes("composite_query")?i=async(a,...o)=>{var c,d;a=Object.assign(Object.assign({},a),(d=(c=e[fr].config).queryTransform)===null||d===void 0?void 0:d.call(c,t,o,Object.assign(Object.assign({},e[fr].config),a)));let f=a.agent||e[fr].config.agent||(0,gd.getDefaultAgent)(),p=pr.Principal.from(a.canisterId||e[fr].config.canisterId),m=Ws.IDL.encode(r.argTypes,o),b=await f.query(p,{methodName:t,arg:m,effectiveCanisterId:a.effectiveCanisterId}),l=Object.assign(Object.assign({},b.httpDetails),{requestDetails:b.requestDetails});switch(b.status){case"rejected":throw new oc(p,t,b);case"replied":return r.annotations.includes(ze.ACTOR_METHOD_WITH_HTTP_DETAILS)?{httpDetails:l,result:$i(r.retTypes,b.reply.arg)}:$i(r.retTypes,b.reply.arg)}}:i=async(a,...o)=>{var c,d;a=Object.assign(Object.assign({},a),(d=(c=e[fr].config).callTransform)===null||d===void 0?void 0:d.call(c,t,o,Object.assign(Object.assign({},e[fr].config),a)));let f=a.agent||e[fr].config.agent||(0,gd.getDefaultAgent)(),{canisterId:p,effectiveCanisterId:m,pollingStrategyFactory:b}=Object.assign(Object.assign(Object.assign({},x_),e[fr].config),a),l=pr.Principal.from(p),A=m!==void 0?pr.Principal.from(m):l,v=Ws.IDL.encode(r.argTypes,o),{requestId:F,response:C,requestDetails:E}=await f.call(l,{methodName:t,arg:v,effectiveCanisterId:A}),H,x;if(C.body&&C.body.certificate){if(f.rootKey==null)throw new Error("Agent is missing root key");let D=C.body.certificate;x=await Gi.Certificate.create({certificate:(0,Ws.bufFromBufLike)(D),rootKey:f.rootKey,canisterId:pr.Principal.from(p),blsVerify:n});let ae=[new TextEncoder().encode("request_status"),F];switch(new TextDecoder().decode((0,Gi.lookupResultToBuffer)(x.lookup([...ae,"status"])))){case"replied":H=(0,Gi.lookupResultToBuffer)(x.lookup([...ae,"reply"]));break;case"rejected":{let ne=new Uint8Array((0,Gi.lookupResultToBuffer)(x.lookup([...ae,"reject_code"])))[0],w=new TextDecoder().decode((0,Gi.lookupResultToBuffer)(x.lookup([...ae,"reject_message"]))),g=(0,Gi.lookupResultToBuffer)(x.lookup([...ae,"error_code"])),S=g?new TextDecoder().decode(g):void 0;throw new Ys(l,t,F,C,ne,w,S)}}}else if(C.body&&"reject_message"in C.body){let{reject_code:D,reject_message:ae,error_code:Q}=C.body;throw new Ys(l,t,F,C,D,ae,Q)}if(C.status===202){let D=b(),ae=await(0,w_.pollForResponse)(f,A,F,D,n);x=ae.certificate,H=ae.reply}let q=r.annotations.includes(ze.ACTOR_METHOD_WITH_HTTP_DETAILS),K=r.annotations.includes(ze.ACTOR_METHOD_WITH_CERTIFICATE),G=Object.assign(Object.assign({},C),{requestDetails:E});if(H!==void 0)return q&&K?{httpDetails:G,certificate:x,result:$i(r.retTypes,H)}:K?{certificate:x,result:$i(r.retTypes,H)}:q?{httpDetails:G,result:$i(r.retTypes,H)}:$i(r.retTypes,H);if(r.retTypes.length===0)return q?{httpDetails:C,result:void 0}:void 0;throw new Error(`Call was returned undefined, but type [${r.retTypes.join(",")}].`)};let s=(...a)=>i({},...a);return s.withOptions=a=>(...o)=>i(a,...o),s}function wd(e){function t(r,n){if(e.effectiveCanisterId)return{effectiveCanisterId:pr.Principal.from(e.effectiveCanisterId)};let i=n[0],s=pr.Principal.fromHex("");return i&&typeof i=="object"&&i.target_canister&&r==="install_chunked_code"&&(s=pr.Principal.from(i.target_canister)),i&&typeof i=="object"&&i.canister_id&&(s=pr.Principal.from(i.canister_id)),{effectiveCanisterId:s}}return Js.createActor(fN.default,Object.assign(Object.assign(Object.assign({},e),{canisterId:pr.Principal.fromHex("")}),{callTransform:t,queryTransform:t}))}ze.getManagementCanister=wd;var xd=class extends Js{constructor(t){super(t)}};ze.AdvancedActor=xd});var T_=ee(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});Td.default=({IDL:e})=>e.Service({retrieve:e.Func([e.Text],[e.Vec(e.Nat8)],["query"]),store:e.Func([e.Text,e.Vec(e.Nat8)],[],[])})});var N_=ee(Wi=>{"use strict";var hN=Wi&&Wi.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Wi,"__esModule",{value:!0});Wi.createAssetCanisterActor=void 0;var _N=cc(),yN=hN(T_());function mN(e){return _N.Actor.createActor(yN.default,e)}Wi.createAssetCanisterActor=mN});var E_=ee(zr=>{"use strict";var gN=zr&&zr.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),bN=zr&&zr.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),wN=zr&&zr.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&gN(t,e,r);return bN(t,e),t};Object.defineProperty(zr,"__esModule",{value:!0});zr.fetchCandid=void 0;var xN=Ct(),TN=wN(Ds()),NN=hd(),EN=cc();async function ON(e,t){t||(t=await NN.HttpAgent.create());let n=(await TN.request({agent:t,canisterId:xN.Principal.fromText(e),paths:["candid"]})).get("candid");if(n)return n;let i=({IDL:a})=>a.Service({__get_candid_interface_tmp_hack:a.Func([],[a.Text],["query"])});return await EN.Actor.createActor(i,{agent:t,canisterId:e}).__get_candid_interface_tmp_hack()}zr.fetchCandid=ON});var gt=ee(Pe=>{"use strict";var O_=Pe&&Pe.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),vN=Pe&&Pe.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Ft=Pe&&Pe.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&O_(t,e,r)},Nd=Pe&&Pe.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&O_(t,e,r);return vN(t,e),t};Object.defineProperty(Pe,"__esModule",{value:!0});Pe.Cbor=Pe.CanisterStatus=Pe.polling=void 0;Ft(cc(),Pe);Ft(qs(),Pe);Ft(fo(),Pe);Ft(Rs(),Pe);Ft(ol(),Pe);Ft(N_(),Pe);Ft(Fi(),Pe);Ft(cd(),Pe);Ft(E_(),Pe);Ft(dd(),Pe);Ft(ud(),Pe);Ft(Ns(),Pe);Ft(jl(),Pe);Ft($t(),Pe);Ft(yl(),Pe);Pe.polling=Nd(ac());Pe.CanisterStatus=Nd(Ds());Pe.Cbor=Nd(vs());Ft(ac(),Pe)});var De=ee((W6,K_)=>{"use strict";var Ad=Object.defineProperty,RN=Object.getOwnPropertyDescriptor,AN=Object.getOwnPropertyNames,SN=Object.prototype.hasOwnProperty,IN=(e,t)=>{for(var r in t)Ad(e,r,{get:t[r],enumerable:!0})},BN=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of AN(t))!SN.call(e,i)&&i!==r&&Ad(e,i,{get:()=>t[i],enumerable:!(n=RN(t,i))||n.enumerable});return e},PN=e=>BN(Ad({},"__esModule",{value:!0}),e),S_={};IN(S_,{AgentManager:()=>LN,Canister:()=>kN,FromStringToTokenError:()=>I_,ICPToken:()=>CN,InvalidPercentageError:()=>C_,NullishError:()=>q_,TokenAmount:()=>qN,TokenAmountV2:()=>DN,arrayBufferToUint8Array:()=>YN,arrayOfNumberToUint8Array:()=>ZN,asNonNullish:()=>KN,asciiStringToByteArray:()=>XN,assertNonNullish:()=>ta,assertPercentageNumber:()=>GN,base64ToUint8Array:()=>s2,bigEndianCrc32:()=>c2,bigIntToUint8Array:()=>WN,candidNumberArrayToBigInt:()=>t2,convertStringToE8s:()=>B_,createAgent:()=>U_,createServices:()=>HN,debounce:()=>y2,decodeBase32:()=>n2,defaultAgent:()=>F_,encodeBase32:()=>r2,fromDefinedNullable:()=>g2,fromNullable:()=>Sd,fromNullishNullable:()=>b2,hashObject:()=>l2,hashText:()=>j_,hexStringToUint8Array:()=>QN,isEmptyString:()=>MN,isNullish:()=>ea,jsonReplacer:()=>M_,jsonReviver:()=>u2,nonNullish:()=>Yr,notEmptyString:()=>P_,nowInBigIntNanoSeconds:()=>h2,numberToUint8Array:()=>zN,principalToSubAccount:()=>w2,queryAndUpdate:()=>jN,secondsToDuration:()=>f2,smallerVersion:()=>x2,toBigIntNanoSeconds:()=>_2,toNullable:()=>m2,uint8ArrayToArrayOfNumber:()=>JN,uint8ArrayToBase64:()=>i2,uint8ArrayToBigInt:()=>$N,uint8ArrayToHexString:()=>D_,uint8ArraysEqual:()=>e2});K_.exports=PN(S_);var I_=(e=>(e[e.FractionalMoreThan8Decimals=0]="FractionalMoreThan8Decimals",e[e.InvalidFormat=1]="InvalidFormat",e[e.FractionalTooManyDecimals=2]="FractionalTooManyDecimals",e))(I_||{}),FN=BigInt(1e8),UN=8,B_=e=>{let t=e.includes("e")?Number(e).toLocaleString("en",{useGrouping:!1,maximumFractionDigits:20}):e;t=t.trim().replace(/[,']/g,"");let r=t.match(/\d*(\.\d*)?/);if(!r||r[0]!==t)return 1;let[n,i]=t.split("."),s=BigInt(0);if(n)try{s+=BigInt(n)*FN}catch{return 1}if(i){if(i.length>8)return 0;try{s+=BigInt(i.padEnd(8,"0"))}catch{return 1}}return s},VN=({amount:e,decimals:t})=>{e=e.trim().replace(/[,']/g,"");let r=e.match(/\d*(\.\d*)?/);if(!r||r[0]!==e)return 1;let[n,i]=e.split("."),s=0n,a=10n**BigInt(t);if(n)try{s+=BigInt(n)*a}catch{return 1}if(i){if(i.length>t)return 2;try{s+=BigInt(i.padEnd(t,"0"))}catch{return 1}}return s},CN={symbol:"ICP",name:"Internet Computer",decimals:8},qN=class Xs{constructor(t,r){if(this.e8s=t,this.token=r,r.decimals!==8)throw new Error("Use TokenAmountV2 for number of decimals other than 8")}static fromE8s({amount:t,token:r}){return new Xs(t,r)}static fromString({amount:t,token:r}){if(r.decimals!==8)throw new Error("Use TokenAmountV2 for number of decimals other than 8");let n=B_(t);return typeof n=="bigint"?new Xs(n,r):n}static fromNumber({amount:t,token:r}){let n=Xs.fromString({amount:t.toString(),token:r});if(n instanceof Xs)return n;throw n===0?new Error(`Number ${t} has more than 8 decimals`):new Error(`Invalid number ${t}`)}toE8s(){return this.e8s}},DN=class Qs{constructor(t,r){this.ulps=t,this.token=r}static fromUlps({amount:t,token:r}){return new Qs(t,r)}static fromString({amount:t,token:r}){let n=VN({amount:t,decimals:r.decimals});return typeof n=="bigint"?new Qs(n,r):n}static fromNumber({amount:t,token:r}){let n=Qs.fromString({amount:t.toFixed(Math.min(UN,r.decimals)),token:r});if(n instanceof Qs)return n;throw n===2?new Error(`Number ${t} has more than ${r.decimals} decimals`):new Error(`Invalid number ${t}`)}toUlps(){return this.ulps}toE8s(){return this.token.decimals<8?this.ulps*10n**BigInt(8-this.token.decimals):this.token.decimals===8?this.ulps:this.ulps/10n**BigInt(this.token.decimals-8)}},kN=class{constructor(e,t,r){this.id=e,this.service=t,this.certifiedService=r}get canisterId(){return this.id}caller=({certified:e=!0})=>e?this.certifiedService:this.service},ea=e=>e==null,Yr=e=>!ea(e),P_=e=>Yr(e)&&e!=="",MN=e=>!P_(e),jN=async({request:e,onLoad:t,onQueryError:r,onUpdateError:n,strategy:i="query_and_update",identity:s,resolution:a="race"})=>{let o=!1,c=f=>e({certified:f,identity:s}).then(p=>{o||t({certified:f,response:p})}).catch(p=>{f||r==null||r({error:p,identity:s}),!o&&(ea(n)||(console.error(p),f&&n({error:p,identity:s})))}).finally(()=>o=o||f),d=i==="query"?[c(!1)]:i==="update"?[c(!0)]:[c(!1),c(!0)];await(a==="all_settled"?Promise.allSettled(d):Promise.race(d))},v_=gt(),Ed=gt(),F_=()=>Ed.HttpAgent.createSync({host:"https://icp-api.io",identity:new Ed.AnonymousIdentity}),U_=async({identity:e,host:t,fetchRootKey:r=!1,verifyQuerySignatures:n=!1,retryTimes:i})=>await Ed.HttpAgent.create({identity:e,...Yr(t)&&{host:t},verifyQuerySignatures:n,...Yr(i)&&{retryTimes:i},shouldFetchRootKey:r}),LN=class V_{constructor(t){this.config=t}agents=void 0;static create(t){return new V_(t)}getAgent=async({identity:t})=>{let r=t.getPrincipal().toText();if(ea(this.agents)||ea(this.agents[r])){let n=await U_({identity:t,fetchRootKey:this.config.fetchRootKey,host:this.config.host,verifyQuerySignatures:!0});return this.agents={...this.agents??{},[r]:n},n}return this.agents[r]};clearAgents=()=>{this.agents=null}},HN=({options:{canisterId:e,serviceOverride:t,certifiedServiceOverride:r,agent:n,callTransform:i,queryTransform:s},idlFactory:a,certifiedIdlFactory:o})=>{let c=n??F_(),d=t??v_.Actor.createActor(a,{agent:c,canisterId:e,callTransform:i,queryTransform:s}),f=r??v_.Actor.createActor(o,{agent:c,canisterId:e,callTransform:i,queryTransform:s});return{service:d,certifiedService:f,agent:c,canisterId:e}},C_=class extends Error{},q_=class extends Error{},ta=(e,t)=>{if(e==null)throw new q_(t)},KN=(e,t)=>(ta(e,t),e),GN=e=>{if(e<0||e>100)throw new C_(`${e} is not a valid percentage number.`)},$N=e=>{let t=new DataView(e.buffer,e.byteOffset,e.byteLength);if(typeof t.getBigUint64=="function")return t.getBigUint64(0);let r=BigInt(t.getUint32(0)),n=BigInt(t.getUint32(4));return(r<<BigInt(32))+n},WN=e=>{let t=new ArrayBuffer(8),r=new DataView(t);if(typeof r.setBigUint64=="function")r.setBigUint64(0,e);else{let n=Number(e>>BigInt(32)),i=Number(e&BigInt(4294967295));r.setUint32(0,n),r.setUint32(4,i)}return new Uint8Array(t)},zN=e=>{let t=new DataView(new ArrayBuffer(8));for(let r=7;r>=0;--r)t.setUint8(r,e%256),e=e>>8;return new Uint8Array(t.buffer)},YN=e=>new Uint8Array(e),JN=e=>Array.from(e),ZN=e=>new Uint8Array(e),XN=e=>Array.from(e).map(t=>t.charCodeAt(0)),QN=e=>{let t=e.match(/.{1,2}/g);return ta(t,"Invalid hex string."),Uint8Array.from(t.map(r=>parseInt(r,16)))},e2=({a:e,b:t})=>e.length===t.length&&e.every((r,n)=>r===t[n]),D_=e=>(e instanceof Uint8Array||(e=Uint8Array.from(e)),e.reduce((t,r)=>t+r.toString(16).padStart(2,"0"),"")),t2=e=>{let t=0n;for(let r=e.length-1;r>=0;r--)t=(t<<32n)+BigInt(e[r]);return t},uc="abcdefghijklmnopqrstuvwxyz234567",zi=Object.create(null);for(let e=0;e<uc.length;e++)zi[uc[e]]=e;zi[0]=zi.o;zi[1]=zi.i;var r2=e=>{let t=0,r=0,n="",i=s=>(t<0?r|=s>>-t:r=s<<t&248,t>3?(t-=8,1):(t<4&&(n+=uc[r>>3],t+=5),0));for(let s=0;s<e.length;)s+=i(e[s]);return n+(t<0?uc[r>>3]:"")},n2=e=>{let t=0,r=0,n=new Uint8Array(e.length*4/3|0),i=0,s=a=>{let o=zi[a.toLowerCase()];ta(o,`Invalid character: ${JSON.stringify(a)}`),o<<=3,r|=o>>>t,t+=5,t>=8&&(n[i++]=r,t-=8,t>0?r=o<<5-t&255:r=0)};for(let a of e)s(a);return n.slice(0,i)},i2=e=>btoa(String.fromCharCode(...new Uint8Array(e))),s2=e=>Uint8Array.from(atob(e),t=>t.charCodeAt(0)),a2=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]),o2=e=>{let t=-1;for(let r=0;r<e.length;r++){let n=(e[r]^t)&255;t=a2[n]^t>>>8}return(t^-1)>>>0},c2=e=>{let t=new ArrayBuffer(4);return new DataView(t).setUint32(0,o2(e),!1),new Uint8Array(t)},k_=Ct(),Od="__bigint__",vd="__principal__",Rd="__uint8array__",M_=(e,t)=>typeof t=="bigint"?{[Od]:`${t}`}:Yr(t)&&t instanceof k_.Principal?{[vd]:t.toText()}:Yr(t)&&t instanceof Uint8Array?{[Rd]:Array.from(t)}:t,u2=(e,t)=>{let r=n=>t[n];return Yr(t)&&typeof t=="object"&&Od in t?BigInt(r(Od)):Yr(t)&&typeof t=="object"&&vd in t?k_.Principal.fromText(r(vd)):Yr(t)&&typeof t=="object"&&Rd in t?Uint8Array.from(r(Rd)):t},l2=async e=>{let t=JSON.stringify(e,M_);return await j_(t)},j_=async e=>{let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return D_(new Uint8Array(r))},d2={year:"year",year_plural:"years",month:"month",month_plural:"months",day:"day",day_plural:"days",hour:"hour",hour_plural:"hours",minute:"minute",minute_plural:"minutes",second:"second",second_plural:"seconds"},f2=({seconds:e,i18n:t=d2})=>{let r=e/BigInt(60),n=r/BigInt(60);r-=n*BigInt(60);let i=n/BigInt(24);n-=i*BigInt(24);let s=p2(i);return i-=L_(s),[Zs({labelKey:"year",amount:s}),Zs({labelKey:"day",amount:i}),Zs({labelKey:"hour",amount:n}),Zs({labelKey:"minute",amount:r}),...e>BigInt(0)&&e<BigInt(60)?[Zs({labelKey:"second",amount:e})]:[]].filter(({amount:a})=>a>0).slice(0,2).map(a=>`${a.amount} ${a.amount===1?t[a.labelKey]:t[`${a.labelKey}_plural`]}`).join(", ")},p2=e=>{let t=e/BigInt(365);for(;L_(t)>e;)t--;return t},L_=e=>{let t=e/BigInt(4);return e*BigInt(365)+t},Zs=({labelKey:e,amount:t})=>({labelKey:e,amount:Number(t)}),H_=1000000n,h2=()=>BigInt(Date.now())*H_,_2=e=>BigInt(e.getTime())*H_,y2=(e,t)=>{let r;return(...n)=>{let i=()=>e(...n);r&&clearTimeout(r),r=setTimeout(i,t!==void 0&&t>0?t:300)}},m2=e=>Yr(e)?[e]:[],Sd=e=>e?.[0],g2=e=>{let t=Sd(e);return ta(t),t},b2=e=>Sd(e??[]),w2=e=>{let t=e.toUint8Array(),r=new Uint8Array(32);return r[0]=t.length,r.set(t,1),r},R_=({nums:e,amountZeros:t})=>t>e.length?[...e,...[...Array(t-e.length).keys()].map(()=>0)]:e,A_=e=>{if(!Number.isNaN(Number(e)))return Number(e);let t=e.split("").reduce((r,n)=>Number.isNaN(Number(n))?r:r+n,"");return Number(t)},x2=({minVersion:e,currentVersion:t})=>{let r=R_({nums:e.split(".").map(A_),amountZeros:3}).join(".");return R_({nums:t.split(".").map(A_),amountZeros:3}).join(".").localeCompare(r,void 0,{numeric:!0,sensitivity:"base"})<0}});var _y=ee(Jr=>{"use strict";var bc=Jr&&Jr.__classPrivateFieldSet||function(e,t,r,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 t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,r):i?i.value=r:t.set(e,r),r},Cn=Jr&&Jr.__classPrivateFieldGet||function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},mc,gc,Qi,es;Object.defineProperty(Jr,"__esModule",{value:!0});Jr.Ed25519KeyIdentity=Jr.Ed25519PublicKey=void 0;var W2=gt(),ir=gt(),ia=ad();function hy(e){return e!==null&&typeof e=="object"}var oi=class e{constructor(t){if(mc.set(this,void 0),gc.set(this,void 0),t.byteLength!==e.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");bc(this,mc,t,"f"),bc(this,gc,e.derEncode(t),"f")}static from(t){if(typeof t=="string"){let r=(0,ir.fromHex)(t);return this.fromRaw(r)}else if(hy(t)){let r=t;if(hy(r)&&Object.hasOwnProperty.call(r,"__derEncodedPublicKey__"))return this.fromDer(r);if(ArrayBuffer.isView(r)){let n=r;return this.fromRaw((0,ir.bufFromBufLike)(n.buffer))}else{if(r instanceof ArrayBuffer)return this.fromRaw(r);if("rawKey"in r)return this.fromRaw(r.rawKey);if("derKey"in r)return this.fromDer(r.derKey);if("toDer"in r)return this.fromDer(r.toDer())}}throw new Error("Cannot construct Ed25519PublicKey from the provided key.")}static fromRaw(t){return new e(t)}static fromDer(t){return new e(this.derDecode(t))}static derEncode(t){let r=(0,ir.wrapDER)(t,ir.ED25519_OID).buffer;return r.__derEncodedPublicKey__=void 0,r}static derDecode(t){let r=(0,ir.unwrapDER)(t,ir.ED25519_OID);if(r.length!==this.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");return r}get rawKey(){return Cn(this,mc,"f")}get derKey(){return Cn(this,gc,"f")}toDer(){return this.derKey}toRaw(){return this.rawKey}};Jr.Ed25519PublicKey=oi;mc=new WeakMap,gc=new WeakMap;oi.RAW_KEY_LENGTH=32;var Cd=class e extends ir.SignIdentity{constructor(t,r){super(),Qi.set(this,void 0),es.set(this,void 0),bc(this,Qi,oi.from(t),"f"),bc(this,es,new Uint8Array(r),"f")}static generate(t){if(t&&t.length!==32)throw new Error("Ed25519 Seed needs to be 32 bytes long.");t||(t=ia.ed25519.utils.randomPrivateKey()),(0,W2.bufEquals)(t,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 r=new Uint8Array(32);for(let i=0;i<32;i++)r[i]=new Uint8Array(t)[i];let n=ia.ed25519.getPublicKey(r);return e.fromKeyPair(n,r)}static fromParsedJson(t){let[r,n]=t;return new e(oi.fromDer((0,ir.fromHex)(r)),(0,ir.fromHex)(n))}static fromJSON(t){let r=JSON.parse(t);if(Array.isArray(r)){if(typeof r[0]=="string"&&typeof r[1]=="string")return this.fromParsedJson([r[0],r[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(t)}`)}static fromKeyPair(t,r){return new e(oi.fromRaw(t),r)}static fromSecretKey(t){let r=ia.ed25519.getPublicKey(new Uint8Array(t));return e.fromKeyPair(r,t)}toJSON(){return[(0,ir.toHex)(Cn(this,Qi,"f").toDer()),(0,ir.toHex)(Cn(this,es,"f"))]}getKeyPair(){return{secretKey:Cn(this,es,"f"),publicKey:Cn(this,Qi,"f")}}getPublicKey(){return Cn(this,Qi,"f")}async sign(t){let r=new Uint8Array(t),n=(0,ir.uint8ToBuf)(ia.ed25519.sign(r,Cn(this,es,"f").slice(0,32)));return Object.defineProperty(n,"__signature__",{enumerable:!1,value:void 0}),n}static verify(t,r,n){let[i,s,a]=[t,r,n].map(o=>(typeof o=="string"&&(o=(0,ir.fromHex)(o)),o instanceof Uint8Array&&(o=o.buffer),new Uint8Array(o)));return ia.ed25519.verify(s,i,a)}};Jr.Ed25519KeyIdentity=Cd;Qi=new WeakMap,es=new WeakMap});var my=ee(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.ECDSAKeyIdentity=ci.CryptoError=void 0;var z2=gt(),wc=class e extends Error{constructor(t){super(t),this.message=t,Object.setPrototypeOf(this,e.prototype)}};ci.CryptoError=wc;function yy(e){if(typeof global<"u"&&global.crypto&&global.crypto.subtle)return global.crypto.subtle;if(e)return e;if(typeof crypto<"u"&&crypto.subtle)return crypto.subtle;throw new wc("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 xc=class e extends z2.SignIdentity{constructor(t,r,n){super(),this._keyPair=t,this._derKey=r,this._subtleCrypto=n}static async generate(t){let{extractable:r=!1,keyUsages:n=["sign","verify"],subtleCrypto:i}=t??{},s=yy(i),a=await s.generateKey({name:"ECDSA",namedCurve:"P-256"},r,n),o=await s.exportKey("spki",a.publicKey);return new this(a,o,s)}static async fromKeyPair(t,r){let n=yy(r),i=await n.exportKey("spki",t.publicKey);return new e(t,i,n)}getKeyPair(){return this._keyPair}getPublicKey(){let t=this._derKey,r=Object.create(this._keyPair.publicKey);return r.toDer=function(){return t},r}async sign(t){let r={name:"ECDSA",hash:{name:"SHA-256"}};return await this._subtleCrypto.sign(r,this._keyPair.privateKey,t)}};ci.ECDSAKeyIdentity=xc;ci.default=xc});var Dd=ee(Dn=>{"use strict";var Y2=Dn&&Dn.__classPrivateFieldSet||function(e,t,r,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 t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,r):i?i.value=r:t.set(e,r),r},sa=Dn&&Dn.__classPrivateFieldGet||function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},qn;Object.defineProperty(Dn,"__esModule",{value:!0});Dn.PartialIdentity=void 0;var J2=Ct(),qd=class{constructor(t){qn.set(this,void 0),Y2(this,qn,t,"f")}get rawKey(){return sa(this,qn,"f").rawKey}get derKey(){return sa(this,qn,"f").derKey}toDer(){return sa(this,qn,"f").toDer()}getPublicKey(){return sa(this,qn,"f")}getPrincipal(){return J2.Principal.from(sa(this,qn,"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.")}};Dn.PartialIdentity=qd;qn=new WeakMap});var gy=ee(Ze=>{"use strict";var Z2=Ze&&Ze.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),X2=Ze&&Ze.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Q2=Ze&&Ze.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&Z2(t,e,r);return X2(t,e),t},eE=Ze&&Ze.__classPrivateFieldSet||function(e,t,r,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 t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,r):i?i.value=r:t.set(e,r),r},tE=Ze&&Ze.__classPrivateFieldGet||function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},rE=Ze&&Ze.__rest||function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]]);return r},Tc;Object.defineProperty(Ze,"__esModule",{value:!0});Ze.isDelegationValid=Ze.PartialDelegationIdentity=Ze.DelegationIdentity=Ze.DelegationChain=Ze.Delegation=void 0;var kn=gt(),Md=Ct(),aa=Q2(Os()),nE=Dd(),iE=new TextEncoder().encode("ic-request-auth-delegation"),sE=new TextEncoder().encode(`
57
- ic-request`);function kd(e){if(typeof e!="string"||e.length<64)throw new Error("Invalid public key.");return(0,kn.fromHex)(e)}var oa=class{constructor(t,r,n){this.pubkey=t,this.expiration=r,this.targets=n}toCBOR(){return aa.value.map(Object.assign({pubkey:aa.value.bytes(this.pubkey),expiration:aa.value.u64(this.expiration.toString(16),16)},this.targets&&{targets:aa.value.array(this.targets.map(t=>aa.value.bytes(t.toUint8Array())))}))}toJSON(){return Object.assign({expiration:this.expiration.toString(16),pubkey:(0,kn.toHex)(this.pubkey)},this.targets&&{targets:this.targets.map(t=>t.toHex())})}};Ze.Delegation=oa;async function aE(e,t,r,n){let i=new oa(t.toDer(),BigInt(+r)*BigInt(1e6),n),s=new Uint8Array([...iE,...new Uint8Array((0,kn.requestIdOf)(Object.assign({},i)))]),a=await e.sign(s);return{delegation:i,signature:a}}var jd=class e{constructor(t,r){this.delegations=t,this.publicKey=r}static async create(t,r,n=new Date(Date.now()+900*1e3),i={}){var s,a;let o=await aE(t,r,n,i.targets);return new e([...((s=i.previous)===null||s===void 0?void 0:s.delegations)||[],o],((a=i.previous)===null||a===void 0?void 0:a.publicKey)||t.getPublicKey().toDer())}static fromJSON(t){let{publicKey:r,delegations:n}=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(n))throw new Error("Invalid delegations.");let i=n.map(s=>{let{delegation:a,signature:o}=s,{pubkey:c,expiration:d,targets:f}=a;if(f!==void 0&&!Array.isArray(f))throw new Error("Invalid targets.");return{delegation:new oa(kd(c),BigInt("0x"+d),f&&f.map(p=>{if(typeof p!="string")throw new Error("Invalid target.");return Md.Principal.fromHex(p)})),signature:kd(o)}});return new this(i,kd(r))}static fromDelegations(t,r){return new this(t,r)}toJSON(){return{delegations:this.delegations.map(t=>{let{delegation:r,signature:n}=t,{targets:i}=r;return{delegation:Object.assign({expiration:r.expiration.toString(16),pubkey:(0,kn.toHex)(r.pubkey)},i&&{targets:i.map(s=>s.toHex())}),signature:(0,kn.toHex)(n)}}),publicKey:(0,kn.toHex)(this.publicKey)}}};Ze.DelegationChain=jd;var Ld=class extends kn.SignIdentity{constructor(t,r){super(),this._inner=t,this._delegation=r}static fromDelegation(t,r){return new this(t,r)}getDelegation(){return this._delegation}getPublicKey(){return{derKey:this._delegation.publicKey,toDer:()=>this._delegation.publicKey}}sign(t){return this._inner.sign(t)}async transformRequest(t){let{body:r}=t,n=rE(t,["body"]),i=await(0,kn.requestIdOf)(r);return Object.assign(Object.assign({},n),{body:{content:r,sender_sig:await this.sign(new Uint8Array([...sE,...new Uint8Array(i)])),sender_delegation:this._delegation.delegations,sender_pubkey:this._delegation.publicKey}})}};Ze.DelegationIdentity=Ld;var Hd=class e extends nE.PartialIdentity{constructor(t,r){super(t),Tc.set(this,void 0),eE(this,Tc,r,"f")}get delegation(){return tE(this,Tc,"f")}static fromDelegation(t,r){return new e(t,r)}};Ze.PartialDelegationIdentity=Hd;Tc=new WeakMap;function oE(e,t){for(let{delegation:i}of e.delegations)if(+new Date(Number(i.expiration/BigInt(1e6)))<=+Date.now())return!1;let r=[],n=t?.scope;n&&(Array.isArray(n)?r.push(...n.map(i=>typeof i=="string"?Md.Principal.fromText(i):i)):r.push(typeof n=="string"?Md.Principal.fromText(n):n));for(let i of r){let s=i.toText();for(let{delegation:a}of e.delegations){if(a.targets===void 0)continue;let o=!0;for(let c of a.targets)if(c.toText()===s){o=!1;break}if(o)return!1}}return!0}Ze.isDelegationValid=oE});var by=ee(Mn=>{"use strict";var cE=Mn&&Mn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Mn,"__esModule",{value:!0});Mn.WebAuthnIdentity=Mn.CosePublicKey=void 0;var ui=gt(),Kd=cE(to()),uE=Kn(),lE=Ri();function dE(e){return(0,ui.wrapDER)(e,ui.DER_COSE_OID).buffer}function fE(e){let t=new DataView(new ArrayBuffer(2)),r=e.slice(53,55);[...new Uint8Array(r)].forEach((i,s)=>t.setUint8(s,i));let n=t.getUint16(0);return e.slice(55+n)}var Nc=class{constructor(t){this._cose=t,this._encodedKey=dE(t)}toDer(){return this._encodedKey}getCose(){return this._cose}};Mn.CosePublicKey=Nc;function pE(e="<ic0.app>"){return typeof e=="string"?Uint8Array.from(e,t=>t.charCodeAt(0)):e}async function hE(e){let t=await navigator.credentials.create(e??{publicKey:{authenticatorSelection:{userVerification:"preferred"},attestation:"direct",challenge:pE(),pubKeyCredParams:[{type:"public-key",alg:Gd.ECDSA_WITH_SHA256}],rp:{name:"Internet Identity Service"},user:{id:(0,uE.randomBytes)(16),name:"Internet Identity",displayName:"Internet Identity"}}});return t===null?null:{id:t.id,response:t.response,type:t.type,authenticatorAttachment:t.authenticatorAttachment,getClientExtensionResults:t.getClientExtensionResults,rawId:(0,lE.bufFromBufLike)(t.rawId)}}var Gd;(function(e){e[e.ECDSA_WITH_SHA256=-7]="ECDSA_WITH_SHA256"})(Gd||(Gd={}));var $d=class extends ui.SignIdentity{constructor(t,r,n){super(),this.rawId=t,this.authenticatorAttachment=n,this._publicKey=new Nc(r)}static fromJSON(t){let{publicKey:r,rawId:n}=JSON.parse(t);if(typeof r!="string"||typeof n!="string")throw new Error("Invalid JSON string.");return new this((0,ui.fromHex)(n),(0,ui.fromHex)(r),void 0)}static async create(t){var r;let n=await hE(t);if(!n||n.type!=="public-key")throw new Error("Could not create credentials.");let i=n.response;if(i.attestationObject===void 0)throw new Error("Was expecting an attestation response.");let s=Kd.default.decodeFirst(new Uint8Array(i.attestationObject));return new this(n.rawId,fE(s.authData),(r=n.authenticatorAttachment)!==null&&r!==void 0?r:void 0)}getPublicKey(){return this._publicKey}getAuthenticatorAttachment(){return this.authenticatorAttachment}async sign(t){let r=await navigator.credentials.get({publicKey:{allowCredentials:[{type:"public-key",id:this.rawId}],challenge:t,userVerification:"preferred"}});r.authenticatorAttachment!==null&&(this.authenticatorAttachment=r.authenticatorAttachment);let n=r.response,i=Kd.default.encode(new Kd.default.Tagged(55799,{authenticator_data:new Uint8Array(n.authenticatorData),client_data_json:new TextDecoder().decode(n.clientDataJSON),signature:new Uint8Array(n.signature)}));if(!i)throw new Error("failed to encode cbor");return i.buffer}toJSON(){return{publicKey:(0,ui.toHex)(this._publicKey.getCose()),rawId:(0,ui.toHex)(this.rawId)}}};Mn.WebAuthnIdentity=$d});var Yd=ee(Ye=>{"use strict";var _E=Ye&&Ye.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),zd=Ye&&Ye.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&_E(t,e,r)};Object.defineProperty(Ye,"__esModule",{value:!0});Ye.Secp256k1KeyIdentity=Ye.ED25519_OID=Ye.DER_COSE_OID=Ye.unwrapDER=Ye.wrapDER=Ye.WebAuthnIdentity=Ye.Ed25519PublicKey=Ye.Ed25519KeyIdentity=void 0;var wy=_y();Object.defineProperty(Ye,"Ed25519KeyIdentity",{enumerable:!0,get:function(){return wy.Ed25519KeyIdentity}});Object.defineProperty(Ye,"Ed25519PublicKey",{enumerable:!0,get:function(){return wy.Ed25519PublicKey}});zd(my(),Ye);zd(gy(),Ye);zd(Dd(),Ye);var yE=by();Object.defineProperty(Ye,"WebAuthnIdentity",{enumerable:!0,get:function(){return yE.WebAuthnIdentity}});var Ec=gt();Object.defineProperty(Ye,"wrapDER",{enumerable:!0,get:function(){return Ec.wrapDER}});Object.defineProperty(Ye,"unwrapDER",{enumerable:!0,get:function(){return Ec.unwrapDER}});Object.defineProperty(Ye,"DER_COSE_OID",{enumerable:!0,get:function(){return Ec.DER_COSE_OID}});Object.defineProperty(Ye,"ED25519_OID",{enumerable:!0,get:function(){return Ec.ED25519_OID}});var Wd=class{constructor(){throw new Error("Secp256k1KeyIdentity has been moved to a new repo: @dfinity/identity-secp256k1")}};Ye.Secp256k1KeyIdentity=Wd});var Zd=ee(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});Oc.IdleManager=void 0;var xy=["mousedown","mousemove","keydown","touchstart","wheel"],Jd=class{constructor(t={}){var r;this.callbacks=[],this.idleTimeout=600*1e3,this.timeoutID=void 0;let{onIdle:n,idleTimeout:i=600*1e3}=t||{};this.callbacks=n?[n]:[],this.idleTimeout=i;let s=this._resetTimer.bind(this);window.addEventListener("load",s,!0),xy.forEach(function(o){document.addEventListener(o,s,!0)});let a=(o,c)=>{let d;return(...f)=>{let p=this,m=function(){d=void 0,o.apply(p,f)};clearTimeout(d),d=window.setTimeout(m,c)}};if(t?.captureScroll){let o=a(s,(r=t?.scrollDebounce)!==null&&r!==void 0?r:100);window.addEventListener("scroll",o,!0)}s()}static create(t={}){return new this(t)}registerCallback(t){this.callbacks.push(t)}exit(){clearTimeout(this.timeoutID),window.removeEventListener("load",this._resetTimer,!0);let t=this._resetTimer.bind(this);xy.forEach(function(r){document.removeEventListener(r,t,!0)}),this.callbacks.forEach(r=>r())}_resetTimer(){let t=this.exit.bind(this);window.clearTimeout(this.timeoutID),this.timeoutID=window.setTimeout(t,this.idleTimeout)}};Oc.IdleManager=Jd});function gE(){return Ty||(Ty=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function bE(){return Ny||(Ny=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function wE(e){let t=new Promise((r,n)=>{let i=()=>{e.removeEventListener("success",s),e.removeEventListener("error",a)},s=()=>{r(_r(e.result)),i()},a=()=>{n(e.error),i()};e.addEventListener("success",s),e.addEventListener("error",a)});return t.then(r=>{r instanceof IDBCursor&&Ey.set(r,e)}).catch(()=>{}),tf.set(t,e),t}function xE(e){if(Qd.has(e))return;let t=new Promise((r,n)=>{let i=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",a),e.removeEventListener("abort",a)},s=()=>{r(),i()},a=()=>{n(e.error||new DOMException("AbortError","AbortError")),i()};e.addEventListener("complete",s),e.addEventListener("error",a),e.addEventListener("abort",a)});Qd.set(e,t)}function vy(e){ef=e(ef)}function TE(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(t,...r){let n=e.call(ca(this),t,...r);return Oy.set(n,t.sort?t.sort():[t]),_r(n)}:bE().includes(e)?function(...t){return e.apply(ca(this),t),_r(Ey.get(this))}:function(...t){return _r(e.apply(ca(this),t))}}function NE(e){return typeof e=="function"?TE(e):(e instanceof IDBTransaction&&xE(e),mE(e,gE())?new Proxy(e,ef):e)}function _r(e){if(e instanceof IDBRequest)return wE(e);if(Xd.has(e))return Xd.get(e);let t=NE(e);return t!==e&&(Xd.set(e,t),tf.set(t,e)),t}var mE,Ty,Ny,Ey,Qd,Oy,Xd,tf,ef,ca,rf=Tf(()=>{mE=(e,t)=>t.some(r=>e instanceof r);Ey=new WeakMap,Qd=new WeakMap,Oy=new WeakMap,Xd=new WeakMap,tf=new WeakMap;ef={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return Qd.get(e);if(t==="objectStoreNames")return e.objectStoreNames||Oy.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return _r(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};ca=e=>tf.get(e)});var Ay={};Zm(Ay,{deleteDB:()=>OE,openDB:()=>EE,unwrap:()=>ca,wrap:()=>_r});function EE(e,t,{blocked:r,upgrade:n,blocking:i,terminated:s}={}){let a=indexedDB.open(e,t),o=_r(a);return n&&a.addEventListener("upgradeneeded",c=>{n(_r(a.result),c.oldVersion,c.newVersion,_r(a.transaction),c)}),r&&a.addEventListener("blocked",c=>r(c.oldVersion,c.newVersion,c)),o.then(c=>{s&&c.addEventListener("close",()=>s()),i&&c.addEventListener("versionchange",d=>i(d.oldVersion,d.newVersion,d))}).catch(()=>{}),o}function OE(e,{blocked:t}={}){let r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",n=>t(n.oldVersion,n)),_r(r).then(()=>{})}function Ry(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(nf.get(t))return nf.get(t);let r=t.replace(/FromIndex$/,""),n=t!==r,i=RE.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(i||vE.includes(r)))return;let s=async function(a,...o){let c=this.transaction(a,i?"readwrite":"readonly"),d=c.store;return n&&(d=d.index(o.shift())),(await Promise.all([d[r](...o),i&&c.done]))[0]};return nf.set(t,s),s}var vE,RE,nf,Sy=Tf(()=>{rf();rf();vE=["get","getKey","getAll","getAllKeys","count"],RE=["put","add","delete","clear"],nf=new Map;vy(e=>({...e,get:(t,r,n)=>Ry(t,r)||e.get(t,r,n),has:(t,r)=>!!Ry(t,r)||e.has(t,r)}))});var af=ee(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.IdbKeyVal=void 0;var AE=(Sy(),Xm(Ay)),ua=Rc(),Iy="auth-client-db",By="ic-keyval",SE=async(e=Iy,t=By,r)=>(ua.isBrowser&&(localStorage!=null&&localStorage.getItem(ua.KEY_STORAGE_DELEGATION))&&(localStorage.removeItem(ua.KEY_STORAGE_DELEGATION),localStorage.removeItem(ua.KEY_STORAGE_KEY)),await(0,AE.openDB)(e,r,{upgrade:n=>{n.objectStoreNames.contains(t)&&n.clear(t),n.createObjectStore(t)}}));async function IE(e,t,r){return await e.get(t,r)}async function BE(e,t,r,n){return await e.put(t,n,r)}async function PE(e,t,r){return await e.delete(t,r)}var sf=class e{constructor(t,r){this._db=t,this._storeName=r}static async create(t){let{dbName:r=Iy,storeName:n=By,version:i=ua.DB_VERSION}=t??{},s=await SE(r,n,i);return new e(s,n)}async set(t,r){return await BE(this._db,this._storeName,t,r)}async get(t){var r;return(r=await IE(this._db,this._storeName,t))!==null&&r!==void 0?r:null}async remove(t){return await PE(this._db,this._storeName,t)}};vc.IdbKeyVal=sf});var Rc=ee(it=>{"use strict";var FE=it&&it.__classPrivateFieldSet||function(e,t,r,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 t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,r):i?i.value=r:t.set(e,r),r},UE=it&&it.__classPrivateFieldGet||function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},Ac;Object.defineProperty(it,"__esModule",{value:!0});it.IdbStorage=it.LocalStorage=it.isBrowser=it.DB_VERSION=it.KEY_VECTOR=it.KEY_STORAGE_DELEGATION=it.KEY_STORAGE_KEY=void 0;var VE=af();it.KEY_STORAGE_KEY="identity";it.KEY_STORAGE_DELEGATION="delegation";it.KEY_VECTOR="iv";it.DB_VERSION=1;it.isBrowser=typeof window<"u";var of=class{constructor(t="ic-",r){this.prefix=t,this._localStorage=r}get(t){return Promise.resolve(this._getLocalStorage().getItem(this.prefix+t))}set(t,r){return this._getLocalStorage().setItem(this.prefix+t,r),Promise.resolve()}remove(t){return this._getLocalStorage().removeItem(this.prefix+t),Promise.resolve()}_getLocalStorage(){if(this._localStorage)return this._localStorage;let t=typeof window>"u"?typeof global>"u"?typeof self>"u"?void 0:self.localStorage:global.localStorage:window.localStorage;if(!t)throw new Error("Could not find local storage.");return t}};it.LocalStorage=of;var cf=class{constructor(t){Ac.set(this,void 0),FE(this,Ac,t??{},"f")}get _db(){return new Promise(t=>{if(this.initializedDb){t(this.initializedDb);return}VE.IdbKeyVal.create(UE(this,Ac,"f")).then(r=>{this.initializedDb=r,t(r)})})}async get(t){return await(await this._db).get(t)}async set(t,r){await(await this._db).set(t,r)}async remove(t){await(await this._db).remove(t)}};it.IdbStorage=cf;Ac=new WeakMap});var Ic=ee(et=>{"use strict";var CE=et&&et.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),qE=et&&et.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&CE(t,e,r)};Object.defineProperty(et,"__esModule",{value:!0});et.AuthClient=et.ERROR_USER_INTERRUPT=et.IdbKeyVal=et.KEY_STORAGE_KEY=et.KEY_STORAGE_DELEGATION=et.LocalStorage=et.IdbStorage=void 0;var Py=gt(),sr=Yd(),Fy=Zd(),Et=Rc(),Sc=Rc();Object.defineProperty(et,"IdbStorage",{enumerable:!0,get:function(){return Sc.IdbStorage}});Object.defineProperty(et,"LocalStorage",{enumerable:!0,get:function(){return Sc.LocalStorage}});Object.defineProperty(et,"KEY_STORAGE_DELEGATION",{enumerable:!0,get:function(){return Sc.KEY_STORAGE_DELEGATION}});Object.defineProperty(et,"KEY_STORAGE_KEY",{enumerable:!0,get:function(){return Sc.KEY_STORAGE_KEY}});var DE=af();Object.defineProperty(et,"IdbKeyVal",{enumerable:!0,get:function(){return DE.IdbKeyVal}});var kE="https://identity.ic0.app",ME="#authorize",uf="ECDSA",lf="Ed25519",jE=500;et.ERROR_USER_INTERRUPT="UserInterrupt";qE(Zd(),et);var ff=class{constructor(t,r,n,i,s,a,o,c){this._identity=t,this._key=r,this._chain=n,this._storage=i,this.idleManager=s,this._createOptions=a,this._idpWindow=o,this._eventHandler=c,this._registerDefaultIdleCallback()}static async create(t={}){var r,n,i;let s=(r=t.storage)!==null&&r!==void 0?r:new Et.IdbStorage,a=(n=t.keyType)!==null&&n!==void 0?n:uf,o=null;if(t.identity)o=t.identity;else{let p=await s.get(Et.KEY_STORAGE_KEY);if(!p&&Et.isBrowser)try{let m=new Et.LocalStorage,b=await m.get(Et.KEY_STORAGE_DELEGATION),l=await m.get(Et.KEY_STORAGE_KEY);b&&l&&a===uf&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await s.set(Et.KEY_STORAGE_DELEGATION,b),await s.set(Et.KEY_STORAGE_KEY,l),p=b,await m.remove(Et.KEY_STORAGE_DELEGATION),await m.remove(Et.KEY_STORAGE_KEY))}catch(m){console.error("error while attempting to recover localstorage: "+m)}if(p)try{typeof p=="object"?a===lf&&typeof p=="string"?o=await sr.Ed25519KeyIdentity.fromJSON(p):o=await sr.ECDSAKeyIdentity.fromKeyPair(p):typeof p=="string"&&(o=sr.Ed25519KeyIdentity.fromJSON(p))}catch{}}let c=new Py.AnonymousIdentity,d=null;if(o)try{let p=await s.get(Et.KEY_STORAGE_DELEGATION);if(typeof p=="object"&&p!==null)throw new Error("Delegation chain is incorrectly stored. A delegation chain should be stored as a string.");t.identity?c=t.identity:p&&(d=sr.DelegationChain.fromJSON(p),(0,sr.isDelegationValid)(d)?"toDer"in o?c=sr.PartialDelegationIdentity.fromDelegation(o,d):c=sr.DelegationIdentity.fromDelegation(o,d):(await df(s),o=null))}catch(p){console.error(p),await df(s),o=null}let f;return!((i=t.idleOptions)===null||i===void 0)&&i.disableIdle?f=void 0:(d||t.identity)&&(f=Fy.IdleManager.create(t.idleOptions)),o||(a===lf?(o=await sr.Ed25519KeyIdentity.generate(),await s.set(Et.KEY_STORAGE_KEY,JSON.stringify(o.toJSON()))):(t.storage&&a===uf&&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 '${lf}' as the key type, as it can serialize to a string`),o=await sr.ECDSAKeyIdentity.generate(),await s.set(Et.KEY_STORAGE_KEY,o.getKeyPair()))),new this(c,o,d,s,f,t)}_registerDefaultIdleCallback(){var t,r;let n=(t=this._createOptions)===null||t===void 0?void 0:t.idleOptions;!n?.onIdle&&!n?.disableDefaultIdleCallback&&((r=this.idleManager)===null||r===void 0||r.registerCallback(()=>{this.logout(),location.reload()}))}async _handleSuccess(t,r){var n,i;let s=t.delegations.map(d=>({delegation:new sr.Delegation(d.delegation.pubkey,d.delegation.expiration,d.delegation.targets),signature:d.signature.buffer})),a=sr.DelegationChain.fromDelegations(s,t.userPublicKey.buffer),o=this._key;if(!o)return;this._chain=a,"toDer"in o?this._identity=sr.PartialDelegationIdentity.fromDelegation(o,this._chain):this._identity=sr.DelegationIdentity.fromDelegation(o,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=Fy.IdleManager.create(c),this._registerDefaultIdleCallback()),this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(Et.KEY_STORAGE_DELEGATION,JSON.stringify(this._chain.toJSON())),r?.(t)}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null}async login(t){var r,n,i,s;let a=BigInt(8)*BigInt(36e11),o=new URL(((r=t?.identityProvider)===null||r===void 0?void 0:r.toString())||kE);o.hash=ME,(n=this._idpWindow)===null||n===void 0||n.close(),this._removeEventListener(),this._eventHandler=this._getEventHandler(o,Object.assign({maxTimeToLive:(i=t?.maxTimeToLive)!==null&&i!==void 0?i:a},t)),window.addEventListener("message",this._eventHandler),this._idpWindow=(s=window.open(o.toString(),"idpWindow",t?.windowOpenerFeatures))!==null&&s!==void 0?s:void 0;let c=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(et.ERROR_USER_INTERRUPT,t?.onError):setTimeout(c,jE))};c()}_getEventHandler(t,r){return async n=>{var i,s,a;if(n.origin!==t.origin)return;let o=n.data;switch(o.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:r?.maxTimeToLive,allowPinAuthentication:r?.allowPinAuthentication,derivationOrigin:(s=r?.derivationOrigin)===null||s===void 0?void 0:s.toString()},r?.customValues);(a=this._idpWindow)===null||a===void 0||a.postMessage(c,t.origin);break}case"authorize-client-success":try{await this._handleSuccess(o,r?.onSuccess)}catch(c){this._handleFailure(c.message,r?.onError)}break;case"authorize-client-failure":this._handleFailure(o.text,r?.onError);break;default:break}}}_handleFailure(t,r){var n;(n=this._idpWindow)===null||n===void 0||n.close(),r?.(t),this._removeEventListener(),delete this._idpWindow}_removeEventListener(){this._eventHandler&&window.removeEventListener("message",this._eventHandler),this._eventHandler=void 0}async logout(t={}){if(await df(this._storage),this._identity=new Py.AnonymousIdentity,this._chain=null,t.returnTo)try{window.history.pushState({},"",t.returnTo)}catch{window.location.href=t.returnTo}}};et.AuthClient=ff;async function df(e){await e.remove(Et.KEY_STORAGE_KEY),await e.remove(Et.KEY_STORAGE_DELEGATION),await e.remove(Et.KEY_VECTOR)}});var Bm=be(De(),1);var Y_=be(De(),1),lc=be(gt(),1),J_=be(De(),1),na=be(gt(),1),Lt=be(De(),1),X_=be(De(),1),ry=be(De(),1),T2=({authData:e})=>{if(e.byteLength<37)return{invalidAuthData:null};if(e.byteLength<53)return{invalidAuthData:null};let t=e.slice(37,53),r=N2({bytes:t});return"aaguid"in r?{aaguidBytes:t,aaguidText:r.aaguid}:{unknownProvider:null}},N2=({bytes:e})=>{if(e.length!==16)return{invalidBytes:null};let t=(e instanceof Uint8Array?(0,Y_.uint8ArrayToArrayOfNumber)(e):e).map(r=>r.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5");return t==="00000000-0000-0000-0000-000000000000"?{unknownProvider:null}:{aaguid:t}};function E2(e){let t=new DataView(new ArrayBuffer(2)),r=e.slice(53,55);[...new Uint8Array(r)].forEach((i,s)=>t.setUint8(s,i));let n=t.getUint16(0);return e.slice(55+n)}function O2(e){return(0,lc.wrapDER)(e.buffer,lc.DER_COSE_OID).buffer}var v2=class{constructor(e){this._cose=e,this._encodedKey=O2(e)}_encodedKey;toDer(){return this._encodedKey}},Z_=class{#e;#t;constructor({rawId:e,cose:t}){this.#e=e,this.#t=new v2(t)}getPublicKey(){return this.#t}getCredentialId(){return this.#e}getCredentialIdText(){return(0,J_.uint8ArrayToBase64)(this.#e)}},R2=class extends Z_{#e;#t;constructor({authData:e,...t}){super(t);let r=T2({authData:e});this.#e="aaguidText"in r?r.aaguidText:void 0,this.#t="aaguidBytes"in r?r.aaguidBytes:void 0}getAAGUID(){return this.#t}getAAGUIDText(){return this.#e}},A2=class extends Z_{},S2=class extends Error{},I2=class extends Error{},B2=class extends Error{},P2=class extends Error{},F2=class extends Error{},U2=class extends Error{},V2=class extends Error{},G_=class extends Error{};var C2={ECDSA_WITH_SHA256:-7,RSA_WITH_SHA256:-257},q2=6e4,Q_=()=>window.crypto.getRandomValues(new Uint8Array(16)),D2=()=>Q_(),k2=()=>Q_(),M2=()=>{let{location:{href:e}}=window,t=URL.parse(e);if((0,X_.isNullish)(t))throw new S2;let{hostname:r}=t;return r},ey=({appId:e})=>e?.id??M2(),j2=({appId:e,user:t}={})=>{let{document:{title:r}}=window,n=()=>({rp:{name:e?.name??r,id:ey({appId:e})}}),i=()=>({user:{id:k2(),name:t?.name??t?.displayName??r,displayName:t?.displayName??r}});return{attestation:"direct",challenge:D2(),...n(),...i(),pubKeyCredParams:Object.values(C2).map(s=>({type:"public-key",alg:s})),excludeCredentials:[],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"preferred",residentKey:"required",requireResidentKey:!0}}},L2=(e={})=>({rpId:ey(e),allowCredentials:[],userVerification:"required"}),Id=async({fn:e,step:t,onProgress:r})=>{r?.({step:t,state:"in_progress"});try{let n=await e();return r?.({step:t,state:"success"}),n}catch(n){throw r?.({step:t,state:"error"}),n}},Vn=(e=>(e[e.RequestingUserCredential=0]="RequestingUserCredential",e[e.FinalizingCredential=1]="FinalizingCredential",e[e.Signing=2]="Signing",e))(Vn||{}),ty=({timeout:e})=>AbortSignal.timeout(e??q2),H2=async({challenge:e,credentialIds:t,passkeyOptions:r,timeout:n})=>await navigator.credentials.get({publicKey:{...L2(r),challenge:e.buffer,allowCredentials:(t??[]).map(i=>({id:i.buffer,type:"public-key"}))},signal:ty({timeout:n})}),$_=e=>{if(e.status!=="initialized")throw new I2},W_=e=>{if((0,Lt.isNullish)(e))throw new B2},z_=({type:e})=>{if(e!=="public-key")throw new P2},Bd=class ra extends na.SignIdentity{#e;#t;constructor({onProgress:t,...r}){if(super(),this.#e=t,"retrievePublicKey"in r){let{retrievePublicKey:n}=r;this.#t={status:"pending",retrievePublicKey:n};return}this.#t=ra.#r({credential:new R2(r)})}static#r({credential:t}){return{status:"initialized",credential:t}}static async createWithNewCredential({passkeyOptions:t,timeout:r,...n}={}){let i=await navigator.credentials.create({publicKey:j2(t),signal:ty({timeout:r})});W_(i),z_(i);let{response:{attestationObject:s},rawId:a}=i;if((0,Lt.isNullish)(s))throw new F2;let{authData:o}=na.Cbor.decode(s),c=E2(o);return new ra({...n,rawId:(0,Lt.arrayBufferToUint8Array)(a),cose:c,authData:o})}static async createWithExistingCredential(t){return new ra(t)}getPublicKey(){$_(this.#t);let{credential:t}=this.#t;return t.getPublicKey()}getCredential(){$_(this.#t);let{credential:t}=this.#t;return t}async sign(t){let r=await Id({fn:async()=>{let n=await H2({challenge:(0,Lt.arrayBufferToUint8Array)(t),...this.#t.status==="initialized"&&{credentialIds:[this.#t.credential.getCredentialId()]}});return W_(n),z_(n),n},step:0,onProgress:this.#e});return await Id({fn:async()=>{let{rawId:n}=r;if(this.#t.status==="initialized"){if(!(0,Lt.uint8ArraysEqual)({a:this.#t.credential.getCredentialId(),b:(0,Lt.arrayBufferToUint8Array)(n)}))throw new U2;return}let{retrievePublicKey:i}=this.#t,s=await i({credentialId:(0,Lt.arrayBufferToUint8Array)(n)});this.#t=ra.#r({credential:new A2({rawId:(0,Lt.arrayBufferToUint8Array)(n),cose:s})})},step:1,onProgress:this.#e}),await Id({fn:async()=>{let{response:n}=r,{clientDataJSON:i}=n,{authenticatorData:s,signature:a}="authenticatorData"in n&&"signature"in n?n:{};if((0,Lt.isNullish)(s))throw new G_;if((0,Lt.isNullish)(a))throw new G_;let o=na.Cbor.encode({authenticator_data:s,client_data_json:new TextDecoder().decode(i),signature:(0,Lt.arrayBufferToUint8Array)(a)});if((0,Lt.isNullish)(o))throw new V2;return Object.assign(o,{__signature__:void 0}),o},step:2,onProgress:this.#e})}},K2=async()=>(0,ry.nonNullish)(window.PublicKeyCredential)&&"isUserVerifyingPlatformAuthenticatorAvailable"in PublicKeyCredential?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1;var _m=be(De(),1);var Yi=class{callbacks=[];populate(t){this.callbacks.forEach(({callback:r})=>r(t))}subscribe(t){let r=Symbol();return this.callbacks.push({id:r,callback:t}),()=>this.callbacks=this.callbacks.filter(({id:n})=>n!==r)}};var hr=class e extends Yi{static instance;authUser=null;constructor(){super()}static getInstance(){return e.instance||(e.instance=new e),e.instance}set(t){this.authUser=t,this.populate(t)}get(){return this.authUser}subscribe(t){let r=super.subscribe(t);return t(this.authUser),r}reset(){this.authUser=null,this.populate(this.authUser)}};var Pd=({message:e,detail:t})=>{let r=new CustomEvent(e,{detail:t,bubbles:!0});document.dispatchEvent(r)};var hm=be(De(),1);var ay=be(gt(),1),fc=be(De(),1);var dc=be(De(),1);var iy=be(gt(),1),Fd=be(De(),1);var Ji="http://127.0.0.1:5987",ny="rdmx6-jaaaa-aaaaa-aaadq-cai";var sy=async({identity:e,container:t})=>{let n=(0,Fd.nonNullish)(t)&&t!==!1?t===!0?Ji:t:"https://icp-api.io",i=(0,Fd.nonNullish)(t);return await iy.HttpAgent.create({identity:e,shouldFetchRootKey:i,host:n})};var Zi=class e{static instance;#e=void 0;constructor(){}static getInstance(){return(0,dc.isNullish)(e.instance)&&(e.instance=new e),e.instance}async getAgent({identity:t,...r}){let n=t.getPrincipal().toText();if((0,dc.isNullish)(this.#e)||(0,dc.isNullish)(this.#e[n])){let i=await sy({identity:t,...r});return this.#e={...this.#e??{},[n]:i},i}return this.#e[n]}reset(){this.#e=null}};var Xi=class e{static instance;#e=void 0;constructor(){}static getInstance(){return(0,fc.isNullish)(e.instance)&&(e.instance=new e),e.instance}async getActor({satelliteId:t,identity:r,actorKey:n,...i}){let s=`${n}#${r.getPrincipal().toText()}#${t};`;if((0,fc.isNullish)(this.#e)||(0,fc.isNullish)(this.#e[s])){let a=await this.createActor({satelliteId:t,identity:r,...i});return this.#e={...this.#e??{},[s]:a},a}return this.#e[s]}reset(){this.#e=null}async createActor({idlFactory:t,satelliteId:r,...n}){let i=await Zi.getInstance().getAgent(n);return ay.Actor.createActor(t,{agent:i,canisterId:r})}};var oy=e=>(e.preventDefault(),e.returnValue="Are you sure you want to exit?"),G2=()=>{window.addEventListener("beforeunload",oy,{capture:!0})},$2=()=>{window.removeEventListener("beforeunload",oy,{capture:!0})},Ud=async({fn:e})=>{try{return G2(),await e()}finally{$2()}};var la=be(De(),1);var nr=class e extends Yi{static instance;env;constructor(){super()}static getInstance(){return e.instance||(e.instance=new e),e.instance}set(t){this.env=t,this.populate(t)}get(){return this.env}reset(){this.env=null}subscribe(t){let r=super.subscribe(t);return t(this.env),r}};var cy=BigInt(144e11),uy=!1,ly={width:576,height:576},dy={width:505,height:705},fy="internetcomputer.org";var Vd=be(De(),1);var pc=be(De(),1),py=async e=>{let t=new Blob([JSON.stringify(e,pc.jsonReplacer)],{type:"application/json; charset=utf-8"});return new Uint8Array(await t.arrayBuffer())},hc=async e=>{let t=new Blob([e instanceof Uint8Array?e:new Uint8Array(e)],{type:"application/json; charset=utf-8"});return JSON.parse(await t.text(),pc.jsonReviver)},_c=()=>typeof window<"u";var yc=({width:e,height:t})=>{if(!_c()||(0,Vd.isNullish)(window)||(0,Vd.isNullish)(window.top))return;let{top:{innerWidth:r,innerHeight:n}}=window,i=n/2+screenY-t/2,s=r/2+screenX-e/2;return`toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=${e}, height=${t}, top=${i}, left=${s}`};var Vy=be(Ic(),1),Cy=be(De(),1);var Zr=async({fn:e,step:t,onProgress:r})=>{r?.({step:t,state:"in_progress"});try{let n=await e();return r?.({step:t,state:"success"}),n}catch(n){throw r?.({step:t,state:"error"}),n}};var Uy=(r=>(r[r.AuthorizingWithProvider=0]="AuthorizingWithProvider",r[r.CreatingOrRetrievingUser=1]="CreatingOrRetrievingUser",r))(Uy||{});var Bc=class extends Error{},li=class extends Error{},Pc=class extends Error{},Fc=class extends Error{},Uc=class extends Error{},Vc=class extends Error{},Cc=class extends Error{},qc=class extends Error{};var ts=class{async signIn({options:t,authClient:r,initAuth:n}){await Zr({fn:async()=>await this.#e({options:t,authClient:r}),step:0,onProgress:t?.onProgress}),await Zr({fn:async()=>await n({provider:this.id}),step:1,onProgress:t?.onProgress})}#e({options:t,authClient:r}){return new Promise(async(n,i)=>{if((0,Cy.isNullish)(r)){i(new li("No client is ready to perform a sign-in. Have you initialized the Satellite?"));return}await r.login({onSuccess:n,onError:s=>{if(s===Vy.ERROR_USER_INTERRUPT){i(new Pc(s));return}i(new Bc(s))},maxTimeToLive:t?.maxTimeToLiveInNanoseconds??cy,allowPinAuthentication:t?.allowPin??uy,...t?.derivationOrigin!==void 0&&{derivationOrigin:t.derivationOrigin},...this.signInOptions({windowed:t?.windowed})})})}};var Dc=class extends ts{#e;constructor({domain:t}){super(),this.#e=t}get id(){return"internet_identity"}signInOptions({windowed:t}){let r=()=>{let n=nr.getInstance().get()?.container;if((0,la.isNullish)(n)||n===!1)return`https://identity.${this.#e??fy}`;let i=nr.getInstance().get(),s=(0,la.nonNullish)(i)&&(0,la.nonNullish)(i?.internetIdentityId)?i.internetIdentityId:ny,{host:a,protocol:o}=new URL(n===!0?Ji:n);return/apple/i.test(navigator?.vendor)?`${o}//${a}?canisterId=${s}`:`${o}//${s}.${a.replace("127.0.0.1","localhost")}`};return{...t!==!1&&{windowOpenerFeatures:yc(ly)},identityProvider:r()}}};var kc=class extends ts{#e;#t;constructor({appName:t,logoUrl:r}){super(),this.#e=t,this.#t=r}get id(){return"nfid"}signInOptions({windowed:t}){return{...t!==!1&&{windowOpenerFeatures:yc(dy)},identityProvider:`https://nfid.one/authenticate/?applicationName=${encodeURI(this.#e)}&applicationLogo=${encodeURI(this.#t)}`}}};var cm=be(gt(),1),is=be(Ic(),1),Qr=be(Yd(),1),ns=be(De(),1);var Xr={certified:!1};var qy=be(gt(),1),Dy=be(De(),1);var tt=e=>(0,Dy.nonNullish)(e)?e:Mc()??new qy.AnonymousIdentity;var Sr=be(De(),1);var Ly=be(De(),1);var LE=be(gt(),1),HE=be(De(),1),KE=be(De(),1),GE=be(gt(),1);var ky=({IDL:e})=>{let t=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),r=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}),s=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),a=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(s),description:e.Opt(e.Text),created_at:e.Opt(s)}),o=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(a),paginate:e.Opt(o)}),d=e.Record({controllers:e.Vec(e.Principal)}),f=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),p=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:f,expires_at:e.Opt(e.Nat64)}),m=e.Record({version:e.Opt(e.Nat64)}),b=e.Variant({Db:e.Null,Storage:e.Null}),l=e.Record({version:e.Opt(e.Nat64)}),A=e.Record({proposal_ids:e.Vec(e.Nat)}),v=e.Record({cycles:e.Nat,destination_id:e.Principal}),F=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}),C=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),E=e.Record({key:F,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,C)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),H=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),x=e.Record({allowed_callers:e.Vec(e.Principal)}),q=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(H),rules:e.Opt(x)}),K=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),G=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}),ae=e.Variant({Deny:e.Null,Allow:e.Null}),Q=e.Record({status_code:e.Nat16,location:e.Text}),ne=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(ae),redirects:e.Opt(e.Vec(e.Tuple(e.Text,Q)))}),w=e.Record({db:e.Opt(G),authentication:e.Opt(q),storage:ne}),g=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)}),S=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),R=e.Record({clear_existing_assets:e.Opt(e.Bool)}),I=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),j=e.Variant({AssetsUpgrade:R,SegmentsDeployment:I}),Y=e.Record({status:S,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:j}),oe=e.Variant({Heap:e.Null,Stable:e.Null}),se=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),z=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),U=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(oe),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:se,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(z),write:se,max_changes_per_user:e.Opt(e.Nat32)}),_=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)}),Z=e.Record({memory:oe,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}),re=e.Variant({Callback:e.Record({token:Z,callback:e.Func([],[],["query"])})}),le=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(re),status_code:e.Nat16}),X=e.Record({token:e.Opt(Z),body:e.Vec(e.Nat8)}),u=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}),h=e.Record({batch_id:e.Nat}),y=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,E)),items_length:e.Nat64}),P=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),O=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,g)),items_length:e.Nat64}),B=e.Record({desc:e.Bool}),M=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),T=e.Record({order:e.Opt(B),paginate:e.Opt(M)}),V=e.Record({proposal_id:e.Nat}),L=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(V,Y)),items_length:e.Nat64}),k=e.Record({include_system:e.Bool}),J=e.Record({matcher:e.Opt(k)}),te=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,U)),items_length:e.Nat64}),de=e.Record({stable:e.Nat64,heap:e.Nat64}),ge=e.Record({version:e.Opt(e.Nat64),internet_identity:e.Opt(H),rules:e.Opt(x)}),Ie=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:f,expires_at:e.Opt(e.Nat64)}),Ue=e.Record({controller:Ie,controllers:e.Vec(e.Principal)}),_e=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(K)}),fe=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),Ke=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(oe),max_size:e.Opt(e.Nat),read:se,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(z),write:se,max_changes_per_user:e.Opt(e.Nat32)}),Ht=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(ae),redirects:e.Opt(e.Vec(e.Tuple(e.Text,Q)))}),Ut=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Vt=e.Record({chunk_id:e.Nat});return e.Service({commit_asset_upload:e.Func([t],[],[]),commit_proposal:e.Func([r],[e.Null],[]),commit_proposal_asset_upload:e.Func([t],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(t)],[],[]),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([d],[e.Vec(e.Tuple(e.Principal,p))],[]),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([b,e.Text,l],[],[]),delete_proposal_assets:e.Func([A],[],[]),deposit_cycles:e.Func([v],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(E)],["query"]),get_auth_config:e.Func([],[e.Opt(q)],["query"]),get_config:e.Func([],[w],[]),get_db_config:e.Func([],[e.Opt(G)],["query"]),get_doc:e.Func([e.Text,e.Text],[e.Opt(g)],["query"]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(E)))],["query"]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(g)))],["query"]),get_proposal:e.Func([e.Nat],[e.Opt(Y)],["query"]),get_rule:e.Func([b,e.Text],[e.Opt(U)],["query"]),get_storage_config:e.Func([],[ne],["query"]),http_request:e.Func([_],[le],["query"]),http_request_streaming_callback:e.Func([Z],[X],["query"]),init_asset_upload:e.Func([u],[h],[]),init_proposal:e.Func([j],[e.Nat,Y],[]),init_proposal_asset_upload:e.Func([u,e.Nat],[h],[]),init_proposal_many_assets_upload:e.Func([e.Vec(u),e.Nat],[e.Vec(e.Tuple(e.Text,h))],[]),list_assets:e.Func([e.Text,c],[y],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,p))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,P))],["query"]),list_docs:e.Func([e.Text,c],[O],["query"]),list_proposals:e.Func([T],[L],["query"]),list_rules:e.Func([b,J],[te],["query"]),memory_size:e.Func([],[de],["query"]),reject_proposal:e.Func([r],[e.Null],[]),set_auth_config:e.Func([ge],[q],[]),set_controllers:e.Func([Ue],[e.Vec(e.Tuple(e.Principal,p))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([_e],[G],[]),set_doc:e.Func([e.Text,e.Text,fe],[g],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,fe))],[e.Vec(e.Tuple(e.Text,g))],[]),set_rule:e.Func([b,e.Text,Ke],[U],[]),set_storage_config:e.Func([Ht],[ne],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Y],[]),upload_asset_chunk:e.Func([Ut],[Vt],[]),upload_proposal_asset_chunk:e.Func([Ut],[Vt],[])})},My=({IDL:e})=>{let t=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),r=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}),s=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),a=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(s),description:e.Opt(e.Text),created_at:e.Opt(s)}),o=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(a),paginate:e.Opt(o)}),d=e.Record({controllers:e.Vec(e.Principal)}),f=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),p=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:f,expires_at:e.Opt(e.Nat64)}),m=e.Record({version:e.Opt(e.Nat64)}),b=e.Variant({Db:e.Null,Storage:e.Null}),l=e.Record({version:e.Opt(e.Nat64)}),A=e.Record({proposal_ids:e.Vec(e.Nat)}),v=e.Record({cycles:e.Nat,destination_id:e.Principal}),F=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}),C=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),E=e.Record({key:F,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,C)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),H=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),x=e.Record({allowed_callers:e.Vec(e.Principal)}),q=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(H),rules:e.Opt(x)}),K=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),G=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}),ae=e.Variant({Deny:e.Null,Allow:e.Null}),Q=e.Record({status_code:e.Nat16,location:e.Text}),ne=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(ae),redirects:e.Opt(e.Vec(e.Tuple(e.Text,Q)))}),w=e.Record({db:e.Opt(G),authentication:e.Opt(q),storage:ne}),g=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)}),S=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),R=e.Record({clear_existing_assets:e.Opt(e.Bool)}),I=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),j=e.Variant({AssetsUpgrade:R,SegmentsDeployment:I}),Y=e.Record({status:S,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:j}),oe=e.Variant({Heap:e.Null,Stable:e.Null}),se=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),z=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),U=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(oe),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:se,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(z),write:se,max_changes_per_user:e.Opt(e.Nat32)}),_=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)}),Z=e.Record({memory:oe,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}),re=e.Variant({Callback:e.Record({token:Z,callback:e.Func([],[],[])})}),le=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(re),status_code:e.Nat16}),X=e.Record({token:e.Opt(Z),body:e.Vec(e.Nat8)}),u=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}),h=e.Record({batch_id:e.Nat}),y=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,E)),items_length:e.Nat64}),P=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),O=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,g)),items_length:e.Nat64}),B=e.Record({desc:e.Bool}),M=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),T=e.Record({order:e.Opt(B),paginate:e.Opt(M)}),V=e.Record({proposal_id:e.Nat}),L=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(V,Y)),items_length:e.Nat64}),k=e.Record({include_system:e.Bool}),J=e.Record({matcher:e.Opt(k)}),te=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,U)),items_length:e.Nat64}),de=e.Record({stable:e.Nat64,heap:e.Nat64}),ge=e.Record({version:e.Opt(e.Nat64),internet_identity:e.Opt(H),rules:e.Opt(x)}),Ie=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:f,expires_at:e.Opt(e.Nat64)}),Ue=e.Record({controller:Ie,controllers:e.Vec(e.Principal)}),_e=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(K)}),fe=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),Ke=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(oe),max_size:e.Opt(e.Nat),read:se,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(z),write:se,max_changes_per_user:e.Opt(e.Nat32)}),Ht=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(ae),redirects:e.Opt(e.Vec(e.Tuple(e.Text,Q)))}),Ut=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Vt=e.Record({chunk_id:e.Nat});return e.Service({commit_asset_upload:e.Func([t],[],[]),commit_proposal:e.Func([r],[e.Null],[]),commit_proposal_asset_upload:e.Func([t],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(t)],[],[]),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([d],[e.Vec(e.Tuple(e.Principal,p))],[]),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([b,e.Text,l],[],[]),delete_proposal_assets:e.Func([A],[],[]),deposit_cycles:e.Func([v],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(E)],[]),get_auth_config:e.Func([],[e.Opt(q)],[]),get_config:e.Func([],[w],[]),get_db_config:e.Func([],[e.Opt(G)],[]),get_doc:e.Func([e.Text,e.Text],[e.Opt(g)],[]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(E)))],[]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(g)))],[]),get_proposal:e.Func([e.Nat],[e.Opt(Y)],[]),get_rule:e.Func([b,e.Text],[e.Opt(U)],[]),get_storage_config:e.Func([],[ne],[]),http_request:e.Func([_],[le],[]),http_request_streaming_callback:e.Func([Z],[X],[]),init_asset_upload:e.Func([u],[h],[]),init_proposal:e.Func([j],[e.Nat,Y],[]),init_proposal_asset_upload:e.Func([u,e.Nat],[h],[]),init_proposal_many_assets_upload:e.Func([e.Vec(u),e.Nat],[e.Vec(e.Tuple(e.Text,h))],[]),list_assets:e.Func([e.Text,c],[y],[]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,p))],[]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,P))],[]),list_docs:e.Func([e.Text,c],[O],[]),list_proposals:e.Func([T],[L],[]),list_rules:e.Func([b,J],[te],[]),memory_size:e.Func([],[de],[]),reject_proposal:e.Func([r],[e.Null],[]),set_auth_config:e.Func([ge],[q],[]),set_controllers:e.Func([Ue],[e.Vec(e.Tuple(e.Principal,p))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([_e],[G],[]),set_doc:e.Func([e.Text,e.Text,fe],[g],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,fe))],[e.Vec(e.Tuple(e.Text,g))],[]),set_rule:e.Func([b,e.Text,Ke],[U],[]),set_storage_config:e.Func([Ht],[ne],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Y],[]),upload_asset_chunk:e.Func([Ut],[Vt],[]),upload_proposal_asset_chunk:e.Func([Ut],[Vt],[])})};var jc=be(De(),1);var jy=({satelliteId:e,container:t})=>{let{satelliteId:r}=pf({satelliteId:e}),{container:n}=hf({container:t});if((0,jc.nonNullish)(n)&&n!==!1){let{host:i,protocol:s}=new URL(n===!0?Ji:n);return`${s}//${r??"unknown"}.${i.replace("127.0.0.1","localhost")}`}return`https://${r??"unknown"}.icp0.io`},pf=({satelliteId:e})=>(0,jc.nonNullish)(e)?{satelliteId:e}:nr.getInstance().get()??{satelliteId:void 0},hf=({container:e})=>(0,jc.nonNullish)(e)?{container:e}:nr.getInstance().get()??{container:void 0};var dt=({satellite:e,options:{certified:t}})=>Ky({idlFactory:t?My:ky,actorKey:`stock#${t?"update":"query"}`,...e}),Hy=({idlFactory:e,...t})=>Ky({idlFactory:e,actorKey:"extended#query",...t}),Ky=async({satelliteId:e,container:t,...r})=>{let{satelliteId:n}=pf({satelliteId:e});(0,Ly.assertNonNullish)(n,"No satellite ID defined. Did you initialize Juno?");let{container:i}=hf({container:t});return await Xi.getInstance().getActor({satelliteId:n,container:i,...r})};var $y=be(Ct(),1),st=be(De(),1);var Gy=e=>{if((0,st.isNullish)(e))return(0,st.toNullable)();switch(e.matcher){case"equal":return(0,st.toNullable)({Equal:e.timestamp});case"greaterThan":return(0,st.toNullable)({GreaterThan:e.timestamp});case"lessThan":return(0,st.toNullable)({LessThan:e.timestamp});case"between":return(0,st.toNullable)({Between:[e.timestamps.start,e.timestamps.end]});default:throw new qc("Invalid list matcher for timestamp",e)}},jn=({matcher:e,paginate:t,order:r,owner:n})=>({matcher:(0,st.isNullish)(e)?[]:[{key:(0,st.toNullable)(e.key),description:(0,st.toNullable)(e.description),created_at:Gy(e.createdAt),updated_at:Gy(e.updatedAt)}],paginate:(0,st.toNullable)((0,st.isNullish)(t)?void 0:{start_after:(0,st.toNullable)(t.startAfter),limit:(0,st.toNullable)((0,st.isNullish)(t.limit)?void 0:BigInt(t.limit))}),order:(0,st.toNullable)((0,st.isNullish)(r)?void 0:{desc:r.desc,field:r.field==="created_at"?{CreatedAt:null}:r.field==="updated_at"?{UpdatedAt:null}:{Keys:null}}),owner:(0,st.toNullable)((0,st.isNullish)(n)?void 0:typeof n=="string"?$y.Principal.fromText(n):n)});var Wy=async({data:e})=>{try{return await hc(e)}catch(t){console.error("The data parsing has failed, mapping to undefined as a fallback.",t);return}};var di=be(De(),1);var _f=async e=>{let{data:t,version:r,description:n}=e;return{description:(0,di.toNullable)(n),data:await py(t),version:(0,di.toNullable)(r)}},yf=e=>{let{version:t}=e;return{version:(0,di.toNullable)(t)}},da=async({doc:e,key:t})=>{let{owner:r,version:n,description:i,data:s,...a}=e;return{key:t,description:(0,di.fromNullable)(i),owner:r.toText(),data:await hc(s),version:(0,di.fromNullable)(n),...a}};var zy=async({collection:e,key:t,...r})=>{let{get_doc:n}=await dt(r),i=(0,Sr.fromNullable)(await n(e,t));if(!(0,Sr.isNullish)(i))return da({doc:i,key:t})},Yy=async({docs:e,...t})=>{let{get_many_docs:r}=await dt(t),n=e.map(({collection:a,key:o})=>[a,o]),i=await r(n),s=[];for(let[a,o]of i){let c=(0,Sr.fromNullable)(o);s.push((0,Sr.nonNullish)(c)?await da({key:a,doc:c}):void 0)}return s},Jy=async({collection:e,doc:t,...r})=>{let{set_doc:n}=await dt(r),{key:i}=t,s=await _f(t),a=await n(e,i,s);return await da({key:i,doc:a})},Zy=async({docs:e,...t})=>{let{set_many_docs:r}=await dt(t),n=[];for(let{collection:a,doc:o}of e){let{key:c}=o;n.push([a,c,await _f(o)])}let i=await r(n),s=[];for(let[a,o]of i)s.push(await da({key:a,doc:o}));return s},Xy=async({collection:e,doc:t,...r})=>{let{del_doc:n}=await dt(r),{key:i}=t;return n(e,i,yf(t))},Qy=async({docs:e,...t})=>{let{del_many_docs:r}=await dt(t),n=e.map(({collection:i,doc:s})=>[i,s.key,yf(s)]);await r(n)},em=async({collection:e,filter:t,...r})=>{let{del_filtered_docs:n}=await dt(r);return n(e,jn(t))},tm=async({collection:e,filter:t,...r})=>{let{list_docs:n}=await dt(r),{items:i,items_page:s,items_length:a,matches_length:o,matches_pages:c}=await n(e,jn(t)),d=[];for(let[f,p]of i){let{data:m,owner:b,description:l,version:A,...v}=p;d.push({key:f,description:(0,Sr.fromNullable)(l),owner:b.toText(),data:await Wy({data:m}),version:(0,Sr.fromNullable)(A),...v})}return{items:d,items_length:a,items_page:(0,Sr.fromNullable)(s),matches_length:o,matches_pages:(0,Sr.fromNullable)(c)}},rm=async({collection:e,filter:t,...r})=>{let{count_docs:n}=await dt(r);return n(e,jn(t))};var Lc=async({satellite:e,options:t,...r})=>{let n=tt(e?.identity);return await zy({...r,satellite:{...e,identity:n},options:t??Xr})},I4=async({satellite:e,options:t,...r})=>{let n=tt(e?.identity);return await Yy({...r,satellite:{...e,identity:n},options:t??Xr})},nm=async({satellite:e,...t})=>{let r=tt(e?.identity);return await Jy({...t,satellite:{...e,identity:r},options:{certified:!0}})},im=async({satellite:e,...t})=>{let r=tt(e?.identity);return await Zy({...t,satellite:{...e,identity:r},options:{certified:!0}})},B4=async({satellite:e,...t})=>{let r=tt(e?.identity);return await Xy({...t,satellite:{...e,identity:r},options:{certified:!0}})},P4=async({satellite:e,...t})=>{let r=tt(e?.identity);return await Qy({...t,satellite:{...e,identity:r},options:{certified:!0}})},F4=async({satellite:e,filter:t,...r})=>{let n=tt(e?.identity);return await em({...r,filter:t??{},satellite:{...e,identity:n},options:{certified:!0}})},U4=async({satellite:e,options:t,filter:r,...n})=>{let i=tt(e?.identity);return await tm({...n,filter:r??{},satellite:{...e,identity:i},options:t??Xr})},V4=async({satellite:e,options:t,filter:r,...n})=>{let i=tt(e?.identity);return await rm({...n,filter:r??{},satellite:{...e,identity:i},options:t??Xr})};var rs=be(De(),1);var sm=async({delegationIdentity:e,passkeyIdentity:t,satelliteId:r})=>{let n=t.getCredential().getAAGUID(),[i,s]=await im({docs:[{collection:"#user",doc:{key:e.getPrincipal().toText(),data:{provider:"webauthn",providerData:{webauthn:{...(0,rs.nonNullish)(n)&&{aaguid:(0,rs.uint8ArrayToArrayOfNumber)(n)}}}}}},{collection:"#user-webauthn",doc:{key:t.getCredential().getCredentialIdText(),data:{publicKey:(0,rs.arrayBufferToUint8Array)(t.getPublicKey().toDer())}}}],satellite:{identity:e,satelliteId:r}});return i};var am=(s=>(s[s.RequestingUserCredential=0]="RequestingUserCredential",s[s.FinalizingCredential=1]="FinalizingCredential",s[s.Signing=2]="Signing",s[s.FinalizingSession=3]="FinalizingSession",s[s.RetrievingUser=4]="RetrievingUser",s))(am||{}),om=(a=>(a[a.CreatingUserCredential=0]="CreatingUserCredential",a[a.ValidatingUserCredential=1]="ValidatingUserCredential",a[a.FinalizingCredential=2]="FinalizingCredential",a[a.Signing=3]="Signing",a[a.FinalizingSession=4]="FinalizingSession",a[a.RegisteringUser=5]="RegisteringUser",a))(om||{});var fa=class{get id(){return"webauthn"}async signUp({options:{onProgress:t,maxTimeToLiveInMilliseconds:r,passkey:n}={},loadAuthWithUser:i}){let{satelliteId:s}=nr.getInstance().get()??{satelliteId:void 0};if((0,ns.isNullish)(s))throw new li("Satellite ID not set. Have you initialized the Satellite?");let a=({step:A,state:v})=>{switch(A){case Vn.RequestingUserCredential:t?.({step:1,state:v});break;case Vn.FinalizingCredential:t?.({step:2,state:v});break;case Vn.Signing:t?.({step:3,state:v});break}},c=await Zr({fn:async()=>await Bd.createWithNewCredential({onProgress:a,passkeyOptions:n}),step:0,onProgress:t}),{delegationIdentity:d,sessionKey:f}=await this.#e({identity:c,maxTimeToLiveInMilliseconds:r}),m=await Zr({fn:async()=>await sm({delegationIdentity:d,passkeyIdentity:c,satelliteId:s}),step:5,onProgress:t});await Zr({fn:async()=>await this.#t({delegationIdentity:d,sessionKey:f}),step:4,onProgress:t}),await Zr({fn:async()=>await i({user:m}),step:5,onProgress:t})}async signIn({options:{onProgress:t,maxTimeToLiveInMilliseconds:r}={},loadAuth:n}){let{satelliteId:i}=nr.getInstance().get()??{satelliteId:void 0};if((0,ns.isNullish)(i))throw new li("Satellite ID not set. Have you initialized the Satellite?");let s=async({credentialId:p})=>{let m=await Lc({collection:"#user-webauthn",key:(0,ns.uint8ArrayToBase64)(p),options:{certified:!0},satellite:{identity:new cm.AnonymousIdentity,satelliteId:i}});if((0,ns.isNullish)(m))throw new Uc("No public key found for the selected passkey.");let{data:b}=m,{publicKey:l}=b;return(0,Qr.unwrapDER)(l.buffer,Qr.DER_COSE_OID)},a=({step:p,state:m})=>{switch(p){case Vn.RequestingUserCredential:t?.({step:0,state:m});break;case Vn.FinalizingCredential:t?.({step:1,state:m});break;case Vn.Signing:t?.({step:2,state:m});break}},o=await Bd.createWithExistingCredential({retrievePublicKey:s,onProgress:a}),{delegationIdentity:c,sessionKey:d}=await this.#e({identity:o,maxTimeToLiveInMilliseconds:r});await Zr({fn:async()=>await this.#t({delegationIdentity:c,sessionKey:d}),step:3,onProgress:t}),await Zr({fn:n,step:4,onProgress:t})}async#e({identity:t,maxTimeToLiveInMilliseconds:r}){let n=await Qr.ECDSAKeyIdentity.generate({extractable:!1}),i=r??144e5,s=await Qr.DelegationChain.create(t,n.getPublicKey(),new Date(Date.now()+i));return{delegationIdentity:Qr.DelegationIdentity.fromDelegation(n,s),sessionKey:n}}async#t({sessionKey:t,delegationIdentity:r}){let n=new is.IdbStorage;await Promise.all([n.set(is.KEY_STORAGE_KEY,t.getKeyPair()),n.set(is.KEY_STORAGE_DELEGATION,JSON.stringify(r.getDelegation().toJSON()))])}};var ss=be(Ic(),1),pa=()=>ss.AuthClient.create({idleOptions:{disableIdle:!0,disableDefaultIdleCallback:!0}}),um=async()=>(await new ss.IdbStorage().remove(ss.KEY_STORAGE_KEY),await pa());var ha=be(De(),1);var mf=({error:e,type:t})=>typeof e=="string"?e.includes(t):e instanceof Error?e.message.includes(t):!1;var lm="juno.datastore.error.user.cannot_update";var dm=async({provider:e})=>{let{user:t,userId:r}=await gf();if((0,ha.nonNullish)(t))return t;try{return await WE({userId:r,provider:e})}catch(n){if(mf({error:n,type:lm})){let i=await fm({userId:r});if((0,ha.nonNullish)(i))return i}throw n}},gf=async()=>{let e=Mc();if((0,ha.isNullish)(e))throw new Cc("No identity to initialize the user. Have you initialized Juno?");let t=e.getPrincipal().toText(),r=await fm({userId:t});return{userId:t,user:r}},fm=({userId:e})=>Lc({collection:"#user",key:e}),WE=({userId:e,...t})=>nm({collection:"#user",doc:{key:e,data:t}});var yr,bf=async()=>{await wf({fn:async()=>{let{user:t}=await gf();hr.getInstance().set(t??null)}})},zE=async({user:e})=>{await wf({fn:async()=>{hr.getInstance().set(e)}})},pm=async({provider:e})=>{await wf({fn:async()=>{let r=await dm({provider:e});hr.getInstance().set(r)}})},wf=async({fn:e})=>{if(yr=await pa(),!await yr.isAuthenticated()){yr=await um();return}await e()},YE=async e=>{let t=async()=>await ZE(e);if(Object.values(e)[0].context?.windowGuard===!1){await t();return}await Ud({fn:t})},JE=async e=>{let t=async()=>await XE(e);if(Object.values(e)?.[0].context?.windowGuard===!1){await t();return}await Ud({fn:t})},ZE=async e=>{if("webauthn"in e){let{webauthn:{options:t}}=e;await new fa().signIn({options:t,loadAuth:bf});return}if("nfid"in e){let{nfid:{options:t}}=e,{appName:r,logoUrl:n,...i}=t??{};await new kc({appName:r,logoUrl:n}).signIn({options:i,authClient:yr,initAuth:pm});return}if("internet_identity"in e){let{internet_identity:{options:t}}=e,{domain:r,...n}=t??{};await new Dc({domain:r}).signIn({options:n,authClient:yr,initAuth:pm});return}throw new Fc("An unknown or unsupported provider was provided for sign-in.")},XE=async e=>{if("webauthn"in e){let{webauthn:{options:t}}=e;await new fa().signUp({options:t,loadAuthWithUser:zE});return}throw new Vc("An unknown or unsupported provider was provided for sign-up.")},xf=async e=>{await QE(),yr=await pa(),e?.windowReload!==!1&&window.location.reload()},QE=async()=>{await yr?.logout(),yr=null,hr.getInstance().reset(),Xi.getInstance().reset(),Zi.getInstance().reset()},Mc=()=>yr?.getIdentity(),eO=async()=>(yr??await pa()).getIdentity(),tO=async()=>{let e=hr.getInstance().get();return(0,hm.isNullish)(e)||!(await yr?.isAuthenticated()??!1)?null:yr?.getIdentity()??null};var ym=e=>{let t=e===!0?"./workers/auth.worker.js":e,r=new Worker(t),n=async()=>{Pd({message:"junoSignOutAuthTimer"}),await xf()};return r.onmessage=async({data:i})=>{let{msg:s,data:a}=i;switch(s){case"junoSignOutAuthTimer":await n();return;case"junoDelegationRemainingTime":Pd({message:"junoDelegationRemainingTime",detail:a?.authRemainingTime});return}},hr.getInstance().subscribe(i=>{if((0,_m.isNullish)(i)){r.postMessage({msg:"junoStopAuthTimer"});return}r.postMessage({msg:"junoStartAuthTimer"})})};var mm=()=>{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()},gm=()=>{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 TR=async({idlFactory:e,satellite:t})=>{let r=tt(t?.identity);return await Hy({idlFactory:e,...t,identity:r})};var ya=be(De(),1);var _a=be(De(),1);var as=be(De(),1);var bm=async({asset:{data:e,headers:t,...r},actor:n,progress:i})=>{let{init_asset_upload:s,upload_asset_chunk:a,commit_asset_upload:o}=n,{batch_id:c}=await s(rO(r));i?.onInitiatedBatch();let{chunkIds:d}=await sO({data:e,uploadFn:a,batchId:c});i?.onUploadedFileChunks(r.fullPath),await iO({commitFn:o,batchId:c,data:e,headers:t,chunkIds:d}),i?.onCommittedBatch()};var rO=({filename:e,collection:t,token:r,fullPath:n,encoding:i,description:s})=>({collection:t,full_path:n,name:e,token:(0,as.toNullable)(r),encoding_type:(0,as.toNullable)(i),description:(0,as.toNullable)(s)}),nO=({batchId:e,chunkIds:t,headers:r,data:n})=>{let i=r.find(([s,a])=>s.toLowerCase()==="content-type")===void 0&&n.type!==void 0&&n.type!==""?[["Content-Type",n.type]]:void 0;return{batch_id:e,chunk_ids:t.map(({chunk_id:s})=>s),headers:[...r,...i??[]]}},iO=async({commitFn:e,...t})=>{let r=nO(t);await e(r)},sO=async({data:e,uploadFn:t,batchId:r})=>{let n=[],i=_c()?new Blob([await e.arrayBuffer()]):e,s=0n;for(let o=0;o<i.size;o+=19e5){let c=i.slice(o,o+19e5);n.push({batchId:r,chunk:c,uploadFn:t,orderId:s}),s++}let a=[];for await(let o of aO({uploadChunks:n}))a=[...a,...o];return{chunkIds:a}};async function*aO({uploadChunks:e,limit:t=12}){for(let r=0;r<e.length;r=r+t){let n=e.slice(r,r+t);yield await Promise.all(n.map(i=>oO(i)))}}var oO=async({batchId:e,chunk:t,uploadFn:r,orderId:n})=>r({batch_id:e,content:new Uint8Array(await t.arrayBuffer()),order_id:(0,as.toNullable)(n)});var wm=async({asset:e,...t})=>{let r=await dt(t);await bm({actor:r,asset:e})},xm=async({collection:e,filter:t,...r})=>{let{list_assets:n}=await dt(r),{items:i,items_length:s,items_page:a,matches_length:o,matches_pages:c}=await n(e,jn(t));return{items:i.map(([d,f])=>f),items_length:s,items_page:(0,_a.fromNullable)(a),matches_length:o,matches_pages:(0,_a.fromNullable)(c)}},Tm=async({collection:e,filter:t,...r})=>{let{count_assets:n}=await dt(r);return n(e,jn(t))},Nm=async({collection:e,fullPath:t,...r})=>(await dt(r)).del_asset(e,t),Em=async({assets:e,satellite:t})=>{let{del_many_assets:r}=await dt({satellite:t,options:{certified:!0}}),n=e.map(({collection:i,fullPath:s})=>[i,s]);await r(n)},Om=async({collection:e,filter:t,...r})=>{let{del_filtered_assets:n}=await dt(r);return n(e,jn(t))},vm=async({collection:e,fullPath:t,...r})=>{let{get_asset:n}=await dt(r);return(0,_a.fromNullable)(await n(e,t))},Rm=async({assets:e,...t})=>{let{get_many_assets:r}=await dt(t),n=e.map(({collection:s,fullPath:a})=>[s,a]);return(await r(n)).map(([s,a])=>(0,_a.fromNullable)(a))};var Am=e=>btoa([...e].map(t=>String.fromCharCode(t)).join(""));var CR=e=>Sm(e),qR=e=>Sm({filename:e.data.name,...e}),Sm=async({filename:e,data:t,collection:r,headers:n=[],fullPath:i,token:s,satellite:a,encoding:o,description:c})=>{let d=tt(a?.identity),f=decodeURI(e),p=i??`/${r}/${f}`,m={...a,identity:d};return await wm({asset:{data:t,filename:f,collection:r,token:s,headers:n,fullPath:p,encoding:o,description:c},satellite:m,options:{certified:!0}}),{downloadUrl:Im({satellite:m,assetKey:{fullPath:p,token:s}}),fullPath:p,name:f}},DR=async({collection:e,filter:t,satellite:r,options:n})=>{let i={...r,identity:tt(r?.identity)},{items:s,...a}=await xm({collection:e,filter:t??{},satellite:i,options:n??Xr}),o=s.map(({key:{full_path:c,token:d,name:f,owner:p,description:m},headers:b,encodings:l,created_at:A,updated_at:v})=>{let F=(0,ya.fromNullable)(d);return{fullPath:c,description:(0,ya.fromNullable)(m),name:f,downloadUrl:Im({satellite:i,assetKey:{fullPath:c,token:F}}),token:F,headers:b,encodings:l.reduce((C,[E,{modified:H,sha256:x,total_length:q}])=>({...C,[E]:{modified:H,sha256:Am(x),total_length:q}}),{}),owner:p.toText(),created_at:A,updated_at:v}});return{items:o,assets:o,...a}},kR=async({collection:e,filter:t,satellite:r,options:n})=>{let i={...r,identity:tt(r?.identity)};return await Tm({collection:e,satellite:i,filter:t??{},options:n??Xr})},MR=({collection:e,fullPath:t,satellite:r})=>Nm({collection:e,fullPath:t,satellite:{...r,identity:tt(r?.identity)},options:{certified:!0}}),jR=({assets:e,satellite:t})=>Em({assets:e,satellite:{...t,identity:tt(t?.identity)},options:{certified:!0}}),LR=async({collection:e,satellite:t,filter:r})=>{let n={...t,identity:tt(t?.identity)};return await Om({collection:e,satellite:n,filter:r??{},options:{certified:!0}})},HR=async({satellite:e,options:t,...r})=>{let n=tt(e?.identity);return await vm({...r,satellite:{...e,identity:n},options:t??Xr})},KR=async({satellite:e,options:t,...r})=>{let n=tt(e?.identity);return await Rm({...r,satellite:{...e,identity:n},options:t??Xr})},Im=({assetKey:{fullPath:e,token:t},satellite:r})=>{let n={...r,identity:tt(r?.identity)};return`${jy(n)}${e}${(0,ya.nonNullish)(t)?`?token=${t}`:""}`};var cO=e=>{let t=e?.satelliteId??mm();(0,Bm.assertNonNullish)(t,"Satellite ID is not configured. Juno cannot be initialized.");let r=e?.container??gm();return{satelliteId:t,internetIdentityId:e?.internetIdentityId,workers:e?.workers,container:r}},XR=e=>uO(e),uO=async e=>{let t=cO(e);nr.getInstance().set(t),await bf();let r=t.workers?.auth!==void 0?ym(t.workers.auth):void 0;return[...r?[r]:[]]},lO=e=>hr.getInstance().subscribe(e),QR=lO;export{Uy as AuthClientSignInProgressStep,Cc as InitError,Dc as InternetIdentityProvider,qc as ListError,kc as NFIDProvider,Bc as SignInError,li as SignInInitError,Fc as SignInProviderNotSupportedError,Pc as SignInUserInterruptError,Vc as SignUpProviderNotSupportedError,am as WebAuthnSignInProgressStep,Uc as WebAuthnSignInRetrievePublicKeyError,om as WebAuthnSignUpProgressStep,QR as authSubscribe,kR as countAssets,V4 as countDocs,MR as deleteAsset,B4 as deleteDoc,LR as deleteFilteredAssets,F4 as deleteFilteredDocs,jR as deleteManyAssets,P4 as deleteManyDocs,Im as downloadUrl,HR as getAsset,Lc as getDoc,tO as getIdentityOnce,KR as getManyAssets,I4 as getManyDocs,TR as getSatelliteExtendedActor,XR as initJuno,uO as initSatellite,K2 as isWebAuthnAvailable,DR as listAssets,U4 as listDocs,lO as onAuthStateChange,nm as setDoc,im as setManyDocs,YE as signIn,xf as signOut,JE as signUp,eO as unsafeIdentity,CR as uploadBlob,qR as uploadFile};
57
+ ic-request`);function kd(e){if(typeof e!="string"||e.length<64)throw new Error("Invalid public key.");return(0,kn.fromHex)(e)}var oa=class{constructor(t,r,n){this.pubkey=t,this.expiration=r,this.targets=n}toCBOR(){return aa.value.map(Object.assign({pubkey:aa.value.bytes(this.pubkey),expiration:aa.value.u64(this.expiration.toString(16),16)},this.targets&&{targets:aa.value.array(this.targets.map(t=>aa.value.bytes(t.toUint8Array())))}))}toJSON(){return Object.assign({expiration:this.expiration.toString(16),pubkey:(0,kn.toHex)(this.pubkey)},this.targets&&{targets:this.targets.map(t=>t.toHex())})}};Ze.Delegation=oa;async function aE(e,t,r,n){let i=new oa(t.toDer(),BigInt(+r)*BigInt(1e6),n),s=new Uint8Array([...iE,...new Uint8Array((0,kn.requestIdOf)(Object.assign({},i)))]),a=await e.sign(s);return{delegation:i,signature:a}}var jd=class e{constructor(t,r){this.delegations=t,this.publicKey=r}static async create(t,r,n=new Date(Date.now()+900*1e3),i={}){var s,a;let o=await aE(t,r,n,i.targets);return new e([...((s=i.previous)===null||s===void 0?void 0:s.delegations)||[],o],((a=i.previous)===null||a===void 0?void 0:a.publicKey)||t.getPublicKey().toDer())}static fromJSON(t){let{publicKey:r,delegations:n}=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(n))throw new Error("Invalid delegations.");let i=n.map(s=>{let{delegation:a,signature:o}=s,{pubkey:c,expiration:d,targets:f}=a;if(f!==void 0&&!Array.isArray(f))throw new Error("Invalid targets.");return{delegation:new oa(kd(c),BigInt("0x"+d),f&&f.map(p=>{if(typeof p!="string")throw new Error("Invalid target.");return Md.Principal.fromHex(p)})),signature:kd(o)}});return new this(i,kd(r))}static fromDelegations(t,r){return new this(t,r)}toJSON(){return{delegations:this.delegations.map(t=>{let{delegation:r,signature:n}=t,{targets:i}=r;return{delegation:Object.assign({expiration:r.expiration.toString(16),pubkey:(0,kn.toHex)(r.pubkey)},i&&{targets:i.map(s=>s.toHex())}),signature:(0,kn.toHex)(n)}}),publicKey:(0,kn.toHex)(this.publicKey)}}};Ze.DelegationChain=jd;var Ld=class extends kn.SignIdentity{constructor(t,r){super(),this._inner=t,this._delegation=r}static fromDelegation(t,r){return new this(t,r)}getDelegation(){return this._delegation}getPublicKey(){return{derKey:this._delegation.publicKey,toDer:()=>this._delegation.publicKey}}sign(t){return this._inner.sign(t)}async transformRequest(t){let{body:r}=t,n=rE(t,["body"]),i=await(0,kn.requestIdOf)(r);return Object.assign(Object.assign({},n),{body:{content:r,sender_sig:await this.sign(new Uint8Array([...sE,...new Uint8Array(i)])),sender_delegation:this._delegation.delegations,sender_pubkey:this._delegation.publicKey}})}};Ze.DelegationIdentity=Ld;var Hd=class e extends nE.PartialIdentity{constructor(t,r){super(t),Tc.set(this,void 0),eE(this,Tc,r,"f")}get delegation(){return tE(this,Tc,"f")}static fromDelegation(t,r){return new e(t,r)}};Ze.PartialDelegationIdentity=Hd;Tc=new WeakMap;function oE(e,t){for(let{delegation:i}of e.delegations)if(+new Date(Number(i.expiration/BigInt(1e6)))<=+Date.now())return!1;let r=[],n=t?.scope;n&&(Array.isArray(n)?r.push(...n.map(i=>typeof i=="string"?Md.Principal.fromText(i):i)):r.push(typeof n=="string"?Md.Principal.fromText(n):n));for(let i of r){let s=i.toText();for(let{delegation:a}of e.delegations){if(a.targets===void 0)continue;let o=!0;for(let c of a.targets)if(c.toText()===s){o=!1;break}if(o)return!1}}return!0}Ze.isDelegationValid=oE});var by=ee(Mn=>{"use strict";var cE=Mn&&Mn.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Mn,"__esModule",{value:!0});Mn.WebAuthnIdentity=Mn.CosePublicKey=void 0;var ui=gt(),Kd=cE(to()),uE=Kn(),lE=Ri();function dE(e){return(0,ui.wrapDER)(e,ui.DER_COSE_OID).buffer}function fE(e){let t=new DataView(new ArrayBuffer(2)),r=e.slice(53,55);[...new Uint8Array(r)].forEach((i,s)=>t.setUint8(s,i));let n=t.getUint16(0);return e.slice(55+n)}var Nc=class{constructor(t){this._cose=t,this._encodedKey=dE(t)}toDer(){return this._encodedKey}getCose(){return this._cose}};Mn.CosePublicKey=Nc;function pE(e="<ic0.app>"){return typeof e=="string"?Uint8Array.from(e,t=>t.charCodeAt(0)):e}async function hE(e){let t=await navigator.credentials.create(e??{publicKey:{authenticatorSelection:{userVerification:"preferred"},attestation:"direct",challenge:pE(),pubKeyCredParams:[{type:"public-key",alg:Gd.ECDSA_WITH_SHA256}],rp:{name:"Internet Identity Service"},user:{id:(0,uE.randomBytes)(16),name:"Internet Identity",displayName:"Internet Identity"}}});return t===null?null:{id:t.id,response:t.response,type:t.type,authenticatorAttachment:t.authenticatorAttachment,getClientExtensionResults:t.getClientExtensionResults,rawId:(0,lE.bufFromBufLike)(t.rawId)}}var Gd;(function(e){e[e.ECDSA_WITH_SHA256=-7]="ECDSA_WITH_SHA256"})(Gd||(Gd={}));var $d=class extends ui.SignIdentity{constructor(t,r,n){super(),this.rawId=t,this.authenticatorAttachment=n,this._publicKey=new Nc(r)}static fromJSON(t){let{publicKey:r,rawId:n}=JSON.parse(t);if(typeof r!="string"||typeof n!="string")throw new Error("Invalid JSON string.");return new this((0,ui.fromHex)(n),(0,ui.fromHex)(r),void 0)}static async create(t){var r;let n=await hE(t);if(!n||n.type!=="public-key")throw new Error("Could not create credentials.");let i=n.response;if(i.attestationObject===void 0)throw new Error("Was expecting an attestation response.");let s=Kd.default.decodeFirst(new Uint8Array(i.attestationObject));return new this(n.rawId,fE(s.authData),(r=n.authenticatorAttachment)!==null&&r!==void 0?r:void 0)}getPublicKey(){return this._publicKey}getAuthenticatorAttachment(){return this.authenticatorAttachment}async sign(t){let r=await navigator.credentials.get({publicKey:{allowCredentials:[{type:"public-key",id:this.rawId}],challenge:t,userVerification:"preferred"}});r.authenticatorAttachment!==null&&(this.authenticatorAttachment=r.authenticatorAttachment);let n=r.response,i=Kd.default.encode(new Kd.default.Tagged(55799,{authenticator_data:new Uint8Array(n.authenticatorData),client_data_json:new TextDecoder().decode(n.clientDataJSON),signature:new Uint8Array(n.signature)}));if(!i)throw new Error("failed to encode cbor");return i.buffer}toJSON(){return{publicKey:(0,ui.toHex)(this._publicKey.getCose()),rawId:(0,ui.toHex)(this.rawId)}}};Mn.WebAuthnIdentity=$d});var Yd=ee(Ye=>{"use strict";var _E=Ye&&Ye.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),zd=Ye&&Ye.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&_E(t,e,r)};Object.defineProperty(Ye,"__esModule",{value:!0});Ye.Secp256k1KeyIdentity=Ye.ED25519_OID=Ye.DER_COSE_OID=Ye.unwrapDER=Ye.wrapDER=Ye.WebAuthnIdentity=Ye.Ed25519PublicKey=Ye.Ed25519KeyIdentity=void 0;var wy=_y();Object.defineProperty(Ye,"Ed25519KeyIdentity",{enumerable:!0,get:function(){return wy.Ed25519KeyIdentity}});Object.defineProperty(Ye,"Ed25519PublicKey",{enumerable:!0,get:function(){return wy.Ed25519PublicKey}});zd(my(),Ye);zd(gy(),Ye);zd(Dd(),Ye);var yE=by();Object.defineProperty(Ye,"WebAuthnIdentity",{enumerable:!0,get:function(){return yE.WebAuthnIdentity}});var Ec=gt();Object.defineProperty(Ye,"wrapDER",{enumerable:!0,get:function(){return Ec.wrapDER}});Object.defineProperty(Ye,"unwrapDER",{enumerable:!0,get:function(){return Ec.unwrapDER}});Object.defineProperty(Ye,"DER_COSE_OID",{enumerable:!0,get:function(){return Ec.DER_COSE_OID}});Object.defineProperty(Ye,"ED25519_OID",{enumerable:!0,get:function(){return Ec.ED25519_OID}});var Wd=class{constructor(){throw new Error("Secp256k1KeyIdentity has been moved to a new repo: @dfinity/identity-secp256k1")}};Ye.Secp256k1KeyIdentity=Wd});var Zd=ee(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});Oc.IdleManager=void 0;var xy=["mousedown","mousemove","keydown","touchstart","wheel"],Jd=class{constructor(t={}){var r;this.callbacks=[],this.idleTimeout=600*1e3,this.timeoutID=void 0;let{onIdle:n,idleTimeout:i=600*1e3}=t||{};this.callbacks=n?[n]:[],this.idleTimeout=i;let s=this._resetTimer.bind(this);window.addEventListener("load",s,!0),xy.forEach(function(o){document.addEventListener(o,s,!0)});let a=(o,c)=>{let d;return(...f)=>{let p=this,m=function(){d=void 0,o.apply(p,f)};clearTimeout(d),d=window.setTimeout(m,c)}};if(t?.captureScroll){let o=a(s,(r=t?.scrollDebounce)!==null&&r!==void 0?r:100);window.addEventListener("scroll",o,!0)}s()}static create(t={}){return new this(t)}registerCallback(t){this.callbacks.push(t)}exit(){clearTimeout(this.timeoutID),window.removeEventListener("load",this._resetTimer,!0);let t=this._resetTimer.bind(this);xy.forEach(function(r){document.removeEventListener(r,t,!0)}),this.callbacks.forEach(r=>r())}_resetTimer(){let t=this.exit.bind(this);window.clearTimeout(this.timeoutID),this.timeoutID=window.setTimeout(t,this.idleTimeout)}};Oc.IdleManager=Jd});function gE(){return Ty||(Ty=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function bE(){return Ny||(Ny=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function wE(e){let t=new Promise((r,n)=>{let i=()=>{e.removeEventListener("success",s),e.removeEventListener("error",a)},s=()=>{r(_r(e.result)),i()},a=()=>{n(e.error),i()};e.addEventListener("success",s),e.addEventListener("error",a)});return t.then(r=>{r instanceof IDBCursor&&Ey.set(r,e)}).catch(()=>{}),tf.set(t,e),t}function xE(e){if(Qd.has(e))return;let t=new Promise((r,n)=>{let i=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",a),e.removeEventListener("abort",a)},s=()=>{r(),i()},a=()=>{n(e.error||new DOMException("AbortError","AbortError")),i()};e.addEventListener("complete",s),e.addEventListener("error",a),e.addEventListener("abort",a)});Qd.set(e,t)}function vy(e){ef=e(ef)}function TE(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(t,...r){let n=e.call(ca(this),t,...r);return Oy.set(n,t.sort?t.sort():[t]),_r(n)}:bE().includes(e)?function(...t){return e.apply(ca(this),t),_r(Ey.get(this))}:function(...t){return _r(e.apply(ca(this),t))}}function NE(e){return typeof e=="function"?TE(e):(e instanceof IDBTransaction&&xE(e),mE(e,gE())?new Proxy(e,ef):e)}function _r(e){if(e instanceof IDBRequest)return wE(e);if(Xd.has(e))return Xd.get(e);let t=NE(e);return t!==e&&(Xd.set(e,t),tf.set(t,e)),t}var mE,Ty,Ny,Ey,Qd,Oy,Xd,tf,ef,ca,rf=Tf(()=>{mE=(e,t)=>t.some(r=>e instanceof r);Ey=new WeakMap,Qd=new WeakMap,Oy=new WeakMap,Xd=new WeakMap,tf=new WeakMap;ef={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return Qd.get(e);if(t==="objectStoreNames")return e.objectStoreNames||Oy.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return _r(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};ca=e=>tf.get(e)});var Ay={};Zm(Ay,{deleteDB:()=>OE,openDB:()=>EE,unwrap:()=>ca,wrap:()=>_r});function EE(e,t,{blocked:r,upgrade:n,blocking:i,terminated:s}={}){let a=indexedDB.open(e,t),o=_r(a);return n&&a.addEventListener("upgradeneeded",c=>{n(_r(a.result),c.oldVersion,c.newVersion,_r(a.transaction),c)}),r&&a.addEventListener("blocked",c=>r(c.oldVersion,c.newVersion,c)),o.then(c=>{s&&c.addEventListener("close",()=>s()),i&&c.addEventListener("versionchange",d=>i(d.oldVersion,d.newVersion,d))}).catch(()=>{}),o}function OE(e,{blocked:t}={}){let r=indexedDB.deleteDatabase(e);return t&&r.addEventListener("blocked",n=>t(n.oldVersion,n)),_r(r).then(()=>{})}function Ry(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(nf.get(t))return nf.get(t);let r=t.replace(/FromIndex$/,""),n=t!==r,i=RE.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(i||vE.includes(r)))return;let s=async function(a,...o){let c=this.transaction(a,i?"readwrite":"readonly"),d=c.store;return n&&(d=d.index(o.shift())),(await Promise.all([d[r](...o),i&&c.done]))[0]};return nf.set(t,s),s}var vE,RE,nf,Sy=Tf(()=>{rf();rf();vE=["get","getKey","getAll","getAllKeys","count"],RE=["put","add","delete","clear"],nf=new Map;vy(e=>({...e,get:(t,r,n)=>Ry(t,r)||e.get(t,r,n),has:(t,r)=>!!Ry(t,r)||e.has(t,r)}))});var af=ee(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.IdbKeyVal=void 0;var AE=(Sy(),Xm(Ay)),ua=Rc(),Iy="auth-client-db",By="ic-keyval",SE=async(e=Iy,t=By,r)=>(ua.isBrowser&&(localStorage!=null&&localStorage.getItem(ua.KEY_STORAGE_DELEGATION))&&(localStorage.removeItem(ua.KEY_STORAGE_DELEGATION),localStorage.removeItem(ua.KEY_STORAGE_KEY)),await(0,AE.openDB)(e,r,{upgrade:n=>{n.objectStoreNames.contains(t)&&n.clear(t),n.createObjectStore(t)}}));async function IE(e,t,r){return await e.get(t,r)}async function BE(e,t,r,n){return await e.put(t,n,r)}async function PE(e,t,r){return await e.delete(t,r)}var sf=class e{constructor(t,r){this._db=t,this._storeName=r}static async create(t){let{dbName:r=Iy,storeName:n=By,version:i=ua.DB_VERSION}=t??{},s=await SE(r,n,i);return new e(s,n)}async set(t,r){return await BE(this._db,this._storeName,t,r)}async get(t){var r;return(r=await IE(this._db,this._storeName,t))!==null&&r!==void 0?r:null}async remove(t){return await PE(this._db,this._storeName,t)}};vc.IdbKeyVal=sf});var Rc=ee(it=>{"use strict";var FE=it&&it.__classPrivateFieldSet||function(e,t,r,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 t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(e,r):i?i.value=r:t.set(e,r),r},UE=it&&it.__classPrivateFieldGet||function(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)},Ac;Object.defineProperty(it,"__esModule",{value:!0});it.IdbStorage=it.LocalStorage=it.isBrowser=it.DB_VERSION=it.KEY_VECTOR=it.KEY_STORAGE_DELEGATION=it.KEY_STORAGE_KEY=void 0;var VE=af();it.KEY_STORAGE_KEY="identity";it.KEY_STORAGE_DELEGATION="delegation";it.KEY_VECTOR="iv";it.DB_VERSION=1;it.isBrowser=typeof window<"u";var of=class{constructor(t="ic-",r){this.prefix=t,this._localStorage=r}get(t){return Promise.resolve(this._getLocalStorage().getItem(this.prefix+t))}set(t,r){return this._getLocalStorage().setItem(this.prefix+t,r),Promise.resolve()}remove(t){return this._getLocalStorage().removeItem(this.prefix+t),Promise.resolve()}_getLocalStorage(){if(this._localStorage)return this._localStorage;let t=typeof window>"u"?typeof global>"u"?typeof self>"u"?void 0:self.localStorage:global.localStorage:window.localStorage;if(!t)throw new Error("Could not find local storage.");return t}};it.LocalStorage=of;var cf=class{constructor(t){Ac.set(this,void 0),FE(this,Ac,t??{},"f")}get _db(){return new Promise(t=>{if(this.initializedDb){t(this.initializedDb);return}VE.IdbKeyVal.create(UE(this,Ac,"f")).then(r=>{this.initializedDb=r,t(r)})})}async get(t){return await(await this._db).get(t)}async set(t,r){await(await this._db).set(t,r)}async remove(t){await(await this._db).remove(t)}};it.IdbStorage=cf;Ac=new WeakMap});var Ic=ee(et=>{"use strict";var CE=et&&et.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),qE=et&&et.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&CE(t,e,r)};Object.defineProperty(et,"__esModule",{value:!0});et.AuthClient=et.ERROR_USER_INTERRUPT=et.IdbKeyVal=et.KEY_STORAGE_KEY=et.KEY_STORAGE_DELEGATION=et.LocalStorage=et.IdbStorage=void 0;var Py=gt(),sr=Yd(),Fy=Zd(),Et=Rc(),Sc=Rc();Object.defineProperty(et,"IdbStorage",{enumerable:!0,get:function(){return Sc.IdbStorage}});Object.defineProperty(et,"LocalStorage",{enumerable:!0,get:function(){return Sc.LocalStorage}});Object.defineProperty(et,"KEY_STORAGE_DELEGATION",{enumerable:!0,get:function(){return Sc.KEY_STORAGE_DELEGATION}});Object.defineProperty(et,"KEY_STORAGE_KEY",{enumerable:!0,get:function(){return Sc.KEY_STORAGE_KEY}});var DE=af();Object.defineProperty(et,"IdbKeyVal",{enumerable:!0,get:function(){return DE.IdbKeyVal}});var kE="https://identity.ic0.app",ME="#authorize",uf="ECDSA",lf="Ed25519",jE=500;et.ERROR_USER_INTERRUPT="UserInterrupt";qE(Zd(),et);var ff=class{constructor(t,r,n,i,s,a,o,c){this._identity=t,this._key=r,this._chain=n,this._storage=i,this.idleManager=s,this._createOptions=a,this._idpWindow=o,this._eventHandler=c,this._registerDefaultIdleCallback()}static async create(t={}){var r,n,i;let s=(r=t.storage)!==null&&r!==void 0?r:new Et.IdbStorage,a=(n=t.keyType)!==null&&n!==void 0?n:uf,o=null;if(t.identity)o=t.identity;else{let p=await s.get(Et.KEY_STORAGE_KEY);if(!p&&Et.isBrowser)try{let m=new Et.LocalStorage,b=await m.get(Et.KEY_STORAGE_DELEGATION),l=await m.get(Et.KEY_STORAGE_KEY);b&&l&&a===uf&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await s.set(Et.KEY_STORAGE_DELEGATION,b),await s.set(Et.KEY_STORAGE_KEY,l),p=b,await m.remove(Et.KEY_STORAGE_DELEGATION),await m.remove(Et.KEY_STORAGE_KEY))}catch(m){console.error("error while attempting to recover localstorage: "+m)}if(p)try{typeof p=="object"?a===lf&&typeof p=="string"?o=await sr.Ed25519KeyIdentity.fromJSON(p):o=await sr.ECDSAKeyIdentity.fromKeyPair(p):typeof p=="string"&&(o=sr.Ed25519KeyIdentity.fromJSON(p))}catch{}}let c=new Py.AnonymousIdentity,d=null;if(o)try{let p=await s.get(Et.KEY_STORAGE_DELEGATION);if(typeof p=="object"&&p!==null)throw new Error("Delegation chain is incorrectly stored. A delegation chain should be stored as a string.");t.identity?c=t.identity:p&&(d=sr.DelegationChain.fromJSON(p),(0,sr.isDelegationValid)(d)?"toDer"in o?c=sr.PartialDelegationIdentity.fromDelegation(o,d):c=sr.DelegationIdentity.fromDelegation(o,d):(await df(s),o=null))}catch(p){console.error(p),await df(s),o=null}let f;return!((i=t.idleOptions)===null||i===void 0)&&i.disableIdle?f=void 0:(d||t.identity)&&(f=Fy.IdleManager.create(t.idleOptions)),o||(a===lf?(o=await sr.Ed25519KeyIdentity.generate(),await s.set(Et.KEY_STORAGE_KEY,JSON.stringify(o.toJSON()))):(t.storage&&a===uf&&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 '${lf}' as the key type, as it can serialize to a string`),o=await sr.ECDSAKeyIdentity.generate(),await s.set(Et.KEY_STORAGE_KEY,o.getKeyPair()))),new this(c,o,d,s,f,t)}_registerDefaultIdleCallback(){var t,r;let n=(t=this._createOptions)===null||t===void 0?void 0:t.idleOptions;!n?.onIdle&&!n?.disableDefaultIdleCallback&&((r=this.idleManager)===null||r===void 0||r.registerCallback(()=>{this.logout(),location.reload()}))}async _handleSuccess(t,r){var n,i;let s=t.delegations.map(d=>({delegation:new sr.Delegation(d.delegation.pubkey,d.delegation.expiration,d.delegation.targets),signature:d.signature.buffer})),a=sr.DelegationChain.fromDelegations(s,t.userPublicKey.buffer),o=this._key;if(!o)return;this._chain=a,"toDer"in o?this._identity=sr.PartialDelegationIdentity.fromDelegation(o,this._chain):this._identity=sr.DelegationIdentity.fromDelegation(o,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=Fy.IdleManager.create(c),this._registerDefaultIdleCallback()),this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(Et.KEY_STORAGE_DELEGATION,JSON.stringify(this._chain.toJSON())),r?.(t)}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null}async login(t){var r,n,i,s;let a=BigInt(8)*BigInt(36e11),o=new URL(((r=t?.identityProvider)===null||r===void 0?void 0:r.toString())||kE);o.hash=ME,(n=this._idpWindow)===null||n===void 0||n.close(),this._removeEventListener(),this._eventHandler=this._getEventHandler(o,Object.assign({maxTimeToLive:(i=t?.maxTimeToLive)!==null&&i!==void 0?i:a},t)),window.addEventListener("message",this._eventHandler),this._idpWindow=(s=window.open(o.toString(),"idpWindow",t?.windowOpenerFeatures))!==null&&s!==void 0?s:void 0;let c=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(et.ERROR_USER_INTERRUPT,t?.onError):setTimeout(c,jE))};c()}_getEventHandler(t,r){return async n=>{var i,s,a;if(n.origin!==t.origin)return;let o=n.data;switch(o.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:r?.maxTimeToLive,allowPinAuthentication:r?.allowPinAuthentication,derivationOrigin:(s=r?.derivationOrigin)===null||s===void 0?void 0:s.toString()},r?.customValues);(a=this._idpWindow)===null||a===void 0||a.postMessage(c,t.origin);break}case"authorize-client-success":try{await this._handleSuccess(o,r?.onSuccess)}catch(c){this._handleFailure(c.message,r?.onError)}break;case"authorize-client-failure":this._handleFailure(o.text,r?.onError);break;default:break}}}_handleFailure(t,r){var n;(n=this._idpWindow)===null||n===void 0||n.close(),r?.(t),this._removeEventListener(),delete this._idpWindow}_removeEventListener(){this._eventHandler&&window.removeEventListener("message",this._eventHandler),this._eventHandler=void 0}async logout(t={}){if(await df(this._storage),this._identity=new Py.AnonymousIdentity,this._chain=null,t.returnTo)try{window.history.pushState({},"",t.returnTo)}catch{window.location.href=t.returnTo}}};et.AuthClient=ff;async function df(e){await e.remove(Et.KEY_STORAGE_KEY),await e.remove(Et.KEY_STORAGE_DELEGATION),await e.remove(Et.KEY_VECTOR)}});var Bm=be(De(),1);var Y_=be(De(),1),lc=be(gt(),1),J_=be(De(),1),na=be(gt(),1),Lt=be(De(),1),X_=be(De(),1),ry=be(De(),1),T2=({authData:e})=>{if(e.byteLength<37)return{invalidAuthData:null};if(e.byteLength<53)return{invalidAuthData:null};let t=e.slice(37,53),r=N2({bytes:t});return"aaguid"in r?{aaguidBytes:t,aaguidText:r.aaguid}:{unknownProvider:null}},N2=({bytes:e})=>{if(e.length!==16)return{invalidBytes:null};let t=(e instanceof Uint8Array?(0,Y_.uint8ArrayToArrayOfNumber)(e):e).map(r=>r.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5");return t==="00000000-0000-0000-0000-000000000000"?{unknownProvider:null}:{aaguid:t}};function E2(e){let t=new DataView(new ArrayBuffer(2)),r=e.slice(53,55);[...new Uint8Array(r)].forEach((i,s)=>t.setUint8(s,i));let n=t.getUint16(0);return e.slice(55+n)}function O2(e){return(0,lc.wrapDER)(e.buffer,lc.DER_COSE_OID).buffer}var v2=class{constructor(e){this._cose=e,this._encodedKey=O2(e)}_encodedKey;toDer(){return this._encodedKey}},Z_=class{#e;#t;constructor({rawId:e,cose:t}){this.#e=e,this.#t=new v2(t)}getPublicKey(){return this.#t}getCredentialId(){return this.#e}getCredentialIdText(){return(0,J_.uint8ArrayToBase64)(this.#e)}},R2=class extends Z_{#e;#t;constructor({authData:e,...t}){super(t);let r=T2({authData:e});this.#e="aaguidText"in r?r.aaguidText:void 0,this.#t="aaguidBytes"in r?r.aaguidBytes:void 0}getAAGUID(){return this.#t}getAAGUIDText(){return this.#e}},A2=class extends Z_{},S2=class extends Error{},I2=class extends Error{},B2=class extends Error{},P2=class extends Error{},F2=class extends Error{},U2=class extends Error{},V2=class extends Error{},G_=class extends Error{};var C2={ECDSA_WITH_SHA256:-7,RSA_WITH_SHA256:-257},q2=6e4,Q_=()=>window.crypto.getRandomValues(new Uint8Array(16)),D2=()=>Q_(),k2=()=>Q_(),M2=()=>{let{location:{href:e}}=window,t=URL.parse(e);if((0,X_.isNullish)(t))throw new S2;let{hostname:r}=t;return r},ey=({appId:e})=>e?.id??M2(),j2=({appId:e,user:t}={})=>{let{document:{title:r}}=window,n=()=>({rp:{name:e?.name??r,id:ey({appId:e})}}),i=()=>({user:{id:k2(),name:t?.name??t?.displayName??r,displayName:t?.displayName??r}});return{attestation:"direct",challenge:D2(),...n(),...i(),pubKeyCredParams:Object.values(C2).map(s=>({type:"public-key",alg:s})),excludeCredentials:[],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"preferred",residentKey:"required",requireResidentKey:!0}}},L2=(e={})=>({rpId:ey(e),allowCredentials:[],userVerification:"required"}),Id=async({fn:e,step:t,onProgress:r})=>{r?.({step:t,state:"in_progress"});try{let n=await e();return r?.({step:t,state:"success"}),n}catch(n){throw r?.({step:t,state:"error"}),n}},Vn=(e=>(e[e.RequestingUserCredential=0]="RequestingUserCredential",e[e.FinalizingCredential=1]="FinalizingCredential",e[e.Signing=2]="Signing",e))(Vn||{}),ty=({timeout:e})=>AbortSignal.timeout(e??q2),H2=async({challenge:e,credentialIds:t,passkeyOptions:r,timeout:n})=>await navigator.credentials.get({publicKey:{...L2(r),challenge:e.buffer,allowCredentials:(t??[]).map(i=>({id:i.buffer,type:"public-key"}))},signal:ty({timeout:n})}),$_=e=>{if(e.status!=="initialized")throw new I2},W_=e=>{if((0,Lt.isNullish)(e))throw new B2},z_=({type:e})=>{if(e!=="public-key")throw new P2},Bd=class ra extends na.SignIdentity{#e;#t;constructor({onProgress:t,...r}){if(super(),this.#e=t,"retrievePublicKey"in r){let{retrievePublicKey:n}=r;this.#t={status:"pending",retrievePublicKey:n};return}this.#t=ra.#r({credential:new R2(r)})}static#r({credential:t}){return{status:"initialized",credential:t}}static async createWithNewCredential({passkeyOptions:t,timeout:r,...n}={}){let i=await navigator.credentials.create({publicKey:j2(t),signal:ty({timeout:r})});W_(i),z_(i);let{response:{attestationObject:s},rawId:a}=i;if((0,Lt.isNullish)(s))throw new F2;let{authData:o}=na.Cbor.decode(s),c=E2(o);return new ra({...n,rawId:(0,Lt.arrayBufferToUint8Array)(a),cose:c,authData:o})}static async createWithExistingCredential(t){return new ra(t)}getPublicKey(){$_(this.#t);let{credential:t}=this.#t;return t.getPublicKey()}getCredential(){$_(this.#t);let{credential:t}=this.#t;return t}async sign(t){let r=await Id({fn:async()=>{let n=await H2({challenge:(0,Lt.arrayBufferToUint8Array)(t),...this.#t.status==="initialized"&&{credentialIds:[this.#t.credential.getCredentialId()]}});return W_(n),z_(n),n},step:0,onProgress:this.#e});return await Id({fn:async()=>{let{rawId:n}=r;if(this.#t.status==="initialized"){if(!(0,Lt.uint8ArraysEqual)({a:this.#t.credential.getCredentialId(),b:(0,Lt.arrayBufferToUint8Array)(n)}))throw new U2;return}let{retrievePublicKey:i}=this.#t,s=await i({credentialId:(0,Lt.arrayBufferToUint8Array)(n)});this.#t=ra.#r({credential:new A2({rawId:(0,Lt.arrayBufferToUint8Array)(n),cose:s})})},step:1,onProgress:this.#e}),await Id({fn:async()=>{let{response:n}=r,{clientDataJSON:i}=n,{authenticatorData:s,signature:a}="authenticatorData"in n&&"signature"in n?n:{};if((0,Lt.isNullish)(s))throw new G_;if((0,Lt.isNullish)(a))throw new G_;let o=na.Cbor.encode({authenticator_data:s,client_data_json:new TextDecoder().decode(i),signature:(0,Lt.arrayBufferToUint8Array)(a)});if((0,Lt.isNullish)(o))throw new V2;return Object.assign(o,{__signature__:void 0}),o},step:2,onProgress:this.#e})}},K2=async()=>(0,ry.nonNullish)(window.PublicKeyCredential)&&"isUserVerifyingPlatformAuthenticatorAvailable"in PublicKeyCredential?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1;var _m=be(De(),1);var Yi=class{callbacks=[];populate(t){this.callbacks.forEach(({callback:r})=>r(t))}subscribe(t){let r=Symbol();return this.callbacks.push({id:r,callback:t}),()=>this.callbacks=this.callbacks.filter(({id:n})=>n!==r)}};var hr=class e extends Yi{static instance;authUser=null;constructor(){super()}static getInstance(){return e.instance||(e.instance=new e),e.instance}set(t){this.authUser=t,this.populate(t)}get(){return this.authUser}subscribe(t){let r=super.subscribe(t);return t(this.authUser),r}reset(){this.authUser=null,this.populate(this.authUser)}};var Pd=({message:e,detail:t})=>{let r=new CustomEvent(e,{detail:t,bubbles:!0});document.dispatchEvent(r)};var hm=be(De(),1);var ay=be(gt(),1),fc=be(De(),1);var dc=be(De(),1);var iy=be(gt(),1),Fd=be(De(),1);var Ji="http://127.0.0.1:5987",ny="rdmx6-jaaaa-aaaaa-aaadq-cai";var sy=async({identity:e,container:t})=>{let n=(0,Fd.nonNullish)(t)&&t!==!1?t===!0?Ji:t:"https://icp-api.io",i=(0,Fd.nonNullish)(t);return await iy.HttpAgent.create({identity:e,shouldFetchRootKey:i,host:n})};var Zi=class e{static instance;#e=void 0;constructor(){}static getInstance(){return(0,dc.isNullish)(e.instance)&&(e.instance=new e),e.instance}async getAgent({identity:t,...r}){let n=t.getPrincipal().toText();if((0,dc.isNullish)(this.#e)||(0,dc.isNullish)(this.#e[n])){let i=await sy({identity:t,...r});return this.#e={...this.#e??{},[n]:i},i}return this.#e[n]}reset(){this.#e=null}};var Xi=class e{static instance;#e=void 0;constructor(){}static getInstance(){return(0,fc.isNullish)(e.instance)&&(e.instance=new e),e.instance}async getActor({satelliteId:t,identity:r,actorKey:n,...i}){let s=`${n}#${r.getPrincipal().toText()}#${t};`;if((0,fc.isNullish)(this.#e)||(0,fc.isNullish)(this.#e[s])){let a=await this.createActor({satelliteId:t,identity:r,...i});return this.#e={...this.#e??{},[s]:a},a}return this.#e[s]}reset(){this.#e=null}async createActor({idlFactory:t,satelliteId:r,...n}){let i=await Zi.getInstance().getAgent(n);return ay.Actor.createActor(t,{agent:i,canisterId:r})}};var oy=e=>(e.preventDefault(),e.returnValue="Are you sure you want to exit?"),G2=()=>{window.addEventListener("beforeunload",oy,{capture:!0})},$2=()=>{window.removeEventListener("beforeunload",oy,{capture:!0})},Ud=async({fn:e})=>{try{return G2(),await e()}finally{$2()}};var la=be(De(),1);var nr=class e extends Yi{static instance;env;constructor(){super()}static getInstance(){return e.instance||(e.instance=new e),e.instance}set(t){this.env=t,this.populate(t)}get(){return this.env}reset(){this.env=null}subscribe(t){let r=super.subscribe(t);return t(this.env),r}};var cy=BigInt(144e11),uy=!1,ly={width:576,height:576},dy={width:505,height:705},fy="internetcomputer.org";var Vd=be(De(),1);var pc=be(De(),1),py=async e=>{let t=new Blob([JSON.stringify(e,pc.jsonReplacer)],{type:"application/json; charset=utf-8"});return new Uint8Array(await t.arrayBuffer())},hc=async e=>{let t=new Blob([e instanceof Uint8Array?e:new Uint8Array(e)],{type:"application/json; charset=utf-8"});return JSON.parse(await t.text(),pc.jsonReviver)},_c=()=>typeof window<"u";var yc=({width:e,height:t})=>{if(!_c()||(0,Vd.isNullish)(window)||(0,Vd.isNullish)(window.top))return;let{top:{innerWidth:r,innerHeight:n}}=window,i=n/2+screenY-t/2,s=r/2+screenX-e/2;return`toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=${e}, height=${t}, top=${i}, left=${s}`};var Vy=be(Ic(),1),Cy=be(De(),1);var Zr=async({fn:e,step:t,onProgress:r})=>{r?.({step:t,state:"in_progress"});try{let n=await e();return r?.({step:t,state:"success"}),n}catch(n){throw r?.({step:t,state:"error"}),n}};var Uy=(r=>(r[r.AuthorizingWithProvider=0]="AuthorizingWithProvider",r[r.CreatingOrRetrievingUser=1]="CreatingOrRetrievingUser",r))(Uy||{});var Bc=class extends Error{},li=class extends Error{},Pc=class extends Error{},Fc=class extends Error{},Uc=class extends Error{},Vc=class extends Error{},Cc=class extends Error{},qc=class extends Error{};var ts=class{async signIn({options:t,authClient:r,initAuth:n}){await Zr({fn:async()=>await this.#e({options:t,authClient:r}),step:0,onProgress:t?.onProgress}),await Zr({fn:async()=>await n({provider:this.id}),step:1,onProgress:t?.onProgress})}#e({options:t,authClient:r}){return new Promise(async(n,i)=>{if((0,Cy.isNullish)(r)){i(new li("No client is ready to perform a sign-in. Have you initialized the Satellite?"));return}await r.login({onSuccess:n,onError:s=>{if(s===Vy.ERROR_USER_INTERRUPT){i(new Pc(s));return}i(new Bc(s))},maxTimeToLive:t?.maxTimeToLiveInNanoseconds??cy,allowPinAuthentication:t?.allowPin??uy,...t?.derivationOrigin!==void 0&&{derivationOrigin:t.derivationOrigin},...this.signInOptions({windowed:t?.windowed})})})}};var Dc=class extends ts{#e;constructor({domain:t}){super(),this.#e=t}get id(){return"internet_identity"}signInOptions({windowed:t}){let r=()=>{let n=nr.getInstance().get()?.container;if((0,la.isNullish)(n)||n===!1)return`https://identity.${this.#e??fy}`;let i=nr.getInstance().get(),s=(0,la.nonNullish)(i)&&(0,la.nonNullish)(i?.internetIdentityId)?i.internetIdentityId:ny,{host:a,protocol:o}=new URL(n===!0?Ji:n);return/apple/i.test(navigator?.vendor)?`${o}//${a}?canisterId=${s}`:`${o}//${s}.${a.replace("127.0.0.1","localhost")}`};return{...t!==!1&&{windowOpenerFeatures:yc(ly)},identityProvider:r()}}};var kc=class extends ts{#e;#t;constructor({appName:t,logoUrl:r}){super(),this.#e=t,this.#t=r}get id(){return"nfid"}signInOptions({windowed:t}){return{...t!==!1&&{windowOpenerFeatures:yc(dy)},identityProvider:`https://nfid.one/authenticate/?applicationName=${encodeURI(this.#e)}&applicationLogo=${encodeURI(this.#t)}`}}};var cm=be(gt(),1),is=be(Ic(),1),Qr=be(Yd(),1),ns=be(De(),1);var Xr={certified:!1};var qy=be(gt(),1),Dy=be(De(),1);var tt=e=>(0,Dy.nonNullish)(e)?e:Mc()??new qy.AnonymousIdentity;var Sr=be(De(),1);var Ly=be(De(),1);var LE=be(gt(),1),HE=be(De(),1),KE=be(De(),1),GE=be(gt(),1);var ky=({IDL:e})=>{let t=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),r=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}),s=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),a=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(s),description:e.Opt(e.Text),created_at:e.Opt(s)}),o=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(a),paginate:e.Opt(o)}),d=e.Record({controllers:e.Vec(e.Principal)}),f=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),p=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:f,expires_at:e.Opt(e.Nat64)}),m=e.Record({version:e.Opt(e.Nat64)}),b=e.Variant({Db:e.Null,Storage:e.Null}),l=e.Record({version:e.Opt(e.Nat64)}),A=e.Record({proposal_ids:e.Vec(e.Nat)}),v=e.Record({cycles:e.Nat,destination_id:e.Principal}),F=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}),C=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),E=e.Record({key:F,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,C)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),H=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),x=e.Record({allowed_callers:e.Vec(e.Principal)}),q=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(H),rules:e.Opt(x)}),K=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),G=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}),ae=e.Variant({Deny:e.Null,Allow:e.Null}),Q=e.Record({status_code:e.Nat16,location:e.Text}),ne=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(ae),redirects:e.Opt(e.Vec(e.Tuple(e.Text,Q)))}),w=e.Record({db:e.Opt(G),authentication:e.Opt(q),storage:ne}),g=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)}),S=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),R=e.Record({clear_existing_assets:e.Opt(e.Bool)}),I=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),j=e.Variant({AssetsUpgrade:R,SegmentsDeployment:I}),Y=e.Record({status:S,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:j}),oe=e.Variant({Heap:e.Null,Stable:e.Null}),se=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),z=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),U=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(oe),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:se,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(z),write:se,max_changes_per_user:e.Opt(e.Nat32)}),_=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)}),Z=e.Record({memory:oe,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}),re=e.Variant({Callback:e.Record({token:Z,callback:e.Func([],[],["query"])})}),le=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(re),status_code:e.Nat16}),X=e.Record({token:e.Opt(Z),body:e.Vec(e.Nat8)}),u=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}),h=e.Record({batch_id:e.Nat}),y=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,E)),items_length:e.Nat64}),P=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),O=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,g)),items_length:e.Nat64}),B=e.Record({desc:e.Bool}),M=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),T=e.Record({order:e.Opt(B),paginate:e.Opt(M)}),V=e.Record({proposal_id:e.Nat}),L=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(V,Y)),items_length:e.Nat64}),k=e.Record({include_system:e.Bool}),J=e.Record({matcher:e.Opt(k)}),te=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,U)),items_length:e.Nat64}),de=e.Record({stable:e.Nat64,heap:e.Nat64}),ge=e.Record({version:e.Opt(e.Nat64),internet_identity:e.Opt(H),rules:e.Opt(x)}),Ie=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:f,expires_at:e.Opt(e.Nat64)}),Ue=e.Record({controller:Ie,controllers:e.Vec(e.Principal)}),_e=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(K)}),fe=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),Ke=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(oe),max_size:e.Opt(e.Nat),read:se,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(z),write:se,max_changes_per_user:e.Opt(e.Nat32)}),Ht=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(ae),redirects:e.Opt(e.Vec(e.Tuple(e.Text,Q)))}),Ut=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Vt=e.Record({chunk_id:e.Nat});return e.Service({commit_asset_upload:e.Func([t],[],[]),commit_proposal:e.Func([r],[e.Null],[]),commit_proposal_asset_upload:e.Func([t],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(t)],[],[]),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([d],[e.Vec(e.Tuple(e.Principal,p))],[]),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([b,e.Text,l],[],[]),delete_proposal_assets:e.Func([A],[],[]),deposit_cycles:e.Func([v],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(E)],["query"]),get_auth_config:e.Func([],[e.Opt(q)],["query"]),get_config:e.Func([],[w],[]),get_db_config:e.Func([],[e.Opt(G)],["query"]),get_doc:e.Func([e.Text,e.Text],[e.Opt(g)],["query"]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(E)))],["query"]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(g)))],["query"]),get_proposal:e.Func([e.Nat],[e.Opt(Y)],["query"]),get_rule:e.Func([b,e.Text],[e.Opt(U)],["query"]),get_storage_config:e.Func([],[ne],["query"]),http_request:e.Func([_],[le],["query"]),http_request_streaming_callback:e.Func([Z],[X],["query"]),init_asset_upload:e.Func([u],[h],[]),init_proposal:e.Func([j],[e.Nat,Y],[]),init_proposal_asset_upload:e.Func([u,e.Nat],[h],[]),init_proposal_many_assets_upload:e.Func([e.Vec(u),e.Nat],[e.Vec(e.Tuple(e.Text,h))],[]),list_assets:e.Func([e.Text,c],[y],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,p))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,P))],["query"]),list_docs:e.Func([e.Text,c],[O],["query"]),list_proposals:e.Func([T],[L],["query"]),list_rules:e.Func([b,J],[te],["query"]),memory_size:e.Func([],[de],["query"]),reject_proposal:e.Func([r],[e.Null],[]),set_auth_config:e.Func([ge],[q],[]),set_controllers:e.Func([Ue],[e.Vec(e.Tuple(e.Principal,p))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([_e],[G],[]),set_doc:e.Func([e.Text,e.Text,fe],[g],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,fe))],[e.Vec(e.Tuple(e.Text,g))],[]),set_rule:e.Func([b,e.Text,Ke],[U],[]),set_storage_config:e.Func([Ht],[ne],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Y],[]),upload_asset_chunk:e.Func([Ut],[Vt],[]),upload_proposal_asset_chunk:e.Func([Ut],[Vt],[])})},My=({IDL:e})=>{let t=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),r=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}),s=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),a=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(s),description:e.Opt(e.Text),created_at:e.Opt(s)}),o=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(a),paginate:e.Opt(o)}),d=e.Record({controllers:e.Vec(e.Principal)}),f=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),p=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:f,expires_at:e.Opt(e.Nat64)}),m=e.Record({version:e.Opt(e.Nat64)}),b=e.Variant({Db:e.Null,Storage:e.Null}),l=e.Record({version:e.Opt(e.Nat64)}),A=e.Record({proposal_ids:e.Vec(e.Nat)}),v=e.Record({cycles:e.Nat,destination_id:e.Principal}),F=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}),C=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),E=e.Record({key:F,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,C)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),H=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),x=e.Record({allowed_callers:e.Vec(e.Principal)}),q=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(H),rules:e.Opt(x)}),K=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),G=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}),ae=e.Variant({Deny:e.Null,Allow:e.Null}),Q=e.Record({status_code:e.Nat16,location:e.Text}),ne=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(ae),redirects:e.Opt(e.Vec(e.Tuple(e.Text,Q)))}),w=e.Record({db:e.Opt(G),authentication:e.Opt(q),storage:ne}),g=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)}),S=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),R=e.Record({clear_existing_assets:e.Opt(e.Bool)}),I=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),j=e.Variant({AssetsUpgrade:R,SegmentsDeployment:I}),Y=e.Record({status:S,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:j}),oe=e.Variant({Heap:e.Null,Stable:e.Null}),se=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),z=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),U=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(oe),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:se,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(z),write:se,max_changes_per_user:e.Opt(e.Nat32)}),_=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)}),Z=e.Record({memory:oe,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}),re=e.Variant({Callback:e.Record({token:Z,callback:e.Func([],[],[])})}),le=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(re),status_code:e.Nat16}),X=e.Record({token:e.Opt(Z),body:e.Vec(e.Nat8)}),u=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}),h=e.Record({batch_id:e.Nat}),y=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,E)),items_length:e.Nat64}),P=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),O=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,g)),items_length:e.Nat64}),B=e.Record({desc:e.Bool}),M=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),T=e.Record({order:e.Opt(B),paginate:e.Opt(M)}),V=e.Record({proposal_id:e.Nat}),L=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(V,Y)),items_length:e.Nat64}),k=e.Record({include_system:e.Bool}),J=e.Record({matcher:e.Opt(k)}),te=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,U)),items_length:e.Nat64}),de=e.Record({stable:e.Nat64,heap:e.Nat64}),ge=e.Record({version:e.Opt(e.Nat64),internet_identity:e.Opt(H),rules:e.Opt(x)}),Ie=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:f,expires_at:e.Opt(e.Nat64)}),Ue=e.Record({controller:Ie,controllers:e.Vec(e.Principal)}),_e=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(K)}),fe=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),Ke=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(oe),max_size:e.Opt(e.Nat),read:se,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(z),write:se,max_changes_per_user:e.Opt(e.Nat32)}),Ht=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(ae),redirects:e.Opt(e.Vec(e.Tuple(e.Text,Q)))}),Ut=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Vt=e.Record({chunk_id:e.Nat});return e.Service({commit_asset_upload:e.Func([t],[],[]),commit_proposal:e.Func([r],[e.Null],[]),commit_proposal_asset_upload:e.Func([t],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(t)],[],[]),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([d],[e.Vec(e.Tuple(e.Principal,p))],[]),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([b,e.Text,l],[],[]),delete_proposal_assets:e.Func([A],[],[]),deposit_cycles:e.Func([v],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(E)],[]),get_auth_config:e.Func([],[e.Opt(q)],[]),get_config:e.Func([],[w],[]),get_db_config:e.Func([],[e.Opt(G)],[]),get_doc:e.Func([e.Text,e.Text],[e.Opt(g)],[]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(E)))],[]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(g)))],[]),get_proposal:e.Func([e.Nat],[e.Opt(Y)],[]),get_rule:e.Func([b,e.Text],[e.Opt(U)],[]),get_storage_config:e.Func([],[ne],[]),http_request:e.Func([_],[le],[]),http_request_streaming_callback:e.Func([Z],[X],[]),init_asset_upload:e.Func([u],[h],[]),init_proposal:e.Func([j],[e.Nat,Y],[]),init_proposal_asset_upload:e.Func([u,e.Nat],[h],[]),init_proposal_many_assets_upload:e.Func([e.Vec(u),e.Nat],[e.Vec(e.Tuple(e.Text,h))],[]),list_assets:e.Func([e.Text,c],[y],[]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,p))],[]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,P))],[]),list_docs:e.Func([e.Text,c],[O],[]),list_proposals:e.Func([T],[L],[]),list_rules:e.Func([b,J],[te],[]),memory_size:e.Func([],[de],[]),reject_proposal:e.Func([r],[e.Null],[]),set_auth_config:e.Func([ge],[q],[]),set_controllers:e.Func([Ue],[e.Vec(e.Tuple(e.Principal,p))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([_e],[G],[]),set_doc:e.Func([e.Text,e.Text,fe],[g],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,fe))],[e.Vec(e.Tuple(e.Text,g))],[]),set_rule:e.Func([b,e.Text,Ke],[U],[]),set_storage_config:e.Func([Ht],[ne],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Y],[]),upload_asset_chunk:e.Func([Ut],[Vt],[]),upload_proposal_asset_chunk:e.Func([Ut],[Vt],[])})};var jc=be(De(),1);var jy=({satelliteId:e,container:t})=>{let{satelliteId:r}=pf({satelliteId:e}),{container:n}=hf({container:t});if((0,jc.nonNullish)(n)&&n!==!1){let{host:i,protocol:s}=new URL(n===!0?Ji:n);return`${s}//${r??"unknown"}.${i.replace("127.0.0.1","localhost")}`}return`https://${r??"unknown"}.icp0.io`},pf=({satelliteId:e})=>(0,jc.nonNullish)(e)?{satelliteId:e}:nr.getInstance().get()??{satelliteId:void 0},hf=({container:e})=>(0,jc.nonNullish)(e)?{container:e}:nr.getInstance().get()??{container:void 0};var dt=({satellite:e,options:{certified:t}})=>Ky({idlFactory:t?My:ky,actorKey:`stock#${t?"update":"query"}`,...e}),Hy=({idlFactory:e,...t})=>Ky({idlFactory:e,actorKey:"extended#query",...t}),Ky=async({satelliteId:e,container:t,...r})=>{let{satelliteId:n}=pf({satelliteId:e});(0,Ly.assertNonNullish)(n,"No satellite ID defined. Did you initialize Juno?");let{container:i}=hf({container:t});return await Xi.getInstance().getActor({satelliteId:n,container:i,...r})};var $y=be(Ct(),1),st=be(De(),1);var Gy=e=>{if((0,st.isNullish)(e))return(0,st.toNullable)();switch(e.matcher){case"equal":return(0,st.toNullable)({Equal:e.timestamp});case"greaterThan":return(0,st.toNullable)({GreaterThan:e.timestamp});case"lessThan":return(0,st.toNullable)({LessThan:e.timestamp});case"between":return(0,st.toNullable)({Between:[e.timestamps.start,e.timestamps.end]});default:throw new qc("Invalid list matcher for timestamp",e)}},jn=({matcher:e,paginate:t,order:r,owner:n})=>({matcher:(0,st.isNullish)(e)?[]:[{key:(0,st.toNullable)(e.key),description:(0,st.toNullable)(e.description),created_at:Gy(e.createdAt),updated_at:Gy(e.updatedAt)}],paginate:(0,st.toNullable)((0,st.isNullish)(t)?void 0:{start_after:(0,st.toNullable)(t.startAfter),limit:(0,st.toNullable)((0,st.isNullish)(t.limit)?void 0:BigInt(t.limit))}),order:(0,st.toNullable)((0,st.isNullish)(r)?void 0:{desc:r.desc,field:r.field==="created_at"?{CreatedAt:null}:r.field==="updated_at"?{UpdatedAt:null}:{Keys:null}}),owner:(0,st.toNullable)((0,st.isNullish)(n)?void 0:typeof n=="string"?$y.Principal.fromText(n):n)});var Wy=async({data:e})=>{try{return await hc(e)}catch(t){console.error("The data parsing has failed, mapping to undefined as a fallback.",t);return}};var di=be(De(),1);var _f=async e=>{let{data:t,version:r,description:n}=e;return{description:(0,di.toNullable)(n),data:await py(t),version:(0,di.toNullable)(r)}},yf=e=>{let{version:t}=e;return{version:(0,di.toNullable)(t)}},da=async({doc:e,key:t})=>{let{owner:r,version:n,description:i,data:s,...a}=e;return{key:t,description:(0,di.fromNullable)(i),owner:r.toText(),data:await hc(s),version:(0,di.fromNullable)(n),...a}};var zy=async({collection:e,key:t,...r})=>{let{get_doc:n}=await dt(r),i=(0,Sr.fromNullable)(await n(e,t));if(!(0,Sr.isNullish)(i))return da({doc:i,key:t})},Yy=async({docs:e,...t})=>{let{get_many_docs:r}=await dt(t),n=e.map(({collection:a,key:o})=>[a,o]),i=await r(n),s=[];for(let[a,o]of i){let c=(0,Sr.fromNullable)(o);s.push((0,Sr.nonNullish)(c)?await da({key:a,doc:c}):void 0)}return s},Jy=async({collection:e,doc:t,...r})=>{let{set_doc:n}=await dt(r),{key:i}=t,s=await _f(t),a=await n(e,i,s);return await da({key:i,doc:a})},Zy=async({docs:e,...t})=>{let{set_many_docs:r}=await dt(t),n=[];for(let{collection:a,doc:o}of e){let{key:c}=o;n.push([a,c,await _f(o)])}let i=await r(n),s=[];for(let[a,o]of i)s.push(await da({key:a,doc:o}));return s},Xy=async({collection:e,doc:t,...r})=>{let{del_doc:n}=await dt(r),{key:i}=t;return n(e,i,yf(t))},Qy=async({docs:e,...t})=>{let{del_many_docs:r}=await dt(t),n=e.map(({collection:i,doc:s})=>[i,s.key,yf(s)]);await r(n)},em=async({collection:e,filter:t,...r})=>{let{del_filtered_docs:n}=await dt(r);return n(e,jn(t))},tm=async({collection:e,filter:t,...r})=>{let{list_docs:n}=await dt(r),{items:i,items_page:s,items_length:a,matches_length:o,matches_pages:c}=await n(e,jn(t)),d=[];for(let[f,p]of i){let{data:m,owner:b,description:l,version:A,...v}=p;d.push({key:f,description:(0,Sr.fromNullable)(l),owner:b.toText(),data:await Wy({data:m}),version:(0,Sr.fromNullable)(A),...v})}return{items:d,items_length:a,items_page:(0,Sr.fromNullable)(s),matches_length:o,matches_pages:(0,Sr.fromNullable)(c)}},rm=async({collection:e,filter:t,...r})=>{let{count_docs:n}=await dt(r);return n(e,jn(t))};var Lc=async({satellite:e,options:t,...r})=>{let n=tt(e?.identity);return await zy({...r,satellite:{...e,identity:n},options:t??Xr})},I4=async({satellite:e,options:t,...r})=>{let n=tt(e?.identity);return await Yy({...r,satellite:{...e,identity:n},options:t??Xr})},nm=async({satellite:e,...t})=>{let r=tt(e?.identity);return await Jy({...t,satellite:{...e,identity:r},options:{certified:!0}})},im=async({satellite:e,...t})=>{let r=tt(e?.identity);return await Zy({...t,satellite:{...e,identity:r},options:{certified:!0}})},B4=async({satellite:e,...t})=>{let r=tt(e?.identity);return await Xy({...t,satellite:{...e,identity:r},options:{certified:!0}})},P4=async({satellite:e,...t})=>{let r=tt(e?.identity);return await Qy({...t,satellite:{...e,identity:r},options:{certified:!0}})},F4=async({satellite:e,filter:t,...r})=>{let n=tt(e?.identity);return await em({...r,filter:t??{},satellite:{...e,identity:n},options:{certified:!0}})},U4=async({satellite:e,options:t,filter:r,...n})=>{let i=tt(e?.identity);return await tm({...n,filter:r??{},satellite:{...e,identity:i},options:t??Xr})},V4=async({satellite:e,options:t,filter:r,...n})=>{let i=tt(e?.identity);return await rm({...n,filter:r??{},satellite:{...e,identity:i},options:t??Xr})};var rs=be(De(),1);var sm=async({delegationIdentity:e,passkeyIdentity:t,satelliteId:r})=>{let n=t.getCredential().getAAGUID(),[i,s]=await im({docs:[{collection:"#user",doc:{key:e.getPrincipal().toText(),data:{provider:"webauthn",providerData:{webauthn:{...(0,rs.nonNullish)(n)&&{aaguid:(0,rs.uint8ArrayToArrayOfNumber)(n)}}}}}},{collection:"#user-webauthn",doc:{key:t.getCredential().getCredentialIdText(),data:{publicKey:(0,rs.arrayBufferToUint8Array)(t.getPublicKey().toDer())}}}],satellite:{identity:e,satelliteId:r}});return i};var am=(s=>(s[s.RequestingUserCredential=0]="RequestingUserCredential",s[s.FinalizingCredential=1]="FinalizingCredential",s[s.Signing=2]="Signing",s[s.FinalizingSession=3]="FinalizingSession",s[s.RetrievingUser=4]="RetrievingUser",s))(am||{}),om=(a=>(a[a.CreatingUserCredential=0]="CreatingUserCredential",a[a.ValidatingUserCredential=1]="ValidatingUserCredential",a[a.FinalizingCredential=2]="FinalizingCredential",a[a.Signing=3]="Signing",a[a.FinalizingSession=4]="FinalizingSession",a[a.RegisteringUser=5]="RegisteringUser",a))(om||{});var fa=class{get id(){return"webauthn"}async signUp({options:{onProgress:t,maxTimeToLiveInMilliseconds:r,passkey:n}={},loadAuthWithUser:i}){let{satelliteId:s}=nr.getInstance().get()??{satelliteId:void 0};if((0,ns.isNullish)(s))throw new li("Satellite ID not set. Have you initialized the Satellite?");let a=({step:A,state:v})=>{switch(A){case Vn.RequestingUserCredential:t?.({step:1,state:v});break;case Vn.FinalizingCredential:t?.({step:2,state:v});break;case Vn.Signing:t?.({step:3,state:v});break}},c=await Zr({fn:async()=>await Bd.createWithNewCredential({onProgress:a,passkeyOptions:n}),step:0,onProgress:t}),{delegationIdentity:d,sessionKey:f}=await this.#e({identity:c,maxTimeToLiveInMilliseconds:r}),m=await Zr({fn:async()=>await sm({delegationIdentity:d,passkeyIdentity:c,satelliteId:s}),step:5,onProgress:t});await Zr({fn:async()=>await this.#t({delegationIdentity:d,sessionKey:f}),step:4,onProgress:t}),await Zr({fn:async()=>await i({user:m}),step:5,onProgress:t})}async signIn({options:{onProgress:t,maxTimeToLiveInMilliseconds:r}={},loadAuth:n}){let{satelliteId:i}=nr.getInstance().get()??{satelliteId:void 0};if((0,ns.isNullish)(i))throw new li("Satellite ID not set. Have you initialized the Satellite?");let s=async({credentialId:p})=>{let m=await Lc({collection:"#user-webauthn",key:(0,ns.uint8ArrayToBase64)(p),options:{certified:!0},satellite:{identity:new cm.AnonymousIdentity,satelliteId:i}});if((0,ns.isNullish)(m))throw new Uc("No public key found for the selected passkey.");let{data:b}=m,{publicKey:l}=b;return(0,Qr.unwrapDER)(l.buffer,Qr.DER_COSE_OID)},a=({step:p,state:m})=>{switch(p){case Vn.RequestingUserCredential:t?.({step:0,state:m});break;case Vn.FinalizingCredential:t?.({step:1,state:m});break;case Vn.Signing:t?.({step:2,state:m});break}},o=await Bd.createWithExistingCredential({retrievePublicKey:s,onProgress:a}),{delegationIdentity:c,sessionKey:d}=await this.#e({identity:o,maxTimeToLiveInMilliseconds:r});await Zr({fn:async()=>await this.#t({delegationIdentity:c,sessionKey:d}),step:3,onProgress:t}),await Zr({fn:n,step:4,onProgress:t})}async#e({identity:t,maxTimeToLiveInMilliseconds:r}){let n=await Qr.ECDSAKeyIdentity.generate({extractable:!1}),i=r??144e5,s=await Qr.DelegationChain.create(t,n.getPublicKey(),new Date(Date.now()+i));return{delegationIdentity:Qr.DelegationIdentity.fromDelegation(n,s),sessionKey:n}}async#t({sessionKey:t,delegationIdentity:r}){let n=new is.IdbStorage;await Promise.all([n.set(is.KEY_STORAGE_KEY,t.getKeyPair()),n.set(is.KEY_STORAGE_DELEGATION,JSON.stringify(r.getDelegation().toJSON()))])}};var ss=be(Ic(),1),pa=()=>ss.AuthClient.create({idleOptions:{disableIdle:!0,disableDefaultIdleCallback:!0}}),um=async()=>(await new ss.IdbStorage().remove(ss.KEY_STORAGE_KEY),await pa());var ha=be(De(),1);var mf=({error:e,type:t})=>typeof e=="string"?e.includes(t):e instanceof Error?e.message.includes(t):!1;var lm="juno.datastore.error.user.cannot_update";var dm=async({provider:e})=>{let{user:t,userId:r}=await gf();if((0,ha.nonNullish)(t))return t;try{return await WE({userId:r,provider:e})}catch(n){if(mf({error:n,type:lm})){let i=await fm({userId:r});if((0,ha.nonNullish)(i))return i}throw n}},gf=async()=>{let e=Mc();if((0,ha.isNullish)(e))throw new Cc("No identity to initialize the user. Have you initialized Juno?");let t=e.getPrincipal().toText(),r=await fm({userId:t});return{userId:t,user:r}},fm=({userId:e})=>Lc({collection:"#user",key:e}),WE=({userId:e,...t})=>nm({collection:"#user",doc:{key:e,data:t}});var yr,bf=async()=>{await wf({fn:async()=>{let{user:t}=await gf();hr.getInstance().set(t??null)}})},zE=async({user:e})=>{await wf({fn:async()=>{hr.getInstance().set(e)}})},pm=async({provider:e})=>{await wf({fn:async()=>{let r=await dm({provider:e});hr.getInstance().set(r)}})},wf=async({fn:e})=>{if(yr=await pa(),!await yr.isAuthenticated()){yr=await um();return}await e()},YE=async e=>{let t=async()=>await ZE(e);if(Object.values(e)[0].context?.windowGuard===!1){await t();return}await Ud({fn:t})},JE=async e=>{let t=async()=>await XE(e);if(Object.values(e)?.[0].context?.windowGuard===!1){await t();return}await Ud({fn:t})},ZE=async e=>{if("webauthn"in e){let{webauthn:{options:t}}=e;await new fa().signIn({options:t,loadAuth:bf});return}if("nfid"in e){let{nfid:{options:t}}=e,{appName:r,logoUrl:n,...i}=t??{};await new kc({appName:r,logoUrl:n}).signIn({options:i,authClient:yr,initAuth:pm});return}if("internet_identity"in e){let{internet_identity:{options:t}}=e,{domain:r,...n}=t??{};await new Dc({domain:r}).signIn({options:n,authClient:yr,initAuth:pm});return}throw new Fc("An unknown or unsupported provider was provided for sign-in.")},XE=async e=>{if("webauthn"in e){let{webauthn:{options:t}}=e;await new fa().signUp({options:t,loadAuthWithUser:zE});return}throw new Vc("An unknown or unsupported provider was provided for sign-up.")},xf=async e=>{await QE(),yr=await pa(),e?.windowReload!==!1&&window.location.reload()},QE=async()=>{await yr?.logout(),yr=null,hr.getInstance().reset(),Xi.getInstance().reset(),Zi.getInstance().reset()},Mc=()=>yr?.getIdentity(),eO=async()=>(yr??await pa()).getIdentity(),tO=async()=>{let e=hr.getInstance().get();return(0,hm.isNullish)(e)||!(await yr?.isAuthenticated()??!1)?null:yr?.getIdentity()??null};var ym=e=>{let t=e===!0?"./workers/auth.worker.js":e,r=new Worker(t),n=async()=>{Pd({message:"junoSignOutAuthTimer"}),await xf()};return r.onmessage=async({data:i})=>{let{msg:s,data:a}=i;switch(s){case"junoSignOutAuthTimer":await n();return;case"junoDelegationRemainingTime":Pd({message:"junoDelegationRemainingTime",detail:a?.authRemainingTime});return}},hr.getInstance().subscribe(i=>{if((0,_m.isNullish)(i)){r.postMessage({msg:"junoStopAuthTimer"});return}r.postMessage({msg:"junoStartAuthTimer"})})};var mm=()=>{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()},gm=()=>{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 TR=async({idlFactory:e,satellite:t})=>{let r=tt(t?.identity);return await Hy({idlFactory:e,...t,identity:r})};var ya=be(De(),1);var _a=be(De(),1);var as=be(De(),1);var bm=async({asset:{data:e,headers:t,...r},actor:n,progress:i})=>{let{init_asset_upload:s,upload_asset_chunk:a,commit_asset_upload:o}=n,{batch_id:c}=await s(rO(r));i?.onInitiatedBatch();let{chunkIds:d}=await sO({data:e,uploadFn:a,batchId:c});i?.onUploadedFileChunks(r.fullPath),await iO({commitFn:o,batchId:c,data:e,headers:t,chunkIds:d}),i?.onCommittedBatch()};var rO=({filename:e,collection:t,token:r,fullPath:n,encoding:i,description:s})=>({collection:t,full_path:n,name:e,token:(0,as.toNullable)(r),encoding_type:(0,as.toNullable)(i),description:(0,as.toNullable)(s)}),nO=({batchId:e,chunkIds:t,headers:r,data:n})=>{let i=r.find(([s,a])=>s.toLowerCase()==="content-type")===void 0&&n.type!==void 0&&n.type!==""?[["Content-Type",n.type]]:void 0;return{batch_id:e,chunk_ids:t.map(({chunk_id:s})=>s),headers:[...r,...i??[]]}},iO=async({commitFn:e,...t})=>{let r=nO(t);await e(r)},sO=async({data:e,uploadFn:t,batchId:r})=>{let n=[],i=_c()?new Blob([await e.arrayBuffer()]):e,s=0n;for(let o=0;o<i.size;o+=19e5){let c=i.slice(o,o+19e5);n.push({batchId:r,chunk:c,uploadFn:t,orderId:s}),s++}let a=[];for await(let o of aO({uploadChunks:n}))a=[...a,...o];return{chunkIds:a}};async function*aO({uploadChunks:e,limit:t=12}){for(let r=0;r<e.length;r=r+t){let n=e.slice(r,r+t);yield await Promise.all(n.map(i=>oO(i)))}}var oO=async({batchId:e,chunk:t,uploadFn:r,orderId:n})=>r({batch_id:e,content:new Uint8Array(await t.arrayBuffer()),order_id:(0,as.toNullable)(n)});var wm=async({asset:e,...t})=>{let r=await dt(t);await bm({actor:r,asset:e})},xm=async({collection:e,filter:t,...r})=>{let{list_assets:n}=await dt(r),{items:i,items_length:s,items_page:a,matches_length:o,matches_pages:c}=await n(e,jn(t));return{items:i.map(([d,f])=>f),items_length:s,items_page:(0,_a.fromNullable)(a),matches_length:o,matches_pages:(0,_a.fromNullable)(c)}},Tm=async({collection:e,filter:t,...r})=>{let{count_assets:n}=await dt(r);return n(e,jn(t))},Nm=async({collection:e,fullPath:t,...r})=>(await dt(r)).del_asset(e,t),Em=async({assets:e,satellite:t})=>{let{del_many_assets:r}=await dt({satellite:t,options:{certified:!0}}),n=e.map(({collection:i,fullPath:s})=>[i,s]);await r(n)},Om=async({collection:e,filter:t,...r})=>{let{del_filtered_assets:n}=await dt(r);return n(e,jn(t))},vm=async({collection:e,fullPath:t,...r})=>{let{get_asset:n}=await dt(r);return(0,_a.fromNullable)(await n(e,t))},Rm=async({assets:e,...t})=>{let{get_many_assets:r}=await dt(t),n=e.map(({collection:s,fullPath:a})=>[s,a]);return(await r(n)).map(([s,a])=>(0,_a.fromNullable)(a))};var Am=e=>btoa([...e].map(t=>String.fromCharCode(t)).join(""));var CR=e=>Sm(e),qR=e=>Sm({filename:e.data.name,...e}),Sm=async({filename:e,data:t,collection:r,headers:n=[],fullPath:i,token:s,satellite:a,encoding:o,description:c})=>{let d=tt(a?.identity),f=decodeURI(e),p=i??`/${r}/${f}`,m={...a,identity:d};return await wm({asset:{data:t,filename:f,collection:r,token:s,headers:n,fullPath:p,encoding:o,description:c},satellite:m,options:{certified:!0}}),{downloadUrl:Im({satellite:m,assetKey:{fullPath:p,token:s}}),fullPath:p,name:f}},DR=async({collection:e,filter:t,satellite:r,options:n})=>{let i={...r,identity:tt(r?.identity)},{items:s,...a}=await xm({collection:e,filter:t??{},satellite:i,options:n??Xr}),o=s.map(({key:{full_path:c,token:d,name:f,owner:p,description:m},headers:b,encodings:l,created_at:A,updated_at:v})=>{let F=(0,ya.fromNullable)(d);return{fullPath:c,description:(0,ya.fromNullable)(m),name:f,downloadUrl:Im({satellite:i,assetKey:{fullPath:c,token:F}}),token:F,headers:b,encodings:l.reduce((C,[E,{modified:H,sha256:x,total_length:q}])=>({...C,[E]:{modified:H,sha256:Am(x),total_length:q}}),{}),owner:p.toText(),created_at:A,updated_at:v}});return{items:o,assets:o,...a}},kR=async({collection:e,filter:t,satellite:r,options:n})=>{let i={...r,identity:tt(r?.identity)};return await Tm({collection:e,satellite:i,filter:t??{},options:n??Xr})},MR=({collection:e,fullPath:t,satellite:r})=>Nm({collection:e,fullPath:t,satellite:{...r,identity:tt(r?.identity)},options:{certified:!0}}),jR=({assets:e,satellite:t})=>Em({assets:e,satellite:{...t,identity:tt(t?.identity)},options:{certified:!0}}),LR=async({collection:e,satellite:t,filter:r})=>{let n={...t,identity:tt(t?.identity)};return await Om({collection:e,satellite:n,filter:r??{},options:{certified:!0}})},HR=async({satellite:e,options:t,...r})=>{let n=tt(e?.identity);return await vm({...r,satellite:{...e,identity:n},options:t??Xr})},KR=async({satellite:e,options:t,...r})=>{let n=tt(e?.identity);return await Rm({...r,satellite:{...e,identity:n},options:t??Xr})},Im=({assetKey:{fullPath:e,token:t},satellite:r})=>{let n={...r,identity:tt(r?.identity)};return`${jy(n)}${e}${(0,ya.nonNullish)(t)?`?token=${t}`:""}`};var cO=e=>{let t=e?.satelliteId??mm();(0,Bm.assertNonNullish)(t,"Satellite ID is not configured. Juno cannot be initialized.");let r=e?.container??gm();return{satelliteId:t,internetIdentityId:e?.internetIdentityId,workers:e?.workers,container:r}},XR=e=>uO(e),uO=async e=>{let t=cO(e);nr.getInstance().set(t),await bf();let r=t.workers?.auth!==void 0?ym(t.workers.auth):void 0;return[...r?[r]:[]]},lO=e=>hr.getInstance().subscribe(e),QR=lO;export{Uy as AuthClientSignInProgressStep,Cc as InitError,Dc as InternetIdentityProvider,qc as ListError,kc as NFIDProvider,Bc as SignInError,li as SignInInitError,Fc as SignInProviderNotSupportedError,Pc as SignInUserInterruptError,Vc as SignUpProviderNotSupportedError,am as WebAuthnSignInProgressStep,Uc as WebAuthnSignInRetrievePublicKeyError,om as WebAuthnSignUpProgressStep,QR as authSubscribe,kR as countAssets,V4 as countDocs,MR as deleteAsset,B4 as deleteDoc,LR as deleteFilteredAssets,F4 as deleteFilteredDocs,jR as deleteManyAssets,P4 as deleteManyDocs,Im as downloadUrl,HR as getAsset,Lc as getDoc,tO as getIdentityOnce,KR as getManyAssets,I4 as getManyDocs,TR as getSatelliteExtendedActor,XR as initJuno,uO as initSatellite,K2 as isWebAuthnAvailable,DR as listAssets,U4 as listDocs,lO as onAuthStateChange,nm as setDoc,im as setManyDocs,YE as signIn,xf as signOut,JE as signUp,eO as unsafeIdentity,CR as uploadBlob,qR as uploadFile};
58
58
  /*! Bundled license information:
59
59
 
60
60
  ieee754/index.js: