@junobuild/core 0.0.24 → 0.0.25

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.
@@ -77,6 +77,7 @@ export interface SetTrackEvent {
77
77
  updated_at: [] | [bigint];
78
78
  metadata: [] | [Array<[string, string]>];
79
79
  name: string;
80
+ user_agent: [] | [string];
80
81
  collected_at: bigint;
81
82
  }
82
83
  export interface TrackEvent {
@@ -83,6 +83,7 @@ export const idlFactory = ({IDL}) => {
83
83
  updated_at: IDL.Opt(IDL.Nat64),
84
84
  metadata: IDL.Opt(IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text))),
85
85
  name: IDL.Text,
86
+ user_agent: IDL.Opt(IDL.Text),
86
87
  collected_at: IDL.Nat64
87
88
  });
88
89
  const Result_2 = IDL.Variant({Ok: TrackEvent, Err: IDL.Text});
@@ -19,7 +19,7 @@ ic-request`),Qt=class{getPrincipal(){return this._principal||(this._principal=ot
19
19
  Request ID: ${Xt(r)}
20
20
  `)}throw new Error("unreachable")}var bi=({IDL:e})=>{let t=e.Principal,r=e.Record({controllers:e.Vec(e.Principal),freezing_threshold:e.Nat,memory_allocation:e.Nat,compute_allocation:e.Nat}),i=e.Record({controllers:e.Opt(e.Vec(e.Principal)),freezing_threshold:e.Opt(e.Nat),memory_allocation:e.Opt(e.Nat),compute_allocation:e.Opt(e.Nat)}),a=e.Vec(e.Nat8);return e.Service({canister_status:e.Func([e.Record({canister_id:t})],[e.Record({status:e.Variant({stopped:e.Null,stopping:e.Null,running:e.Null}),memory_size:e.Nat,cycles:e.Nat,settings:r,module_hash:e.Opt(e.Vec(e.Nat8))})],[]),create_canister:e.Func([e.Record({settings:e.Opt(i)})],[e.Record({canister_id:t})],[]),delete_canister:e.Func([e.Record({canister_id:t})],[],[]),deposit_cycles:e.Func([e.Record({canister_id:t})],[],[]),install_code:e.Func([e.Record({arg:e.Vec(e.Nat8),wasm_module:a,mode:e.Variant({reinstall:e.Null,upgrade:e.Null,install:e.Null}),canister_id:t})],[],[]),provisional_create_canister_with_cycles:e.Func([e.Record({settings:e.Opt(i),amount:e.Opt(e.Nat)})],[e.Record({canister_id:t})],[]),provisional_top_up_canister:e.Func([e.Record({canister_id:t,amount:e.Nat})],[],[]),raw_rand:e.Func([],[e.Vec(e.Nat8)],[]),start_canister:e.Func([e.Record({canister_id:t})],[],[]),stop_canister:e.Func([e.Record({canister_id:t})],[],[]),uninstall_code:e.Func([e.Record({canister_id:t})],[],[]),update_settings:e.Func([e.Record({canister_id:e.Principal,settings:i})],[],[])})};var vr=class extends Ke{constructor(t,r,i,a){super(["Call failed:",` Canister: ${t.toText()}`,` Method: ${r} (${i})`,...Object.getOwnPropertyNames(a).map(u=>` "${u}": ${JSON.stringify(a[u])}`)].join(`
21
21
  `)),this.canisterId=t,this.methodName=r,this.type=i,this.props=a}},rn=class extends vr{constructor(t,r,i){var a;super(t,r,"query",{Status:i.status,Code:(a=xr[i.reject_code])!==null&&a!==void 0?a:`Unknown Code "${i.reject_code}"`,Message:i.reject_message}),this.result=i}},nn=class extends vr{constructor(t,r,i,a){super(t,r,"update",Object.assign({"Request ID":Xt(i)},a.body?Object.assign(Object.assign({},a.body.error_code?{"Error code":a.body.error_code}:{}),{"Reject code":String(a.body.reject_code),"Reject message":a.body.reject_message}):{"HTTP status code":a.status.toString(),"HTTP status text":a.statusText})),this.requestId=i,this.response=a}},on;(function(e){e.Install="install",e.Reinstall="reinstall",e.Upgrade="upgrade"})(on||(on={}));var Nt=Symbol.for("ic-agent-metadata"),Lt=class{constructor(t){this[Nt]=Object.freeze(t)}static agentOf(t){return t[Nt].config.agent}static interfaceOf(t){return t[Nt].service}static canisterIdOf(t){return ot.from(t[Nt].config.canisterId)}static async install(t,r){let i=t.mode===void 0?on.Install:t.mode,a=t.arg?[...new Uint8Array(t.arg)]:[],u=[...new Uint8Array(t.module)],d=typeof r.canisterId=="string"?ot.fromText(r.canisterId):r.canisterId;await vi(r).install_code({mode:{[i]:null},arg:a,wasm_module:u,canister_id:d})}static async createCanister(t){let{canister_id:r}=await vi(t||{}).provisional_create_canister_with_cycles({amount:[],settings:[]});return r}static async createAndInstallCanister(t,r,i){let a=await this.createCanister(i);return await this.install(Object.assign({},r),Object.assign(Object.assign({},i),{canisterId:a})),this.createActor(t,Object.assign(Object.assign({},i),{canisterId:a}))}static createActorClass(t,r){let i=t({IDL:Me});class a extends Lt{constructor(d){let m=typeof d.canisterId=="string"?ot.fromText(d.canisterId):d.canisterId;super({config:Object.assign(Object.assign(Object.assign({},Ai),d),{canisterId:m}),service:i});for(let[w,A]of i._fields)r?.httpDetails&&A.annotations.push(an),this[w]=ha(this,w,A,d.blsVerify)}}return a}static createActor(t,r){return new(this.createActorClass(t))(r)}static createActorWithHttpDetails(t,r){return new(this.createActorClass(t,{httpDetails:!0}))(r)}};function br(e,t){let r=Me.decode(e,Ei.Buffer.from(t));switch(r.length){case 0:return;case 1:return r[0];default:return r}}var Ai={pollingStrategyFactory:_r.defaultStrategy},an="http-details";function ha(e,t,r,i){let a;r.annotations.includes("query")||r.annotations.includes("composite_query")?a=async(d,...m)=>{var w,A;d=Object.assign(Object.assign({},d),(A=(w=e[Nt].config).queryTransform)===null||A===void 0?void 0:A.call(w,t,m,Object.assign(Object.assign({},e[Nt].config),d)));let B=d.agent||e[Nt].config.agent||tn(),O=ot.from(d.canisterId||e[Nt].config.canisterId),Z=Me.encode(r.argTypes,m),D=await B.query(O,{methodName:t,arg:Z});switch(D.status){case"rejected":throw new rn(O,t,D);case"replied":return r.annotations.includes(an)?{httpDetails:D.httpDetails,result:br(r.retTypes,D.reply.arg)}:br(r.retTypes,D.reply.arg)}}:a=async(d,...m)=>{var w,A;d=Object.assign(Object.assign({},d),(A=(w=e[Nt].config).callTransform)===null||A===void 0?void 0:A.call(w,t,m,Object.assign(Object.assign({},e[Nt].config),d)));let B=d.agent||e[Nt].config.agent||tn(),{canisterId:O,effectiveCanisterId:Z,pollingStrategyFactory:D}=Object.assign(Object.assign(Object.assign({},Ai),e[Nt].config),d),st=ot.from(O),dt=Z!==void 0?ot.from(Z):st,vt=Me.encode(r.argTypes,m),{requestId:ht,response:Et}=await B.call(st,{methodName:t,arg:vt,effectiveCanisterId:dt});if(!Et.ok||Et.body)throw new nn(st,t,ht,Et);let Vt=D(),Ut=await en(B,dt,ht,Vt,i),Tt=r.annotations.includes(an);if(Ut!==void 0)return Tt?{httpDetails:Et,result:br(r.retTypes,Ut)}:br(r.retTypes,Ut);if(r.retTypes.length===0)return Tt?{httpDetails:Et,result:void 0}:void 0;throw new Error(`Call was returned undefined, but type [${r.retTypes.join(",")}].`)};let u=(...d)=>a({},...d);return u.withOptions=d=>(...m)=>a(d,...m),u}function vi(e){function t(r,i,a){let u=i[0],d=ot.fromHex("");return u&&typeof u=="object"&&u.canister_id&&(d=ot.from(u.canister_id)),{effectiveCanisterId:d}}return Lt.createActor(bi,Object.assign(Object.assign(Object.assign({},e),{canisterId:ot.fromHex("")}),{callTransform:t,queryTransform:t}))}var $e=we(sn());function Te(e){var t;return new Uint8Array(((t=e.match(/.{1,2}/g))!==null&&t!==void 0?t:[]).map(r=>parseInt(r,16))).buffer}function te(e){return new Uint8Array(e).reduce((t,r)=>t+r.toString(16).padStart(2,"0"),"")}var ya=(e,t)=>{if(e.byteLength!==t.byteLength)return!1;let r=new Uint8Array(e),i=new Uint8Array(t);for(let a=0;a<r.length;a++)if(r[a]!==i[a])return!1;return!0},Ui=e=>{if(e<=127)return 1;if(e<=255)return 2;if(e<=65535)return 3;if(e<=16777215)return 4;throw new Error("Length too long (> 4 bytes)")},Ri=(e,t,r)=>{if(r<=127)return e[t]=r,1;if(r<=255)return e[t]=129,e[t+1]=r,2;if(r<=65535)return e[t]=130,e[t+1]=r>>8,e[t+2]=r,3;if(r<=16777215)return e[t]=131,e[t+1]=r>>16,e[t+2]=r>>8,e[t+3]=r,4;throw new Error("Length too long (> 4 bytes)")},fn=(e,t)=>{if(e[t]<128)return 1;if(e[t]===128)throw new Error("Invalid length 0");if(e[t]===129)return 2;if(e[t]===130)return 3;if(e[t]===131)return 4;throw new Error("Length too long (> 4 bytes)")},ma=(e,t)=>{let r=fn(e,t);if(r===1)return e[t];if(r===2)return e[t+1];if(r===3)return(e[t+1]<<8)+e[t+2];if(r===4)return(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];throw new Error("Length too long (> 4 bytes)")},Bi=Uint8Array.from([48,12,6,10,43,6,1,4,1,131,184,67,1,1]),Tr=Uint8Array.from([48,5,6,3,43,101,112]),Nf=Uint8Array.from([48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10]);function Sr(e,t){let r=2+Ui(e.byteLength+1),i=t.byteLength+r+e.byteLength,a=0,u=new Uint8Array(1+Ui(i)+i);return u[a++]=48,a+=Ri(u,a,i),u.set(t,a),a+=t.byteLength,u[a++]=3,a+=Ri(u,a,e.byteLength+1),u[a++]=0,u.set(new Uint8Array(e),a),u}var cn=(e,t)=>{let r=0,i=(m,w)=>{if(a[r++]!==m)throw new Error("Expected: "+w)},a=new Uint8Array(e);if(i(48,"sequence"),r+=fn(a,r),!ya(a.slice(r,r+t.byteLength),t))throw new Error("Not the expected OID.");r+=t.byteLength,i(3,"bit string");let u=ma(a,r)-1;r+=fn(a,r),i(0,"0 padding");let d=a.slice(r);if(u!==d.length)throw new Error(`DER payload mismatch: Expected length ${u} actual length ${d.length}`);return d};var Pt=class{constructor(t){this.rawKey=t,this.derKey=Pt.derEncode(t)}static from(t){return this.fromDer(t.toDer())}static fromRaw(t){return new Pt(t)}static fromDer(t){return new Pt(this.derDecode(t))}static derEncode(t){return Sr(t,Tr).buffer}static derDecode(t){let r=cn(t,Tr);if(r.length!==this.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");return r}toDer(){return this.derKey}toRaw(){return this.rawKey}};Pt.RAW_KEY_LENGTH=32;var jt=class extends Qt{constructor(t,r){super(),this._privateKey=r,this._publicKey=Pt.from(t)}static generate(t){if(t&&t.length!==32)throw new Error("Ed25519 Seed needs to be 32 bytes long.");let{publicKey:r,secretKey:i}=t===void 0?$e.sign.keyPair():$e.sign.keyPair.fromSeed(t);return new this(Pt.fromRaw(r),i)}static fromParsedJson(t){let[r,i]=t;return new jt(Pt.fromDer(Te(r)),Te(i))}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 jt(Pt.fromRaw(t),r)}static fromSecretKey(t){let r=$e.sign.keyPair.fromSecretKey(new Uint8Array(t));return jt.fromKeyPair(r.publicKey,r.secretKey)}toJSON(){return[te(this._publicKey.toDer()),te(this._privateKey)]}getKeyPair(){return{secretKey:this._privateKey,publicKey:this._publicKey}}getPublicKey(){return this._publicKey}async sign(t){let r=new Uint8Array(t);return $e.sign.detached(r,new Uint8Array(this._privateKey)).buffer}};var We=class extends Error{constructor(t){super(t),this.message=t,Object.setPrototypeOf(this,We.prototype)}};function Ni(e){if(e)return e;if(typeof crypto<"u"&&crypto.subtle)return crypto.subtle;throw new We("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 de=class extends Qt{constructor(t,r,i){super(),this._keyPair=t,this._derKey=r,this._subtleCrypto=i}static async generate(t){let{extractable:r=!1,keyUsages:i=["sign","verify"],subtleCrypto:a}=t??{},u=Ni(a),d=await u.generateKey({name:"ECDSA",namedCurve:"P-256"},r,i),m=await u.exportKey("spki",d.publicKey);return new this(d,m,u)}static async fromKeyPair(t,r){let i=Ni(r),a=await i.exportKey("spki",t.publicKey);return new de(t,a,i)}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 this._keyPair.privateKey,await this._subtleCrypto.sign(r,this._keyPair.privateKey,t)}};var Se=we(Yn());var wa=function(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,i=Object.getOwnPropertySymbols(e);a<i.length;a++)t.indexOf(i[a])<0&&Object.prototype.propertyIsEnumerable.call(e,i[a])&&(r[i[a]]=e[i[a]]);return r},ga=new TextEncoder().encode("ic-request-auth-delegation"),_a=new TextEncoder().encode(`
22
- ic-request`);function un(e){if(typeof e!="string"||e.length<64)throw new Error("Invalid public key.");return Te(e)}var Oe=class{constructor(t,r,i){this.pubkey=t,this.expiration=r,this.targets=i}toCBOR(){return Se.value.map(Object.assign({pubkey:Se.value.bytes(this.pubkey),expiration:Se.value.u64(this.expiration.toString(16),16)},this.targets&&{targets:Se.value.array(this.targets.map(t=>Se.value.bytes(t.toUint8Array())))}))}toJSON(){return Object.assign({expiration:this.expiration.toString(16),pubkey:te(this.pubkey)},this.targets&&{targets:this.targets.map(t=>t.toHex())})}};async function ba(e,t,r,i){let a=new Oe(t.toDer(),BigInt(+r)*BigInt(1e6),i),u=new Uint8Array([...ga,...new Uint8Array(ae(a))]),d=await e.sign(u);return{delegation:a,signature:d}}var he=class{constructor(t,r){this.delegations=t,this.publicKey=r}static async create(t,r,i=new Date(Date.now()+15*60*1e3),a={}){var u,d;let m=await ba(t,r,i,a.targets);return new he([...((u=a.previous)===null||u===void 0?void 0:u.delegations)||[],m],((d=a.previous)===null||d===void 0?void 0:d.publicKey)||t.getPublicKey().toDer())}static fromJSON(t){let{publicKey:r,delegations:i}=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(i))throw new Error("Invalid delegations.");let a=i.map(u=>{let{delegation:d,signature:m}=u,{pubkey:w,expiration:A,targets:B}=d;if(B!==void 0&&!Array.isArray(B))throw new Error("Invalid targets.");return{delegation:new Oe(un(w),BigInt(`0x${A}`),B&&B.map(O=>{if(typeof O!="string")throw new Error("Invalid target.");return ot.fromHex(O)})),signature:un(m)}});return new this(a,un(r))}static fromDelegations(t,r){return new this(t,r)}toJSON(){return{delegations:this.delegations.map(t=>{let{delegation:r,signature:i}=t,{targets:a}=r;return{delegation:Object.assign({expiration:r.expiration.toString(16),pubkey:te(r.pubkey)},a&&{targets:a.map(u=>u.toHex())}),signature:te(i)}}),publicKey:te(this.publicKey)}}},ze=class extends Qt{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{toDer:()=>this._delegation.publicKey}}sign(t){return this._inner.sign(t)}async transformRequest(t){let{body:r}=t,i=wa(t,["body"]),a=await ae(r);return Object.assign(Object.assign({},i),{body:{content:r,sender_sig:await this.sign(new Uint8Array([..._a,...new Uint8Array(a)])),sender_delegation:this._delegation.delegations,sender_pubkey:this._delegation.publicKey}})}};function Pi(e,t){for(let{delegation:a}of e.delegations)if(+new Date(Number(a.expiration/BigInt(1e6)))<=+Date.now())return!1;let r=[],i=t?.scope;i&&(Array.isArray(i)?r.push(...i.map(a=>typeof a=="string"?ot.fromText(a):a)):r.push(typeof i=="string"?ot.fromText(i):i));for(let a of r){let u=a.toText();for(let{delegation:d}of e.delegations){if(d.targets===void 0)continue;let m=!0;for(let w of d.targets)if(w.toText()===u){m=!1;break}if(m)return!1}}return!0}var va=we(wo()),Ea=we(sn());var Ci;(function(e){e[e.ECDSA_WITH_SHA256=-7]="ECDSA_WITH_SHA256"})(Ci||(Ci={}));var Fi=["mousedown","mousemove","keydown","touchstart","wheel"],Ge=class{constructor(t={}){var r;this.callbacks=[],this.idleTimeout=10*60*1e3,this.timeoutID=void 0;let{onIdle:i,idleTimeout:a=10*60*1e3}=t||{};this.callbacks=i?[i]:[],this.idleTimeout=a;let u=this._resetTimer.bind(this);window.addEventListener("load",u,!0),Fi.forEach(function(m){document.addEventListener(m,u,!0)});let d=(m,w)=>{let A;return(...B)=>{let O=this,Z=function(){A=void 0,m.apply(O,B)};clearTimeout(A),A=window.setTimeout(Z,w)}};if(t?.captureScroll){let m=d(u,(r=t?.scrollDebounce)!==null&&r!==void 0?r:100);window.addEventListener("scroll",m,!0)}u()}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);Fi.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)}};var Aa=(e,t)=>t.some(r=>e instanceof r),ki,ji;function Ta(){return ki||(ki=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Sa(){return ji||(ji=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Ki=new WeakMap,dn=new WeakMap,Mi=new WeakMap,ln=new WeakMap,pn=new WeakMap;function Oa(e){let t=new Promise((r,i)=>{let a=()=>{e.removeEventListener("success",u),e.removeEventListener("error",d)},u=()=>{r(Wt(e.result)),a()},d=()=>{i(e.error),a()};e.addEventListener("success",u),e.addEventListener("error",d)});return t.then(r=>{r instanceof IDBCursor&&Ki.set(r,e)}).catch(()=>{}),pn.set(t,e),t}function Ua(e){if(dn.has(e))return;let t=new Promise((r,i)=>{let a=()=>{e.removeEventListener("complete",u),e.removeEventListener("error",d),e.removeEventListener("abort",d)},u=()=>{r(),a()},d=()=>{i(e.error||new DOMException("AbortError","AbortError")),a()};e.addEventListener("complete",u),e.addEventListener("error",d),e.addEventListener("abort",d)});dn.set(e,t)}var hn={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return dn.get(e);if(t==="objectStoreNames")return e.objectStoreNames||Mi.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Wt(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}};function Vi(e){hn=e(hn)}function Ra(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(t,...r){let i=e.call(Or(this),t,...r);return Mi.set(i,t.sort?t.sort():[t]),Wt(i)}:Sa().includes(e)?function(...t){return e.apply(Or(this),t),Wt(Ki.get(this))}:function(...t){return Wt(e.apply(Or(this),t))}}function Ba(e){return typeof e=="function"?Ra(e):(e instanceof IDBTransaction&&Ua(e),Aa(e,Ta())?new Proxy(e,hn):e)}function Wt(e){if(e instanceof IDBRequest)return Oa(e);if(ln.has(e))return ln.get(e);let t=Ba(e);return t!==e&&(ln.set(e,t),pn.set(t,e)),t}var Or=e=>pn.get(e);function qi(e,t,{blocked:r,upgrade:i,blocking:a,terminated:u}={}){let d=indexedDB.open(e,t),m=Wt(d);return i&&d.addEventListener("upgradeneeded",w=>{i(Wt(d.result),w.oldVersion,w.newVersion,Wt(d.transaction),w)}),r&&d.addEventListener("blocked",w=>r(w.oldVersion,w.newVersion,w)),m.then(w=>{u&&w.addEventListener("close",()=>u()),a&&w.addEventListener("versionchange",A=>a(A.oldVersion,A.newVersion,A))}).catch(()=>{}),m}var Na=["get","getKey","getAll","getAllKeys","count"],Pa=["put","add","delete","clear"],xn=new Map;function Yi(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(xn.get(t))return xn.get(t);let r=t.replace(/FromIndex$/,""),i=t!==r,a=Pa.includes(r);if(!(r in(i?IDBIndex:IDBObjectStore).prototype)||!(a||Na.includes(r)))return;let u=async function(d,...m){let w=this.transaction(d,a?"readwrite":"readonly"),A=w.store;return i&&(A=A.index(m.shift())),(await Promise.all([A[r](...m),a&&w.done]))[0]};return xn.set(t,u),u}Vi(e=>({...e,get:(t,r,i)=>Yi(t,r)||e.get(t,r,i),has:(t,r)=>!!Yi(t,r)||e.has(t,r)}));var Hi="auth-client-db",$i="ic-keyval",Ca=async(e=Hi,t=$i,r)=>(Ur&&(localStorage!=null&&localStorage.getItem(Kt))&&(localStorage.removeItem(Kt),localStorage.removeItem(Mt)),await qi(e,r,{upgrade:i=>{i.objectStoreNames,i.objectStoreNames.contains(t)&&i.clear(t),i.createObjectStore(t)}}));async function Fa(e,t,r){return await e.get(t,r)}async function ka(e,t,r,i){return await e.put(t,i,r)}async function ja(e,t,r){return await e.delete(t,r)}var pe=class{constructor(t,r){this._db=t,this._storeName=r}static async create(t){let{dbName:r=Hi,storeName:i=$i,version:a=1}=t??{},u=await Ca(r,i,a);return new pe(u,i)}async set(t,r){return await ka(this._db,this._storeName,t,r)}async get(t){var r;return(r=await Fa(this._db,this._storeName,t))!==null&&r!==void 0?r:null}async remove(t){return await ja(this._db,this._storeName,t)}};var Mt="identity",Kt="delegation",Wi="iv",Ka=1,Ur=typeof window<"u",Ie=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 globalThis>"u"?typeof self>"u"?void 0:self.localStorage:globalThis.localStorage:window.localStorage;if(!t)throw new Error("Could not find local storage.");return t}},Je=class{get _db(){return new Promise(t=>{if(this.initializedDb){t(this.initializedDb);return}pe.create({version:Ka}).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)}};var Ma="https://identity.ic0.app",Va="#authorize",yn="ECDSA",mn="Ed25519",Ya=500,qa="UserInterrupt",Rr=class{constructor(t,r,i,a,u,d,m,w){var A;this._identity=t,this._key=r,this._chain=i,this._storage=a,this.idleManager=u,this._createOptions=d,this._idpWindow=m,this._eventHandler=w;let B=this.logout.bind(this),O=d?.idleOptions;!O?.onIdle&&!O?.disableDefaultIdleCallback&&((A=this.idleManager)===null||A===void 0||A.registerCallback(()=>{B(),location.reload()}))}static async create(t={}){var r,i,a;let u=(r=t.storage)!==null&&r!==void 0?r:new Je,d=(i=t.keyType)!==null&&i!==void 0?i:yn,m=null;if(t.identity)m=t.identity;else{let O=await u.get(Mt);if(!O&&Ur)try{let Z=new Ie,D=await Z.get(Kt),st=await Z.get(Mt);D&&st&&d===yn&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await u.set(Kt,D),await u.set(Mt,st),O=D,await Z.remove(Kt),await Z.remove(Mt))}catch(Z){console.error("error while attempting to recover localstorage: "+Z)}if(O)try{typeof O=="object"?d===mn&&typeof O=="string"?m=await jt.fromJSON(O):m=await de.fromKeyPair(O):typeof O=="string"&&(m=jt.fromJSON(O))}catch{}}let w=new Dt,A=null;if(m)try{let O=await u.get(Kt);if(typeof O=="object"&&O!==null)throw new Error("Delegation chain is incorrectly stored. A delegation chain should be stored as a string.");t.identity?w=t.identity:O&&(A=he.fromJSON(O),Pi(A)?w=ze.fromDelegation(m,A):(await wn(u),m=null))}catch(O){console.error(O),await wn(u),m=null}let B;return!((a=t.idleOptions)===null||a===void 0)&&a.disableIdle?B=void 0:(A||t.identity)&&(B=Ge.create(t.idleOptions)),m||(d===mn?(m=await jt.generate(),await u.set(Mt,JSON.stringify(m.toJSON()))):(t.storage&&d===yn&&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 '${mn}' as the key type, as it can serialize to a string`),m=await de.generate(),await u.set(Mt,m.getKeyPair()))),new this(w,m,A,u,B,t)}async _handleSuccess(t,r){var i,a,u;let d=t.delegations.map(A=>({delegation:new Oe(A.delegation.pubkey,A.delegation.expiration,A.delegation.targets),signature:A.signature.buffer})),m=he.fromDelegations(d,t.userPublicKey.buffer),w=this._key;if(w){if(this._chain=m,this._identity=ze.fromDelegation(w,this._chain),(i=this._idpWindow)===null||i===void 0||i.close(),!this.idleManager){let A=(a=this._createOptions)===null||a===void 0?void 0:a.idleOptions;this.idleManager=Ge.create(A),!A?.onIdle&&!A?.disableDefaultIdleCallback&&((u=this.idleManager)===null||u===void 0||u.registerCallback(()=>{this.logout(),location.reload()}))}this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(Kt,JSON.stringify(this._chain.toJSON())),r?.()}}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null}async login(t){var r,i,a,u;let d=BigInt(8)*BigInt(36e11),m=new URL(((r=t?.identityProvider)===null||r===void 0?void 0:r.toString())||Ma);m.hash=Va,(i=this._idpWindow)===null||i===void 0||i.close(),this._removeEventListener(),this._eventHandler=this._getEventHandler(m,Object.assign({maxTimeToLive:(a=t?.maxTimeToLive)!==null&&a!==void 0?a:d},t)),window.addEventListener("message",this._eventHandler),this._idpWindow=(u=window.open(m.toString(),"idpWindow",t?.windowOpenerFeatures))!==null&&u!==void 0?u:void 0;let w=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(qa,t?.onError):setTimeout(w,Ya))};w()}_getEventHandler(t,r){return async i=>{var a,u,d;if(i.origin!==t.origin){console.warn(`WARNING: expected origin '${t.origin}', got '${i.origin}' (ignoring)`);return}let m=i.data;switch(m.kind){case"authorize-ready":{let w={kind:"authorize-client",sessionPublicKey:new Uint8Array((a=this._key)===null||a===void 0?void 0:a.getPublicKey().toDer()),maxTimeToLive:r?.maxTimeToLive,derivationOrigin:(u=r?.derivationOrigin)===null||u===void 0?void 0:u.toString()};(d=this._idpWindow)===null||d===void 0||d.postMessage(w,t.origin);break}case"authorize-client-success":try{await this._handleSuccess(m,r?.onSuccess)}catch(w){this._handleFailure(w.message,r?.onError)}break;case"authorize-client-failure":this._handleFailure(m.text,r?.onError);break;default:break}}}_handleFailure(t,r){var i;(i=this._idpWindow)===null||i===void 0||i.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 wn(this._storage),this._identity=new Dt,this._chain=null,t.returnTo)try{window.history.pushState({},"",t.returnTo)}catch{window.location.href=t.returnTo}}};async function wn(e){await e.remove(Mt),await e.remove(Kt),await e.remove(Wi)}var Br=()=>Rr.create({idleOptions:{disableIdle:!0,disableDefaultIdleCallback:!0}});var gn=async({data:e})=>{try{return await $n(e)}catch(t){console.error("The data parsing has failed, mapping to undefined as a fallback.",t);return}};var Nr=({matcher:e,paginate:t,order:r,owner:i})=>({matcher:yt(e)?[]:[{key:mt(e.key),description:mt(e.description)}],paginate:mt(yt(t)?void 0:{start_after:mt(t.startAfter),limit:mt(yt(t.limit)?void 0:BigInt(t.limit))}),order:mt(yt(r)?void 0:{desc:r.desc,field:r.field==="created_at"?{CreatedAt:null}:r.field==="updated_at"?{UpdatedAt:null}:{Keys:null}}),owner:mt(yt(i)?void 0:typeof i=="string"?ot.fromText(i):i)});var zi=({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({controllers:e.Vec(e.Principal)}),i=e.Variant({Write:e.Null,Admin:e.Null}),a=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:i,expires_at:e.Opt(e.Nat64)}),u=e.Record({updated_at:e.Opt(e.Nat64)}),d=e.Variant({Db:e.Null,Storage:e.Null}),m=e.Record({rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text))))}),w=e.Record({storage:m}),A=e.Record({updated_at:e.Nat64,owner:e.Principal,data:e.Vec(e.Nat8),description:e.Opt(e.Text),created_at:e.Nat64}),B=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text))}),O=e.Record({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}),Z=e.Variant({Callback:e.Record({token:O,callback:e.Func([],[],["query"])})}),D=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(Z),status_code:e.Nat16}),st=e.Record({token:e.Opt(O),body:e.Vec(e.Nat8)}),dt=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}),vt=e.Record({batch_id:e.Nat}),ht=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),Et=e.Record({field:ht,desc:e.Bool}),Vt=e.Record({key:e.Opt(e.Text),description:e.Opt(e.Text)}),Ut=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),Tt=e.Record({order:e.Opt(Et),owner:e.Opt(e.Principal),matcher:e.Opt(Vt),paginate:e.Opt(Ut)}),Xe=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}),Ze=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),Qe=e.Record({key:Xe,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,Ze)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64}),Ue=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,Qe)),items_length:e.Nat64}),xe=e.Record({updated_at:e.Nat64,created_at:e.Nat64,bn_id:e.Opt(e.Text)}),Re=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,A)),items_length:e.Nat64}),ne=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),Be=e.Record({updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:ne,created_at:e.Nat64,write:ne}),Ne=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:i,expires_at:e.Opt(e.Nat64)}),Ct=e.Record({controller:Ne,controllers:e.Vec(e.Principal)}),Pe=e.Record({updated_at:e.Opt(e.Nat64),data:e.Vec(e.Nat8),description:e.Opt(e.Text)}),ee=e.Record({updated_at:e.Opt(e.Nat64),max_size:e.Opt(e.Nat),read:ne,write:ne}),re=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),De=e.Record({chunk_id:e.Nat});return e.Service({commit_asset_upload:e.Func([t],[],[]),del_asset:e.Func([e.Text,e.Text],[],[]),del_assets:e.Func([e.Text],[],[]),del_controllers:e.Func([r],[e.Vec(e.Tuple(e.Principal,a))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,u],[],[]),del_rule:e.Func([d,e.Text,u],[],[]),get_config:e.Func([],[w],[]),get_doc:e.Func([e.Text,e.Text],[e.Opt(A)],["query"]),http_request:e.Func([B],[D],["query"]),http_request_streaming_callback:e.Func([O],[st],["query"]),init_asset_upload:e.Func([dt],[vt],[]),list_assets:e.Func([e.Text,Tt],[Ue],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,a))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,xe))],["query"]),list_docs:e.Func([e.Text,Tt],[Re],["query"]),list_rules:e.Func([d],[e.Vec(e.Tuple(e.Text,Be))],["query"]),set_config:e.Func([w],[],[]),set_controllers:e.Func([Ct],[e.Vec(e.Tuple(e.Principal,a))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_doc:e.Func([e.Text,e.Text,Pe],[A],[]),set_rule:e.Func([d,e.Text,ee],[],[]),upload_asset_chunk:e.Func([re],[De],[]),version:e.Func([],[e.Text],["query"])})};var Gi=async({satelliteId:e,idlFactory:t,identity:r,fetch:i,env:a="prod"})=>{let u=a==="dev"||bt.getInstance().localIdentity(),d=u?"http://127.0.0.1:8000/":"https://icp0.io",m=new ue({identity:r,...d&&{host:d},...i&&{fetch:i}});return u&&await m.fetchRootKey(),Lt.createActor(t,{agent:m,canisterId:e})};var zt=async({satelliteId:e,...t})=>{let{satelliteId:r}=e!==void 0?{satelliteId:e}:bt.getInstance().get()??{satelliteId:void 0};if(!r)throw new Error("No satellite principal defined.");return Gi({satelliteId:r,idlFactory:zi,...t})};var Ii=async({collection:e,key:t,satellite:r})=>{let i=await zt(r),a=Ot(await i.get_doc(e,t));if(yt(a))return;let{data:u,owner:d,description:m,...w}=a,A=await gn({data:u});return{key:t,description:Ot(m),owner:d.toText(),data:A,...w}},Ji=async({collection:e,doc:t,satellite:r})=>{let i=await zt(r),{key:a,data:u,updated_at:d,description:m}=t,w=await i.set_doc(e,a,{description:mt(m),data:await Hn(u),updated_at:mt(d)}),{owner:A,updated_at:B,created_at:O,description:Z}=w;return{key:a,description:Ot(Z),owner:A.toText(),data:u,created_at:O,updated_at:B}},Xi=async({collection:e,doc:t,satellite:r})=>{let i=await zt(r),{key:a,updated_at:u}=t;return i.del_doc(e,a,{updated_at:mt(u)})},Zi=async({collection:e,filter:t,satellite:r})=>{let i=await zt(r),{items:a,items_page:u,items_length:d,matches_length:m,matches_pages:w}=await i.list_docs(e,Nr(t)),A=[];for(let[B,O]of a){let{data:Z,owner:D,description:st,...dt}=O;A.push({key:B,description:Ot(st),owner:D.toText(),data:await gn({data:Z}),...dt})}return{items:A,items_length:d,items_page:Ot(u),matches_length:m,matches_pages:Ot(w)}};var Gt=e=>e!==void 0?e:Pr()??new Dt;var Qi=async({satellite:e,...t})=>{let r=Gt(e?.identity);return Ii({...t,satellite:{...e,identity:r}})},Di=async({satellite:e,...t})=>{let r=Gt(e?.identity);return Ji({...t,satellite:{...e,identity:r}})},$c=async({satellite:e,...t})=>{let r=Gt(e?.identity);return Xi({...t,satellite:{...e,identity:r}})},Wc=async({satellite:e,filter:t,...r})=>{let i=Gt(e?.identity);return Zi({...r,filter:t??{},satellite:{...e,identity:i}})};var Li=async e=>{let t=Pr();if(yt(t))throw new Error("No identity to initialize the user. Have you initialized Juno?");let r=t.getPrincipal().toText(),i=await Qi({collection:"#user",key:r});return yt(i)?await Ha({userId:r,provider:e}):i},Ha=async({userId:e,...t})=>Di({collection:"#user",doc:{key:e,data:t}});var It,_n=async e=>{if(It=It??await Br(),!(await It?.isAuthenticated()??!1))return;let r=await Li(e);Yt.getInstance().set(r)},$a=async e=>new Promise(async(t,r)=>{It=It??await Br();let i=e?.provider??new lr({});await It.login({onSuccess:async()=>{await _n(i.id),t()},onError:a=>r(a),maxTimeToLive:e?.maxTimeToLive??zn,...e?.derivationOrigin!==void 0&&{derivationOrigin:e.derivationOrigin},...i.signInOptions({windowed:e?.windowed})})}),bn=async()=>{await It?.logout(),It=void 0,Yt.getInstance().reset()},Pr=()=>It?.getIdentity(),Wa=async()=>(It??await Br()).getIdentity();var to=e=>{let t=e===!0?"./workers/auth.worker.js":e,r=new Worker(t),i=async()=>{Wn({message:"junoSignOutAuthTimer"}),await bn()};return r.onmessage=async({data:a})=>{let{msg:u}=a;switch(u){case"junoSignOutAuthTimer":await i();return}},Yt.getInstance().subscribe(a=>{if(yt(a)){r.postMessage({msg:"junoStopAuthTimer"});return}r.postMessage({msg:"junoStartAuthTimer"})})};var eo=async({data:e,filename:t,collection:r,headers:i,token:a,fullPath:u,encoding:d,description:m,satellite:w})=>{let A=await zt(w),{batch_id:B}=await A.init_asset_upload({collection:r,full_path:u,name:t,token:mt(a),encoding_type:mt(d),description:mt(m)}),O=19e5,Z=[],D=ur()?new Blob([await e.arrayBuffer()]):e,st=0n;for(let ht=0;ht<D.size;ht+=O){let Et=D.slice(ht,ht+O);Z.push({batchId:B,chunk:Et,actor:A,orderId:st}),st++}let dt=[];for await(let ht of za({uploadChunks:Z}))dt=[...dt,...ht];let vt=i.find(([ht,Et])=>ht.toLowerCase()==="content-type")===void 0&&e.type!==void 0&&e.type!==""?[["Content-Type",e.type]]:void 0;await A.commit_asset_upload({batch_id:B,chunk_ids:dt.map(({chunk_id:ht})=>ht),headers:[...i,...vt||[]]})};async function*za({uploadChunks:e,limit:t=12}){for(let r=0;r<e.length;r=r+t){let i=e.slice(r,r+t);yield await Promise.all(i.map(u=>Ga(u)))}}var Ga=async({batchId:e,chunk:t,actor:r,orderId:i})=>r.upload_asset_chunk({batch_id:e,content:new Uint8Array(await t.arrayBuffer()),order_id:mt(i)}),ro=async({collection:e,satellite:t,filter:r})=>{let i=await zt(t),{items:a,items_length:u,items_page:d,matches_length:m,matches_pages:w}=await i.list_assets(e,Nr(r));return{items:a.map(([A,B])=>B),items_length:u,items_page:Ot(d),matches_length:m,matches_pages:Ot(w)}},no=async({collection:e,fullPath:t,satellite:r})=>(await zt(r)).del_asset(e,t),io=async({collection:e,satellite:t})=>(await zt(t)).del_assets(e);var oo=e=>btoa([...e].map(t=>String.fromCharCode(t)).join(""));var vn=e=>encodeURI(e.toLowerCase().replace(/\s/g,"-"));var _0=async e=>ao(e),b0=async e=>ao({filename:e.data.name,...e}),ao=async({filename:e,data:t,collection:r,headers:i=[],fullPath:a,token:u,satellite:d,encoding:m,description:w})=>{let A=Gt(d?.identity),B=vn(e),O=a||`/${r}/${B}`;return await eo({data:t,filename:vn(B),collection:r,token:u,headers:i,fullPath:O,encoding:m,satellite:{...d,identity:A},description:w}),{downloadUrl:`${Wr()}${O}${u!==void 0?`?token=${u}`:""}`,fullPath:O,name:B}},v0=async({collection:e,satellite:t,filter:r})=>{let{items:i,...a}=await ro({collection:e,satellite:{...t,identity:Gt(t?.identity)},filter:r??{}}),u=Wr();return{assets:i.map(({key:{full_path:d,token:m,name:w,owner:A,description:B},headers:O,encodings:Z,created_at:D,updated_at:st})=>{let dt=Ot(m);return{fullPath:d,description:Ot(B),name:w,downloadUrl:`${u}${d}${dt!==void 0?`?token=${dt}`:""}`,token:dt,headers:O,encodings:Z.reduce((vt,[ht,{modified:Et,sha256:Vt,total_length:Ut}])=>({...vt,[ht]:{modified:Et,sha256:oo(Vt),total_length:Ut}}),{}),owner:A.toText(),created_at:D,updated_at:st}}),...a}},E0=async({collection:e,fullPath:t,satellite:r})=>no({collection:e,fullPath:t,satellite:{...r,identity:Gt(r?.identity)}}),A0=async({collection:e,satellite:t})=>io({collection:e,satellite:{...t,identity:Gt(t?.identity)}});var B0=async e=>{bt.getInstance().set(e),await _n();let t=e.workers?.auth!==void 0?to(e.workers.auth):void 0;return[...t?[t]:[]]},N0=e=>Yt.getInstance().subscribe(e);export{lr as InternetIdentityProvider,Xn as NFIDProvider,N0 as authSubscribe,E0 as deleteAsset,A0 as deleteAssets,$c as deleteDoc,Qi as getDoc,B0 as initJuno,v0 as listAssets,Wc as listDocs,Di as setDoc,$a as signIn,bn as signOut,Wa as unsafeIdentity,_0 as uploadBlob,b0 as uploadFile};
22
+ ic-request`);function un(e){if(typeof e!="string"||e.length<64)throw new Error("Invalid public key.");return Te(e)}var Oe=class{constructor(t,r,i){this.pubkey=t,this.expiration=r,this.targets=i}toCBOR(){return Se.value.map(Object.assign({pubkey:Se.value.bytes(this.pubkey),expiration:Se.value.u64(this.expiration.toString(16),16)},this.targets&&{targets:Se.value.array(this.targets.map(t=>Se.value.bytes(t.toUint8Array())))}))}toJSON(){return Object.assign({expiration:this.expiration.toString(16),pubkey:te(this.pubkey)},this.targets&&{targets:this.targets.map(t=>t.toHex())})}};async function ba(e,t,r,i){let a=new Oe(t.toDer(),BigInt(+r)*BigInt(1e6),i),u=new Uint8Array([...ga,...new Uint8Array(ae(a))]),d=await e.sign(u);return{delegation:a,signature:d}}var he=class{constructor(t,r){this.delegations=t,this.publicKey=r}static async create(t,r,i=new Date(Date.now()+15*60*1e3),a={}){var u,d;let m=await ba(t,r,i,a.targets);return new he([...((u=a.previous)===null||u===void 0?void 0:u.delegations)||[],m],((d=a.previous)===null||d===void 0?void 0:d.publicKey)||t.getPublicKey().toDer())}static fromJSON(t){let{publicKey:r,delegations:i}=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(i))throw new Error("Invalid delegations.");let a=i.map(u=>{let{delegation:d,signature:m}=u,{pubkey:w,expiration:A,targets:B}=d;if(B!==void 0&&!Array.isArray(B))throw new Error("Invalid targets.");return{delegation:new Oe(un(w),BigInt(`0x${A}`),B&&B.map(O=>{if(typeof O!="string")throw new Error("Invalid target.");return ot.fromHex(O)})),signature:un(m)}});return new this(a,un(r))}static fromDelegations(t,r){return new this(t,r)}toJSON(){return{delegations:this.delegations.map(t=>{let{delegation:r,signature:i}=t,{targets:a}=r;return{delegation:Object.assign({expiration:r.expiration.toString(16),pubkey:te(r.pubkey)},a&&{targets:a.map(u=>u.toHex())}),signature:te(i)}}),publicKey:te(this.publicKey)}}},ze=class extends Qt{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{toDer:()=>this._delegation.publicKey}}sign(t){return this._inner.sign(t)}async transformRequest(t){let{body:r}=t,i=wa(t,["body"]),a=await ae(r);return Object.assign(Object.assign({},i),{body:{content:r,sender_sig:await this.sign(new Uint8Array([..._a,...new Uint8Array(a)])),sender_delegation:this._delegation.delegations,sender_pubkey:this._delegation.publicKey}})}};function Pi(e,t){for(let{delegation:a}of e.delegations)if(+new Date(Number(a.expiration/BigInt(1e6)))<=+Date.now())return!1;let r=[],i=t?.scope;i&&(Array.isArray(i)?r.push(...i.map(a=>typeof a=="string"?ot.fromText(a):a)):r.push(typeof i=="string"?ot.fromText(i):i));for(let a of r){let u=a.toText();for(let{delegation:d}of e.delegations){if(d.targets===void 0)continue;let m=!0;for(let w of d.targets)if(w.toText()===u){m=!1;break}if(m)return!1}}return!0}var va=we(wo()),Ea=we(sn());var Ci;(function(e){e[e.ECDSA_WITH_SHA256=-7]="ECDSA_WITH_SHA256"})(Ci||(Ci={}));var Fi=["mousedown","mousemove","keydown","touchstart","wheel"],Ge=class{constructor(t={}){var r;this.callbacks=[],this.idleTimeout=10*60*1e3,this.timeoutID=void 0;let{onIdle:i,idleTimeout:a=10*60*1e3}=t||{};this.callbacks=i?[i]:[],this.idleTimeout=a;let u=this._resetTimer.bind(this);window.addEventListener("load",u,!0),Fi.forEach(function(m){document.addEventListener(m,u,!0)});let d=(m,w)=>{let A;return(...B)=>{let O=this,Z=function(){A=void 0,m.apply(O,B)};clearTimeout(A),A=window.setTimeout(Z,w)}};if(t?.captureScroll){let m=d(u,(r=t?.scrollDebounce)!==null&&r!==void 0?r:100);window.addEventListener("scroll",m,!0)}u()}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);Fi.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)}};var Aa=(e,t)=>t.some(r=>e instanceof r),ki,ji;function Ta(){return ki||(ki=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Sa(){return ji||(ji=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Ki=new WeakMap,dn=new WeakMap,Mi=new WeakMap,ln=new WeakMap,pn=new WeakMap;function Oa(e){let t=new Promise((r,i)=>{let a=()=>{e.removeEventListener("success",u),e.removeEventListener("error",d)},u=()=>{r(Wt(e.result)),a()},d=()=>{i(e.error),a()};e.addEventListener("success",u),e.addEventListener("error",d)});return t.then(r=>{r instanceof IDBCursor&&Ki.set(r,e)}).catch(()=>{}),pn.set(t,e),t}function Ua(e){if(dn.has(e))return;let t=new Promise((r,i)=>{let a=()=>{e.removeEventListener("complete",u),e.removeEventListener("error",d),e.removeEventListener("abort",d)},u=()=>{r(),a()},d=()=>{i(e.error||new DOMException("AbortError","AbortError")),a()};e.addEventListener("complete",u),e.addEventListener("error",d),e.addEventListener("abort",d)});dn.set(e,t)}var hn={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return dn.get(e);if(t==="objectStoreNames")return e.objectStoreNames||Mi.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Wt(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}};function Vi(e){hn=e(hn)}function Ra(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(t,...r){let i=e.call(Or(this),t,...r);return Mi.set(i,t.sort?t.sort():[t]),Wt(i)}:Sa().includes(e)?function(...t){return e.apply(Or(this),t),Wt(Ki.get(this))}:function(...t){return Wt(e.apply(Or(this),t))}}function Ba(e){return typeof e=="function"?Ra(e):(e instanceof IDBTransaction&&Ua(e),Aa(e,Ta())?new Proxy(e,hn):e)}function Wt(e){if(e instanceof IDBRequest)return Oa(e);if(ln.has(e))return ln.get(e);let t=Ba(e);return t!==e&&(ln.set(e,t),pn.set(t,e)),t}var Or=e=>pn.get(e);function qi(e,t,{blocked:r,upgrade:i,blocking:a,terminated:u}={}){let d=indexedDB.open(e,t),m=Wt(d);return i&&d.addEventListener("upgradeneeded",w=>{i(Wt(d.result),w.oldVersion,w.newVersion,Wt(d.transaction),w)}),r&&d.addEventListener("blocked",w=>r(w.oldVersion,w.newVersion,w)),m.then(w=>{u&&w.addEventListener("close",()=>u()),a&&w.addEventListener("versionchange",A=>a(A.oldVersion,A.newVersion,A))}).catch(()=>{}),m}var Na=["get","getKey","getAll","getAllKeys","count"],Pa=["put","add","delete","clear"],xn=new Map;function Yi(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(xn.get(t))return xn.get(t);let r=t.replace(/FromIndex$/,""),i=t!==r,a=Pa.includes(r);if(!(r in(i?IDBIndex:IDBObjectStore).prototype)||!(a||Na.includes(r)))return;let u=async function(d,...m){let w=this.transaction(d,a?"readwrite":"readonly"),A=w.store;return i&&(A=A.index(m.shift())),(await Promise.all([A[r](...m),a&&w.done]))[0]};return xn.set(t,u),u}Vi(e=>({...e,get:(t,r,i)=>Yi(t,r)||e.get(t,r,i),has:(t,r)=>!!Yi(t,r)||e.has(t,r)}));var Hi="auth-client-db",$i="ic-keyval",Ca=async(e=Hi,t=$i,r)=>(Ur&&(localStorage!=null&&localStorage.getItem(Kt))&&(localStorage.removeItem(Kt),localStorage.removeItem(Mt)),await qi(e,r,{upgrade:i=>{i.objectStoreNames,i.objectStoreNames.contains(t)&&i.clear(t),i.createObjectStore(t)}}));async function Fa(e,t,r){return await e.get(t,r)}async function ka(e,t,r,i){return await e.put(t,i,r)}async function ja(e,t,r){return await e.delete(t,r)}var pe=class{constructor(t,r){this._db=t,this._storeName=r}static async create(t){let{dbName:r=Hi,storeName:i=$i,version:a=1}=t??{},u=await Ca(r,i,a);return new pe(u,i)}async set(t,r){return await ka(this._db,this._storeName,t,r)}async get(t){var r;return(r=await Fa(this._db,this._storeName,t))!==null&&r!==void 0?r:null}async remove(t){return await ja(this._db,this._storeName,t)}};var Mt="identity",Kt="delegation",Wi="iv",Ka=1,Ur=typeof window<"u",Ie=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 globalThis>"u"?typeof self>"u"?void 0:self.localStorage:globalThis.localStorage:window.localStorage;if(!t)throw new Error("Could not find local storage.");return t}},Je=class{get _db(){return new Promise(t=>{if(this.initializedDb){t(this.initializedDb);return}pe.create({version:Ka}).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)}};var Ma="https://identity.ic0.app",Va="#authorize",yn="ECDSA",mn="Ed25519",Ya=500,qa="UserInterrupt",Rr=class{constructor(t,r,i,a,u,d,m,w){var A;this._identity=t,this._key=r,this._chain=i,this._storage=a,this.idleManager=u,this._createOptions=d,this._idpWindow=m,this._eventHandler=w;let B=this.logout.bind(this),O=d?.idleOptions;!O?.onIdle&&!O?.disableDefaultIdleCallback&&((A=this.idleManager)===null||A===void 0||A.registerCallback(()=>{B(),location.reload()}))}static async create(t={}){var r,i,a;let u=(r=t.storage)!==null&&r!==void 0?r:new Je,d=(i=t.keyType)!==null&&i!==void 0?i:yn,m=null;if(t.identity)m=t.identity;else{let O=await u.get(Mt);if(!O&&Ur)try{let Z=new Ie,D=await Z.get(Kt),st=await Z.get(Mt);D&&st&&d===yn&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await u.set(Kt,D),await u.set(Mt,st),O=D,await Z.remove(Kt),await Z.remove(Mt))}catch(Z){console.error("error while attempting to recover localstorage: "+Z)}if(O)try{typeof O=="object"?d===mn&&typeof O=="string"?m=await jt.fromJSON(O):m=await de.fromKeyPair(O):typeof O=="string"&&(m=jt.fromJSON(O))}catch{}}let w=new Dt,A=null;if(m)try{let O=await u.get(Kt);if(typeof O=="object"&&O!==null)throw new Error("Delegation chain is incorrectly stored. A delegation chain should be stored as a string.");t.identity?w=t.identity:O&&(A=he.fromJSON(O),Pi(A)?w=ze.fromDelegation(m,A):(await wn(u),m=null))}catch(O){console.error(O),await wn(u),m=null}let B;return!((a=t.idleOptions)===null||a===void 0)&&a.disableIdle?B=void 0:(A||t.identity)&&(B=Ge.create(t.idleOptions)),m||(d===mn?(m=await jt.generate(),await u.set(Mt,JSON.stringify(m.toJSON()))):(t.storage&&d===yn&&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 '${mn}' as the key type, as it can serialize to a string`),m=await de.generate(),await u.set(Mt,m.getKeyPair()))),new this(w,m,A,u,B,t)}async _handleSuccess(t,r){var i,a,u;let d=t.delegations.map(A=>({delegation:new Oe(A.delegation.pubkey,A.delegation.expiration,A.delegation.targets),signature:A.signature.buffer})),m=he.fromDelegations(d,t.userPublicKey.buffer),w=this._key;if(w){if(this._chain=m,this._identity=ze.fromDelegation(w,this._chain),(i=this._idpWindow)===null||i===void 0||i.close(),!this.idleManager){let A=(a=this._createOptions)===null||a===void 0?void 0:a.idleOptions;this.idleManager=Ge.create(A),!A?.onIdle&&!A?.disableDefaultIdleCallback&&((u=this.idleManager)===null||u===void 0||u.registerCallback(()=>{this.logout(),location.reload()}))}this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(Kt,JSON.stringify(this._chain.toJSON())),r?.()}}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null}async login(t){var r,i,a,u;let d=BigInt(8)*BigInt(36e11),m=new URL(((r=t?.identityProvider)===null||r===void 0?void 0:r.toString())||Ma);m.hash=Va,(i=this._idpWindow)===null||i===void 0||i.close(),this._removeEventListener(),this._eventHandler=this._getEventHandler(m,Object.assign({maxTimeToLive:(a=t?.maxTimeToLive)!==null&&a!==void 0?a:d},t)),window.addEventListener("message",this._eventHandler),this._idpWindow=(u=window.open(m.toString(),"idpWindow",t?.windowOpenerFeatures))!==null&&u!==void 0?u:void 0;let w=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(qa,t?.onError):setTimeout(w,Ya))};w()}_getEventHandler(t,r){return async i=>{var a,u,d;if(i.origin!==t.origin){console.warn(`WARNING: expected origin '${t.origin}', got '${i.origin}' (ignoring)`);return}let m=i.data;switch(m.kind){case"authorize-ready":{let w={kind:"authorize-client",sessionPublicKey:new Uint8Array((a=this._key)===null||a===void 0?void 0:a.getPublicKey().toDer()),maxTimeToLive:r?.maxTimeToLive,derivationOrigin:(u=r?.derivationOrigin)===null||u===void 0?void 0:u.toString()};(d=this._idpWindow)===null||d===void 0||d.postMessage(w,t.origin);break}case"authorize-client-success":try{await this._handleSuccess(m,r?.onSuccess)}catch(w){this._handleFailure(w.message,r?.onError)}break;case"authorize-client-failure":this._handleFailure(m.text,r?.onError);break;default:break}}}_handleFailure(t,r){var i;(i=this._idpWindow)===null||i===void 0||i.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 wn(this._storage),this._identity=new Dt,this._chain=null,t.returnTo)try{window.history.pushState({},"",t.returnTo)}catch{window.location.href=t.returnTo}}};async function wn(e){await e.remove(Mt),await e.remove(Kt),await e.remove(Wi)}var Br=()=>Rr.create({idleOptions:{disableIdle:!0,disableDefaultIdleCallback:!0}});var gn=async({data:e})=>{try{return await $n(e)}catch(t){console.error("The data parsing has failed, mapping to undefined as a fallback.",t);return}};var Nr=({matcher:e,paginate:t,order:r,owner:i})=>({matcher:yt(e)?[]:[{key:mt(e.key),description:mt(e.description)}],paginate:mt(yt(t)?void 0:{start_after:mt(t.startAfter),limit:mt(yt(t.limit)?void 0:BigInt(t.limit))}),order:mt(yt(r)?void 0:{desc:r.desc,field:r.field==="created_at"?{CreatedAt:null}:r.field==="updated_at"?{UpdatedAt:null}:{Keys:null}}),owner:mt(yt(i)?void 0:typeof i=="string"?ot.fromText(i):i)});var zi=({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({controllers:e.Vec(e.Principal)}),i=e.Variant({Write:e.Null,Admin:e.Null}),a=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:i,expires_at:e.Opt(e.Nat64)}),u=e.Record({updated_at:e.Opt(e.Nat64)}),d=e.Variant({Db:e.Null,Storage:e.Null}),m=e.Record({rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text))))}),w=e.Record({storage:m}),A=e.Record({updated_at:e.Nat64,owner:e.Principal,data:e.Vec(e.Nat8),description:e.Opt(e.Text),created_at:e.Nat64}),B=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text))}),O=e.Record({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}),Z=e.Variant({Callback:e.Record({token:O,callback:e.Func([],[],["query"])})}),D=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(Z),status_code:e.Nat16}),st=e.Record({token:e.Opt(O),body:e.Vec(e.Nat8)}),dt=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}),vt=e.Record({batch_id:e.Nat}),ht=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),Et=e.Record({field:ht,desc:e.Bool}),Vt=e.Record({key:e.Opt(e.Text),description:e.Opt(e.Text)}),Ut=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),Tt=e.Record({order:e.Opt(Et),owner:e.Opt(e.Principal),matcher:e.Opt(Vt),paginate:e.Opt(Ut)}),Xe=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}),Ze=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),Qe=e.Record({key:Xe,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,Ze)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64}),Ue=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,Qe)),items_length:e.Nat64}),xe=e.Record({updated_at:e.Nat64,created_at:e.Nat64,bn_id:e.Opt(e.Text)}),Re=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,A)),items_length:e.Nat64}),ne=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),Be=e.Record({updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:ne,created_at:e.Nat64,write:ne}),Ne=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:i,expires_at:e.Opt(e.Nat64)}),Ct=e.Record({controller:Ne,controllers:e.Vec(e.Principal)}),Pe=e.Record({updated_at:e.Opt(e.Nat64),data:e.Vec(e.Nat8),description:e.Opt(e.Text)}),ee=e.Record({updated_at:e.Opt(e.Nat64),max_size:e.Opt(e.Nat),read:ne,write:ne}),re=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),De=e.Record({chunk_id:e.Nat});return e.Service({commit_asset_upload:e.Func([t],[],[]),del_asset:e.Func([e.Text,e.Text],[],[]),del_assets:e.Func([e.Text],[],[]),del_controllers:e.Func([r],[e.Vec(e.Tuple(e.Principal,a))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,u],[],[]),del_rule:e.Func([d,e.Text,u],[],[]),get_config:e.Func([],[w],[]),get_doc:e.Func([e.Text,e.Text],[e.Opt(A)],["query"]),http_request:e.Func([B],[D],["query"]),http_request_streaming_callback:e.Func([O],[st],["query"]),init_asset_upload:e.Func([dt],[vt],[]),list_assets:e.Func([e.Text,Tt],[Ue],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,a))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,xe))],["query"]),list_docs:e.Func([e.Text,Tt],[Re],["query"]),list_rules:e.Func([d],[e.Vec(e.Tuple(e.Text,Be))],["query"]),set_config:e.Func([w],[],[]),set_controllers:e.Func([Ct],[e.Vec(e.Tuple(e.Principal,a))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_doc:e.Func([e.Text,e.Text,Pe],[A],[]),set_rule:e.Func([d,e.Text,ee],[],[]),upload_asset_chunk:e.Func([re],[De],[]),version:e.Func([],[e.Text],["query"])})};var Gi=async({satelliteId:e,idlFactory:t,identity:r,fetch:i,env:a="prod"})=>{let u=a==="dev"||bt.getInstance().localIdentity(),d=u?"http://127.0.0.1:8000/":"https://icp-api.io",m=new ue({identity:r,...d&&{host:d},...i&&{fetch:i}});return u&&await m.fetchRootKey(),Lt.createActor(t,{agent:m,canisterId:e})};var zt=async({satelliteId:e,...t})=>{let{satelliteId:r}=e!==void 0?{satelliteId:e}:bt.getInstance().get()??{satelliteId:void 0};if(!r)throw new Error("No satellite principal defined.");return Gi({satelliteId:r,idlFactory:zi,...t})};var Ii=async({collection:e,key:t,satellite:r})=>{let i=await zt(r),a=Ot(await i.get_doc(e,t));if(yt(a))return;let{data:u,owner:d,description:m,...w}=a,A=await gn({data:u});return{key:t,description:Ot(m),owner:d.toText(),data:A,...w}},Ji=async({collection:e,doc:t,satellite:r})=>{let i=await zt(r),{key:a,data:u,updated_at:d,description:m}=t,w=await i.set_doc(e,a,{description:mt(m),data:await Hn(u),updated_at:mt(d)}),{owner:A,updated_at:B,created_at:O,description:Z}=w;return{key:a,description:Ot(Z),owner:A.toText(),data:u,created_at:O,updated_at:B}},Xi=async({collection:e,doc:t,satellite:r})=>{let i=await zt(r),{key:a,updated_at:u}=t;return i.del_doc(e,a,{updated_at:mt(u)})},Zi=async({collection:e,filter:t,satellite:r})=>{let i=await zt(r),{items:a,items_page:u,items_length:d,matches_length:m,matches_pages:w}=await i.list_docs(e,Nr(t)),A=[];for(let[B,O]of a){let{data:Z,owner:D,description:st,...dt}=O;A.push({key:B,description:Ot(st),owner:D.toText(),data:await gn({data:Z}),...dt})}return{items:A,items_length:d,items_page:Ot(u),matches_length:m,matches_pages:Ot(w)}};var Gt=e=>e!==void 0?e:Pr()??new Dt;var Qi=async({satellite:e,...t})=>{let r=Gt(e?.identity);return Ii({...t,satellite:{...e,identity:r}})},Di=async({satellite:e,...t})=>{let r=Gt(e?.identity);return Ji({...t,satellite:{...e,identity:r}})},$c=async({satellite:e,...t})=>{let r=Gt(e?.identity);return Xi({...t,satellite:{...e,identity:r}})},Wc=async({satellite:e,filter:t,...r})=>{let i=Gt(e?.identity);return Zi({...r,filter:t??{},satellite:{...e,identity:i}})};var Li=async e=>{let t=Pr();if(yt(t))throw new Error("No identity to initialize the user. Have you initialized Juno?");let r=t.getPrincipal().toText(),i=await Qi({collection:"#user",key:r});return yt(i)?await Ha({userId:r,provider:e}):i},Ha=async({userId:e,...t})=>Di({collection:"#user",doc:{key:e,data:t}});var It,_n=async e=>{if(It=It??await Br(),!(await It?.isAuthenticated()??!1))return;let r=await Li(e);Yt.getInstance().set(r)},$a=async e=>new Promise(async(t,r)=>{It=It??await Br();let i=e?.provider??new lr({});await It.login({onSuccess:async()=>{await _n(i.id),t()},onError:a=>r(a),maxTimeToLive:e?.maxTimeToLive??zn,...e?.derivationOrigin!==void 0&&{derivationOrigin:e.derivationOrigin},...i.signInOptions({windowed:e?.windowed})})}),bn=async()=>{await It?.logout(),It=void 0,Yt.getInstance().reset()},Pr=()=>It?.getIdentity(),Wa=async()=>(It??await Br()).getIdentity();var to=e=>{let t=e===!0?"./workers/auth.worker.js":e,r=new Worker(t),i=async()=>{Wn({message:"junoSignOutAuthTimer"}),await bn()};return r.onmessage=async({data:a})=>{let{msg:u}=a;switch(u){case"junoSignOutAuthTimer":await i();return}},Yt.getInstance().subscribe(a=>{if(yt(a)){r.postMessage({msg:"junoStopAuthTimer"});return}r.postMessage({msg:"junoStartAuthTimer"})})};var eo=async({data:e,filename:t,collection:r,headers:i,token:a,fullPath:u,encoding:d,description:m,satellite:w})=>{let A=await zt(w),{batch_id:B}=await A.init_asset_upload({collection:r,full_path:u,name:t,token:mt(a),encoding_type:mt(d),description:mt(m)}),O=19e5,Z=[],D=ur()?new Blob([await e.arrayBuffer()]):e,st=0n;for(let ht=0;ht<D.size;ht+=O){let Et=D.slice(ht,ht+O);Z.push({batchId:B,chunk:Et,actor:A,orderId:st}),st++}let dt=[];for await(let ht of za({uploadChunks:Z}))dt=[...dt,...ht];let vt=i.find(([ht,Et])=>ht.toLowerCase()==="content-type")===void 0&&e.type!==void 0&&e.type!==""?[["Content-Type",e.type]]:void 0;await A.commit_asset_upload({batch_id:B,chunk_ids:dt.map(({chunk_id:ht})=>ht),headers:[...i,...vt||[]]})};async function*za({uploadChunks:e,limit:t=12}){for(let r=0;r<e.length;r=r+t){let i=e.slice(r,r+t);yield await Promise.all(i.map(u=>Ga(u)))}}var Ga=async({batchId:e,chunk:t,actor:r,orderId:i})=>r.upload_asset_chunk({batch_id:e,content:new Uint8Array(await t.arrayBuffer()),order_id:mt(i)}),ro=async({collection:e,satellite:t,filter:r})=>{let i=await zt(t),{items:a,items_length:u,items_page:d,matches_length:m,matches_pages:w}=await i.list_assets(e,Nr(r));return{items:a.map(([A,B])=>B),items_length:u,items_page:Ot(d),matches_length:m,matches_pages:Ot(w)}},no=async({collection:e,fullPath:t,satellite:r})=>(await zt(r)).del_asset(e,t),io=async({collection:e,satellite:t})=>(await zt(t)).del_assets(e);var oo=e=>btoa([...e].map(t=>String.fromCharCode(t)).join(""));var vn=e=>encodeURI(e.toLowerCase().replace(/\s/g,"-"));var _0=async e=>ao(e),b0=async e=>ao({filename:e.data.name,...e}),ao=async({filename:e,data:t,collection:r,headers:i=[],fullPath:a,token:u,satellite:d,encoding:m,description:w})=>{let A=Gt(d?.identity),B=vn(e),O=a||`/${r}/${B}`;return await eo({data:t,filename:vn(B),collection:r,token:u,headers:i,fullPath:O,encoding:m,satellite:{...d,identity:A},description:w}),{downloadUrl:`${Wr()}${O}${u!==void 0?`?token=${u}`:""}`,fullPath:O,name:B}},v0=async({collection:e,satellite:t,filter:r})=>{let{items:i,...a}=await ro({collection:e,satellite:{...t,identity:Gt(t?.identity)},filter:r??{}}),u=Wr();return{assets:i.map(({key:{full_path:d,token:m,name:w,owner:A,description:B},headers:O,encodings:Z,created_at:D,updated_at:st})=>{let dt=Ot(m);return{fullPath:d,description:Ot(B),name:w,downloadUrl:`${u}${d}${dt!==void 0?`?token=${dt}`:""}`,token:dt,headers:O,encodings:Z.reduce((vt,[ht,{modified:Et,sha256:Vt,total_length:Ut}])=>({...vt,[ht]:{modified:Et,sha256:oo(Vt),total_length:Ut}}),{}),owner:A.toText(),created_at:D,updated_at:st}}),...a}},E0=async({collection:e,fullPath:t,satellite:r})=>no({collection:e,fullPath:t,satellite:{...r,identity:Gt(r?.identity)}}),A0=async({collection:e,satellite:t})=>io({collection:e,satellite:{...t,identity:Gt(t?.identity)}});var B0=async e=>{bt.getInstance().set(e),await _n();let t=e.workers?.auth!==void 0?to(e.workers.auth):void 0;return[...t?[t]:[]]},N0=e=>Yt.getInstance().subscribe(e);export{lr as InternetIdentityProvider,Xn as NFIDProvider,N0 as authSubscribe,E0 as deleteAsset,A0 as deleteAssets,$c as deleteDoc,Qi as getDoc,B0 as initJuno,v0 as listAssets,Wc as listDocs,Di as setDoc,$a as signIn,bn as signOut,Wa as unsafeIdentity,_0 as uploadBlob,b0 as uploadFile};
23
23
  /*! Bundled license information:
24
24
 
25
25
  buffer/index.js: