@iebh/tera-fy 2.0.10 → 2.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.0.11](https://github.com/IEBH/TERA-fy/compare/v2.0.9...v2.0.11) (2025-03-10)
4
+
5
+
6
+ ### fix
7
+
8
+ * Typo in error handling when loading state ([7abb66c](https://github.com/IEBH/TERA-fy/commit/7abb66c08d6c6ecf1dc1cd0da826fe8927b0c288))
9
+
10
+ ### task
11
+
12
+ * Ported migration step for projects.temp[tool] data to files ([de3affc](https://github.com/IEBH/TERA-fy/commit/de3affc5a8b4eb12823e01122b3685e704ca283e))
13
+
3
14
  ## [2.0.9](https://github.com/IEBH/TERA-fy/compare/v2.0.8...v2.0.9) (2025-03-05)
4
15
 
5
16
 
@@ -24,7 +24,7 @@ This typically indicates that your device does not have a healthy Internet conne
24
24
  if (e.data.event === "start") {
25
25
  setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
26
26
  }
27
- });`,jn=class{constructor(e,t){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=n_,this.params={},this.timeout=wa,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=XR,this.conn=null,this.sendBuffer=[],this.serializer=new Zs,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let a;return i?a=i:typeof fetch=="undefined"?a=(...u)=>Promise.resolve().then(()=>(rr(),Er)).then(({default:c})=>c(...u)):a=fetch,(...u)=>a(...u)},this.endPoint=`${e}/${va.websocket}`,this.httpEndpoint=ba(e),t!=null&&t.transport?this.transport=t.transport:this.transport=null,t!=null&&t.params&&(this.params=t.params),t!=null&&t.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t!=null&&t.timeout&&(this.timeout=t.timeout),t!=null&&t.logger&&(this.logger=t.logger),t!=null&&t.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let s=(n=t==null?void 0:t.params)===null||n===void 0?void 0:n.apikey;if(s&&(this.accessTokenValue=s,this.apiKey=s),this.reconnectAfterMs=t!=null&&t.reconnectAfterMs?t.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=t!=null&&t.encode?t.encode:(i,a)=>a(JSON.stringify(i)),this.decode=t!=null&&t.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new Ar(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t==null?void 0:t.fetch),t!=null&&t.worker){if(typeof window!="undefined"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=(t==null?void 0:t.worker)||!1,this.workerUrl=t==null?void 0:t.workerUrl}this.accessToken=(t==null?void 0:t.accessToken)||null}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this.endpointURL(),void 0,{headers:this.headers});return}if(ZR){this.conn=new WebSocket(this.endpointURL()),this.setupConnection();return}this.conn=new dh(this.endpointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Ad(u_())).then(({default:e})=>{this.conn=new e(this.endpointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:s_}))}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t!=null?t:""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,n){this.logger(e,t,n)}connectionState(){switch(this.conn&&this.conn.readyState){case Ir.connecting:return nr.Connecting;case Ir.open:return nr.Open;case Ir.closing:return nr.Closing;default:return nr.Closed}}isConnected(){return this.connectionState()===nr.Open}channel(e,t={config:{}}){let n=new Fn(`realtime:${e}`,t,this);return this.channels.push(n),n}push(e){let{topic:t,event:n,payload:s,ref:i}=e,a=()=>{this.encode(e,u=>{var c;(c=this.conn)===null||c===void 0||c.send(u)})};this.log("push",`${t} ${n} (${i})`,s),this.isConnected()?a():this.sendBuffer.push(a)}async setAuth(e=null){let t=e||this.accessToken&&await this.accessToken()||this.accessTokenValue;if(t){let n=null;try{n=JSON.parse(atob(t.split(".")[1]))}catch{}if(n&&n.exp&&!(Math.floor(Date.now()/1e3)-n.exp<0))return this.log("auth",`InvalidJWTToken: Invalid value for JWT claim "exp" with value ${n.exp}`),Promise.reject(`InvalidJWTToken: Invalid value for JWT claim "exp" with value ${n.exp}`);this.accessTokenValue=t,this.channels.forEach(s=>{t&&s.updateJoinPayload({access_token:t}),s.joinedOnce&&s._isJoined()&&s._push(Be.access_token,{access_token:t})})}}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(i_,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth()}}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(n=>n.topic===e&&(n._isJoined()||n._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:n,event:s,payload:i,ref:a}=t;a&&a===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${n} ${s} ${a&&"("+a+")"||""}`,i),this.channels.filter(u=>u._isMember(n)).forEach(u=>u._trigger(s,i,a)),this.stateChangeCallbacks.message.forEach(u=>u(t))})}async _onConnOpen(){if(this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this.reconnectTimer.reset(),!this.worker)this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs);else{this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=t=>{this.log("worker","worker error",t.message),this.workerRef.terminate()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(Be.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let n=e.match(/\?/)?"&":"?",s=new URLSearchParams(t);return`${e}${n}${s}`}_workerObjectUrl(e){let t;if(e)t=e;else{let n=new Blob([eP],{type:"application/javascript"});t=URL.createObjectURL(n)}return t}},dh=class{constructor(e,t,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Ir.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}};var Un=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function ge(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var Ta=class extends Un{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},Sr=class extends Un{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var tP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},Ia=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(rr(),Er)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},c_=()=>tP(void 0,void 0,void 0,function*(){return typeof Response=="undefined"?(yield Promise.resolve().then(()=>(rr(),Er))).Response:Response}),Ea=r=>{if(Array.isArray(r))return r.map(t=>Ea(t));if(typeof r=="function"||r!==Object(r))return r;let e={};return Object.entries(r).forEach(([t,n])=>{let s=t.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[s]=Ea(n)}),e};var Rr=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},fh=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),rP=(r,e,t)=>Rr(void 0,void 0,void 0,function*(){let n=yield c_();r instanceof n&&!(t!=null&&t.noResolveJson)?r.json().then(s=>{e(new Ta(fh(s),r.status||500))}).catch(s=>{e(new Sr(fh(s),s))}):e(new Sr(fh(r),r))}),nP=(r,e,t,n)=>{let s={method:r,headers:(e==null?void 0:e.headers)||{}};return r==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),n&&(s.body=JSON.stringify(n)),Object.assign(Object.assign({},s),t))};function ei(r,e,t,n,s,i){return Rr(this,void 0,void 0,function*(){return new Promise((a,u)=>{r(t,nP(e,n,s,i)).then(c=>{if(!c.ok)throw c;return n!=null&&n.noResolveJson?c:c.json()}).then(c=>a(c)).catch(c=>rP(c,u,n))})})}function Bn(r,e,t,n){return Rr(this,void 0,void 0,function*(){return ei(r,"GET",e,t,n)})}function ct(r,e,t,n,s){return Rr(this,void 0,void 0,function*(){return ei(r,"POST",e,n,s,t)})}function l_(r,e,t,n,s){return Rr(this,void 0,void 0,function*(){return ei(r,"PUT",e,n,s,t)})}function h_(r,e,t,n){return Rr(this,void 0,void 0,function*(){return ei(r,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),n)})}function Aa(r,e,t,n,s){return Rr(this,void 0,void 0,function*(){return ei(r,"DELETE",e,n,s,t)})}var Me=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},sP={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},d_={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ti=class{constructor(e,t={},n,s){this.url=e,this.headers=t,this.bucketId=n,this.fetch=Ia(s)}uploadOrUpdate(e,t,n,s){return Me(this,void 0,void 0,function*(){try{let i,a=Object.assign(Object.assign({},d_),s),u=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(a.upsert)}),c=a.metadata;typeof Blob!="undefined"&&n instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),c&&i.append("metadata",this.encodeMetadata(c)),i.append("",n)):typeof FormData!="undefined"&&n instanceof FormData?(i=n,i.append("cacheControl",a.cacheControl),c&&i.append("metadata",this.encodeMetadata(c))):(i=n,u["cache-control"]=`max-age=${a.cacheControl}`,u["content-type"]=a.contentType,c&&(u["x-metadata"]=this.toBase64(this.encodeMetadata(c)))),s!=null&&s.headers&&(u=Object.assign(Object.assign({},u),s.headers));let h=this._removeEmptyFolders(t),f=this._getFinalPath(h),m=yield this.fetch(`${this.url}/object/${f}`,Object.assign({method:e,body:i,headers:u},a!=null&&a.duplex?{duplex:a.duplex}:{})),g=yield m.json();return m.ok?{data:{path:h,id:g.Id,fullPath:g.Key},error:null}:{data:null,error:g}}catch(i){if(ge(i))return{data:null,error:i};throw i}})}upload(e,t,n){return Me(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,n)})}uploadToSignedUrl(e,t,n,s){return Me(this,void 0,void 0,function*(){let i=this._removeEmptyFolders(e),a=this._getFinalPath(i),u=new URL(this.url+`/object/upload/sign/${a}`);u.searchParams.set("token",t);try{let c,h=Object.assign({upsert:d_.upsert},s),f=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob!="undefined"&&n instanceof Blob?(c=new FormData,c.append("cacheControl",h.cacheControl),c.append("",n)):typeof FormData!="undefined"&&n instanceof FormData?(c=n,c.append("cacheControl",h.cacheControl)):(c=n,f["cache-control"]=`max-age=${h.cacheControl}`,f["content-type"]=h.contentType);let m=yield this.fetch(u.toString(),{method:"PUT",body:c,headers:f}),g=yield m.json();return m.ok?{data:{path:i,fullPath:g.Key},error:null}:{data:null,error:g}}catch(c){if(ge(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return Me(this,void 0,void 0,function*(){try{let n=this._getFinalPath(e),s=Object.assign({},this.headers);t!=null&&t.upsert&&(s["x-upsert"]="true");let i=yield ct(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:s}),a=new URL(this.url+i.url),u=a.searchParams.get("token");if(!u)throw new Un("No token returned by API");return{data:{signedUrl:a.toString(),path:e,token:u},error:null}}catch(n){if(ge(n))return{data:null,error:n};throw n}})}update(e,t,n){return Me(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,n)})}move(e,t,n){return Me(this,void 0,void 0,function*(){try{return{data:yield ct(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers}),error:null}}catch(s){if(ge(s))return{data:null,error:s};throw s}})}copy(e,t,n){return Me(this,void 0,void 0,function*(){try{return{data:{path:(yield ct(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers})).Key},error:null}}catch(s){if(ge(s))return{data:null,error:s};throw s}})}createSignedUrl(e,t,n){return Me(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=yield ct(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},n!=null&&n.transform?{transform:n.transform}:{}),{headers:this.headers}),a=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${a}`)},{data:i,error:null}}catch(s){if(ge(s))return{data:null,error:s};throw s}})}createSignedUrls(e,t,n){return Me(this,void 0,void 0,function*(){try{let s=yield ct(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return{data:s.map(a=>Object.assign(Object.assign({},a),{signedUrl:a.signedURL?encodeURI(`${this.url}${a.signedURL}${i}`):null})),error:null}}catch(s){if(ge(s))return{data:null,error:s};throw s}})}download(e,t){return Me(this,void 0,void 0,function*(){let s=typeof(t==null?void 0:t.transform)!="undefined"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),a=i?`?${i}`:"";try{let u=this._getFinalPath(e);return{data:yield(yield Bn(this.fetch,`${this.url}/${s}/${u}${a}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(u){if(ge(u))return{data:null,error:u};throw u}})}info(e){return Me(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{let n=yield Bn(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:Ea(n),error:null}}catch(n){if(ge(n))return{data:null,error:n};throw n}})}exists(e){return Me(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{return yield h_(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(ge(n)&&n instanceof Sr){let s=n.originalError;if([400,404].includes(s==null?void 0:s.status))return{data:!1,error:n}}throw n}})}getPublicUrl(e,t){let n=this._getFinalPath(e),s=[],i=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";i!==""&&s.push(i);let u=typeof(t==null?void 0:t.transform)!="undefined"?"render/image":"object",c=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});c!==""&&s.push(c);let h=s.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${u}/public/${n}${h}`)}}}remove(e){return Me(this,void 0,void 0,function*(){try{return{data:yield Aa(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}})}list(e,t,n){return Me(this,void 0,void 0,function*(){try{let s=Object.assign(Object.assign(Object.assign({},sP),t),{prefix:e||""});return{data:yield ct(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},n),error:null}}catch(s){if(ge(s))return{data:null,error:s};throw s}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer!="undefined"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var f_="2.7.1";var p_={"X-Client-Info":`storage-js/${f_}`};var $n=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},ri=class{constructor(e,t={},n){this.url=e,this.headers=Object.assign(Object.assign({},p_),t),this.fetch=Ia(n)}listBuckets(){return $n(this,void 0,void 0,function*(){try{return{data:yield Bn(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(ge(e))return{data:null,error:e};throw e}})}getBucket(e){return $n(this,void 0,void 0,function*(){try{return{data:yield Bn(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return $n(this,void 0,void 0,function*(){try{return{data:yield ct(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(ge(n))return{data:null,error:n};throw n}})}updateBucket(e,t){return $n(this,void 0,void 0,function*(){try{return{data:yield l_(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(ge(n))return{data:null,error:n};throw n}})}emptyBucket(e){return $n(this,void 0,void 0,function*(){try{return{data:yield ct(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}})}deleteBucket(e){return $n(this,void 0,void 0,function*(){try{return{data:yield Aa(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}})}};var ni=class extends ri{constructor(e,t={},n){super(e,t,n)}from(e){return new ti(this.url,this.headers,e,this.fetch)}};var m_="2.48.1";var si="";typeof Deno!="undefined"?si="deno":typeof document!="undefined"?si="web":typeof navigator!="undefined"&&navigator.product==="ReactNative"?si="react-native":si="node";var iP={"X-Client-Info":`supabase-js-${si}/${m_}`},g_={headers:iP},y_={schema:"public"},__={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},v_={};rr();var oP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},aP=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=Wl:e=fetch,(...t)=>e(...t)},uP=()=>typeof Headers=="undefined"?Ql:Headers,w_=(r,e,t)=>{let n=aP(t),s=uP();return(i,a)=>oP(void 0,void 0,void 0,function*(){var u;let c=(u=yield e())!==null&&u!==void 0?u:r,h=new s(a==null?void 0:a.headers);return h.has("apikey")||h.set("apikey",r),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),n(i,Object.assign(Object.assign({},a),{headers:h}))})};var cP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})};function b_(r){return r.replace(/\/$/,"")}function T_(r,e){let{db:t,auth:n,realtime:s,global:i}=r,{db:a,auth:u,realtime:c,global:h}=e,f={db:Object.assign(Object.assign({},a),t),auth:Object.assign(Object.assign({},u),n),realtime:Object.assign(Object.assign({},c),s),global:Object.assign(Object.assign({},h),i),accessToken:()=>cP(this,void 0,void 0,function*(){return""})};return r.accessToken?f.accessToken=r.accessToken:delete f.accessToken,f}var xa="2.67.3";var E_="http://localhost:9999",I_="supabase.auth.token";var A_={"X-Client-Info":`gotrue-js/${xa}`},ph=10;var ii="X-Supabase-Api-Version",mh={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function x_(r){return Math.round(Date.now()/1e3)+r}function S_(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let e=Math.random()*16|0;return(r=="x"?e:e&3|8).toString(16)})}var Qe=()=>typeof window!="undefined"&&typeof document!="undefined",Pr={tested:!1,writable:!1},sr=()=>{if(!Qe())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Pr.tested)return Pr.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Pr.tested=!0,Pr.writable=!0}catch{Pr.tested=!0,Pr.writable=!1}return Pr.writable};function R_(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return t.searchParams.forEach((n,s)=>{e[s]=n}),e}var Sa=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(rr(),Er)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},P_=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",gh=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},ai=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},ui=async(r,e)=>{await r.removeItem(e)};function lP(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",n,s,i,a,u,c,h,f=0;for(r=r.replace("-","+").replace("_","/");f<r.length;)a=e.indexOf(r.charAt(f++)),u=e.indexOf(r.charAt(f++)),c=e.indexOf(r.charAt(f++)),h=e.indexOf(r.charAt(f++)),n=a<<2|u>>4,s=(u&15)<<4|c>>2,i=(c&3)<<6|h,t=t+String.fromCharCode(n),c!=64&&s!=0&&(t=t+String.fromCharCode(s)),h!=64&&i!=0&&(t=t+String.fromCharCode(i));return t}var oi=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};oi.promiseConstructor=Promise;function yh(r){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=r.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let n=t[1];return JSON.parse(lP(n))}async function C_(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function k_(r,e){return new Promise((n,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let a=await r(i);if(!e(i,null,a)){n(a);return}}catch(a){if(!e(i,a)){s(a);return}}})()})}function hP(r){return("0"+r.toString(16)).substr(-2)}function dP(){let e=new Uint32Array(56);if(typeof crypto=="undefined"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=t.length,s="";for(let i=0;i<56;i++)s+=t.charAt(Math.floor(Math.random()*n));return s}return crypto.getRandomValues(e),Array.from(e,hP).join("")}async function fP(r){let t=new TextEncoder().encode(r),n=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(n);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}function pP(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function mP(r){if(!(typeof crypto!="undefined"&&typeof crypto.subtle!="undefined"&&typeof TextEncoder!="undefined"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),r;let t=await fP(r);return pP(t)}async function Cr(r,e,t=!1){let n=dP(),s=n;t&&(s+="/PASSWORD_RECOVERY"),await gh(r,`${e}-code-verifier`,s);let i=await mP(n);return[i,n===i?"plain":"s256"]}var gP=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function D_(r){let e=r.headers.get(ii);if(!e||!e.match(gP))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var ci=class extends Error{constructor(e,t,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=n}};function z(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var Ra=class extends ci{constructor(e,t,n){super(e,t,n),this.name="AuthApiError",this.status=t,this.code=n}};function O_(r){return z(r)&&r.name==="AuthApiError"}var qn=class extends ci{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},Pt=class extends ci{constructor(e,t,n,s){super(e,n,s),this.name=t,this.status=n}},ze=class extends Pt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function N_(r){return z(r)&&r.name==="AuthSessionMissingError"}var zn=class extends Pt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},kr=class extends Pt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Dr=class extends Pt{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};function V_(r){return z(r)&&r.name==="AuthImplicitGrantRedirectError"}var li=class extends Pt{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},Gn=class extends Pt{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Pa(r){return z(r)&&r.name==="AuthRetryableFetchError"}var hi=class extends Pt{constructor(e,t,n){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=n}};var yP=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(r);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(r,n[s])&&(t[n[s]]=r[n[s]]);return t},Or=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),_P=[502,503,504];async function L_(r){var e;if(!P_(r))throw new Gn(Or(r),0);if(_P.includes(r.status))throw new Gn(Or(r),r.status);let t;try{t=await r.json()}catch(i){throw new qn(Or(i),i)}let n,s=D_(r);if(s&&s.getTime()>=mh["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?n=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(n=t.error_code),n){if(n==="weak_password")throw new hi(Or(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new ze}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((i,a)=>i&&typeof a=="string",!0))throw new hi(Or(t),r.status,t.weak_password.reasons);throw new Ra(Or(t),r.status||500,n)}var vP=(r,e,t,n)=>{let s={method:r,headers:(e==null?void 0:e.headers)||{}};return r==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),s.body=JSON.stringify(n),Object.assign(Object.assign({},s),t))};async function K(r,e,t,n){var s;let i=Object.assign({},n==null?void 0:n.headers);i[ii]||(i[ii]=mh["2024-01-01"].name),n!=null&&n.jwt&&(i.Authorization=`Bearer ${n.jwt}`);let a=(s=n==null?void 0:n.query)!==null&&s!==void 0?s:{};n!=null&&n.redirectTo&&(a.redirect_to=n.redirectTo);let u=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",c=await wP(r,e,t+u,{headers:i,noResolveJson:n==null?void 0:n.noResolveJson},{},n==null?void 0:n.body);return n!=null&&n.xform?n==null?void 0:n.xform(c):{data:Object.assign({},c),error:null}}async function wP(r,e,t,n,s,i){let a=vP(e,n,s,i),u;try{u=await r(t,Object.assign({},a))}catch(c){throw console.error(c),new Gn(Or(c),0)}if(u.ok||await L_(u),n!=null&&n.noResolveJson)return u;try{return await u.json()}catch(c){await L_(c)}}function Ct(r){var e;let t=null;bP(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=x_(r.expires_in)));let n=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:n},error:null}}function _h(r){let e=Ct(r);return!e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((t,n)=>t&&typeof n=="string",!0)&&(e.data.weak_password=r.weak_password),e}function lt(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function M_(r){return{data:r,error:null}}function F_(r){let{action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:i}=r,a=yP(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),u={action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:i},c=Object.assign({},a);return{data:{properties:u,user:c},error:null}}function j_(r){return r}function bP(r){return r.access_token&&r.refresh_token&&r.expires_in}var TP=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(r);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(r,n[s])&&(t[n[s]]=r[n[s]]);return t},Nr=class{constructor({url:e="",headers:t={},fetch:n}){this.url=e,this.headers=t,this.fetch=Sa(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await K(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(z(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,t={}){try{return await K(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:lt})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:t}=e,n=TP(e,["options"]),s=Object.assign(Object.assign({},n),t);return"newEmail"in n&&(s.new_email=n==null?void 0:n.newEmail,delete s.newEmail),await K(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:F_,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(z(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await K(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:lt})}catch(t){if(z(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,n,s,i,a,u,c;try{let h={nextPage:null,lastPage:0,total:0},f=await K(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:"",per_page:(i=(s=e==null?void 0:e.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:j_});if(f.error)throw f.error;let m=await f.json(),g=(a=f.headers.get("x-total-count"))!==null&&a!==void 0?a:0,E=(c=(u=f.headers.get("link"))===null||u===void 0?void 0:u.split(","))!==null&&c!==void 0?c:[];return E.length>0&&(E.forEach(P=>{let C=parseInt(P.split(";")[0].split("=")[1].substring(0,1)),R=JSON.parse(P.split(";")[1].split("=")[1]);h[`${R}Page`]=C}),h.total=parseInt(g)),{data:Object.assign(Object.assign({},m),h),error:null}}catch(h){if(z(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await K(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:lt})}catch(t){if(z(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await K(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:lt})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,t=!1){try{return await K(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:lt})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){try{let{data:t,error:n}=await K(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:t,error:n}}catch(t){if(z(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await K(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(z(t))return{data:null,error:t};throw t}}};var U_={getItem:r=>sr()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{sr()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{sr()&&globalThis.localStorage.removeItem(r)}};function vh(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function B_(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self!="undefined"&&(self.globalThis=self)}}var Vr={debug:!!(globalThis&&sr()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},di=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Ca=class extends di{};async function wh(r,e,t){Vr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),Vr.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async s=>{if(s){Vr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,s.name);try{return await t()}finally{Vr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,s.name)}}else{if(e===0)throw Vr.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Ca(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Vr.debug)try{let i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}}))}B_();var EP={url:E_,storageKey:I_,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:A_,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},fi=30*1e3,$_=3;async function q_(r,e,t){return await t()}var Lr=class r{constructor(e){var t,n;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=r.nextInstanceID,r.nextInstanceID+=1,this.instanceID>0&&Qe()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let s=Object.assign(Object.assign({},EP),e);if(this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.persistSession=s.persistSession,this.storageKey=s.storageKey,this.autoRefreshToken=s.autoRefreshToken,this.admin=new Nr({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Sa(s.fetch),this.lock=s.lock||q_,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,s.lock?this.lock=s.lock:Qe()&&(!((t=globalThis==null?void 0:globalThis.navigator)===null||t===void 0)&&t.locks)?this.lock=wh:this.lock=q_,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?s.storage?this.storage=s.storage:sr()?this.storage=U_:(this.memoryStorage={},this.storage=vh(this.memoryStorage)):(this.memoryStorage={},this.storage=vh(this.memoryStorage)),Qe()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${xa}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let t=R_(window.location.href),n="none";if(this._isImplicitGrantCallback(t)?n="implicit":await this._isPKCECallback(t)&&(n="pkce"),Qe()&&this.detectSessionInUrl&&n!=="none"){let{data:s,error:i}=await this._getSessionFromURL(t,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),V_(i)){let c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}let{session:a,redirectType:u}=s;return this._debug("#_initialize()","detected session in URL",a,"redirect type",u),await this._saveSession(a),setTimeout(async()=>{u==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return z(t)?{error:t}:{error:new qn("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,n,s;try{let i=await K(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(t=e==null?void 0:e.options)===null||t===void 0?void 0:t.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(s=e==null?void 0:e.options)===null||s===void 0?void 0:s.captchaToken}},xform:Ct}),{data:a,error:u}=i;if(u||!a)return{data:{user:null,session:null},error:u};let c=a.session,h=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(i){if(z(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(e){var t,n,s;try{let i;if("email"in e){let{email:f,password:m,options:g}=e,E=null,P=null;this.flowType==="pkce"&&([E,P]=await Cr(this.storage,this.storageKey)),i=await K(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:g==null?void 0:g.emailRedirectTo,body:{email:f,password:m,data:(t=g==null?void 0:g.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken},code_challenge:E,code_challenge_method:P},xform:Ct})}else if("phone"in e){let{phone:f,password:m,options:g}=e;i=await K(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:f,password:m,data:(n=g==null?void 0:g.data)!==null&&n!==void 0?n:{},channel:(s=g==null?void 0:g.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken}},xform:Ct})}else throw new kr("You must provide either an email or phone number and a password");let{data:a,error:u}=i;if(u||!a)return{data:{user:null,session:null},error:u};let c=a.session,h=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(i){if(z(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:a,options:u}=e;t=await K(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:_h})}else if("phone"in e){let{phone:i,password:a,options:u}=e;t=await K(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:_h})}else throw new kr("You must provide either an email or phone number and a password");let{data:n,error:s}=t;return s?{data:{user:null,session:null},error:s}:!n||!n.session||!n.user?{data:{user:null,session:null},error:new zn}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:s})}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,n,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await ai(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(t!=null?t:"").split("/");try{let{data:i,error:a}=await K(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Ct});if(await ui(this.storage,`${this.storageKey}-code-verifier`),a)throw a;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new zn}:(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),{data:Object.assign(Object.assign({},i),{redirectType:s!=null?s:null}),error:a})}catch(i){if(z(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(e){try{let{options:t,provider:n,token:s,access_token:i,nonce:a}=e,u=await K(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:s,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:Ct}),{data:c,error:h}=u;return h?{data:{user:null,session:null},error:h}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new zn}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:h})}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,n,s,i,a;try{if("email"in e){let{email:u,options:c}=e,h=null,f=null;this.flowType==="pkce"&&([h,f]=await Cr(this.storage,this.storageKey));let{error:m}=await K(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:u,data:(t=c==null?void 0:c.data)!==null&&t!==void 0?t:{},create_user:(n=c==null?void 0:c.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:h,code_challenge_method:f},redirectTo:c==null?void 0:c.emailRedirectTo});return{data:{user:null,session:null},error:m}}if("phone"in e){let{phone:u,options:c}=e,{data:h,error:f}=await K(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:u,data:(s=c==null?void 0:c.data)!==null&&s!==void 0?s:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(a=c==null?void 0:c.channel)!==null&&a!==void 0?a:"sms"}});return{data:{user:null,session:null,messageId:h==null?void 0:h.message_id},error:f}}throw new kr("You must provide either an email or phone number.")}catch(u){if(z(u))return{data:{user:null,session:null},error:u};throw u}}async verifyOtp(e){var t,n;try{let s,i;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:a,error:u}=await K(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:Ct});if(u)throw u;if(!a)throw new Error("An error occurred on token verification.");let c=a.session,h=a.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(s){if(z(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithSSO(e){var t,n,s;try{let i=null,a=null;return this.flowType==="pkce"&&([i,a]=await Cr(this.storage,this.storageKey)),await K(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(n=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&n!==void 0?n:void 0}),!((s=e==null?void 0:e.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:a}),headers:this.headers,xform:M_})}catch(i){if(z(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;if(n)throw n;if(!t)throw new ze;let{error:s}=await K(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:s}})}catch(e){if(z(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:n,type:s,options:i}=e,{error:a}=await K(this.fetch,"POST",t,{headers:this.headers,body:{email:n,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:a}}else if("phone"in e){let{phone:n,type:s,options:i}=e,{data:a,error:u}=await K(this.fetch,"POST",t,{headers:this.headers,body:{phone:n,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:u}}throw new kr("You must provide either an email or phone number and a type")}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await n,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let n=t();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await ai(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.storage.isServer){let a=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,h,f)=>(!a&&h==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),a=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,h,f))})}return{data:{session:e},error:null}}let{session:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:s},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await K(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:lt}):await this._useSession(async t=>{var n,s,i;let{data:a,error:u}=t;if(u)throw u;return!(!((n=a.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new ze}:await K(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=a.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:lt})})}catch(t){if(z(t))return N_(t)&&(await this._removeSession(),await ui(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async n=>{let{data:s,error:i}=n;if(i)throw i;if(!s.session)throw new ze;let a=s.session,u=null,c=null;this.flowType==="pkce"&&e.email!=null&&([u,c]=await Cr(this.storage,this.storageKey));let{data:h,error:f}=await K(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:u,code_challenge_method:c}),jwt:a.access_token,xform:lt});if(f)throw f;return a.user=h.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),{data:{user:a.user},error:null}})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}_decodeJWT(e){return yh(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new ze;let t=Date.now()/1e3,n=t,s=!0,i=null,a=yh(e.access_token);if(a.exp&&(n=a.exp,s=n<=t),s){let{session:u,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!u)return{data:{user:null,session:null},error:null};i=u}else{let{data:u,error:c}=await this._getUser(e.access_token);if(c)throw c;i={access_token:e.access_token,refresh_token:e.refresh_token,user:u.user,token_type:"bearer",expires_in:n-t,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(t){if(z(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var n;if(!e){let{data:a,error:u}=t;if(u)throw u;e=(n=a.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new ze;let{session:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:s?{data:{user:s.user,session:s},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!Qe())throw new Dr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Dr(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new li("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Dr("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new li("No code detected.");let{data:M,error:U}=await this._exchangeCodeForSession(e.code);if(U)throw U;let G=new URL(window.location.href);return G.searchParams.delete("code"),window.history.replaceState(window.history.state,"",G.toString()),{data:{session:M.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:s,access_token:i,refresh_token:a,expires_in:u,expires_at:c,token_type:h}=e;if(!i||!u||!a||!h)throw new Dr("No session defined in URL");let f=Math.round(Date.now()/1e3),m=parseInt(u),g=f+m;c&&(g=parseInt(c));let E=g-f;E*1e3<=fi&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${E}s, should have been closer to ${m}s`);let P=g-m;f-P>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",P,g,f):f-P<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",P,g,f);let{data:C,error:R}=await this._getUser(i);if(R)throw R;let N={provider_token:n,provider_refresh_token:s,access_token:i,expires_in:m,expires_at:g,refresh_token:a,token_type:h,user:C.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:N,redirectType:e.type},error:null}}catch(n){if(z(n))return{data:{session:null,redirectType:null},error:n};throw n}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await ai(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var n;let{data:s,error:i}=t;if(i)return{error:i};let a=(n=s.session)===null||n===void 0?void 0:n.access_token;if(a){let{error:u}=await this.admin.signOut(a,e);if(u&&!(O_(u)&&(u.status===404||u.status===401||u.status===403)))return{error:u}}return e!=="others"&&(await this._removeSession(),await ui(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){let t=S_(),n={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,n),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async t=>{var n,s;try{let{data:{session:i},error:a}=t;if(a)throw a;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,t={}){let n=null,s=null;this.flowType==="pkce"&&([n,s]=await Cr(this.storage,this.storageKey,!0));try{return await K(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(z(i))return{data:null,error:i};throw i}}async getUserIdentities(){var e;try{let{data:t,error:n}=await this.getUser();if(n)throw n;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(z(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:n,error:s}=await this._useSession(async i=>{var a,u,c,h,f;let{data:m,error:g}=i;if(g)throw g;let E=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(u=e.options)===null||u===void 0?void 0:u.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await K(this.fetch,"GET",E,{headers:this.headers,jwt:(f=(h=m.session)===null||h===void 0?void 0:h.access_token)!==null&&f!==void 0?f:void 0})});if(s)throw s;return Qe()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),{data:{provider:e.provider,url:n==null?void 0:n.url},error:null}}catch(n){if(z(n))return{data:{provider:e.provider,url:null},error:n};throw n}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var n,s;let{data:i,error:a}=t;if(a)throw a;return await K(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(z(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let n=Date.now();return await k_(async s=>(s>0&&await C_(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await K(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Ct})),(s,i)=>{let a=200*Math.pow(2,s);return i&&Pa(i)&&Date.now()+a-n<fi})}catch(n){if(this._debug(t,"error",n),z(n))return{data:{session:null,user:null},error:n};throw n}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",n),Qe()&&!t.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let n=await ai(this.storage,this.storageKey);if(this._debug(t,"session from storage",n),!this._isValidSession(n)){this._debug(t,"session is not valid"),n!==null&&await this._removeSession();return}let s=Math.round(Date.now()/1e3),i=((e=n.expires_at)!==null&&e!==void 0?e:1/0)<s+ph;if(this._debug(t,`session has${i?"":" not"} expired with margin of ${ph}s`),i){if(this.autoRefreshToken&&n.refresh_token){let{error:a}=await this._callRefreshToken(n.refresh_token);a&&(console.error(a),Pa(a)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(t,"error",n),console.error(n);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,n;if(!e)throw new ze;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new oi;let{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new ze;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let u={session:i.session,error:null};return this.refreshingDeferred.resolve(u),u}catch(i){if(this._debug(s,"error",i),z(i)){let a={session:null,error:i};return Pa(i)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(a),a}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,n=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],a=Array.from(this.stateChangeEmitters.values()).map(async u=>{try{await u.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(a),i.length>0){for(let u=0;u<i.length;u+=1)console.error(i[u]);throw i[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await gh(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await ui(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Qe()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),fi);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno!="undefined"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:n}}=t;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((n.expires_at*1e3-e)/fi);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${fi}ms, refresh threshold is ${$_} ticks`),s<=$_&&await this._callRefreshToken(n.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof di)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Qe()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,n){let s=[`provider=${encodeURIComponent(t)}`];if(n!=null&&n.redirectTo&&s.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&s.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){let[i,a]=await Cr(this.storage,this.storageKey),u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});s.push(u.toString())}if(n!=null&&n.queryParams){let i=new URLSearchParams(n.queryParams);s.push(i.toString())}return n!=null&&n.skipBrowserRedirect&&s.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;return i?{data:null,error:i}:await K(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token})})}catch(t){if(z(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var n,s;let{data:i,error:a}=t;if(a)return{data:null,error:a};let u=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:c,error:h}=await K(this.fetch,"POST",`${this.url}/factors`,{body:u,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});return h?{data:null,error:h}:(e.factorType==="totp"&&(!((s=c==null?void 0:c.totp)===null||s===void 0)&&s.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),{data:c,error:null})})}catch(t){if(z(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;if(i)return{data:null,error:i};let{data:a,error:u}=await K(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token});return u?{data:null,error:u}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),{data:a,error:u})})}catch(t){if(z(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;return i?{data:null,error:i}:await K(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token})})}catch(t){if(z(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:n}=await this._challenge({factorId:e.factorId});return n?{data:null,error:n}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let n=(e==null?void 0:e.factors)||[],s=n.filter(a=>a.factor_type==="totp"&&a.status==="verified"),i=n.filter(a=>a.factor_type==="phone"&&a.status==="verified");return{data:{all:n,totp:s,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,n;let{data:{session:s},error:i}=e;if(i)return{data:null,error:i};if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let a=this._decodeJWT(s.access_token),u=null;a.aal&&(u=a.aal);let c=u;((n=(t=s.user.factors)===null||t===void 0?void 0:t.filter(m=>m.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(c="aal2");let f=a.amr||[];return{data:{currentLevel:u,nextLevel:c,currentAuthenticationMethods:f},error:null}}))}};Lr.nextInstanceID=0;var IP=Lr,bh=IP;var ka=class extends bh{constructor(e){super(e)}};var AP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},pi=class{constructor(e,t,n){var s,i,a;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let u=b_(e);this.realtimeUrl=`${u}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${u}/auth/v1`,this.storageUrl=`${u}/storage/v1`,this.functionsUrl=`${u}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,h={db:y_,realtime:v_,auth:Object.assign(Object.assign({},__),{storageKey:c}),global:g_},f=T_(n!=null?n:{},h);this.storageKey=(s=f.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(i=f.global.headers)!==null&&i!==void 0?i:{},f.accessToken?(this.accessToken=f.accessToken,this.auth=new Proxy({},{get:(m,g)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(g)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((a=f.auth)!==null&&a!==void 0?a:{},this.headers,f.global.fetch),this.fetch=w_(t,this._getAccessToken.bind(this),f.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},f.realtime)),this.rest=new t_(`${u}/rest/v1`,{headers:this.headers,schema:f.db.schema,fetch:this.fetch}),f.accessToken||this._listenForAuthEvents()}get functions(){return new Ks(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new ni(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},n={}){return this.rest.rpc(e,t,n)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return AP(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();let{data:n}=yield this.auth.getSession();return(t=(e=n.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:s,storageKey:i,flowType:a,lock:u,debug:c},h,f){let m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new ka({url:this.authUrl,headers:Object.assign(Object.assign({},m),h),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:s,flowType:a,lock:u,debug:c,fetch:f,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new jn(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,n)=>{this._handleTokenChanged(t,"CLIENT",n==null?void 0:n.access_token)})}_handleTokenChanged(e,t,n){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==n?this.changedAccessToken=n:e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var z_=(r,e,t)=>new pi(r,e,t);function xP(r,e){return Object.fromEntries(Object.entries(r).sort(e||void 0).map(([t,n])=>[t,n]))}function Da(r,e){return Array.isArray(r)?r.map(t=>Da(t,e)):typeof r=="object"?Object.fromEntries(Object.entries(xP(r,e)).map(([t,n])=>[t,Da(n,e)])):r}var G_={id:"~date",test:r=>r instanceof Date,serialize:r=>({_:"~date",v:r.toISOString()}),deserialize:r=>new Date(r.v)};var K_={id:"~function",test:r=>typeof r=="function",serialize:r=>({_:"~function",v:r.toString()}),deserialize:v=>eval(v.v.toString())};var H_={id:"~infinity",test:r=>r===1/0||r===-1/0,serialize:r=>({_:"~infinity",v:r===1/0?1:0}),deserialize:r=>r.v==1?1/0:-1/0};var W_={id:"~nan",test:r=>Number.isNaN(r),serialize:r=>({_:"~nan"}),deserialize:r=>NaN};var Q_={id:"~regexp",test:r=>r instanceof RegExp,serialize:r=>({_:"~regexp",v:r.source,f:r.flags}),deserialize:r=>new RegExp(r.v,r.f)};var J_={id:"~set",test:r=>r instanceof Set,serialize:r=>({_:"~set",v:Array.from(r)}),deserialize:r=>new Set(r.v)};var Y_={id:"~undefined",test:r=>r===void 0,serialize:r=>({_:"~undefined"}),deserialize:r=>{}};var Kn={settings:{stringify:!0,destringify:!0,clone:!1,depth:0,modules:[G_,K_,H_,W_,Q_,J_,Y_],circular:!0,symetric:!1},loadedModules:{},loadModules(r){return r.map(e=>{if(Z(e)){if(!e.id)throw new Error("Provided custom module does not expose an `id` property");return Kn.loadedModules[e.id]=e}else throw new Error("Unknown module type")})},serialize(r,e){let t=so(e,Kn.settings),n=Kn.loadModules(t.modules),s=t.symetric?Da(r):t.clone?Kt(r):r,i=new Map,a=(u,c)=>{let h=Z(u);if(h&&t.circular){let g=i.get(u);if(g)return Ht(s,c,{_:"~circular",p:g.join(".")});i.set(u,c)}let f=n.find(g=>g.test(u)),m=(!t.depth||c.length<t.depth)&&h;if(f){let g=f.serialize(u);if(f.recursive&&m){let E=Se(u);t.symetric&&E.sort(),Ht(s,c,g),E.forEach(P=>a(u[P],c.concat(P)))}else c.length?Ht(s,c,g):s=g}else if(m){let g=Se(u);t.symetric&&g.sort(),g.forEach(E=>a(u[E],c.concat(E)))}};return a(s,[]),t.stringify?JSON.stringify(s):s},deserialize(r,e){let t=so(e,Kn.settings),n=Kn.loadModules(t.modules),s=du(n,"id"),i=t.destringify?JSON.parse(r):t.clone?Kt(r):r,a=(u,c)=>{if(Z(u)&&u._&&typeof u._=="string"&&u._.startsWith("~")&&s[u._]){let h=s[u._].deserialize(u);c.length?s[u._].recursive&&Z(h)?(Ht(i,c,h),Se(h).forEach(f=>a(u[f],[...c,f]))):Ht(i,c,h):i=h}else t.circular&&Z(u)&&u._&&u._=="~circular"?Ht(i,c,ms(i,u.p)):(!t.depth||c.length<t.depth)&&Z(u)&&Se(u).forEach(h=>a(u[h],c.concat(h)))};return a(i,[]),i}},mi=Kn;var X_="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Z_=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=X_[t[r]&63];return e};var re=class re{constructor(e,t){de(this,"path");de(this,"docRef");de(this,"value");de(this,"throttle",250);de(this,"config",{heartbeatInterval:5e4,syncroRegistryUrl:"https://tera-tools.com/api/sync",context:{}});de(this,"isDirty",!1);de(this,"_destroyActions",[]);de(this,"_heartbeatTimer");this.path=e,Object.assign(this,{...t,config:{...this.config,...t==null?void 0:t.config}}),re.session||(re.session=`syncro_${Z_()}`)}debug(...e){}destroy(){return this.debug("Destroy!"),Promise.all(this._destroyActions.map(e=>e())).then(()=>this._destroyActions=[])}getReactive(e){console.warn("Syncro.getReactive has not been subclassed, assuming a POJO response");let t={...e};return{doc:t,setState(n){Object.entries(n||{}).forEach(([s,i])=>t[s]=i)},getState(){return Kt(t)},watch(n){}}}static pathSplit(e,t){var a;let n={allowAsterisk:!1,...t},i={...(a=new RegExp("^(?<entity>\\w+?)::(?<id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:::(?<relation>[\\w\\-"+(n.allowAsterisk?"\\*":"")+"]+?))?$").exec(e))==null?void 0:a.groups};if(!i)throw new Error(`Invalid session path syntax "${e}"`);if(re.SyncroEntities&&!(i.entity in SyncroEntities))throw new Error(`Unsupported entity "${e}" -> Entity="${i.entity}"`);return{...i,fsCollection:i.entity,fsId:i.relation?`${i.id}::${i.relation}`:i.id}}static toFirestore(e={}){return mi.serialize(e,{circular:!1,clone:!0,modules:[ev,...mi.settings.modules],stringify:!1})}static fromFirestore(e={}){return mi.deserialize(e,{circular:!1,clone:!0,modules:[ev,...mi.settings.modules],destringify:!1})}static toFirestoreFields(e){let t={};for(let[n,s]of Object.entries(e)){let i=typeof s;i==="string"?t[n]={stringValue:s}:i==="number"?t[n]={doubleValue:s}:i==="boolean"?t[n]={booleanValue:s}:s===null?t[n]={nullValue:null}:Array.isArray(s)?t[n]={arrayValue:{values:s.map(a=>re.toFirestoreFields({item:a}).item)}}:i==="object"&&(t[n]={mapValue:{fields:re.toFirestoreFields(s)}})}return t}static fromFirestoreFields(e={}){let t={};for(let n in e){let s=e[n];if(["stringValue","booleanValue","doubleValue","integerValue","timestampValue","mapValue","arrayValue"].find(a=>a===n)){if(["stringValue","booleanValue","doubleValue","integerValue","timestampValue"].find(u=>u===n))return s;if(n=="mapValue")return re.fromFirestoreFields(s.fields||{});if(n=="arrayValue"){let u=s.values;return u?u.map(c=>re.fromFirestoreFields(c)):[]}}else t[n]=re.fromFirestoreFields(s)}return t}static getSnapshot(e){let{fsCollection:t,fsId:n}=re.pathSplit(e);return Promise.resolve().then(async()=>Hl(la(re.firestore,t,n))).then(s=>s?re.fromFirestore(s.data()):null)}static setSnapshot(e,t,n){let s={method:"merge",...n},{fsCollection:i,fsId:a}=re.pathSplit(e);return Promise.resolve().then(()=>(s.method=="merge"?"FirestoreUpdateDoc":"FirestoreSetDoc")(la(re.firestore,i,a),re.toFirestore(t))).then(()=>t)}static wrapSupabase(e){return Promise.resolve(e).then(t=>{var n,s;if(t!=null&&t.error)throw/JSON object requested, multiple \(or no\) rows returned$/.test(t.error.message)?(console.warn("Supabase query threw record not found against query",e.url.search),console.warn("Supabase raw error",t),new Error("NOT-FOUND")):(console.warn("Supabase query threw",t.error.message),new Error(`${((n=t.error)==null?void 0:n.code)||"UnknownError"}: ${((s=t.error)==null?void 0:s.message)||"Unknown Supabase error"}`));if(t.data)return t.data})}mount(e){let t={initialState:null,...e},{fsCollection:n,fsId:s,entity:i,id:a,relation:u}=re.pathSplit(this.path),c,h;return Promise.resolve().then(()=>this.setHeartbeat(!1)).then(async()=>{this.docRef=la(re.firestore,n,s);let f=await this.getFirestoreState();if(c=this.getReactive(f),!c.doc||!c.setState||!c.getState||!c.watch)throw new Error("Syncro.getReactive() requires a returned `doc`, `setState()`, `getState()` + `watch()`");this.value=h=c.doc,this.debug("Initial state",{doc:h}),this._destroyActions.push(Fy(this.docRef,m=>{let g=re.fromFirestore(m.data());this.debug("Incoming snapshot",{snapshotData:g}),c.setState(g)}))}).then(()=>{if(lu(h))return t.initialState?(this.debug("Populate initial Syncro state (from provided initialState)"),this.setFirestoreState(t.initialState,{method:"set"})):(this.debug(`Populate initial Syncro state (from "${i}" Syncro worker)`),fetch(`${this.config.syncroRegistryUrl}/${this.path}`).then(f=>f.ok||Promise.reject(`Failed to check Syncro "${path}" status - ${f.statusText}`)))}).then(()=>{c.watch(fu(f=>{this.debug("Local change",{newState:f}),this.markDirty(),this.setFirestoreState(f,{method:"merge"})},this.throttle))}).then(()=>this.setHeartbeat(!0,{immediate:!0})).then(()=>this)}setHeartbeat(e=!0,t){let n={immediate:!0,...t};clearTimeout(this._heartbeatTimer),e&&(this._heartbeatTimer=setTimeout(async()=>{await this.heartbeat(),e&&this.setHeartbeat(!0)},this.config.heartbeatInterval),n.immediate&&this.heartbeat())}async heartbeat(){this.debug("heartbeat!"),await fetch(`${this.config.syncroRegistryUrl}/${this.path}/heartbeat`,{method:"post",headers:{"Content-Type":"application/json"},body:JSON.stringify({session:re.session,...this.isDirty&&{dirty:!0}})}).then(e=>e.ok?null:console.warn(this.path,`Heartbeat failed - ${e.statusText}`,{response:e})).then(()=>this.isDirty=!1)}setFirestoreState(e,t){let n={method:"merge",...t};if(!this.docRef)throw new Error("mount() must be called before setting Firestore state");return(n.method=="set"?Ly:My)(this.docRef,re.toFirestore(e))}getFirestoreState(){if(!this.docRef)throw new Error("mount() must be called before getting Firestore state");return Hl(this.docRef).then(e=>re.fromFirestore(e.data()))}markDirty(){return this.isDirty=!0,this}flush(e){let t={destroy:!1,...e};return fetch(`${this.config.syncroRegistryUrl}/${this.path}/flush`+(t.destroy?"?destroy=1":"")).then(n=>n.ok?null:Promise.reject(n.statusText||"An error occured"))}};de(re,"firebase"),de(re,"firestore"),de(re,"supabase"),de(re,"session"),de(re,"SyncroEntities");var ir=re;var ev={id:"~array",recursive:!0,test:r=>Array.isArray(r),serialize:r=>({_:"~array",...r}),deserialize:r=>{let e=Array.from({length:Object.keys(r).length-1});return Object.entries(r).filter(([t])=>t!=="_").forEach(([t,n])=>e[+t]=n),e}};var gi=class{init(){}constructor(e,t){}};var yi=class extends gi{constructor(){super(...arguments);de(this,"syncros",{})}async init(t){let n={firebaseApiKey:null,firebaseAuthDomain:null,firebaseProjectId:null,firebaseAppId:null,supabaseUrl:null,supabaseKey:null,...await this.getCredentials(),...t},s=Object.keys(n).filter(i=>i===null);if(s.length>0)throw new Error("Firebase plugin requires mandatory options: "+s.join(", "));ir.firebase=Du({apiKey:n.firebaseApiKey,authDomain:n.firebaseAuthDomain,projectId:n.firebaseProjectId,appId:n.firebaseAppId}),ir.firestore=Py(this.firebase),ir.supabase=z_(n.supabaseUrl,n.supabaseKey)}_mountNamespace(t){let n;return Promise.resolve().then(()=>this.requireProject()).then(s=>{let i=t=="_PROJECT"?`projects::${s.id}`:`project_namespaces::${s.id}::${t}`;return n=this.syncros[t]=new ir(i,{debug:(...a)=>this.debug(`SYNCRO://${i}`,...a),getReactive:this.getReactive}),n.mount()}).then(()=>{this.namespaces[t]=n.value})}_unmountNamespace(t){let n=this.syncros[t];return delete this.namespaces[t],delete this.syncros[t],n.destroy()}};var Th=class extends yi{constructor(){super(...arguments);de(this,"Vue");de(this,"project",null);de(this,"reactiveId",1001)}async init(t){let n={app:null,Vue:null,globalName:"$tera",...t};if(!n.Vue)throw new Error("Vue instance to use must be specified in init options as `Vue`");if(this.Vue=n.Vue,!n.app)throw new Error("Vue Root / App instance to use must be specified in init options as `app`");this.app=n.app,n.globalName&&(this.Vue.prototype[n.globalName]=this),await super.init(n),this.project=await this.mountNamespace("_PROJECT")}getReactive(t){let n=this.Vue.observable(t),s=`_teraFy_${this.reactiveId++}`;return this.app[s]=n,{doc:n,setState(i){Object.entries(i||{}).filter(([a])=>!hu(n[a],i[a])).forEach(([a,u])=>n[a]=u)},getState(){return Kt(n)},watch:i=>{this.app.$watch(s,i,{deep:!0})}}}};export{Th as default};
27
+ });`,jn=class{constructor(e,t){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=n_,this.params={},this.timeout=wa,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=XR,this.conn=null,this.sendBuffer=[],this.serializer=new Zs,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let a;return i?a=i:typeof fetch=="undefined"?a=(...u)=>Promise.resolve().then(()=>(rr(),Er)).then(({default:c})=>c(...u)):a=fetch,(...u)=>a(...u)},this.endPoint=`${e}/${va.websocket}`,this.httpEndpoint=ba(e),t!=null&&t.transport?this.transport=t.transport:this.transport=null,t!=null&&t.params&&(this.params=t.params),t!=null&&t.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t!=null&&t.timeout&&(this.timeout=t.timeout),t!=null&&t.logger&&(this.logger=t.logger),t!=null&&t.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let s=(n=t==null?void 0:t.params)===null||n===void 0?void 0:n.apikey;if(s&&(this.accessTokenValue=s,this.apiKey=s),this.reconnectAfterMs=t!=null&&t.reconnectAfterMs?t.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=t!=null&&t.encode?t.encode:(i,a)=>a(JSON.stringify(i)),this.decode=t!=null&&t.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new Ar(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(t==null?void 0:t.fetch),t!=null&&t.worker){if(typeof window!="undefined"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=(t==null?void 0:t.worker)||!1,this.workerUrl=t==null?void 0:t.workerUrl}this.accessToken=(t==null?void 0:t.accessToken)||null}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this.endpointURL(),void 0,{headers:this.headers});return}if(ZR){this.conn=new WebSocket(this.endpointURL()),this.setupConnection();return}this.conn=new dh(this.endpointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Ad(u_())).then(({default:e})=>{this.conn=new e(this.endpointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:s_}))}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t!=null?t:""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e}log(e,t,n){this.logger(e,t,n)}connectionState(){switch(this.conn&&this.conn.readyState){case Ir.connecting:return nr.Connecting;case Ir.open:return nr.Open;case Ir.closing:return nr.Closing;default:return nr.Closed}}isConnected(){return this.connectionState()===nr.Open}channel(e,t={config:{}}){let n=new Fn(`realtime:${e}`,t,this);return this.channels.push(n),n}push(e){let{topic:t,event:n,payload:s,ref:i}=e,a=()=>{this.encode(e,u=>{var c;(c=this.conn)===null||c===void 0||c.send(u)})};this.log("push",`${t} ${n} (${i})`,s),this.isConnected()?a():this.sendBuffer.push(a)}async setAuth(e=null){let t=e||this.accessToken&&await this.accessToken()||this.accessTokenValue;if(t){let n=null;try{n=JSON.parse(atob(t.split(".")[1]))}catch{}if(n&&n.exp&&!(Math.floor(Date.now()/1e3)-n.exp<0))return this.log("auth",`InvalidJWTToken: Invalid value for JWT claim "exp" with value ${n.exp}`),Promise.reject(`InvalidJWTToken: Invalid value for JWT claim "exp" with value ${n.exp}`);this.accessTokenValue=t,this.channels.forEach(s=>{t&&s.updateJoinPayload({access_token:t}),s.joinedOnce&&s._isJoined()&&s._push(Be.access_token,{access_token:t})})}}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(i_,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth()}}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(n=>n.topic===e&&(n._isJoined()||n._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:n,event:s,payload:i,ref:a}=t;a&&a===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${n} ${s} ${a&&"("+a+")"||""}`,i),this.channels.filter(u=>u._isMember(n)).forEach(u=>u._trigger(s,i,a)),this.stateChangeCallbacks.message.forEach(u=>u(t))})}async _onConnOpen(){if(this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this.reconnectTimer.reset(),!this.worker)this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs);else{this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=t=>{this.log("worker","worker error",t.message),this.workerRef.terminate()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(Be.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;let n=e.match(/\?/)?"&":"?",s=new URLSearchParams(t);return`${e}${n}${s}`}_workerObjectUrl(e){let t;if(e)t=e;else{let n=new Blob([eP],{type:"application/javascript"});t=URL.createObjectURL(n)}return t}},dh=class{constructor(e,t,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=Ir.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}};var Un=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function ge(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var Ta=class extends Un{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},Sr=class extends Un{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var tP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},Ia=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(rr(),Er)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},c_=()=>tP(void 0,void 0,void 0,function*(){return typeof Response=="undefined"?(yield Promise.resolve().then(()=>(rr(),Er))).Response:Response}),Ea=r=>{if(Array.isArray(r))return r.map(t=>Ea(t));if(typeof r=="function"||r!==Object(r))return r;let e={};return Object.entries(r).forEach(([t,n])=>{let s=t.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[s]=Ea(n)}),e};var Rr=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},fh=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),rP=(r,e,t)=>Rr(void 0,void 0,void 0,function*(){let n=yield c_();r instanceof n&&!(t!=null&&t.noResolveJson)?r.json().then(s=>{e(new Ta(fh(s),r.status||500))}).catch(s=>{e(new Sr(fh(s),s))}):e(new Sr(fh(r),r))}),nP=(r,e,t,n)=>{let s={method:r,headers:(e==null?void 0:e.headers)||{}};return r==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),n&&(s.body=JSON.stringify(n)),Object.assign(Object.assign({},s),t))};function ei(r,e,t,n,s,i){return Rr(this,void 0,void 0,function*(){return new Promise((a,u)=>{r(t,nP(e,n,s,i)).then(c=>{if(!c.ok)throw c;return n!=null&&n.noResolveJson?c:c.json()}).then(c=>a(c)).catch(c=>rP(c,u,n))})})}function Bn(r,e,t,n){return Rr(this,void 0,void 0,function*(){return ei(r,"GET",e,t,n)})}function ct(r,e,t,n,s){return Rr(this,void 0,void 0,function*(){return ei(r,"POST",e,n,s,t)})}function l_(r,e,t,n,s){return Rr(this,void 0,void 0,function*(){return ei(r,"PUT",e,n,s,t)})}function h_(r,e,t,n){return Rr(this,void 0,void 0,function*(){return ei(r,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),n)})}function Aa(r,e,t,n,s){return Rr(this,void 0,void 0,function*(){return ei(r,"DELETE",e,n,s,t)})}var Me=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},sP={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},d_={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ti=class{constructor(e,t={},n,s){this.url=e,this.headers=t,this.bucketId=n,this.fetch=Ia(s)}uploadOrUpdate(e,t,n,s){return Me(this,void 0,void 0,function*(){try{let i,a=Object.assign(Object.assign({},d_),s),u=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(a.upsert)}),c=a.metadata;typeof Blob!="undefined"&&n instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),c&&i.append("metadata",this.encodeMetadata(c)),i.append("",n)):typeof FormData!="undefined"&&n instanceof FormData?(i=n,i.append("cacheControl",a.cacheControl),c&&i.append("metadata",this.encodeMetadata(c))):(i=n,u["cache-control"]=`max-age=${a.cacheControl}`,u["content-type"]=a.contentType,c&&(u["x-metadata"]=this.toBase64(this.encodeMetadata(c)))),s!=null&&s.headers&&(u=Object.assign(Object.assign({},u),s.headers));let h=this._removeEmptyFolders(t),f=this._getFinalPath(h),m=yield this.fetch(`${this.url}/object/${f}`,Object.assign({method:e,body:i,headers:u},a!=null&&a.duplex?{duplex:a.duplex}:{})),g=yield m.json();return m.ok?{data:{path:h,id:g.Id,fullPath:g.Key},error:null}:{data:null,error:g}}catch(i){if(ge(i))return{data:null,error:i};throw i}})}upload(e,t,n){return Me(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,n)})}uploadToSignedUrl(e,t,n,s){return Me(this,void 0,void 0,function*(){let i=this._removeEmptyFolders(e),a=this._getFinalPath(i),u=new URL(this.url+`/object/upload/sign/${a}`);u.searchParams.set("token",t);try{let c,h=Object.assign({upsert:d_.upsert},s),f=Object.assign(Object.assign({},this.headers),{"x-upsert":String(h.upsert)});typeof Blob!="undefined"&&n instanceof Blob?(c=new FormData,c.append("cacheControl",h.cacheControl),c.append("",n)):typeof FormData!="undefined"&&n instanceof FormData?(c=n,c.append("cacheControl",h.cacheControl)):(c=n,f["cache-control"]=`max-age=${h.cacheControl}`,f["content-type"]=h.contentType);let m=yield this.fetch(u.toString(),{method:"PUT",body:c,headers:f}),g=yield m.json();return m.ok?{data:{path:i,fullPath:g.Key},error:null}:{data:null,error:g}}catch(c){if(ge(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(e,t){return Me(this,void 0,void 0,function*(){try{let n=this._getFinalPath(e),s=Object.assign({},this.headers);t!=null&&t.upsert&&(s["x-upsert"]="true");let i=yield ct(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:s}),a=new URL(this.url+i.url),u=a.searchParams.get("token");if(!u)throw new Un("No token returned by API");return{data:{signedUrl:a.toString(),path:e,token:u},error:null}}catch(n){if(ge(n))return{data:null,error:n};throw n}})}update(e,t,n){return Me(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,n)})}move(e,t,n){return Me(this,void 0,void 0,function*(){try{return{data:yield ct(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers}),error:null}}catch(s){if(ge(s))return{data:null,error:s};throw s}})}copy(e,t,n){return Me(this,void 0,void 0,function*(){try{return{data:{path:(yield ct(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n==null?void 0:n.destinationBucket},{headers:this.headers})).Key},error:null}}catch(s){if(ge(s))return{data:null,error:s};throw s}})}createSignedUrl(e,t,n){return Me(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=yield ct(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},n!=null&&n.transform?{transform:n.transform}:{}),{headers:this.headers}),a=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${a}`)},{data:i,error:null}}catch(s){if(ge(s))return{data:null,error:s};throw s}})}createSignedUrls(e,t,n){return Me(this,void 0,void 0,function*(){try{let s=yield ct(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return{data:s.map(a=>Object.assign(Object.assign({},a),{signedUrl:a.signedURL?encodeURI(`${this.url}${a.signedURL}${i}`):null})),error:null}}catch(s){if(ge(s))return{data:null,error:s};throw s}})}download(e,t){return Me(this,void 0,void 0,function*(){let s=typeof(t==null?void 0:t.transform)!="undefined"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),a=i?`?${i}`:"";try{let u=this._getFinalPath(e);return{data:yield(yield Bn(this.fetch,`${this.url}/${s}/${u}${a}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(u){if(ge(u))return{data:null,error:u};throw u}})}info(e){return Me(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{let n=yield Bn(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:Ea(n),error:null}}catch(n){if(ge(n))return{data:null,error:n};throw n}})}exists(e){return Me(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{return yield h_(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(ge(n)&&n instanceof Sr){let s=n.originalError;if([400,404].includes(s==null?void 0:s.status))return{data:!1,error:n}}throw n}})}getPublicUrl(e,t){let n=this._getFinalPath(e),s=[],i=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";i!==""&&s.push(i);let u=typeof(t==null?void 0:t.transform)!="undefined"?"render/image":"object",c=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});c!==""&&s.push(c);let h=s.join("&");return h!==""&&(h=`?${h}`),{data:{publicUrl:encodeURI(`${this.url}/${u}/public/${n}${h}`)}}}remove(e){return Me(this,void 0,void 0,function*(){try{return{data:yield Aa(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}})}list(e,t,n){return Me(this,void 0,void 0,function*(){try{let s=Object.assign(Object.assign(Object.assign({},sP),t),{prefix:e||""});return{data:yield ct(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},n),error:null}}catch(s){if(ge(s))return{data:null,error:s};throw s}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer!="undefined"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}};var f_="2.7.1";var p_={"X-Client-Info":`storage-js/${f_}`};var $n=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},ri=class{constructor(e,t={},n){this.url=e,this.headers=Object.assign(Object.assign({},p_),t),this.fetch=Ia(n)}listBuckets(){return $n(this,void 0,void 0,function*(){try{return{data:yield Bn(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(ge(e))return{data:null,error:e};throw e}})}getBucket(e){return $n(this,void 0,void 0,function*(){try{return{data:yield Bn(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return $n(this,void 0,void 0,function*(){try{return{data:yield ct(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(ge(n))return{data:null,error:n};throw n}})}updateBucket(e,t){return $n(this,void 0,void 0,function*(){try{return{data:yield l_(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(ge(n))return{data:null,error:n};throw n}})}emptyBucket(e){return $n(this,void 0,void 0,function*(){try{return{data:yield ct(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}})}deleteBucket(e){return $n(this,void 0,void 0,function*(){try{return{data:yield Aa(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}})}};var ni=class extends ri{constructor(e,t={},n){super(e,t,n)}from(e){return new ti(this.url,this.headers,e,this.fetch)}};var m_="2.48.1";var si="";typeof Deno!="undefined"?si="deno":typeof document!="undefined"?si="web":typeof navigator!="undefined"&&navigator.product==="ReactNative"?si="react-native":si="node";var iP={"X-Client-Info":`supabase-js-${si}/${m_}`},g_={headers:iP},y_={schema:"public"},__={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},v_={};rr();var oP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},aP=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=Wl:e=fetch,(...t)=>e(...t)},uP=()=>typeof Headers=="undefined"?Ql:Headers,w_=(r,e,t)=>{let n=aP(t),s=uP();return(i,a)=>oP(void 0,void 0,void 0,function*(){var u;let c=(u=yield e())!==null&&u!==void 0?u:r,h=new s(a==null?void 0:a.headers);return h.has("apikey")||h.set("apikey",r),h.has("Authorization")||h.set("Authorization",`Bearer ${c}`),n(i,Object.assign(Object.assign({},a),{headers:h}))})};var cP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})};function b_(r){return r.replace(/\/$/,"")}function T_(r,e){let{db:t,auth:n,realtime:s,global:i}=r,{db:a,auth:u,realtime:c,global:h}=e,f={db:Object.assign(Object.assign({},a),t),auth:Object.assign(Object.assign({},u),n),realtime:Object.assign(Object.assign({},c),s),global:Object.assign(Object.assign({},h),i),accessToken:()=>cP(this,void 0,void 0,function*(){return""})};return r.accessToken?f.accessToken=r.accessToken:delete f.accessToken,f}var xa="2.67.3";var E_="http://localhost:9999",I_="supabase.auth.token";var A_={"X-Client-Info":`gotrue-js/${xa}`},ph=10;var ii="X-Supabase-Api-Version",mh={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function x_(r){return Math.round(Date.now()/1e3)+r}function S_(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){let e=Math.random()*16|0;return(r=="x"?e:e&3|8).toString(16)})}var Qe=()=>typeof window!="undefined"&&typeof document!="undefined",Pr={tested:!1,writable:!1},sr=()=>{if(!Qe())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Pr.tested)return Pr.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Pr.tested=!0,Pr.writable=!0}catch{Pr.tested=!0,Pr.writable=!1}return Pr.writable};function R_(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return t.searchParams.forEach((n,s)=>{e[s]=n}),e}var Sa=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(rr(),Er)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},P_=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",gh=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},ai=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},ui=async(r,e)=>{await r.removeItem(e)};function lP(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",n,s,i,a,u,c,h,f=0;for(r=r.replace("-","+").replace("_","/");f<r.length;)a=e.indexOf(r.charAt(f++)),u=e.indexOf(r.charAt(f++)),c=e.indexOf(r.charAt(f++)),h=e.indexOf(r.charAt(f++)),n=a<<2|u>>4,s=(u&15)<<4|c>>2,i=(c&3)<<6|h,t=t+String.fromCharCode(n),c!=64&&s!=0&&(t=t+String.fromCharCode(s)),h!=64&&i!=0&&(t=t+String.fromCharCode(i));return t}var oi=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};oi.promiseConstructor=Promise;function yh(r){let e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=r.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");let n=t[1];return JSON.parse(lP(n))}async function C_(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function k_(r,e){return new Promise((n,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let a=await r(i);if(!e(i,null,a)){n(a);return}}catch(a){if(!e(i,a)){s(a);return}}})()})}function hP(r){return("0"+r.toString(16)).substr(-2)}function dP(){let e=new Uint32Array(56);if(typeof crypto=="undefined"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=t.length,s="";for(let i=0;i<56;i++)s+=t.charAt(Math.floor(Math.random()*n));return s}return crypto.getRandomValues(e),Array.from(e,hP).join("")}async function fP(r){let t=new TextEncoder().encode(r),n=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(n);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}function pP(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function mP(r){if(!(typeof crypto!="undefined"&&typeof crypto.subtle!="undefined"&&typeof TextEncoder!="undefined"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),r;let t=await fP(r);return pP(t)}async function Cr(r,e,t=!1){let n=dP(),s=n;t&&(s+="/PASSWORD_RECOVERY"),await gh(r,`${e}-code-verifier`,s);let i=await mP(n);return[i,n===i?"plain":"s256"]}var gP=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function D_(r){let e=r.headers.get(ii);if(!e||!e.match(gP))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var ci=class extends Error{constructor(e,t,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=n}};function z(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var Ra=class extends ci{constructor(e,t,n){super(e,t,n),this.name="AuthApiError",this.status=t,this.code=n}};function O_(r){return z(r)&&r.name==="AuthApiError"}var qn=class extends ci{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},Pt=class extends ci{constructor(e,t,n,s){super(e,n,s),this.name=t,this.status=n}},ze=class extends Pt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function N_(r){return z(r)&&r.name==="AuthSessionMissingError"}var zn=class extends Pt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},kr=class extends Pt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Dr=class extends Pt{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};function V_(r){return z(r)&&r.name==="AuthImplicitGrantRedirectError"}var li=class extends Pt{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}},Gn=class extends Pt{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function Pa(r){return z(r)&&r.name==="AuthRetryableFetchError"}var hi=class extends Pt{constructor(e,t,n){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=n}};var yP=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(r);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(r,n[s])&&(t[n[s]]=r[n[s]]);return t},Or=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),_P=[502,503,504];async function L_(r){var e;if(!P_(r))throw new Gn(Or(r),0);if(_P.includes(r.status))throw new Gn(Or(r),r.status);let t;try{t=await r.json()}catch(i){throw new qn(Or(i),i)}let n,s=D_(r);if(s&&s.getTime()>=mh["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?n=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(n=t.error_code),n){if(n==="weak_password")throw new hi(Or(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new ze}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((i,a)=>i&&typeof a=="string",!0))throw new hi(Or(t),r.status,t.weak_password.reasons);throw new Ra(Or(t),r.status||500,n)}var vP=(r,e,t,n)=>{let s={method:r,headers:(e==null?void 0:e.headers)||{}};return r==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),s.body=JSON.stringify(n),Object.assign(Object.assign({},s),t))};async function K(r,e,t,n){var s;let i=Object.assign({},n==null?void 0:n.headers);i[ii]||(i[ii]=mh["2024-01-01"].name),n!=null&&n.jwt&&(i.Authorization=`Bearer ${n.jwt}`);let a=(s=n==null?void 0:n.query)!==null&&s!==void 0?s:{};n!=null&&n.redirectTo&&(a.redirect_to=n.redirectTo);let u=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",c=await wP(r,e,t+u,{headers:i,noResolveJson:n==null?void 0:n.noResolveJson},{},n==null?void 0:n.body);return n!=null&&n.xform?n==null?void 0:n.xform(c):{data:Object.assign({},c),error:null}}async function wP(r,e,t,n,s,i){let a=vP(e,n,s,i),u;try{u=await r(t,Object.assign({},a))}catch(c){throw console.error(c),new Gn(Or(c),0)}if(u.ok||await L_(u),n!=null&&n.noResolveJson)return u;try{return await u.json()}catch(c){await L_(c)}}function Ct(r){var e;let t=null;bP(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=x_(r.expires_in)));let n=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:n},error:null}}function _h(r){let e=Ct(r);return!e.error&&r.weak_password&&typeof r.weak_password=="object"&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.message&&typeof r.weak_password.message=="string"&&r.weak_password.reasons.reduce((t,n)=>t&&typeof n=="string",!0)&&(e.data.weak_password=r.weak_password),e}function lt(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function M_(r){return{data:r,error:null}}function F_(r){let{action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:i}=r,a=yP(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),u={action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:i},c=Object.assign({},a);return{data:{properties:u,user:c},error:null}}function j_(r){return r}function bP(r){return r.access_token&&r.refresh_token&&r.expires_in}var TP=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(r);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(r,n[s])&&(t[n[s]]=r[n[s]]);return t},Nr=class{constructor({url:e="",headers:t={},fetch:n}){this.url=e,this.headers=t,this.fetch=Sa(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await K(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(z(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,t={}){try{return await K(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:lt})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:t}=e,n=TP(e,["options"]),s=Object.assign(Object.assign({},n),t);return"newEmail"in n&&(s.new_email=n==null?void 0:n.newEmail,delete s.newEmail),await K(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:F_,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(z(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await K(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:lt})}catch(t){if(z(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,n,s,i,a,u,c;try{let h={nextPage:null,lastPage:0,total:0},f=await K(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&n!==void 0?n:"",per_page:(i=(s=e==null?void 0:e.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:j_});if(f.error)throw f.error;let m=await f.json(),g=(a=f.headers.get("x-total-count"))!==null&&a!==void 0?a:0,E=(c=(u=f.headers.get("link"))===null||u===void 0?void 0:u.split(","))!==null&&c!==void 0?c:[];return E.length>0&&(E.forEach(P=>{let C=parseInt(P.split(";")[0].split("=")[1].substring(0,1)),R=JSON.parse(P.split(";")[1].split("=")[1]);h[`${R}Page`]=C}),h.total=parseInt(g)),{data:Object.assign(Object.assign({},m),h),error:null}}catch(h){if(z(h))return{data:{users:[]},error:h};throw h}}async getUserById(e){try{return await K(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:lt})}catch(t){if(z(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await K(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:lt})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,t=!1){try{return await K(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:lt})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){try{let{data:t,error:n}=await K(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:t,error:n}}catch(t){if(z(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await K(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(z(t))return{data:null,error:t};throw t}}};var U_={getItem:r=>sr()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{sr()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{sr()&&globalThis.localStorage.removeItem(r)}};function vh(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function B_(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self!="undefined"&&(self.globalThis=self)}}var Vr={debug:!!(globalThis&&sr()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},di=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Ca=class extends di{};async function wh(r,e,t){Vr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),Vr.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",r)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(r,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async s=>{if(s){Vr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,s.name);try{return await t()}finally{Vr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,s.name)}}else{if(e===0)throw Vr.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Ca(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Vr.debug)try{let i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}}))}B_();var EP={url:E_,storageKey:I_,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:A_,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},fi=30*1e3,$_=3;async function q_(r,e,t){return await t()}var Lr=class r{constructor(e){var t,n;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=r.nextInstanceID,r.nextInstanceID+=1,this.instanceID>0&&Qe()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let s=Object.assign(Object.assign({},EP),e);if(this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.persistSession=s.persistSession,this.storageKey=s.storageKey,this.autoRefreshToken=s.autoRefreshToken,this.admin=new Nr({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Sa(s.fetch),this.lock=s.lock||q_,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,s.lock?this.lock=s.lock:Qe()&&(!((t=globalThis==null?void 0:globalThis.navigator)===null||t===void 0)&&t.locks)?this.lock=wh:this.lock=q_,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?s.storage?this.storage=s.storage:sr()?this.storage=U_:(this.memoryStorage={},this.storage=vh(this.memoryStorage)):(this.memoryStorage={},this.storage=vh(this.memoryStorage)),Qe()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${xa}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let t=R_(window.location.href),n="none";if(this._isImplicitGrantCallback(t)?n="implicit":await this._isPKCECallback(t)&&(n="pkce"),Qe()&&this.detectSessionInUrl&&n!=="none"){let{data:s,error:i}=await this._getSessionFromURL(t,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),V_(i)){let c=(e=i.details)===null||e===void 0?void 0:e.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}let{session:a,redirectType:u}=s;return this._debug("#_initialize()","detected session in URL",a,"redirect type",u),await this._saveSession(a),setTimeout(async()=>{u==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return z(t)?{error:t}:{error:new qn("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,n,s;try{let i=await K(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(t=e==null?void 0:e.options)===null||t===void 0?void 0:t.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(s=e==null?void 0:e.options)===null||s===void 0?void 0:s.captchaToken}},xform:Ct}),{data:a,error:u}=i;if(u||!a)return{data:{user:null,session:null},error:u};let c=a.session,h=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(i){if(z(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(e){var t,n,s;try{let i;if("email"in e){let{email:f,password:m,options:g}=e,E=null,P=null;this.flowType==="pkce"&&([E,P]=await Cr(this.storage,this.storageKey)),i=await K(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:g==null?void 0:g.emailRedirectTo,body:{email:f,password:m,data:(t=g==null?void 0:g.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken},code_challenge:E,code_challenge_method:P},xform:Ct})}else if("phone"in e){let{phone:f,password:m,options:g}=e;i=await K(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:f,password:m,data:(n=g==null?void 0:g.data)!==null&&n!==void 0?n:{},channel:(s=g==null?void 0:g.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:g==null?void 0:g.captchaToken}},xform:Ct})}else throw new kr("You must provide either an email or phone number and a password");let{data:a,error:u}=i;if(u||!a)return{data:{user:null,session:null},error:u};let c=a.session,h=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(i){if(z(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(e){try{let t;if("email"in e){let{email:i,password:a,options:u}=e;t=await K(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:a,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:_h})}else if("phone"in e){let{phone:i,password:a,options:u}=e;t=await K(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:a,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken}},xform:_h})}else throw new kr("You must provide either an email or phone number and a password");let{data:n,error:s}=t;return s?{data:{user:null,session:null},error:s}:!n||!n.session||!n.user?{data:{user:null,session:null},error:new zn}:(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),{data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:s})}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,n,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await ai(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(t!=null?t:"").split("/");try{let{data:i,error:a}=await K(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Ct});if(await ui(this.storage,`${this.storageKey}-code-verifier`),a)throw a;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new zn}:(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),{data:Object.assign(Object.assign({},i),{redirectType:s!=null?s:null}),error:a})}catch(i){if(z(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(e){try{let{options:t,provider:n,token:s,access_token:i,nonce:a}=e,u=await K(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:s,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:Ct}),{data:c,error:h}=u;return h?{data:{user:null,session:null},error:h}:!c||!c.session||!c.user?{data:{user:null,session:null},error:new zn}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:h})}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,n,s,i,a;try{if("email"in e){let{email:u,options:c}=e,h=null,f=null;this.flowType==="pkce"&&([h,f]=await Cr(this.storage,this.storageKey));let{error:m}=await K(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:u,data:(t=c==null?void 0:c.data)!==null&&t!==void 0?t:{},create_user:(n=c==null?void 0:c.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:h,code_challenge_method:f},redirectTo:c==null?void 0:c.emailRedirectTo});return{data:{user:null,session:null},error:m}}if("phone"in e){let{phone:u,options:c}=e,{data:h,error:f}=await K(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:u,data:(s=c==null?void 0:c.data)!==null&&s!==void 0?s:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(a=c==null?void 0:c.channel)!==null&&a!==void 0?a:"sms"}});return{data:{user:null,session:null,messageId:h==null?void 0:h.message_id},error:f}}throw new kr("You must provide either an email or phone number.")}catch(u){if(z(u))return{data:{user:null,session:null},error:u};throw u}}async verifyOtp(e){var t,n;try{let s,i;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:a,error:u}=await K(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:Ct});if(u)throw u;if(!a)throw new Error("An error occurred on token verification.");let c=a.session,h=a.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),{data:{user:h,session:c},error:null}}catch(s){if(z(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithSSO(e){var t,n,s;try{let i=null,a=null;return this.flowType==="pkce"&&([i,a]=await Cr(this.storage,this.storageKey)),await K(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(n=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&n!==void 0?n:void 0}),!((s=e==null?void 0:e.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:a}),headers:this.headers,xform:M_})}catch(i){if(z(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;if(n)throw n;if(!t)throw new ze;let{error:s}=await K(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:s}})}catch(e){if(z(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{let t=`${this.url}/resend`;if("email"in e){let{email:n,type:s,options:i}=e,{error:a}=await K(this.fetch,"POST",t,{headers:this.headers,body:{email:n,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:a}}else if("phone"in e){let{phone:n,type:s,options:i}=e,{data:a,error:u}=await K(this.fetch,"POST",t,{headers:this.headers,body:{phone:n,type:s,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:a==null?void 0:a.message_id},error:u}}throw new kr("You must provide either an email or phone number and a type")}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await n,await t()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let n=t();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null,t=await ai(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.storage.isServer){let a=this.suppressGetSessionWarning;e=new Proxy(e,{get:(c,h,f)=>(!a&&h==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),a=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,h,f))})}return{data:{session:e},error:null}}let{session:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:s},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await K(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:lt}):await this._useSession(async t=>{var n,s,i;let{data:a,error:u}=t;if(u)throw u;return!(!((n=a.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new ze}:await K(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=a.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:lt})})}catch(t){if(z(t))return N_(t)&&(await this._removeSession(),await ui(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async n=>{let{data:s,error:i}=n;if(i)throw i;if(!s.session)throw new ze;let a=s.session,u=null,c=null;this.flowType==="pkce"&&e.email!=null&&([u,c]=await Cr(this.storage,this.storageKey));let{data:h,error:f}=await K(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:u,code_challenge_method:c}),jwt:a.access_token,xform:lt});if(f)throw f;return a.user=h.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),{data:{user:a.user},error:null}})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}_decodeJWT(e){return yh(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new ze;let t=Date.now()/1e3,n=t,s=!0,i=null,a=yh(e.access_token);if(a.exp&&(n=a.exp,s=n<=t),s){let{session:u,error:c}=await this._callRefreshToken(e.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!u)return{data:{user:null,session:null},error:null};i=u}else{let{data:u,error:c}=await this._getUser(e.access_token);if(c)throw c;i={access_token:e.access_token,refresh_token:e.refresh_token,user:u.user,token_type:"bearer",expires_in:n-t,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(t){if(z(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var n;if(!e){let{data:a,error:u}=t;if(u)throw u;e=(n=a.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new ze;let{session:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:s?{data:{user:s.user,session:s},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(z(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!Qe())throw new Dr("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Dr(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new li("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Dr("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new li("No code detected.");let{data:M,error:U}=await this._exchangeCodeForSession(e.code);if(U)throw U;let G=new URL(window.location.href);return G.searchParams.delete("code"),window.history.replaceState(window.history.state,"",G.toString()),{data:{session:M.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:s,access_token:i,refresh_token:a,expires_in:u,expires_at:c,token_type:h}=e;if(!i||!u||!a||!h)throw new Dr("No session defined in URL");let f=Math.round(Date.now()/1e3),m=parseInt(u),g=f+m;c&&(g=parseInt(c));let E=g-f;E*1e3<=fi&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${E}s, should have been closer to ${m}s`);let P=g-m;f-P>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",P,g,f):f-P<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",P,g,f);let{data:C,error:R}=await this._getUser(i);if(R)throw R;let N={provider_token:n,provider_refresh_token:s,access_token:i,expires_in:m,expires_at:g,refresh_token:a,token_type:h,user:C.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:N,redirectType:e.type},error:null}}catch(n){if(z(n))return{data:{session:null,redirectType:null},error:n};throw n}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){let t=await ai(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var n;let{data:s,error:i}=t;if(i)return{error:i};let a=(n=s.session)===null||n===void 0?void 0:n.access_token;if(a){let{error:u}=await this.admin.signOut(a,e);if(u&&!(O_(u)&&(u.status===404||u.status===401||u.status===403)))return{error:u}}return e!=="others"&&(await this._removeSession(),await ui(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){let t=S_(),n={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,n),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async t=>{var n,s;try{let{data:{session:i},error:a}=t;if(a)throw a;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,t={}){let n=null,s=null;this.flowType==="pkce"&&([n,s]=await Cr(this.storage,this.storageKey,!0));try{return await K(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(z(i))return{data:null,error:i};throw i}}async getUserIdentities(){var e;try{let{data:t,error:n}=await this.getUser();if(n)throw n;return{data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null}}catch(t){if(z(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:n,error:s}=await this._useSession(async i=>{var a,u,c,h,f;let{data:m,error:g}=i;if(g)throw g;let E=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(a=e.options)===null||a===void 0?void 0:a.redirectTo,scopes:(u=e.options)===null||u===void 0?void 0:u.scopes,queryParams:(c=e.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await K(this.fetch,"GET",E,{headers:this.headers,jwt:(f=(h=m.session)===null||h===void 0?void 0:h.access_token)!==null&&f!==void 0?f:void 0})});if(s)throw s;return Qe()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(n==null?void 0:n.url),{data:{provider:e.provider,url:n==null?void 0:n.url},error:null}}catch(n){if(z(n))return{data:{provider:e.provider,url:null},error:n};throw n}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var n,s;let{data:i,error:a}=t;if(a)throw a;return await K(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(z(t))return{data:null,error:t};throw t}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let n=Date.now();return await k_(async s=>(s>0&&await C_(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await K(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Ct})),(s,i)=>{let a=200*Math.pow(2,s);return i&&Pa(i)&&Date.now()+a-n<fi})}catch(n){if(this._debug(t,"error",n),z(n))return{data:{session:null,user:null},error:n};throw n}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",n),Qe()&&!t.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let n=await ai(this.storage,this.storageKey);if(this._debug(t,"session from storage",n),!this._isValidSession(n)){this._debug(t,"session is not valid"),n!==null&&await this._removeSession();return}let s=Math.round(Date.now()/1e3),i=((e=n.expires_at)!==null&&e!==void 0?e:1/0)<s+ph;if(this._debug(t,`session has${i?"":" not"} expired with margin of ${ph}s`),i){if(this.autoRefreshToken&&n.refresh_token){let{error:a}=await this._callRefreshToken(n.refresh_token);a&&(console.error(a),Pa(a)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(t,"error",n),console.error(n);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,n;if(!e)throw new ze;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new oi;let{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new ze;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let u={session:i.session,error:null};return this.refreshingDeferred.resolve(u),u}catch(i){if(this._debug(s,"error",i),z(i)){let a={session:null,error:i};return Pa(i)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(a),a}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,n=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:t});let i=[],a=Array.from(this.stateChangeEmitters.values()).map(async u=>{try{await u.callback(e,t)}catch(c){i.push(c)}});if(await Promise.all(a),i.length>0){for(let u=0;u<i.length;u+=1)console.error(i[u]);throw i[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await gh(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await ui(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Qe()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),fi);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno!="undefined"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:n}}=t;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((n.expires_at*1e3-e)/fi);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${fi}ms, refresh threshold is ${$_} ticks`),s<=$_&&await this._callRefreshToken(n.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof di)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Qe()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,n){let s=[`provider=${encodeURIComponent(t)}`];if(n!=null&&n.redirectTo&&s.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n!=null&&n.scopes&&s.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){let[i,a]=await Cr(this.storage,this.storageKey),u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});s.push(u.toString())}if(n!=null&&n.queryParams){let i=new URLSearchParams(n.queryParams);s.push(i.toString())}return n!=null&&n.skipBrowserRedirect&&s.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;return i?{data:null,error:i}:await K(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token})})}catch(t){if(z(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var n,s;let{data:i,error:a}=t;if(a)return{data:null,error:a};let u=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:c,error:h}=await K(this.fetch,"POST",`${this.url}/factors`,{body:u,headers:this.headers,jwt:(n=i==null?void 0:i.session)===null||n===void 0?void 0:n.access_token});return h?{data:null,error:h}:(e.factorType==="totp"&&(!((s=c==null?void 0:c.totp)===null||s===void 0)&&s.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),{data:c,error:null})})}catch(t){if(z(t))return{data:null,error:t};throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;if(i)return{data:null,error:i};let{data:a,error:u}=await K(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token});return u?{data:null,error:u}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),{data:a,error:u})})}catch(t){if(z(t))return{data:null,error:t};throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var n;let{data:s,error:i}=t;return i?{data:null,error:i}:await K(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:{channel:e.channel},headers:this.headers,jwt:(n=s==null?void 0:s.session)===null||n===void 0?void 0:n.access_token})})}catch(t){if(z(t))return{data:null,error:t};throw t}})}async _challengeAndVerify(e){let{data:t,error:n}=await this._challenge({factorId:e.factorId});return n?{data:null,error:n}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let n=(e==null?void 0:e.factors)||[],s=n.filter(a=>a.factor_type==="totp"&&a.status==="verified"),i=n.filter(a=>a.factor_type==="phone"&&a.status==="verified");return{data:{all:n,totp:s,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,n;let{data:{session:s},error:i}=e;if(i)return{data:null,error:i};if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let a=this._decodeJWT(s.access_token),u=null;a.aal&&(u=a.aal);let c=u;((n=(t=s.user.factors)===null||t===void 0?void 0:t.filter(m=>m.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(c="aal2");let f=a.amr||[];return{data:{currentLevel:u,nextLevel:c,currentAuthenticationMethods:f},error:null}}))}};Lr.nextInstanceID=0;var IP=Lr,bh=IP;var ka=class extends bh{constructor(e){super(e)}};var AP=function(r,e,t,n){function s(i){return i instanceof t?i:new t(function(a){a(i)})}return new(t||(t=Promise))(function(i,a){function u(f){try{h(n.next(f))}catch(m){a(m)}}function c(f){try{h(n.throw(f))}catch(m){a(m)}}function h(f){f.done?i(f.value):s(f.value).then(u,c)}h((n=n.apply(r,e||[])).next())})},pi=class{constructor(e,t,n){var s,i,a;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let u=b_(e);this.realtimeUrl=`${u}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${u}/auth/v1`,this.storageUrl=`${u}/storage/v1`,this.functionsUrl=`${u}/functions/v1`;let c=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,h={db:y_,realtime:v_,auth:Object.assign(Object.assign({},__),{storageKey:c}),global:g_},f=T_(n!=null?n:{},h);this.storageKey=(s=f.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(i=f.global.headers)!==null&&i!==void 0?i:{},f.accessToken?(this.accessToken=f.accessToken,this.auth=new Proxy({},{get:(m,g)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(g)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((a=f.auth)!==null&&a!==void 0?a:{},this.headers,f.global.fetch),this.fetch=w_(t,this._getAccessToken.bind(this),f.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},f.realtime)),this.rest=new t_(`${u}/rest/v1`,{headers:this.headers,schema:f.db.schema,fetch:this.fetch}),f.accessToken||this._listenForAuthEvents()}get functions(){return new Ks(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new ni(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},n={}){return this.rest.rpc(e,t,n)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return AP(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();let{data:n}=yield this.auth.getSession();return(t=(e=n.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:s,storageKey:i,flowType:a,lock:u,debug:c},h,f){let m={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new ka({url:this.authUrl,headers:Object.assign(Object.assign({},m),h),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:s,flowType:a,lock:u,debug:c,fetch:f,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new jn(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,n)=>{this._handleTokenChanged(t,"CLIENT",n==null?void 0:n.access_token)})}_handleTokenChanged(e,t,n){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==n?this.changedAccessToken=n:e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};var z_=(r,e,t)=>new pi(r,e,t);function xP(r,e){return Object.fromEntries(Object.entries(r).sort(e||void 0).map(([t,n])=>[t,n]))}function Da(r,e){return Array.isArray(r)?r.map(t=>Da(t,e)):typeof r=="object"?Object.fromEntries(Object.entries(xP(r,e)).map(([t,n])=>[t,Da(n,e)])):r}var G_={id:"~date",test:r=>r instanceof Date,serialize:r=>({_:"~date",v:r.toISOString()}),deserialize:r=>new Date(r.v)};var K_={id:"~function",test:r=>typeof r=="function",serialize:r=>({_:"~function",v:r.toString()}),deserialize:v=>eval(v.v.toString())};var H_={id:"~infinity",test:r=>r===1/0||r===-1/0,serialize:r=>({_:"~infinity",v:r===1/0?1:0}),deserialize:r=>r.v==1?1/0:-1/0};var W_={id:"~nan",test:r=>Number.isNaN(r),serialize:r=>({_:"~nan"}),deserialize:r=>NaN};var Q_={id:"~regexp",test:r=>r instanceof RegExp,serialize:r=>({_:"~regexp",v:r.source,f:r.flags}),deserialize:r=>new RegExp(r.v,r.f)};var J_={id:"~set",test:r=>r instanceof Set,serialize:r=>({_:"~set",v:Array.from(r)}),deserialize:r=>new Set(r.v)};var Y_={id:"~undefined",test:r=>r===void 0,serialize:r=>({_:"~undefined"}),deserialize:r=>{}};var Kn={settings:{stringify:!0,destringify:!0,clone:!1,depth:0,modules:[G_,K_,H_,W_,Q_,J_,Y_],circular:!0,symetric:!1},loadedModules:{},loadModules(r){return r.map(e=>{if(Z(e)){if(!e.id)throw new Error("Provided custom module does not expose an `id` property");return Kn.loadedModules[e.id]=e}else throw new Error("Unknown module type")})},serialize(r,e){let t=so(e,Kn.settings),n=Kn.loadModules(t.modules),s=t.symetric?Da(r):t.clone?Kt(r):r,i=new Map,a=(u,c)=>{let h=Z(u);if(h&&t.circular){let g=i.get(u);if(g)return Ht(s,c,{_:"~circular",p:g.join(".")});i.set(u,c)}let f=n.find(g=>g.test(u)),m=(!t.depth||c.length<t.depth)&&h;if(f){let g=f.serialize(u);if(f.recursive&&m){let E=Se(u);t.symetric&&E.sort(),Ht(s,c,g),E.forEach(P=>a(u[P],c.concat(P)))}else c.length?Ht(s,c,g):s=g}else if(m){let g=Se(u);t.symetric&&g.sort(),g.forEach(E=>a(u[E],c.concat(E)))}};return a(s,[]),t.stringify?JSON.stringify(s):s},deserialize(r,e){let t=so(e,Kn.settings),n=Kn.loadModules(t.modules),s=du(n,"id"),i=t.destringify?JSON.parse(r):t.clone?Kt(r):r,a=(u,c)=>{if(Z(u)&&u._&&typeof u._=="string"&&u._.startsWith("~")&&s[u._]){let h=s[u._].deserialize(u);c.length?s[u._].recursive&&Z(h)?(Ht(i,c,h),Se(h).forEach(f=>a(u[f],[...c,f]))):Ht(i,c,h):i=h}else t.circular&&Z(u)&&u._&&u._=="~circular"?Ht(i,c,ms(i,u.p)):(!t.depth||c.length<t.depth)&&Z(u)&&Se(u).forEach(h=>a(u[h],c.concat(h)))};return a(i,[]),i}},mi=Kn;var X_="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Z_=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=X_[t[r]&63];return e};var re=class re{constructor(e,t){de(this,"path");de(this,"docRef");de(this,"value");de(this,"throttle",250);de(this,"config",{heartbeatInterval:5e4,syncroRegistryUrl:"https://tera-tools.com/api/sync",context:{}});de(this,"isDirty",!1);de(this,"_destroyActions",[]);de(this,"_heartbeatTimer");this.path=e,Object.assign(this,{...t,config:{...this.config,...t==null?void 0:t.config}}),re.session||(re.session=`syncro_${Z_()}`)}debug(...e){}destroy(){return this.debug("Destroy!"),Promise.all(this._destroyActions.map(e=>e())).then(()=>this._destroyActions=[])}getReactive(e){console.warn("Syncro.getReactive has not been subclassed, assuming a POJO response");let t={...e};return{doc:t,setState(n){Object.entries(n||{}).forEach(([s,i])=>t[s]=i)},getState(){return Kt(t)},watch(n){}}}static pathSplit(e,t){var a;let n={allowAsterisk:!1,...t},i={...(a=new RegExp("^(?<entity>\\w+?)::(?<id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:::(?<relation>[\\w\\-"+(n.allowAsterisk?"\\*":"")+"]+?))?$").exec(e))==null?void 0:a.groups};if(!i)throw new Error(`Invalid session path syntax "${e}"`);if(re.SyncroEntities&&!(i.entity in SyncroEntities))throw new Error(`Unsupported entity "${e}" -> Entity="${i.entity}"`);return{...i,fsCollection:i.entity,fsId:i.relation?`${i.id}::${i.relation}`:i.id}}static toFirestore(e={}){return mi.serialize(e,{circular:!1,clone:!0,modules:[ev,...mi.settings.modules],stringify:!1})}static fromFirestore(e={}){return mi.deserialize(e,{circular:!1,clone:!0,modules:[ev,...mi.settings.modules],destringify:!1})}static toFirestoreFields(e){let t={};for(let[n,s]of Object.entries(e)){let i=typeof s;i==="string"?t[n]={stringValue:s}:i==="number"?t[n]={doubleValue:s}:i==="boolean"?t[n]={booleanValue:s}:s===null?t[n]={nullValue:null}:Array.isArray(s)?t[n]={arrayValue:{values:s.map(a=>re.toFirestoreFields({item:a}).item)}}:i==="object"&&(t[n]={mapValue:{fields:re.toFirestoreFields(s)}})}return t}static fromFirestoreFields(e={}){let t={};for(let n in e){let s=e[n];if(["stringValue","booleanValue","doubleValue","integerValue","timestampValue","mapValue","arrayValue"].find(a=>a===n)){if(["stringValue","booleanValue","doubleValue","integerValue","timestampValue"].find(u=>u===n))return s;if(n=="mapValue")return re.fromFirestoreFields(s.fields||{});if(n=="arrayValue"){let u=s.values;return u?u.map(c=>re.fromFirestoreFields(c)):[]}}else t[n]=re.fromFirestoreFields(s)}return t}static getSnapshot(e){let{fsCollection:t,fsId:n}=re.pathSplit(e);return Promise.resolve().then(async()=>Hl(la(re.firestore,t,n))).then(s=>s?re.fromFirestore(s.data()):null)}static setSnapshot(e,t,n){let s={method:"merge",...n},{fsCollection:i,fsId:a}=re.pathSplit(e);return Promise.resolve().then(()=>(s.method=="merge"?"FirestoreUpdateDoc":"FirestoreSetDoc")(la(re.firestore,i,a),re.toFirestore(t))).then(()=>t)}static wrapSupabase(e){return Promise.resolve(e).then(t=>{var n,s;if(t!=null&&t.error)throw/JSON object requested, multiple \(or no\) rows returned$/.test(t.error.message)?(console.warn("Supabase query threw record not found against query",e.url.search),console.warn("Supabase raw error",t),new Error("NOT-FOUND")):(console.warn("Supabase query threw",t.error.message),new Error(`${((n=t.error)==null?void 0:n.code)||"UnknownError"}: ${((s=t.error)==null?void 0:s.message)||"Unknown Supabase error"}`));if(t.data)return t.data})}mount(e){let t={initialState:null,...e},{fsCollection:n,fsId:s,entity:i,id:a,relation:u}=re.pathSplit(this.path),c,h;return Promise.resolve().then(()=>this.setHeartbeat(!1)).then(async()=>{this.docRef=la(re.firestore,n,s);let f=await this.getFirestoreState();if(c=this.getReactive(f),!c.doc||!c.setState||!c.getState||!c.watch)throw new Error("Syncro.getReactive() requires a returned `doc`, `setState()`, `getState()` + `watch()`");this.value=h=c.doc,this.debug("Initial state",{doc:h}),this._destroyActions.push(Fy(this.docRef,m=>{let g=re.fromFirestore(m.data());this.debug("Incoming snapshot",{snapshotData:g}),c.setState(g)}))}).then(()=>{if(lu(h))return t.initialState?(this.debug("Populate initial Syncro state (from provided initialState)"),this.setFirestoreState(t.initialState,{method:"set"})):(this.debug(`Populate initial Syncro state (from "${i}" Syncro worker)`),fetch(`${this.config.syncroRegistryUrl}/${this.path}`).then(f=>f.ok||Promise.reject(`Failed to check Syncro "${n}::${s}" status - ${f.statusText}`)))}).then(()=>{c.watch(fu(f=>{this.debug("Local change",{newState:f}),this.markDirty(),this.setFirestoreState(f,{method:"merge"})},this.throttle))}).then(()=>this.setHeartbeat(!0,{immediate:!0})).then(()=>this)}setHeartbeat(e=!0,t){let n={immediate:!0,...t};clearTimeout(this._heartbeatTimer),e&&(this._heartbeatTimer=setTimeout(async()=>{await this.heartbeat(),e&&this.setHeartbeat(!0)},this.config.heartbeatInterval),n.immediate&&this.heartbeat())}async heartbeat(){this.debug("heartbeat!"),await fetch(`${this.config.syncroRegistryUrl}/${this.path}/heartbeat`,{method:"post",headers:{"Content-Type":"application/json"},body:JSON.stringify({session:re.session,...this.isDirty&&{dirty:!0}})}).then(e=>e.ok?null:console.warn(this.path,`Heartbeat failed - ${e.statusText}`,{response:e})).then(()=>this.isDirty=!1)}setFirestoreState(e,t){let n={method:"merge",...t};if(!this.docRef)throw new Error("mount() must be called before setting Firestore state");return(n.method=="set"?Ly:My)(this.docRef,re.toFirestore(e))}getFirestoreState(){if(!this.docRef)throw new Error("mount() must be called before getting Firestore state");return Hl(this.docRef).then(e=>re.fromFirestore(e.data()))}markDirty(){return this.isDirty=!0,this}flush(e){let t={destroy:!1,...e};return fetch(`${this.config.syncroRegistryUrl}/${this.path}/flush`+(t.destroy?"?destroy=1":"")).then(n=>n.ok?null:Promise.reject(n.statusText||"An error occured"))}};de(re,"firebase"),de(re,"firestore"),de(re,"supabase"),de(re,"session"),de(re,"SyncroEntities");var ir=re;var ev={id:"~array",recursive:!0,test:r=>Array.isArray(r),serialize:r=>({_:"~array",...r}),deserialize:r=>{let e=Array.from({length:Object.keys(r).length-1});return Object.entries(r).filter(([t])=>t!=="_").forEach(([t,n])=>e[+t]=n),e}};var gi=class{init(){}constructor(e,t){}};var yi=class extends gi{constructor(){super(...arguments);de(this,"syncros",{})}async init(t){let n={firebaseApiKey:null,firebaseAuthDomain:null,firebaseProjectId:null,firebaseAppId:null,supabaseUrl:null,supabaseKey:null,...await this.getCredentials(),...t},s=Object.keys(n).filter(i=>i===null);if(s.length>0)throw new Error("Firebase plugin requires mandatory options: "+s.join(", "));ir.firebase=Du({apiKey:n.firebaseApiKey,authDomain:n.firebaseAuthDomain,projectId:n.firebaseProjectId,appId:n.firebaseAppId}),ir.firestore=Py(this.firebase),ir.supabase=z_(n.supabaseUrl,n.supabaseKey)}_mountNamespace(t){let n;return Promise.resolve().then(()=>this.requireProject()).then(s=>{let i=t=="_PROJECT"?`projects::${s.id}`:`project_namespaces::${s.id}::${t}`;return n=this.syncros[t]=new ir(i,{debug:(...a)=>this.debug(`SYNCRO://${i}`,...a),getReactive:this.getReactive}),n.mount()}).then(()=>{this.namespaces[t]=n.value})}_unmountNamespace(t){let n=this.syncros[t];return delete this.namespaces[t],delete this.syncros[t],n.destroy()}};var Th=class extends yi{constructor(){super(...arguments);de(this,"Vue");de(this,"project",null);de(this,"reactiveId",1001)}async init(t){let n={app:null,Vue:null,globalName:"$tera",...t};if(!n.Vue)throw new Error("Vue instance to use must be specified in init options as `Vue`");if(this.Vue=n.Vue,!n.app)throw new Error("Vue Root / App instance to use must be specified in init options as `app`");this.app=n.app,n.globalName&&(this.Vue.prototype[n.globalName]=this),await super.init(n),this.project=await this.mountNamespace("_PROJECT")}getReactive(t){let n=this.Vue.observable(t),s=`_teraFy_${this.reactiveId++}`;return this.app[s]=n,{doc:n,setState(i){Object.entries(i||{}).filter(([a])=>!hu(n[a],i[a])).forEach(([a,u])=>n[a]=u)},getState(){return Kt(n)},watch:i=>{this.app.$watch(s,i,{deep:!0})}}}};export{Th as default};
28
28
  /*! Bundled license information:
29
29
 
30
30
  lodash-es/lodash.js:
@@ -1,5 +1,6 @@
1
1
  import Reflib from '@iebh/reflib';
2
2
  import {v4 as uuid4} from 'uuid';
3
+ import {nanoid} from 'nanoid';
3
4
  import Syncro from './syncro.js';
4
5
 
5
6
  /**
@@ -15,46 +16,68 @@ export default {
15
16
  projects: { // {{{
16
17
  singular: 'project',
17
18
  async initState({supabase, id}) {
18
- const result = await Syncro.wrapSupabase(supabase.from('projects')
19
+ let data = await Syncro.wrapSupabase(supabase
20
+ .from('projects')
19
21
  .select('data')
20
- .limit(1)
22
+ .maybeSingle()
21
23
  .eq('id', id)
22
24
  );
25
+ if (!data) throw new Error(`Syncro project "${id}" not found`);
26
+ data = data.data;
23
27
 
24
- if (result.length !== 1) {
25
- throw new Error(`Syncro project "${id}" not found`);
26
- }
27
-
28
- const data = result[0].data;
29
- console.log('[MIGRATION] State of temp at start:', data.temp);
30
-
31
- // Check if temp variable exists
28
+ // MIGRATION - Move data.temp{} into Supabase files + add pointer to filename {{{
32
29
  if (
33
- !data.temp // Project contains no temp subkey
34
- || Object.values(data.temp).every(t => typeof t != 'object') // None of the temp keys are objects
35
- ) return data;
30
+ data.temp // Project contains no temp subkey
31
+ && Object.values(data.temp).some(t => typeof t == 'object') // Some of the temp keys are objects
32
+ ) {
33
+ console.log('[MIGRATION] tera-fy project v1 -> v2', data.temp);
36
34
 
37
- throw new Error('Project data version unsupported');
35
+ await Promise.all(
36
+ Object.entries(data.temp)
37
+ .filter(([, branch]) => typeof branch == 'object')
38
+ .map(([toolKey, ]) => {
39
+ console.log(`[MIGRATION] Converting data.temp[${toolKey}]...`);
38
40
 
39
- // MIGRATION - Move data.temp{} into Supabase files + add pointer to filename
40
- await Promise.all(
41
- Object.entries(data.temp)
42
- .filter(([toolKey, branch]) => typeof branch == 'object')
43
- .map(([toolKey, branch]) => {
44
- console.log(`[MIGRATION] Converting data.temp[${toolKey}]...`);
41
+ const toolName = toolKey.split('-')[0];
42
+ const fileName = `data-${toolName}-${nanoid()}.json`;
43
+ console.log('[MIGRATION] Creating filename:', fileName);
45
44
 
46
- const toolName = toolKey.split('-')[0];
47
- const fileName = `data-${toolName}-${nanoid()}.json`;
48
- console.log('[MIGRATION] Creating filename:', fileName);
45
+ return Promise.resolve()
46
+ .then(()=> Syncro.wrapSupabase(supabase.storage // Split data.temp[toolKey] -> file {{{
47
+ .from('projects')
48
+ .upload(
49
+ `${id}/${fileName}`,
50
+ new File(
51
+ [
52
+ new Blob(
53
+ [
54
+ JSON.stringify(data.temp[toolKey], null, '\t'),
55
+ ],
56
+ {
57
+ type: 'application/json',
58
+ },
59
+ ),
60
+ ],
61
+ fileName,
62
+ {
63
+ type: 'application/json',
64
+ },
65
+ ),
66
+ {
67
+ cacheControl: '3600',
68
+ upsert: true,
69
+ },
70
+ )
71
+ )) // }}}
72
+ .then(()=> data.temp[toolKey] = fileName) // Replace data.temp[toolKey] with new filename
73
+ .catch(e => {
74
+ console.warn('[MIGRATION] Failed to create file', fileName, '-', e);
75
+ throw e;
76
+ })
49
77
 
50
- // FIXME: All of this needs converting over to a Cloudflare Worker compatible environment
51
- /* const projectFile = await tera.createProjectFile(fileName);
52
- console.log('[MIGRATION] Setting file contents:', projectFile, 'to:', data.temp[toolKey]);
53
- await projectFile.setContents(data.temp[toolKey])
54
- console.log('[MIGRATION] Overwriting temp key with filepath:', fileName);
55
- data.temp[toolKey] = fileName; */
56
- })
57
- );
78
+ })
79
+ );
80
+ } // }}}
58
81
 
