/* esm.sh - @dfinity/auth-client@1.4.0 */
import{AnonymousIdentity as K}from"/@dfinity/agent@1.4.0/X-ZEBkZmluaXR5L2NhbmRpZEAxLjQuMCxAZGZpbml0eS9wcmluY2lwYWxAMS40LjA/es2022/agent.mjs";import{Delegation as j,DelegationChain as R,isDelegationValid as z,DelegationIdentity as k,Ed25519KeyIdentity as T,ECDSAKeyIdentity as P,PartialDelegationIdentity as C}from"/@dfinity/identity@^1.4.0?deps=@dfinity/agent@1.4.0,@dfinity/candid@1.4.0,@dfinity/principal@1.4.0&target=es2022";var O=["mousedown","mousemove","keydown","touchstart","wheel"],g=class{constructor(e={}){var t;this.callbacks=[],this.idleTimeout=600*1e3,this.timeoutID=void 0;let{onIdle:i,idleTimeout:n=600*1e3}=e||{};this.callbacks=i?[i]:[],this.idleTimeout=n;let a=this._resetTimer.bind(this);window.addEventListener("load",a,!0),O.forEach(function(r){document.addEventListener(r,a,!0)});let d=(r,l)=>{let c;return(...v)=>{let s=this,_=function(){c=void 0,r.apply(s,v)};clearTimeout(c),c=window.setTimeout(_,l)}};if(e?.captureScroll){let r=d(a,(t=e?.scrollDebounce)!==null&&t!==void 0?t:100);window.addEventListener("scroll",r,!0)}a()}static create(e={}){return new this(e)}registerCallback(e){this.callbacks.push(e)}exit(){clearTimeout(this.timeoutID),window.removeEventListener("load",this._resetTimer,!0);let e=this._resetTimer.bind(this);O.forEach(function(t){document.removeEventListener(t,e,!0)}),this.callbacks.forEach(t=>t())}_resetTimer(){let e=this.exit.bind(this);window.clearTimeout(this.timeoutID),this.timeoutID=window.setTimeout(e,this.idleTimeout)}};import{openDB as G}from"/idb@^7.0.2?target=es2022";var L="auth-client-db",x="ic-keyval",B=async(o=L,e=x,t)=>(y&&(localStorage!=null&&localStorage.getItem(u))&&(localStorage.removeItem(u),localStorage.removeItem(h)),await G(o,t,{upgrade:i=>{i.objectStoreNames,i.objectStoreNames.contains(e)&&i.clear(e),i.createObjectStore(e)}}));async function V(o,e,t){return await o.get(e,t)}async function W(o,e,t,i){return await o.put(e,i,t)}async function F(o,e,t){return await o.delete(e,t)}var w=class o{constructor(e,t){this._db=e,this._storeName=t}static async create(e){let{dbName:t=L,storeName:i=x,version:n=N}=e??{},a=await B(t,i,n);return new o(a,i)}async set(e,t){return await W(this._db,this._storeName,e,t)}async get(e){var t;return(t=await V(this._db,this._storeName,e))!==null&&t!==void 0?t:null}async remove(e){return await F(this._db,this._storeName,e)}};var H=function(o,e,t,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?o!==e||!n:!e.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(o,t):n?n.value=t:e.set(o,t),t},M=function(o,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?o!==e||!i:!e.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(o):i?i.value:e.get(o)},E,h="identity",u="delegation",A="iv",N=1,y=typeof window<"u",m=class{constructor(e="ic-",t){this.prefix=e,this._localStorage=t}get(e){return Promise.resolve(this._getLocalStorage().getItem(this.prefix+e))}set(e,t){return this._getLocalStorage().setItem(this.prefix+e,t),Promise.resolve()}remove(e){return this._getLocalStorage().removeItem(this.prefix+e),Promise.resolve()}_getLocalStorage(){if(this._localStorage)return this._localStorage;let e=typeof window>"u"?typeof globalThis>"u"?typeof self>"u"?void 0:self.localStorage:globalThis.localStorage:window.localStorage;if(!e)throw new Error("Could not find local storage.");return e}},f=class{constructor(e){E.set(this,void 0),H(this,E,e??{},"f")}get _db(){return new Promise(e=>{if(this.initializedDb){e(this.initializedDb);return}w.create(M(this,E,"f")).then(t=>{this.initializedDb=t,e(t)})})}async get(e){return await(await this._db).get(e)}async set(e,t){await(await this._db).set(e,t)}async remove(e){await(await this._db).remove(e)}};E=new WeakMap;var J="https://identity.ic0.app",U="#authorize",S="ECDSA",I="Ed25519",$=500,q="UserInterrupt",Y=class{constructor(e,t,i,n,a,d,r,l){this._identity=e,this._key=t,this._chain=i,this._storage=n,this.idleManager=a,this._createOptions=d,this._idpWindow=r,this._eventHandler=l,this._registerDefaultIdleCallback()}static async create(e={}){var t,i,n;let a=(t=e.storage)!==null&&t!==void 0?t:new f,d=(i=e.keyType)!==null&&i!==void 0?i:S,r=null;if(e.identity)r=e.identity;else{let s=await a.get(h);if(!s&&y)try{let _=new m,b=await _.get(u),D=await _.get(h);b&&D&&d===S&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await a.set(u,b),await a.set(h,D),s=b,await _.remove(u),await _.remove(h))}catch(_){console.error("error while attempting to recover localstorage: "+_)}if(s)try{typeof s=="object"?d===I&&typeof s=="string"?r=await T.fromJSON(s):r=await P.fromKeyPair(s):typeof s=="string"&&(r=T.fromJSON(s))}catch{}}let l=new K,c=null;if(r)try{let s=await a.get(u);if(typeof s=="object"&&s!==null)throw new Error("Delegation chain is incorrectly stored. A delegation chain should be stored as a string.");e.identity?l=e.identity:s&&(c=R.fromJSON(s),z(c)?"toDer"in r?l=C.fromDelegation(r,c):l=k.fromDelegation(r,c):(await p(a),r=null))}catch(s){console.error(s),await p(a),r=null}let v;return!((n=e.idleOptions)===null||n===void 0)&&n.disableIdle?v=void 0:(c||e.identity)&&(v=g.create(e.idleOptions)),r||(d===I?(r=await T.generate(),await a.set(h,JSON.stringify(r.toJSON()))):(e.storage&&d===S&&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 '${I}' as the key type, as it can serialize to a string`),r=await P.generate(),await a.set(h,r.getKeyPair()))),new this(l,r,c,a,v,e)}_registerDefaultIdleCallback(){var e,t;let i=(e=this._createOptions)===null||e===void 0?void 0:e.idleOptions;!i?.onIdle&&!i?.disableDefaultIdleCallback&&((t=this.idleManager)===null||t===void 0||t.registerCallback(()=>{this.logout(),location.reload()}))}async _handleSuccess(e,t){var i,n;let a=e.delegations.map(c=>({delegation:new j(c.delegation.pubkey,c.delegation.expiration,c.delegation.targets),signature:c.signature.buffer})),d=R.fromDelegations(a,e.userPublicKey.buffer),r=this._key;if(!r)return;this._chain=d,"toDer"in r?this._identity=C.fromDelegation(r,this._chain):this._identity=k.fromDelegation(r,this._chain),(i=this._idpWindow)===null||i===void 0||i.close();let l=(n=this._createOptions)===null||n===void 0?void 0:n.idleOptions;!this.idleManager&&!l?.disableIdle&&(this.idleManager=g.create(l),this._registerDefaultIdleCallback()),this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(u,JSON.stringify(this._chain.toJSON())),t?.(e)}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null}async login(e){var t,i,n,a;let d=BigInt(8)*BigInt(36e11),r=new URL(((t=e?.identityProvider)===null||t===void 0?void 0:t.toString())||J);r.hash=U,(i=this._idpWindow)===null||i===void 0||i.close(),this._removeEventListener(),this._eventHandler=this._getEventHandler(r,Object.assign({maxTimeToLive:(n=e?.maxTimeToLive)!==null&&n!==void 0?n:d},e)),window.addEventListener("message",this._eventHandler),this._idpWindow=(a=window.open(r.toString(),"idpWindow",e?.windowOpenerFeatures))!==null&&a!==void 0?a:void 0;let l=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(q,e?.onError):setTimeout(l,$))};l()}_getEventHandler(e,t){return async i=>{var n,a,d;if(i.origin!==e.origin){console.warn(`WARNING: expected origin '${e.origin}', got '${i.origin}' (ignoring)`);return}let r=i.data;switch(r.kind){case"authorize-ready":{let l=Object.assign({kind:"authorize-client",sessionPublicKey:new Uint8Array((n=this._key)===null||n===void 0?void 0:n.getPublicKey().toDer()),maxTimeToLive:t?.maxTimeToLive,allowPinAuthentication:t?.allowPinAuthentication,derivationOrigin:(a=t?.derivationOrigin)===null||a===void 0?void 0:a.toString()},t?.customValues);(d=this._idpWindow)===null||d===void 0||d.postMessage(l,e.origin);break}case"authorize-client-success":try{await this._handleSuccess(r,t?.onSuccess)}catch(l){this._handleFailure(l.message,t?.onError)}break;case"authorize-client-failure":this._handleFailure(r.text,t?.onError);break;default:break}}}_handleFailure(e,t){var i;(i=this._idpWindow)===null||i===void 0||i.close(),t?.(e),this._removeEventListener(),delete this._idpWindow}_removeEventListener(){this._eventHandler&&window.removeEventListener("message",this._eventHandler),this._eventHandler=void 0}async logout(e={}){if(await p(this._storage),this._identity=new K,this._chain=null,e.returnTo)try{window.history.pushState({},"",e.returnTo)}catch{window.location.href=e.returnTo}}};async function p(o){await o.remove(h),await o.remove(u),await o.remove(A)}export{Y as AuthClient,q as ERROR_USER_INTERRUPT,w as IdbKeyVal,f as IdbStorage,g as IdleManager,u as KEY_STORAGE_DELEGATION,h as KEY_STORAGE_KEY,m as LocalStorage};
//# sourceMappingURL=auth-client.mjs.map