@iebh/tera-fy 2.0.17 → 2.0.18

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,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.0.18](https://github.com/IEBH/TERA-fy/compare/v2.0.16...v2.0.18) (2025-03-31)
4
+
5
+
6
+ ### fix
7
+
8
+ * Supabase(y) invokation issues + bug addressing DB which should point at storage system ([8e4beff](https://github.com/IEBH/TERA-fy/commit/8e4beff42704c70afb88668659e8b9940f4c87a3))
9
+
3
10
  ## [2.0.16](https://github.com/IEBH/TERA-fy/compare/v2.0.15...v2.0.16) (2025-03-27)
4
11
 
5
12
 
@@ -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
- });`,Bn=class{constructor(e,t){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=u_,this.params={},this.timeout=Ta,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=lP,this.conn=null,this.sendBuffer=[],this.serializer=new ti,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(()=>(nr(),Ir)).then(({default:c})=>c(...u)):a=fetch,(...u)=>a(...u)},this.endPoint=`${e}/${ba.websocket}`,this.httpEndpoint=Ea(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(hP){this.conn=new WebSocket(this.endpointURL()),this.setupConnection();return}this.conn=new mh(this.endpointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>ou(f_())).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:c_}))}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 xr.connecting:return sr.Connecting;case xr.open:return sr.Open;case xr.closing:return sr.Closing;default:return sr.Closed}}isConnected(){return this.connectionState()===sr.Open}channel(e,t={config:{}}){let n=new Un(`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($e.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(l_,"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($e.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([dP],{type:"application/javascript"});t=URL.createObjectURL(n)}return t}},mh=class{constructor(e,t,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=xr.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}};var $n=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 Ia=class extends $n{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},Rr=class extends $n{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var fP=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())})},Aa=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(nr(),Ir)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},p_=()=>fP(void 0,void 0,void 0,function*(){return typeof Response=="undefined"?(yield Promise.resolve().then(()=>(nr(),Ir))).Response:Response}),xa=r=>{if(Array.isArray(r))return r.map(t=>xa(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]=xa(n)}),e};var Pr=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())})},gh=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),pP=(r,e,t)=>Pr(void 0,void 0,void 0,function*(){let n=yield p_();r instanceof n&&!(t!=null&&t.noResolveJson)?r.json().then(s=>{e(new Ia(gh(s),r.status||500))}).catch(s=>{e(new Rr(gh(s),s))}):e(new Rr(gh(r),r))}),mP=(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 ri(r,e,t,n,s,i){return Pr(this,void 0,void 0,function*(){return new Promise((a,u)=>{r(t,mP(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=>pP(c,u,n))})})}function qn(r,e,t,n){return Pr(this,void 0,void 0,function*(){return ri(r,"GET",e,t,n)})}function lt(r,e,t,n,s){return Pr(this,void 0,void 0,function*(){return ri(r,"POST",e,n,s,t)})}function m_(r,e,t,n,s){return Pr(this,void 0,void 0,function*(){return ri(r,"PUT",e,n,s,t)})}function g_(r,e,t,n){return Pr(this,void 0,void 0,function*(){return ri(r,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),n)})}function Sa(r,e,t,n,s){return Pr(this,void 0,void 0,function*(){return ri(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())})},gP={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},y_={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ni=class{constructor(e,t={},n,s){this.url=e,this.headers=t,this.bucketId=n,this.fetch=Aa(s)}uploadOrUpdate(e,t,n,s){return Me(this,void 0,void 0,function*(){try{let i,a=Object.assign(Object.assign({},y_),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:y_.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 lt(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 $n("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 lt(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 lt(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 lt(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 lt(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 qn(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 qn(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:xa(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 g_(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(ge(n)&&n instanceof Rr){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 Sa(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({},gP),t),{prefix:e||""});return{data:yield lt(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 __="2.7.1";var v_={"X-Client-Info":`storage-js/${__}`};var zn=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())})},si=class{constructor(e,t={},n){this.url=e,this.headers=Object.assign(Object.assign({},v_),t),this.fetch=Aa(n)}listBuckets(){return zn(this,void 0,void 0,function*(){try{return{data:yield qn(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 zn(this,void 0,void 0,function*(){try{return{data:yield qn(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 zn(this,void 0,void 0,function*(){try{return{data:yield lt(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 zn(this,void 0,void 0,function*(){try{return{data:yield m_(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 zn(this,void 0,void 0,function*(){try{return{data:yield lt(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 zn(this,void 0,void 0,function*(){try{return{data:yield Sa(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}})}};var ii=class extends si{constructor(e,t={},n){super(e,t,n)}from(e){return new ni(this.url,this.headers,e,this.fetch)}};var w_="2.48.1";var oi="";typeof Deno!="undefined"?oi="deno":typeof document!="undefined"?oi="web":typeof navigator!="undefined"&&navigator.product==="ReactNative"?oi="react-native":oi="node";var yP={"X-Client-Info":`supabase-js-${oi}/${w_}`},b_={headers:yP},T_={schema:"public"},E_={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},I_={};nr();var _P=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())})},vP=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=Yl:e=fetch,(...t)=>e(...t)},wP=()=>typeof Headers=="undefined"?Xl:Headers,x_=(r,e,t)=>{let n=vP(t),s=wP();return(i,a)=>_P(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 bP=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 A_(r){return r.replace(/\/$/,"")}function S_(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:()=>bP(this,void 0,void 0,function*(){return""})};return r.accessToken?f.accessToken=r.accessToken:delete f.accessToken,f}var Ra="2.67.3";var R_="http://localhost:9999",P_="supabase.auth.token";var C_={"X-Client-Info":`gotrue-js/${Ra}`},yh=10;var ai="X-Supabase-Api-Version",_h={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function k_(r){return Math.round(Date.now()/1e3)+r}function D_(){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 Ye=()=>typeof window!="undefined"&&typeof document!="undefined",Cr={tested:!1,writable:!1},ir=()=>{if(!Ye())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Cr.tested)return Cr.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Cr.tested=!0,Cr.writable=!0}catch{Cr.tested=!0,Cr.writable=!1}return Cr.writable};function O_(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 Pa=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(nr(),Ir)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},N_=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",vh=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},ci=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},li=async(r,e)=>{await r.removeItem(e)};function TP(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 ui=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};ui.promiseConstructor=Promise;function wh(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(TP(n))}async function V_(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function L_(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 EP(r){return("0"+r.toString(16)).substr(-2)}function IP(){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,EP).join("")}async function xP(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 AP(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function SP(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 xP(r);return AP(t)}async function kr(r,e,t=!1){let n=IP(),s=n;t&&(s+="/PASSWORD_RECOVERY"),await vh(r,`${e}-code-verifier`,s);let i=await SP(n);return[i,n===i?"plain":"s256"]}var RP=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function M_(r){let e=r.headers.get(ai);if(!e||!e.match(RP))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var hi=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 Ca=class extends hi{constructor(e,t,n){super(e,t,n),this.name="AuthApiError",this.status=t,this.code=n}};function F_(r){return z(r)&&r.name==="AuthApiError"}var Gn=class extends hi{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},Ct=class extends hi{constructor(e,t,n,s){super(e,n,s),this.name=t,this.status=n}},Ge=class extends Ct{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function j_(r){return z(r)&&r.name==="AuthSessionMissingError"}var Kn=class extends Ct{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Dr=class extends Ct{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Or=class extends Ct{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 U_(r){return z(r)&&r.name==="AuthImplicitGrantRedirectError"}var di=class extends Ct{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}}},Hn=class extends Ct{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function ka(r){return z(r)&&r.name==="AuthRetryableFetchError"}var fi=class extends Ct{constructor(e,t,n){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=n}};var PP=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=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),CP=[502,503,504];async function B_(r){var e;if(!N_(r))throw new Hn(Nr(r),0);if(CP.includes(r.status))throw new Hn(Nr(r),r.status);let t;try{t=await r.json()}catch(i){throw new Gn(Nr(i),i)}let n,s=M_(r);if(s&&s.getTime()>=_h["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 fi(Nr(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new Ge}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 fi(Nr(t),r.status,t.weak_password.reasons);throw new Ca(Nr(t),r.status||500,n)}var kP=(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[ai]||(i[ai]=_h["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 DP(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 DP(r,e,t,n,s,i){let a=kP(e,n,s,i),u;try{u=await r(t,Object.assign({},a))}catch(c){throw console.error(c),new Hn(Nr(c),0)}if(u.ok||await B_(u),n!=null&&n.noResolveJson)return u;try{return await u.json()}catch(c){await B_(c)}}function kt(r){var e;let t=null;OP(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=k_(r.expires_in)));let n=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:n},error:null}}function bh(r){let e=kt(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 ht(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function $_(r){return{data:r,error:null}}function q_(r){let{action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:i}=r,a=PP(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 z_(r){return r}function OP(r){return r.access_token&&r.refresh_token&&r.expires_in}var NP=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},Vr=class{constructor({url:e="",headers:t={},fetch:n}){this.url=e,this.headers=t,this.fetch=Pa(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:ht})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:t}=e,n=NP(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:q_,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:ht})}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:z_});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:ht})}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:ht})}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:ht})}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 G_={getItem:r=>ir()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{ir()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{ir()&&globalThis.localStorage.removeItem(r)}};function Th(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function K_(){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 Lr={debug:!!(globalThis&&ir()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},pi=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Da=class extends pi{};async function Eh(r,e,t){Lr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),Lr.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){Lr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,s.name);try{return await t()}finally{Lr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,s.name)}}else{if(e===0)throw Lr.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Da(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Lr.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()}}))}K_();var VP={url:R_,storageKey:P_,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:C_,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},mi=30*1e3,H_=3;async function W_(r,e,t){return await t()}var Mr=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&&Ye()&&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({},VP),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 Vr({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Pa(s.fetch),this.lock=s.lock||W_,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,s.lock?this.lock=s.lock:Ye()&&(!((t=globalThis==null?void 0:globalThis.navigator)===null||t===void 0)&&t.locks)?this.lock=Eh:this.lock=W_,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:ir()?this.storage=G_:(this.memoryStorage={},this.storage=Th(this.memoryStorage)):(this.memoryStorage={},this.storage=Th(this.memoryStorage)),Ye()&&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} (${Ra}) ${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=O_(window.location.href),n="none";if(this._isImplicitGrantCallback(t)?n="implicit":await this._isPKCECallback(t)&&(n="pkce"),Ye()&&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),U_(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 Gn("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:kt}),{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 kr(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:kt})}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:kt})}else throw new Dr("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:bh})}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:bh})}else throw new Dr("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 Kn}:(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 ci(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:kt});if(await li(this.storage,`${this.storageKey}-code-verifier`),a)throw a;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Kn}:(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:kt}),{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 Kn}:(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 kr(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 Dr("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:kt});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 kr(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:$_})}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 Ge;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 Dr("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 ci(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:ht}):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 Ge}: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:ht})})}catch(t){if(z(t))return j_(t)&&(await this._removeSession(),await li(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 Ge;let a=s.session,u=null,c=null;this.flowType==="pkce"&&e.email!=null&&([u,c]=await kr(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:ht});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 wh(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 Ge;let t=Date.now()/1e3,n=t,s=!0,i=null,a=wh(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 Ge;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(!Ye())throw new Or("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Or(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 di("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Or("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 di("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 Or("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<=mi&&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 ci(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&&!(F_(u)&&(u.status===404||u.status===401||u.status===403)))return{error:u}}return e!=="others"&&(await this._removeSession(),await li(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){let t=D_(),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 kr(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 Ye()&&!(!((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 L_(async s=>(s>0&&await V_(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:kt})),(s,i)=>{let a=200*Math.pow(2,s);return i&&ka(i)&&Date.now()+a-n<mi})}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),Ye()&&!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 ci(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+yh;if(this._debug(t,`session has${i?"":" not"} expired with margin of ${yh}s`),i){if(this.autoRefreshToken&&n.refresh_token){let{error:a}=await this._callRefreshToken(n.refresh_token);a&&(console.error(a),ka(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 Ge;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new ui;let{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new Ge;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 ka(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 vh(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await li(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Ye()&&(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(),mi);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)/mi);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${mi}ms, refresh threshold is ${H_} ticks`),s<=H_&&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 pi)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ye()||!(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 kr(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}}))}};Mr.nextInstanceID=0;var LP=Mr,Ih=LP;var Oa=class extends Ih{constructor(e){super(e)}};var MP=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())})},gi=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=A_(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:T_,realtime:I_,auth:Object.assign(Object.assign({},E_),{storageKey:c}),global:b_},f=S_(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=x_(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 o_(`${u}/rest/v1`,{headers:this.headers,schema:f.db.schema,fetch:this.fetch}),f.accessToken||this._listenForAuthEvents()}get functions(){return new Ws(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new ii(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 MP(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 Oa({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 Bn(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 Q_=(r,e,t)=>new gi(r,e,t);function FP(r,e){return Object.fromEntries(Object.entries(r).sort(e||void 0).map(([t,n])=>[t,n]))}function Na(r,e){return Array.isArray(r)?r.map(t=>Na(t,e)):typeof r=="object"?Object.fromEntries(Object.entries(FP(r,e)).map(([t,n])=>[t,Na(n,e)])):r}var J_={id:"~date",test:r=>r instanceof Date,serialize:r=>({_:"~date",v:r.toISOString()}),deserialize:r=>new Date(r.v)};var Y_={id:"~function",test:r=>typeof r=="function",serialize:r=>({_:"~function",v:r.toString()}),deserialize:v=>eval(v.v.toString())};var X_={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 Z_={id:"~nan",test:r=>Number.isNaN(r),serialize:r=>({_:"~nan"}),deserialize:r=>NaN};var ev={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 tv={id:"~set",test:r=>r instanceof Set,serialize:r=>({_:"~set",v:Array.from(r)}),deserialize:r=>new Set(r.v)};var rv={id:"~undefined",test:r=>r===void 0,serialize:r=>({_:"~undefined"}),deserialize:r=>{}};var Wn={settings:{stringify:!0,destringify:!0,clone:!1,depth:0,modules:[J_,Y_,X_,Z_,ev,tv,rv],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 Wn.loadedModules[e.id]=e}else throw new Error("Unknown module type")})},serialize(r,e){let t=oo(e,Wn.settings),n=Wn.loadModules(t.modules),s=t.symetric?Na(r):t.clone?Ht(r):r,i=new Map,a=(u,c)=>{let h=Z(u);if(h&&t.circular){let g=i.get(u);if(g)return Wt(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(),Wt(s,c,g),E.forEach(P=>a(u[P],c.concat(P)))}else c.length?Wt(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=oo(e,Wn.settings),n=Wn.loadModules(t.modules),s=mu(n,"id"),i=t.destringify?JSON.parse(r):t.clone?Ht(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)?(Wt(i,c,h),Se(h).forEach(f=>a(u[f],[...c,f]))):Wt(i,c,h):i=h}else t.circular&&Z(u)&&u._&&u._=="~circular"?Wt(i,c,ys(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}},yi=Wn;var nv="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var sv=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=nv[t[r]&63];return e};var hv=ou(cv(),1);var UP=Object.prototype.toString,BP=r=>UP.call(r)==="[object Error]",$P=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function xh(r){return r&&BP(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:$P.has(r.message):!1}var Ah=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},lv=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function Sh(r,e){return new Promise((t,n)=>{var u,c,h;e={...e},(u=e.onFailedAttempt)!=null||(e.onFailedAttempt=()=>{}),(c=e.shouldRetry)!=null||(e.shouldRetry=()=>!0),(h=e.retries)!=null||(e.retries=10);let s=hv.default.operation(e),i=()=>{var f;s.stop(),n((f=e.signal)==null?void 0:f.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",i,{once:!0});let a=()=>{var f;(f=e.signal)==null||f.removeEventListener("abort",i),s.stop()};s.attempt(async f=>{try{let m=await r(f);a(),t(m)}catch(m){try{if(!(m instanceof Error))throw new TypeError(`Non-error was thrown: "${m}". You should only throw errors.`);if(m instanceof Ah)throw m.originalError;if(m instanceof TypeError&&!xh(m))throw m;if(lv(m,f,e),await e.shouldRetry(m)||(s.stop(),n(m)),await e.onFailedAttempt(m),!s.retry(m))throw s.mainError()}catch(g){lv(g,f,e),a(),n(g)}}})})}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_${sv()}`)}debug(...e){}debugError(...e){console.log(`[Syncro ${this.path}]`,...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 Ht(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 yi.serialize(e,{circular:!1,clone:!0,modules:[dv,...yi.settings.modules],stringify:!1})}static fromFirestore(e={}){return yi.deserialize(e,{circular:!1,clone:!0,modules:[dv,...yi.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()=>Jl(da(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")(da(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,retries:5,retryMinTime:250,...e},{fsCollection:n,fsId:s,entity:i,id:a,relation:u}=re.pathSplit(this.path),c,h;return Sh(()=>Promise.resolve().then(()=>this.setHeartbeat(!1)).then(async()=>{this.docRef=da(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(qy(this.docRef,m=>{let g=re.fromFirestore(m.data());this.debug("Incoming snapshot",{snapshotData:g}),c.setState(g)}))}).then(()=>{if(fu(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(gu(f=>{this.debug("Local change",{newState:f}),this.markDirty(),this.setFirestoreState(f,{method:"merge"})},this.throttle))}).then(()=>this.setHeartbeat(!0,{immediate:!0})).then(()=>this).catch(async f=>{throw await this.destroy(),f}),{retries:t.retries,minTimeout:t.retryMinTime,randomize:!0,factor:3,onFailedAttempt:f=>this.debugError(`[Attempt ${f.attemptNumber}/${f.attemptNumber+f.retriesLeft-1}] to mount syncro`,f)})}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"?By:$y)(this.docRef,re.toFirestore(e))}getFirestoreState(){if(!this.docRef)throw new Error("mount() must be called before getting Firestore state");return Jl(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 or=re;var dv={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 _i=class{init(){}constructor(e,t){}};var vi=class extends _i{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(", "));or.firebase=Vu({apiKey:n.firebaseApiKey,authDomain:n.firebaseAuthDomain,projectId:n.firebaseProjectId,appId:n.firebaseAppId}),or.firestore=Ny(this.firebase),or.supabase=Q_(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 or(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 Rh=class extends vi{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])=>!pu(n[a],i[a])).forEach(([a,u])=>n[a]=u)},getState(){return Ht(n)},watch:i=>{this.app.$watch(s,i,{deep:!0})}}}};export{Rh as default};
27
+ });`,Bn=class{constructor(e,t){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=u_,this.params={},this.timeout=Ta,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=lP,this.conn=null,this.sendBuffer=[],this.serializer=new ti,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(()=>(nr(),Ir)).then(({default:c})=>c(...u)):a=fetch,(...u)=>a(...u)},this.endPoint=`${e}/${ba.websocket}`,this.httpEndpoint=Ea(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(hP){this.conn=new WebSocket(this.endpointURL()),this.setupConnection();return}this.conn=new mh(this.endpointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>ou(f_())).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:c_}))}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 xr.connecting:return sr.Connecting;case xr.open:return sr.Open;case xr.closing:return sr.Closing;default:return sr.Closed}}isConnected(){return this.connectionState()===sr.Open}channel(e,t={config:{}}){let n=new Un(`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($e.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(l_,"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($e.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([dP],{type:"application/javascript"});t=URL.createObjectURL(n)}return t}},mh=class{constructor(e,t,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=xr.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}};var $n=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 Ia=class extends $n{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},Rr=class extends $n{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var fP=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())})},Aa=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(nr(),Ir)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},p_=()=>fP(void 0,void 0,void 0,function*(){return typeof Response=="undefined"?(yield Promise.resolve().then(()=>(nr(),Ir))).Response:Response}),xa=r=>{if(Array.isArray(r))return r.map(t=>xa(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]=xa(n)}),e};var Pr=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())})},gh=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),pP=(r,e,t)=>Pr(void 0,void 0,void 0,function*(){let n=yield p_();r instanceof n&&!(t!=null&&t.noResolveJson)?r.json().then(s=>{e(new Ia(gh(s),r.status||500))}).catch(s=>{e(new Rr(gh(s),s))}):e(new Rr(gh(r),r))}),mP=(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 ri(r,e,t,n,s,i){return Pr(this,void 0,void 0,function*(){return new Promise((a,u)=>{r(t,mP(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=>pP(c,u,n))})})}function qn(r,e,t,n){return Pr(this,void 0,void 0,function*(){return ri(r,"GET",e,t,n)})}function lt(r,e,t,n,s){return Pr(this,void 0,void 0,function*(){return ri(r,"POST",e,n,s,t)})}function m_(r,e,t,n,s){return Pr(this,void 0,void 0,function*(){return ri(r,"PUT",e,n,s,t)})}function g_(r,e,t,n){return Pr(this,void 0,void 0,function*(){return ri(r,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),n)})}function Sa(r,e,t,n,s){return Pr(this,void 0,void 0,function*(){return ri(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())})},gP={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},y_={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ni=class{constructor(e,t={},n,s){this.url=e,this.headers=t,this.bucketId=n,this.fetch=Aa(s)}uploadOrUpdate(e,t,n,s){return Me(this,void 0,void 0,function*(){try{let i,a=Object.assign(Object.assign({},y_),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:y_.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 lt(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 $n("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 lt(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 lt(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 lt(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 lt(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 qn(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 qn(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:xa(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 g_(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(ge(n)&&n instanceof Rr){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 Sa(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({},gP),t),{prefix:e||""});return{data:yield lt(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 __="2.7.1";var v_={"X-Client-Info":`storage-js/${__}`};var zn=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())})},si=class{constructor(e,t={},n){this.url=e,this.headers=Object.assign(Object.assign({},v_),t),this.fetch=Aa(n)}listBuckets(){return zn(this,void 0,void 0,function*(){try{return{data:yield qn(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 zn(this,void 0,void 0,function*(){try{return{data:yield qn(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 zn(this,void 0,void 0,function*(){try{return{data:yield lt(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 zn(this,void 0,void 0,function*(){try{return{data:yield m_(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 zn(this,void 0,void 0,function*(){try{return{data:yield lt(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 zn(this,void 0,void 0,function*(){try{return{data:yield Sa(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}})}};var ii=class extends si{constructor(e,t={},n){super(e,t,n)}from(e){return new ni(this.url,this.headers,e,this.fetch)}};var w_="2.48.1";var oi="";typeof Deno!="undefined"?oi="deno":typeof document!="undefined"?oi="web":typeof navigator!="undefined"&&navigator.product==="ReactNative"?oi="react-native":oi="node";var yP={"X-Client-Info":`supabase-js-${oi}/${w_}`},b_={headers:yP},T_={schema:"public"},E_={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},I_={};nr();var _P=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())})},vP=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=Yl:e=fetch,(...t)=>e(...t)},wP=()=>typeof Headers=="undefined"?Xl:Headers,x_=(r,e,t)=>{let n=vP(t),s=wP();return(i,a)=>_P(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 bP=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 A_(r){return r.replace(/\/$/,"")}function S_(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:()=>bP(this,void 0,void 0,function*(){return""})};return r.accessToken?f.accessToken=r.accessToken:delete f.accessToken,f}var Ra="2.67.3";var R_="http://localhost:9999",P_="supabase.auth.token";var C_={"X-Client-Info":`gotrue-js/${Ra}`},yh=10;var ai="X-Supabase-Api-Version",_h={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function k_(r){return Math.round(Date.now()/1e3)+r}function D_(){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 Ye=()=>typeof window!="undefined"&&typeof document!="undefined",Cr={tested:!1,writable:!1},ir=()=>{if(!Ye())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Cr.tested)return Cr.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Cr.tested=!0,Cr.writable=!0}catch{Cr.tested=!0,Cr.writable=!1}return Cr.writable};function O_(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 Pa=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(nr(),Ir)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},N_=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",vh=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},ci=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},li=async(r,e)=>{await r.removeItem(e)};function TP(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 ui=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};ui.promiseConstructor=Promise;function wh(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(TP(n))}async function V_(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function L_(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 EP(r){return("0"+r.toString(16)).substr(-2)}function IP(){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,EP).join("")}async function xP(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 AP(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function SP(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 xP(r);return AP(t)}async function kr(r,e,t=!1){let n=IP(),s=n;t&&(s+="/PASSWORD_RECOVERY"),await vh(r,`${e}-code-verifier`,s);let i=await SP(n);return[i,n===i?"plain":"s256"]}var RP=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function M_(r){let e=r.headers.get(ai);if(!e||!e.match(RP))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var hi=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 Ca=class extends hi{constructor(e,t,n){super(e,t,n),this.name="AuthApiError",this.status=t,this.code=n}};function F_(r){return z(r)&&r.name==="AuthApiError"}var Gn=class extends hi{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},Ct=class extends hi{constructor(e,t,n,s){super(e,n,s),this.name=t,this.status=n}},Ge=class extends Ct{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function j_(r){return z(r)&&r.name==="AuthSessionMissingError"}var Kn=class extends Ct{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Dr=class extends Ct{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},Or=class extends Ct{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 U_(r){return z(r)&&r.name==="AuthImplicitGrantRedirectError"}var di=class extends Ct{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}}},Hn=class extends Ct{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function ka(r){return z(r)&&r.name==="AuthRetryableFetchError"}var fi=class extends Ct{constructor(e,t,n){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=n}};var PP=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=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),CP=[502,503,504];async function B_(r){var e;if(!N_(r))throw new Hn(Nr(r),0);if(CP.includes(r.status))throw new Hn(Nr(r),r.status);let t;try{t=await r.json()}catch(i){throw new Gn(Nr(i),i)}let n,s=M_(r);if(s&&s.getTime()>=_h["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 fi(Nr(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new Ge}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 fi(Nr(t),r.status,t.weak_password.reasons);throw new Ca(Nr(t),r.status||500,n)}var kP=(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[ai]||(i[ai]=_h["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 DP(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 DP(r,e,t,n,s,i){let a=kP(e,n,s,i),u;try{u=await r(t,Object.assign({},a))}catch(c){throw console.error(c),new Hn(Nr(c),0)}if(u.ok||await B_(u),n!=null&&n.noResolveJson)return u;try{return await u.json()}catch(c){await B_(c)}}function kt(r){var e;let t=null;OP(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=k_(r.expires_in)));let n=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:n},error:null}}function bh(r){let e=kt(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 ht(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function $_(r){return{data:r,error:null}}function q_(r){let{action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:i}=r,a=PP(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 z_(r){return r}function OP(r){return r.access_token&&r.refresh_token&&r.expires_in}var NP=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},Vr=class{constructor({url:e="",headers:t={},fetch:n}){this.url=e,this.headers=t,this.fetch=Pa(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:ht})}catch(n){if(z(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:t}=e,n=NP(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:q_,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:ht})}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:z_});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:ht})}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:ht})}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:ht})}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 G_={getItem:r=>ir()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{ir()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{ir()&&globalThis.localStorage.removeItem(r)}};function Th(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function K_(){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 Lr={debug:!!(globalThis&&ir()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},pi=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},Da=class extends pi{};async function Eh(r,e,t){Lr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),Lr.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){Lr.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,s.name);try{return await t()}finally{Lr.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,s.name)}}else{if(e===0)throw Lr.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new Da(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Lr.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()}}))}K_();var VP={url:R_,storageKey:P_,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:C_,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},mi=30*1e3,H_=3;async function W_(r,e,t){return await t()}var Mr=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&&Ye()&&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({},VP),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 Vr({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Pa(s.fetch),this.lock=s.lock||W_,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,s.lock?this.lock=s.lock:Ye()&&(!((t=globalThis==null?void 0:globalThis.navigator)===null||t===void 0)&&t.locks)?this.lock=Eh:this.lock=W_,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:ir()?this.storage=G_:(this.memoryStorage={},this.storage=Th(this.memoryStorage)):(this.memoryStorage={},this.storage=Th(this.memoryStorage)),Ye()&&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} (${Ra}) ${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=O_(window.location.href),n="none";if(this._isImplicitGrantCallback(t)?n="implicit":await this._isPKCECallback(t)&&(n="pkce"),Ye()&&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),U_(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 Gn("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:kt}),{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 kr(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:kt})}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:kt})}else throw new Dr("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:bh})}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:bh})}else throw new Dr("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 Kn}:(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 ci(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:kt});if(await li(this.storage,`${this.storageKey}-code-verifier`),a)throw a;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Kn}:(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:kt}),{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 Kn}:(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 kr(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 Dr("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:kt});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 kr(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:$_})}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 Ge;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 Dr("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 ci(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:ht}):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 Ge}: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:ht})})}catch(t){if(z(t))return j_(t)&&(await this._removeSession(),await li(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 Ge;let a=s.session,u=null,c=null;this.flowType==="pkce"&&e.email!=null&&([u,c]=await kr(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:ht});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 wh(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 Ge;let t=Date.now()/1e3,n=t,s=!0,i=null,a=wh(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 Ge;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(!Ye())throw new Or("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Or(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 di("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Or("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 di("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 Or("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<=mi&&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 ci(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&&!(F_(u)&&(u.status===404||u.status===401||u.status===403)))return{error:u}}return e!=="others"&&(await this._removeSession(),await li(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){let t=D_(),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 kr(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 Ye()&&!(!((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 L_(async s=>(s>0&&await V_(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:kt})),(s,i)=>{let a=200*Math.pow(2,s);return i&&ka(i)&&Date.now()+a-n<mi})}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),Ye()&&!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 ci(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+yh;if(this._debug(t,`session has${i?"":" not"} expired with margin of ${yh}s`),i){if(this.autoRefreshToken&&n.refresh_token){let{error:a}=await this._callRefreshToken(n.refresh_token);a&&(console.error(a),ka(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 Ge;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new ui;let{data:i,error:a}=await this._refreshAccessToken(e);if(a)throw a;if(!i.session)throw new Ge;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 ka(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 vh(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await li(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Ye()&&(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(),mi);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)/mi);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${mi}ms, refresh threshold is ${H_} ticks`),s<=H_&&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 pi)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Ye()||!(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 kr(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}}))}};Mr.nextInstanceID=0;var LP=Mr,Ih=LP;var Oa=class extends Ih{constructor(e){super(e)}};var MP=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())})},gi=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=A_(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:T_,realtime:I_,auth:Object.assign(Object.assign({},E_),{storageKey:c}),global:b_},f=S_(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=x_(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 o_(`${u}/rest/v1`,{headers:this.headers,schema:f.db.schema,fetch:this.fetch}),f.accessToken||this._listenForAuthEvents()}get functions(){return new Ws(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new ii(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 MP(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 Oa({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 Bn(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 Q_=(r,e,t)=>new gi(r,e,t);function FP(r,e){return Object.fromEntries(Object.entries(r).sort(e||void 0).map(([t,n])=>[t,n]))}function Na(r,e){return Array.isArray(r)?r.map(t=>Na(t,e)):typeof r=="object"?Object.fromEntries(Object.entries(FP(r,e)).map(([t,n])=>[t,Na(n,e)])):r}var J_={id:"~date",test:r=>r instanceof Date,serialize:r=>({_:"~date",v:r.toISOString()}),deserialize:r=>new Date(r.v)};var Y_={id:"~function",test:r=>typeof r=="function",serialize:r=>({_:"~function",v:r.toString()}),deserialize:v=>eval(v.v.toString())};var X_={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 Z_={id:"~nan",test:r=>Number.isNaN(r),serialize:r=>({_:"~nan"}),deserialize:r=>NaN};var ev={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 tv={id:"~set",test:r=>r instanceof Set,serialize:r=>({_:"~set",v:Array.from(r)}),deserialize:r=>new Set(r.v)};var rv={id:"~undefined",test:r=>r===void 0,serialize:r=>({_:"~undefined"}),deserialize:r=>{}};var Wn={settings:{stringify:!0,destringify:!0,clone:!1,depth:0,modules:[J_,Y_,X_,Z_,ev,tv,rv],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 Wn.loadedModules[e.id]=e}else throw new Error("Unknown module type")})},serialize(r,e){let t=oo(e,Wn.settings),n=Wn.loadModules(t.modules),s=t.symetric?Na(r):t.clone?Ht(r):r,i=new Map,a=(u,c)=>{let h=Z(u);if(h&&t.circular){let g=i.get(u);if(g)return Wt(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(),Wt(s,c,g),E.forEach(P=>a(u[P],c.concat(P)))}else c.length?Wt(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=oo(e,Wn.settings),n=Wn.loadModules(t.modules),s=mu(n,"id"),i=t.destringify?JSON.parse(r):t.clone?Ht(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)?(Wt(i,c,h),Se(h).forEach(f=>a(u[f],[...c,f]))):Wt(i,c,h):i=h}else t.circular&&Z(u)&&u._&&u._=="~circular"?Wt(i,c,ys(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}},yi=Wn;var nv="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var sv=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=nv[t[r]&63];return e};var hv=ou(cv(),1);var UP=Object.prototype.toString,BP=r=>UP.call(r)==="[object Error]",$P=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function xh(r){return r&&BP(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:$P.has(r.message):!1}var Ah=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},lv=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function Sh(r,e){return new Promise((t,n)=>{var u,c,h;e={...e},(u=e.onFailedAttempt)!=null||(e.onFailedAttempt=()=>{}),(c=e.shouldRetry)!=null||(e.shouldRetry=()=>!0),(h=e.retries)!=null||(e.retries=10);let s=hv.default.operation(e),i=()=>{var f;s.stop(),n((f=e.signal)==null?void 0:f.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",i,{once:!0});let a=()=>{var f;(f=e.signal)==null||f.removeEventListener("abort",i),s.stop()};s.attempt(async f=>{try{let m=await r(f);a(),t(m)}catch(m){try{if(!(m instanceof Error))throw new TypeError(`Non-error was thrown: "${m}". You should only throw errors.`);if(m instanceof Ah)throw m.originalError;if(m instanceof TypeError&&!xh(m))throw m;if(lv(m,f,e),await e.shouldRetry(m)||(s.stop(),n(m)),await e.onFailedAttempt(m),!s.retry(m))throw s.mainError()}catch(g){lv(g,f,e),a(),n(g)}}})})}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_${sv()}`)}debug(...e){}debugError(...e){console.log(`[Syncro ${this.path}]`,...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 Ht(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 yi.serialize(e,{circular:!1,clone:!0,modules:[dv,...yi.settings.modules],stringify:!1})}static fromFirestore(e={}){return yi.deserialize(e,{circular:!1,clone:!0,modules:[dv,...yi.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()=>Jl(da(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")(da(re.firestore,i,a),re.toFirestore(t))).then(()=>t)}mount(e){let t={initialState:null,retries:5,retryMinTime:250,...e},{fsCollection:n,fsId:s,entity:i,id:a,relation:u}=re.pathSplit(this.path),c,h;return Sh(()=>Promise.resolve().then(()=>this.setHeartbeat(!1)).then(async()=>{this.docRef=da(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(qy(this.docRef,m=>{let g=re.fromFirestore(m.data());this.debug("Incoming snapshot",{snapshotData:g}),c.setState(g)}))}).then(()=>{if(fu(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(gu(f=>{this.debug("Local change",{newState:f}),this.markDirty(),this.setFirestoreState(f,{method:"merge"})},this.throttle))}).then(()=>this.setHeartbeat(!0,{immediate:!0})).then(()=>this).catch(async f=>{throw await this.destroy(),f}),{retries:t.retries,minTimeout:t.retryMinTime,randomize:!0,factor:3,onFailedAttempt:f=>this.debugError(`[Attempt ${f.attemptNumber}/${f.attemptNumber+f.retriesLeft-1}] to mount syncro`,f)})}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"?By:$y)(this.docRef,re.toFirestore(e))}getFirestoreState(){if(!this.docRef)throw new Error("mount() must be called before getting Firestore state");return Jl(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 or=re;var dv={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 _i=class{init(){}constructor(e,t){}};var vi=class extends _i{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(", "));or.firebase=Vu({apiKey:n.firebaseApiKey,authDomain:n.firebaseAuthDomain,projectId:n.firebaseProjectId,appId:n.firebaseAppId}),or.firestore=Ny(this.firebase),or.supabase=Q_(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 or(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 Rh=class extends vi{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])=>!pu(n[a],i[a])).forEach(([a,u])=>n[a]=u)},getState(){return Ht(n)},watch:i=>{this.app.$watch(s,i,{deep:!0})}}}};export{Rh as default};
28
28
  /*! Bundled license information:
29
29
 
30
30
  lodash-es/lodash.js:
@@ -43,6 +43,7 @@ export default {
43
43
 
44
44
  return Promise.resolve()
45
45
  .then(()=> supabase(s => s // Split data.temp[toolKey] -> file {{{
46
+ .storage
46
47
  .from('projects')
47
48
  .upload(
48
49
  `${id}/${fileName}`,
@@ -42,9 +42,9 @@ export default class Syncro {
42
42
 
43
43
 
44
44
  /**
45
- * Supabase instance in use
45
+ * Supabasey wrapper function in use
46
46
  *
47
- * @type {SupabaseClient}
47
+ * @type {Supabasey}
48
48
  */
49
49
  static supabase;
50
50
 
@@ -444,37 +444,6 @@ export default class Syncro {
444
444
  }
445
445
 
446
446
 
447
- /**
448
- * Wrap a Supabase query so it works more like a classic-JS promise
449
- *
450
- * 1. Flatten non-promise responses into thennables
451
- * 2. The query is forced to respond as a promise (prevents accidental query chaining)
452
- * 3. The response data object is forced as a POJO (if any data is returned, otherwise void)
453
- * 4. Error responses throw with a logical error message rather than a weird object return
454
- * 5. Translate various error messages to something logical
455
- *
456
- * @param {SupabaseQuery} query A Supabase query object or method to execute
457
- * @returns {Object} The data response as a plain JavaScript Object
458
- */
459
- static wrapSupabase(query) {
460
- return Promise.resolve(query)
461
- .then(res => {
462
- if (res?.error) {
463
- if (/JSON object requested, multiple \(or no\) rows returned$/.test(res.error.message)) {
464
- console.warn('Supabase query threw record not found against query', query.url.search);
465
- console.warn('Supabase raw error', res);
466
- throw new Error('NOT-FOUND');
467
- } else {
468
- console.warn('Supabase query threw', res.error.message);
469
- throw new Error(`${res.error?.code || 'UnknownError'}: ${res.error?.message || 'Unknown Supabase error'}`);
470
- }
471
- } else if (res.data) { // Do we have output data
472
- return res.data;
473
- }
474
- })
475
- }
476
-
477
-
478
447
  /**
479
448
  * Mount the remote Firestore document against this Syncro instance
480
449
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iebh/tera-fy",
3
- "version": "2.0.17",
3
+ "version": "2.0.18",
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=.",