59
82
  return data;
60
83
  },
@@ -513,7 +513,7 @@ export default class Syncro {
513
513
  this.debug(`Populate initial Syncro state (from "${entity}" Syncro worker)`);
514
514
 
515
515
  return fetch(`${this.config.syncroRegistryUrl}/${this.path}`)
516
- .then(response => response.ok || Promise.reject(`Failed to check Syncro "${path}" status - ${response.statusText}`))
516
+ .then(response => response.ok || Promise.reject(`Failed to check Syncro "${fsCollection}::${fsId}" status - ${response.statusText}`))
517
517
  }
518
518
  })
519
519
  .then(()=> { // Setup local state watcher
@@ -1568,7 +1568,6 @@ export default class TeraFyServer {
1568
1568
  * @returns {Promise} A promise which resolves when the dialog has been updated
1569
1569
  */
1570
1570
  uiProgress(options) {
1571
- console.warn('uiProgress called, current uiProgressPromise:', this.uiProgressPromise)
1572
1571
  if (options === false) options = {close: true}; // Shorthand to close existing ui progress window
1573
1572
 
1574
1573
  if (this.uiProgressOptions === null) { // New uiProgress window
@@ -1603,7 +1602,6 @@ export default class TeraFyServer {
1603
1602
  keyboard: false,
1604
1603
  })
1605
1604
  );
1606
- console.warn('Set uiProgressPromise:', this.uiProgressPromise)
1607
1605
  return Promise.resolve();
1608
1606
  } else {
1609
1607
  throw new Error('Unknown uiProgress state');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iebh/tera-fy",
3
- "version": "2.0.10",
3
+ "version": "2.0.11",
4
4
  "description": "TERA website worker",
5
5
  "scripts": {
6
6
  "dev": "esbuild --platform=browser --format=esm --bundle lib/terafy.client.js --outfile=dist/terafy.js --minify --serve --servedir=.",