@iebh/tera-fy 2.0.2 → 2.0.3
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 +8 -0
- package/dist/plugin.vue2.es2019.js +1 -1
- package/lib/syncro.js +4 -5
- package/lib/terafy.server.js +2 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [2.0.3](https://github.com/IEBH/TERA-fy/compare/v2.0.2...v2.0.3) (2025-02-19)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### fix
|
|
7
|
+
|
|
8
|
+
* Misc fixes for {get,set}Namespace() ([aef76cf](https://github.com/IEBH/TERA-fy/commit/aef76cf58e887a317c9abdcdd50c00f63db34a56))
|
|
9
|
+
* Regen package-lock ([0f6802f](https://github.com/IEBH/TERA-fy/commit/0f6802f51576930fc4de2d06705edfb5cd03bf7e))
|
|
10
|
+
|
|
3
11
|
## [2.0.2](https://github.com/IEBH/TERA-fy/compare/v2.0.1...v2.0.2) (2025-02-18)
|
|
4
12
|
|
|
5
13
|
|
|
@@ -43,7 +43,7 @@ This typically indicates that your device does not have a healthy Internet conne
|
|
|
43
43
|
if (e.data.event === "start") {
|
|
44
44
|
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
|
|
45
45
|
}
|
|
46
|
-
});`,sa=class{constructor(e,t){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=wE,this.params={},this.timeout=of,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=iU,this.conn=null,this.sendBuffer=[],this.serializer=new ju,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=a=>{let c;return a?c=a:typeof fetch=="undefined"?c=(...h)=>Promise.resolve().then(()=>(Ei(),gs)).then(({default:f})=>f(...h)):c=fetch,(...h)=>c(...h)},this.endPoint=`${e}/${sf.websocket}`,this.httpEndpoint=af(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:a=>[1e3,2e3,5e3,1e4][a-1]||1e4,this.encode=t!=null&&t.encode?t.encode:(a,c)=>c(JSON.stringify(a)),this.decode=t!=null&&t.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new ys(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(sU){this.conn=new WebSocket(this.endpointURL()),this.setupConnection();return}this.conn=new Bg(this.endpointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Dd(xE())).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:bE}))}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 _s.connecting:return Ii.Connecting;case _s.open:return Ii.Open;case _s.closing:return Ii.Closing;default:return Ii.Closed}}isConnected(){return this.connectionState()===Ii.Open}channel(e,t={config:{}}){let n=new ia(`realtime:${e}`,t,this);return this.channels.push(n),n}push(e){let{topic:t,event:n,payload:s,ref:a}=e,c=()=>{this.encode(e,h=>{var f;(f=this.conn)===null||f===void 0||f.send(h)})};this.log("push",`${t} ${n} (${a})`,s),this.isConnected()?c():this.sendBuffer.push(c)}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(rr.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(TE,"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:a,ref:c}=t;c&&c===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${a.status||""} ${n} ${s} ${c&&"("+c+")"||""}`,a),this.channels.filter(h=>h._isMember(n)).forEach(h=>h._trigger(s,a,c)),this.stateChangeCallbacks.message.forEach(h=>h(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(rr.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([oU],{type:"application/javascript"});t=URL.createObjectURL(n)}return t}},Bg=class{constructor(e,t,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=_s.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}};var oa=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function at(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var uf=class extends oa{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},ws=class extends oa{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var aU=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function h(_){try{m(n.next(_))}catch(E){c(E)}}function f(_){try{m(n.throw(_))}catch(E){c(E)}}function m(_){_.done?a(_.value):s(_.value).then(h,f)}m((n=n.apply(r,e||[])).next())})},lf=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(Ei(),gs)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},AE=()=>aU(void 0,void 0,void 0,function*(){return typeof Response=="undefined"?(yield Promise.resolve().then(()=>(Ei(),gs))).Response:Response}),cf=r=>{if(Array.isArray(r))return r.map(t=>cf(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,a=>a.toUpperCase().replace(/[-_]/g,""));e[s]=cf(n)}),e};var bs=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function h(_){try{m(n.next(_))}catch(E){c(E)}}function f(_){try{m(n.throw(_))}catch(E){c(E)}}function m(_){_.done?a(_.value):s(_.value).then(h,f)}m((n=n.apply(r,e||[])).next())})},jg=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),uU=(r,e,t)=>bs(void 0,void 0,void 0,function*(){let n=yield AE();r instanceof n&&!(t!=null&&t.noResolveJson)?r.json().then(s=>{e(new uf(jg(s),r.status||500))}).catch(s=>{e(new ws(jg(s),s))}):e(new ws(jg(r),r))}),cU=(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 $u(r,e,t,n,s,a){return bs(this,void 0,void 0,function*(){return new Promise((c,h)=>{r(t,cU(e,n,s,a)).then(f=>{if(!f.ok)throw f;return n!=null&&n.noResolveJson?f:f.json()}).then(f=>c(f)).catch(f=>uU(f,h,n))})})}function aa(r,e,t,n){return bs(this,void 0,void 0,function*(){return $u(r,"GET",e,t,n)})}function en(r,e,t,n,s){return bs(this,void 0,void 0,function*(){return $u(r,"POST",e,n,s,t)})}function SE(r,e,t,n,s){return bs(this,void 0,void 0,function*(){return $u(r,"PUT",e,n,s,t)})}function RE(r,e,t,n){return bs(this,void 0,void 0,function*(){return $u(r,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),n)})}function hf(r,e,t,n,s){return bs(this,void 0,void 0,function*(){return $u(r,"DELETE",e,n,s,t)})}var Kt=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function h(_){try{m(n.next(_))}catch(E){c(E)}}function f(_){try{m(n.throw(_))}catch(E){c(E)}}function m(_){_.done?a(_.value):s(_.value).then(h,f)}m((n=n.apply(r,e||[])).next())})},lU={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},PE={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},qu=class{constructor(e,t={},n,s){this.url=e,this.headers=t,this.bucketId=n,this.fetch=lf(s)}uploadOrUpdate(e,t,n,s){return Kt(this,void 0,void 0,function*(){try{let a,c=Object.assign(Object.assign({},PE),s),h=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(c.upsert)}),f=c.metadata;typeof Blob!="undefined"&&n instanceof Blob?(a=new FormData,a.append("cacheControl",c.cacheControl),f&&a.append("metadata",this.encodeMetadata(f)),a.append("",n)):typeof FormData!="undefined"&&n instanceof FormData?(a=n,a.append("cacheControl",c.cacheControl),f&&a.append("metadata",this.encodeMetadata(f))):(a=n,h["cache-control"]=`max-age=${c.cacheControl}`,h["content-type"]=c.contentType,f&&(h["x-metadata"]=this.toBase64(this.encodeMetadata(f)))),s!=null&&s.headers&&(h=Object.assign(Object.assign({},h),s.headers));let m=this._removeEmptyFolders(t),_=this._getFinalPath(m),E=yield this.fetch(`${this.url}/object/${_}`,Object.assign({method:e,body:a,headers:h},c!=null&&c.duplex?{duplex:c.duplex}:{})),I=yield E.json();return E.ok?{data:{path:m,id:I.Id,fullPath:I.Key},error:null}:{data:null,error:I}}catch(a){if(at(a))return{data:null,error:a};throw a}})}upload(e,t,n){return Kt(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,n)})}uploadToSignedUrl(e,t,n,s){return Kt(this,void 0,void 0,function*(){let a=this._removeEmptyFolders(e),c=this._getFinalPath(a),h=new URL(this.url+`/object/upload/sign/${c}`);h.searchParams.set("token",t);try{let f,m=Object.assign({upsert:PE.upsert},s),_=Object.assign(Object.assign({},this.headers),{"x-upsert":String(m.upsert)});typeof Blob!="undefined"&&n instanceof Blob?(f=new FormData,f.append("cacheControl",m.cacheControl),f.append("",n)):typeof FormData!="undefined"&&n instanceof FormData?(f=n,f.append("cacheControl",m.cacheControl)):(f=n,_["cache-control"]=`max-age=${m.cacheControl}`,_["content-type"]=m.contentType);let E=yield this.fetch(h.toString(),{method:"PUT",body:f,headers:_}),I=yield E.json();return E.ok?{data:{path:a,fullPath:I.Key},error:null}:{data:null,error:I}}catch(f){if(at(f))return{data:null,error:f};throw f}})}createSignedUploadUrl(e,t){return Kt(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 a=yield en(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:s}),c=new URL(this.url+a.url),h=c.searchParams.get("token");if(!h)throw new oa("No token returned by API");return{data:{signedUrl:c.toString(),path:e,token:h},error:null}}catch(n){if(at(n))return{data:null,error:n};throw n}})}update(e,t,n){return Kt(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,n)})}move(e,t,n){return Kt(this,void 0,void 0,function*(){try{return{data:yield en(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(at(s))return{data:null,error:s};throw s}})}copy(e,t,n){return Kt(this,void 0,void 0,function*(){try{return{data:{path:(yield en(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(at(s))return{data:null,error:s};throw s}})}createSignedUrl(e,t,n){return Kt(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),a=yield en(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},n!=null&&n.transform?{transform:n.transform}:{}),{headers:this.headers}),c=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return a={signedUrl:encodeURI(`${this.url}${a.signedURL}${c}`)},{data:a,error:null}}catch(s){if(at(s))return{data:null,error:s};throw s}})}createSignedUrls(e,t,n){return Kt(this,void 0,void 0,function*(){try{let s=yield en(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),a=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return{data:s.map(c=>Object.assign(Object.assign({},c),{signedUrl:c.signedURL?encodeURI(`${this.url}${c.signedURL}${a}`):null})),error:null}}catch(s){if(at(s))return{data:null,error:s};throw s}})}download(e,t){return Kt(this,void 0,void 0,function*(){let s=typeof(t==null?void 0:t.transform)!="undefined"?"render/image/authenticated":"object",a=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),c=a?`?${a}`:"";try{let h=this._getFinalPath(e);return{data:yield(yield aa(this.fetch,`${this.url}/${s}/${h}${c}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(h){if(at(h))return{data:null,error:h};throw h}})}info(e){return Kt(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{let n=yield aa(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:cf(n),error:null}}catch(n){if(at(n))return{data:null,error:n};throw n}})}exists(e){return Kt(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{return yield RE(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(at(n)&&n instanceof ws){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=[],a=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";a!==""&&s.push(a);let h=typeof(t==null?void 0:t.transform)!="undefined"?"render/image":"object",f=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});f!==""&&s.push(f);let m=s.join("&");return m!==""&&(m=`?${m}`),{data:{publicUrl:encodeURI(`${this.url}/${h}/public/${n}${m}`)}}}remove(e){return Kt(this,void 0,void 0,function*(){try{return{data:yield hf(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(at(t))return{data:null,error:t};throw t}})}list(e,t,n){return Kt(this,void 0,void 0,function*(){try{let s=Object.assign(Object.assign(Object.assign({},lU),t),{prefix:e||""});return{data:yield en(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},n),error:null}}catch(s){if(at(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 CE="2.7.1";var DE={"X-Client-Info":`storage-js/${CE}`};var ua=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function h(_){try{m(n.next(_))}catch(E){c(E)}}function f(_){try{m(n.throw(_))}catch(E){c(E)}}function m(_){_.done?a(_.value):s(_.value).then(h,f)}m((n=n.apply(r,e||[])).next())})},zu=class{constructor(e,t={},n){this.url=e,this.headers=Object.assign(Object.assign({},DE),t),this.fetch=lf(n)}listBuckets(){return ua(this,void 0,void 0,function*(){try{return{data:yield aa(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(at(e))return{data:null,error:e};throw e}})}getBucket(e){return ua(this,void 0,void 0,function*(){try{return{data:yield aa(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(at(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return ua(this,void 0,void 0,function*(){try{return{data:yield en(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(at(n))return{data:null,error:n};throw n}})}updateBucket(e,t){return ua(this,void 0,void 0,function*(){try{return{data:yield SE(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(at(n))return{data:null,error:n};throw n}})}emptyBucket(e){return ua(this,void 0,void 0,function*(){try{return{data:yield en(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(at(t))return{data:null,error:t};throw t}})}deleteBucket(e){return ua(this,void 0,void 0,function*(){try{return{data:yield hf(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(at(t))return{data:null,error:t};throw t}})}};var Gu=class extends zu{constructor(e,t={},n){super(e,t,n)}from(e){return new qu(this.url,this.headers,e,this.fetch)}};var OE="2.48.1";var Ku="";typeof Deno!="undefined"?Ku="deno":typeof document!="undefined"?Ku="web":typeof navigator!="undefined"&&navigator.product==="ReactNative"?Ku="react-native":Ku="node";var hU={"X-Client-Info":`supabase-js-${Ku}/${OE}`},kE={headers:hU},NE={schema:"public"},VE={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},LE={};Ei();var fU=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function h(_){try{m(n.next(_))}catch(E){c(E)}}function f(_){try{m(n.throw(_))}catch(E){c(E)}}function m(_){_.done?a(_.value):s(_.value).then(h,f)}m((n=n.apply(r,e||[])).next())})},dU=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=Tg:e=fetch,(...t)=>e(...t)},pU=()=>typeof Headers=="undefined"?Eg:Headers,ME=(r,e,t)=>{let n=dU(t),s=pU();return(a,c)=>fU(void 0,void 0,void 0,function*(){var h;let f=(h=yield e())!==null&&h!==void 0?h:r,m=new s(c==null?void 0:c.headers);return m.has("apikey")||m.set("apikey",r),m.has("Authorization")||m.set("Authorization",`Bearer ${f}`),n(a,Object.assign(Object.assign({},c),{headers:m}))})};var mU=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function h(_){try{m(n.next(_))}catch(E){c(E)}}function f(_){try{m(n.throw(_))}catch(E){c(E)}}function m(_){_.done?a(_.value):s(_.value).then(h,f)}m((n=n.apply(r,e||[])).next())})};function FE(r){return r.replace(/\/$/,"")}function UE(r,e){let{db:t,auth:n,realtime:s,global:a}=r,{db:c,auth:h,realtime:f,global:m}=e,_={db:Object.assign(Object.assign({},c),t),auth:Object.assign(Object.assign({},h),n),realtime:Object.assign(Object.assign({},f),s),global:Object.assign(Object.assign({},m),a),accessToken:()=>mU(this,void 0,void 0,function*(){return""})};return r.accessToken?_.accessToken=r.accessToken:delete _.accessToken,_}var ff="2.67.3";var BE="http://localhost:9999",jE="supabase.auth.token";var $E={"X-Client-Info":`gotrue-js/${ff}`},$g=10;var Wu="X-Supabase-Api-Version",qg={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function qE(r){return Math.round(Date.now()/1e3)+r}function zE(){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 Rr=()=>typeof window!="undefined"&&typeof document!="undefined",Ts={tested:!1,writable:!1},xi=()=>{if(!Rr())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Ts.tested)return Ts.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Ts.tested=!0,Ts.writable=!0}catch{Ts.tested=!0,Ts.writable=!1}return Ts.writable};function GE(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,a)=>{e[a]=s})}catch{}return t.searchParams.forEach((n,s)=>{e[s]=n}),e}var df=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(Ei(),gs)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},KE=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",zg=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},Qu=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Ju=async(r,e)=>{await r.removeItem(e)};function gU(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",n,s,a,c,h,f,m,_=0;for(r=r.replace("-","+").replace("_","/");_<r.length;)c=e.indexOf(r.charAt(_++)),h=e.indexOf(r.charAt(_++)),f=e.indexOf(r.charAt(_++)),m=e.indexOf(r.charAt(_++)),n=c<<2|h>>4,s=(h&15)<<4|f>>2,a=(f&3)<<6|m,t=t+String.fromCharCode(n),f!=64&&s!=0&&(t=t+String.fromCharCode(s)),m!=64&&a!=0&&(t=t+String.fromCharCode(a));return t}var Hu=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Hu.promiseConstructor=Promise;function Gg(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(gU(n))}async function WE(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function HE(r,e){return new Promise((n,s)=>{(async()=>{for(let a=0;a<1/0;a++)try{let c=await r(a);if(!e(a,null,c)){n(c);return}}catch(c){if(!e(a,c)){s(c);return}}})()})}function _U(r){return("0"+r.toString(16)).substr(-2)}function yU(){let e=new Uint32Array(56);if(typeof crypto=="undefined"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=t.length,s="";for(let a=0;a<56;a++)s+=t.charAt(Math.floor(Math.random()*n));return s}return crypto.getRandomValues(e),Array.from(e,_U).join("")}async function vU(r){let t=new TextEncoder().encode(r),n=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(n);return Array.from(s).map(a=>String.fromCharCode(a)).join("")}function wU(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function bU(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 vU(r);return wU(t)}async function Es(r,e,t=!1){let n=yU(),s=n;t&&(s+="/PASSWORD_RECOVERY"),await zg(r,`${e}-code-verifier`,s);let a=await bU(n);return[a,n===a?"plain":"s256"]}var TU=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function QE(r){let e=r.headers.get(Wu);if(!e||!e.match(TU))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Yu=class extends Error{constructor(e,t,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=n}};function ge(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var pf=class extends Yu{constructor(e,t,n){super(e,t,n),this.name="AuthApiError",this.status=t,this.code=n}};function JE(r){return ge(r)&&r.name==="AuthApiError"}var ca=class extends Yu{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},Nn=class extends Yu{constructor(e,t,n,s){super(e,n,s),this.name=t,this.status=n}},fr=class extends Nn{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function YE(r){return ge(r)&&r.name==="AuthSessionMissingError"}var la=class extends Nn{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Is=class extends Nn{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},xs=class extends Nn{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 XE(r){return ge(r)&&r.name==="AuthImplicitGrantRedirectError"}var Xu=class extends Nn{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}}},ha=class extends Nn{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function mf(r){return ge(r)&&r.name==="AuthRetryableFetchError"}var Zu=class extends Nn{constructor(e,t,n){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=n}};var EU=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},As=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),IU=[502,503,504];async function ZE(r){var e;if(!KE(r))throw new ha(As(r),0);if(IU.includes(r.status))throw new ha(As(r),r.status);let t;try{t=await r.json()}catch(a){throw new ca(As(a),a)}let n,s=QE(r);if(s&&s.getTime()>=qg["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 Zu(As(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new fr}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((a,c)=>a&&typeof c=="string",!0))throw new Zu(As(t),r.status,t.weak_password.reasons);throw new pf(As(t),r.status||500,n)}var xU=(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 Ee(r,e,t,n){var s;let a=Object.assign({},n==null?void 0:n.headers);a[Wu]||(a[Wu]=qg["2024-01-01"].name),n!=null&&n.jwt&&(a.Authorization=`Bearer ${n.jwt}`);let c=(s=n==null?void 0:n.query)!==null&&s!==void 0?s:{};n!=null&&n.redirectTo&&(c.redirect_to=n.redirectTo);let h=Object.keys(c).length?"?"+new URLSearchParams(c).toString():"",f=await AU(r,e,t+h,{headers:a,noResolveJson:n==null?void 0:n.noResolveJson},{},n==null?void 0:n.body);return n!=null&&n.xform?n==null?void 0:n.xform(f):{data:Object.assign({},f),error:null}}async function AU(r,e,t,n,s,a){let c=xU(e,n,s,a),h;try{h=await r(t,Object.assign({},c))}catch(f){throw console.error(f),new ha(As(f),0)}if(h.ok||await ZE(h),n!=null&&n.noResolveJson)return h;try{return await h.json()}catch(f){await ZE(f)}}function Vn(r){var e;let t=null;SU(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=qE(r.expires_in)));let n=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:n},error:null}}function Kg(r){let e=Vn(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 tn(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function eI(r){return{data:r,error:null}}function tI(r){let{action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:a}=r,c=EU(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),h={action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:a},f=Object.assign({},c);return{data:{properties:h,user:f},error:null}}function rI(r){return r}function SU(r){return r.access_token&&r.refresh_token&&r.expires_in}var RU=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},Ss=class{constructor({url:e="",headers:t={},fetch:n}){this.url=e,this.headers=t,this.fetch=df(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await Ee(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(ge(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,t={}){try{return await Ee(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:tn})}catch(n){if(ge(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:t}=e,n=RU(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 Ee(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:tI,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(ge(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await Ee(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:tn})}catch(t){if(ge(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,n,s,a,c,h,f;try{let m={nextPage:null,lastPage:0,total:0},_=await Ee(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:(a=(s=e==null?void 0:e.perPage)===null||s===void 0?void 0:s.toString())!==null&&a!==void 0?a:""},xform:rI});if(_.error)throw _.error;let E=await _.json(),I=(c=_.headers.get("x-total-count"))!==null&&c!==void 0?c:0,k=(f=(h=_.headers.get("link"))===null||h===void 0?void 0:h.split(","))!==null&&f!==void 0?f:[];return k.length>0&&(k.forEach(B=>{let G=parseInt(B.split(";")[0].split("=")[1].substring(0,1)),j=JSON.parse(B.split(";")[1].split("=")[1]);m[`${j}Page`]=G}),m.total=parseInt(I)),{data:Object.assign(Object.assign({},E),m),error:null}}catch(m){if(ge(m))return{data:{users:[]},error:m};throw m}}async getUserById(e){try{return await Ee(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:tn})}catch(t){if(ge(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await Ee(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:tn})}catch(n){if(ge(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,t=!1){try{return await Ee(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:tn})}catch(n){if(ge(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){try{let{data:t,error:n}=await Ee(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(ge(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await Ee(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}}};var nI={getItem:r=>xi()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{xi()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{xi()&&globalThis.localStorage.removeItem(r)}};function Wg(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function iI(){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 Rs={debug:!!(globalThis&&xi()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},ec=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},gf=class extends ec{};async function Hg(r,e,t){Rs.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),Rs.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){Rs.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,s.name);try{return await t()}finally{Rs.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,s.name)}}else{if(e===0)throw Rs.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new gf(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Rs.debug)try{let a=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(a,null," "))}catch(a){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",a)}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()}}))}iI();var PU={url:BE,storageKey:jE,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:$E,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},tc=30*1e3,sI=3;async function oI(r,e,t){return await t()}var Ps=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&&Rr()&&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({},PU),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 Ss({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=df(s.fetch),this.lock=s.lock||oI,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,s.lock?this.lock=s.lock:Rr()&&(!((t=globalThis==null?void 0:globalThis.navigator)===null||t===void 0)&&t.locks)?this.lock=Hg:this.lock=oI,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:xi()?this.storage=nI:(this.memoryStorage={},this.storage=Wg(this.memoryStorage)):(this.memoryStorage={},this.storage=Wg(this.memoryStorage)),Rr()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a),await this._notifyAllSubscribers(a.data.event,a.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${ff}) ${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=GE(window.location.href),n="none";if(this._isImplicitGrantCallback(t)?n="implicit":await this._isPKCECallback(t)&&(n="pkce"),Rr()&&this.detectSessionInUrl&&n!=="none"){let{data:s,error:a}=await this._getSessionFromURL(t,n);if(a){if(this._debug("#_initialize()","error detecting session from URL",a),XE(a)){let f=(e=a.details)===null||e===void 0?void 0:e.code;if(f==="identity_already_exists"||f==="identity_not_found"||f==="single_identity_not_deletable")return{error:a}}return await this._removeSession(),{error:a}}let{session:c,redirectType:h}=s;return this._debug("#_initialize()","detected session in URL",c,"redirect type",h),await this._saveSession(c),setTimeout(async()=>{h==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",c):await this._notifyAllSubscribers("SIGNED_IN",c)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return ge(t)?{error:t}:{error:new ca("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,n,s;try{let a=await Ee(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:Vn}),{data:c,error:h}=a;if(h||!c)return{data:{user:null,session:null},error:h};let f=c.session,m=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",f)),{data:{user:m,session:f},error:null}}catch(a){if(ge(a))return{data:{user:null,session:null},error:a};throw a}}async signUp(e){var t,n,s;try{let a;if("email"in e){let{email:_,password:E,options:I}=e,k=null,B=null;this.flowType==="pkce"&&([k,B]=await Es(this.storage,this.storageKey)),a=await Ee(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:I==null?void 0:I.emailRedirectTo,body:{email:_,password:E,data:(t=I==null?void 0:I.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:I==null?void 0:I.captchaToken},code_challenge:k,code_challenge_method:B},xform:Vn})}else if("phone"in e){let{phone:_,password:E,options:I}=e;a=await Ee(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:_,password:E,data:(n=I==null?void 0:I.data)!==null&&n!==void 0?n:{},channel:(s=I==null?void 0:I.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:I==null?void 0:I.captchaToken}},xform:Vn})}else throw new Is("You must provide either an email or phone number and a password");let{data:c,error:h}=a;if(h||!c)return{data:{user:null,session:null},error:h};let f=c.session,m=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",f)),{data:{user:m,session:f},error:null}}catch(a){if(ge(a))return{data:{user:null,session:null},error:a};throw a}}async signInWithPassword(e){try{let t;if("email"in e){let{email:a,password:c,options:h}=e;t=await Ee(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:a,password:c,gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken}},xform:Kg})}else if("phone"in e){let{phone:a,password:c,options:h}=e;t=await Ee(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:a,password:c,gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken}},xform:Kg})}else throw new Is("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 la}:(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(ge(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,n,s,a;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:(a=e.options)===null||a===void 0?void 0:a.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await Qu(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(t!=null?t:"").split("/");try{let{data:a,error:c}=await Ee(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Vn});if(await Ju(this.storage,`${this.storageKey}-code-verifier`),c)throw c;return!a||!a.session||!a.user?{data:{user:null,session:null,redirectType:null},error:new la}:(a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:Object.assign(Object.assign({},a),{redirectType:s!=null?s:null}),error:c})}catch(a){if(ge(a))return{data:{user:null,session:null,redirectType:null},error:a};throw a}}async signInWithIdToken(e){try{let{options:t,provider:n,token:s,access_token:a,nonce:c}=e,h=await Ee(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:s,access_token:a,nonce:c,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:Vn}),{data:f,error:m}=h;return m?{data:{user:null,session:null},error:m}:!f||!f.session||!f.user?{data:{user:null,session:null},error:new la}:(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("SIGNED_IN",f.session)),{data:f,error:m})}catch(t){if(ge(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,n,s,a,c;try{if("email"in e){let{email:h,options:f}=e,m=null,_=null;this.flowType==="pkce"&&([m,_]=await Es(this.storage,this.storageKey));let{error:E}=await Ee(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:h,data:(t=f==null?void 0:f.data)!==null&&t!==void 0?t:{},create_user:(n=f==null?void 0:f.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:m,code_challenge_method:_},redirectTo:f==null?void 0:f.emailRedirectTo});return{data:{user:null,session:null},error:E}}if("phone"in e){let{phone:h,options:f}=e,{data:m,error:_}=await Ee(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:h,data:(s=f==null?void 0:f.data)!==null&&s!==void 0?s:{},create_user:(a=f==null?void 0:f.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},channel:(c=f==null?void 0:f.channel)!==null&&c!==void 0?c:"sms"}});return{data:{user:null,session:null,messageId:m==null?void 0:m.message_id},error:_}}throw new Is("You must provide either an email or phone number.")}catch(h){if(ge(h))return{data:{user:null,session:null},error:h};throw h}}async verifyOtp(e){var t,n;try{let s,a;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,a=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:c,error:h}=await Ee(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:a}}),redirectTo:s,xform:Vn});if(h)throw h;if(!c)throw new Error("An error occurred on token verification.");let f=c.session,m=c.user;return f!=null&&f.access_token&&(await this._saveSession(f),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",f)),{data:{user:m,session:f},error:null}}catch(s){if(ge(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithSSO(e){var t,n,s;try{let a=null,c=null;return this.flowType==="pkce"&&([a,c]=await Es(this.storage,this.storageKey)),await Ee(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:a,code_challenge_method:c}),headers:this.headers,xform:eI})}catch(a){if(ge(a))return{data:null,error:a};throw a}}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 fr;let{error:s}=await Ee(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:s}})}catch(e){if(ge(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:a}=e,{error:c}=await Ee(this.fetch,"POST",t,{headers:this.headers,body:{email:n,type:s,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},redirectTo:a==null?void 0:a.emailRedirectTo});return{data:{user:null,session:null},error:c}}else if("phone"in e){let{phone:n,type:s,options:a}=e,{data:c,error:h}=await Ee(this.fetch,"POST",t,{headers:this.headers,body:{phone:n,type:s,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}}});return{data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:h}}throw new Is("You must provide either an email or phone number and a type")}catch(t){if(ge(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 Qu(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 c=this.suppressGetSessionWarning;e=new Proxy(e,{get:(f,m,_)=>(!c&&m==="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."),c=!0,this.suppressGetSessionWarning=!0),Reflect.get(f,m,_))})}return{data:{session:e},error:null}}let{session:s,error:a}=await this._callRefreshToken(e.refresh_token);return a?{data:{session:null},error:a}:{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 Ee(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:tn}):await this._useSession(async t=>{var n,s,a;let{data:c,error:h}=t;if(h)throw h;return!(!((n=c.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new fr}:await Ee(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(a=(s=c.session)===null||s===void 0?void 0:s.access_token)!==null&&a!==void 0?a:void 0,xform:tn})})}catch(t){if(ge(t))return YE(t)&&(await this._removeSession(),await Ju(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:a}=n;if(a)throw a;if(!s.session)throw new fr;let c=s.session,h=null,f=null;this.flowType==="pkce"&&e.email!=null&&([h,f]=await Es(this.storage,this.storageKey));let{data:m,error:_}=await Ee(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:h,code_challenge_method:f}),jwt:c.access_token,xform:tn});if(_)throw _;return c.user=m.user,await this._saveSession(c),await this._notifyAllSubscribers("USER_UPDATED",c),{data:{user:c.user},error:null}})}catch(n){if(ge(n))return{data:{user:null},error:n};throw n}}_decodeJWT(e){return Gg(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 fr;let t=Date.now()/1e3,n=t,s=!0,a=null,c=Gg(e.access_token);if(c.exp&&(n=c.exp,s=n<=t),s){let{session:h,error:f}=await this._callRefreshToken(e.refresh_token);if(f)return{data:{user:null,session:null},error:f};if(!h)return{data:{user:null,session:null},error:null};a=h}else{let{data:h,error:f}=await this._getUser(e.access_token);if(f)throw f;a={access_token:e.access_token,refresh_token:e.refresh_token,user:h.user,token_type:"bearer",expires_in:n-t,expires_at:n},await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)}return{data:{user:a.user,session:a},error:null}}catch(t){if(ge(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:c,error:h}=t;if(h)throw h;e=(n=c.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new fr;let{session:s,error:a}=await this._callRefreshToken(e.refresh_token);return a?{data:{user:null,session:null},error:a}:s?{data:{user:s.user,session:s},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(ge(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!Rr())throw new xs("No browser detected.");if(e.error||e.error_description||e.error_code)throw new xs(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 Xu("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new xs("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 Xu("No code detected.");let{data:ee,error:re}=await this._exchangeCodeForSession(e.code);if(re)throw re;let le=new URL(window.location.href);return le.searchParams.delete("code"),window.history.replaceState(window.history.state,"",le.toString()),{data:{session:ee.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:s,access_token:a,refresh_token:c,expires_in:h,expires_at:f,token_type:m}=e;if(!a||!h||!c||!m)throw new xs("No session defined in URL");let _=Math.round(Date.now()/1e3),E=parseInt(h),I=_+E;f&&(I=parseInt(f));let k=I-_;k*1e3<=tc&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${k}s, should have been closer to ${E}s`);let B=I-E;_-B>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",B,I,_):_-B<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",B,I,_);let{data:G,error:j}=await this._getUser(a);if(j)throw j;let J={provider_token:n,provider_refresh_token:s,access_token:a,expires_in:E,expires_at:I,refresh_token:c,token_type:m,user:G.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:J,redirectType:e.type},error:null}}catch(n){if(ge(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 Qu(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:a}=t;if(a)return{error:a};let c=(n=s.session)===null||n===void 0?void 0:n.access_token;if(c){let{error:h}=await this.admin.signOut(c,e);if(h&&!(JE(h)&&(h.status===404||h.status===401||h.status===403)))return{error:h}}return e!=="others"&&(await this._removeSession(),await Ju(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){let t=zE(),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:a},error:c}=t;if(c)throw c;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",a)),this._debug("INITIAL_SESSION","callback id",e,"session",a)}catch(a){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",a),console.error(a)}})}async resetPasswordForEmail(e,t={}){let n=null,s=null;this.flowType==="pkce"&&([n,s]=await Es(this.storage,this.storageKey,!0));try{return await Ee(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(a){if(ge(a))return{data:null,error:a};throw a}}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(ge(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:n,error:s}=await this._useSession(async a=>{var c,h,f,m,_;let{data:E,error:I}=a;if(I)throw I;let k=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(c=e.options)===null||c===void 0?void 0:c.redirectTo,scopes:(h=e.options)===null||h===void 0?void 0:h.scopes,queryParams:(f=e.options)===null||f===void 0?void 0:f.queryParams,skipBrowserRedirect:!0});return await Ee(this.fetch,"GET",k,{headers:this.headers,jwt:(_=(m=E.session)===null||m===void 0?void 0:m.access_token)!==null&&_!==void 0?_:void 0})});if(s)throw s;return Rr()&&!(!((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(ge(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:a,error:c}=t;if(c)throw c;return await Ee(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(n=a.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(ge(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 HE(async s=>(s>0&&await WE(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await Ee(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Vn})),(s,a)=>{let c=200*Math.pow(2,s);return a&&mf(a)&&Date.now()+c-n<tc})}catch(n){if(this._debug(t,"error",n),ge(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),Rr()&&!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 Qu(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),a=((e=n.expires_at)!==null&&e!==void 0?e:1/0)<s+$g;if(this._debug(t,`session has${a?"":" not"} expired with margin of ${$g}s`),a){if(this.autoRefreshToken&&n.refresh_token){let{error:c}=await this._callRefreshToken(n.refresh_token);c&&(console.error(c),mf(c)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",c),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 fr;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new Hu;let{data:a,error:c}=await this._refreshAccessToken(e);if(c)throw c;if(!a.session)throw new fr;await this._saveSession(a.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);let h={session:a.session,error:null};return this.refreshingDeferred.resolve(h),h}catch(a){if(this._debug(s,"error",a),ge(a)){let c={session:null,error:a};return mf(a)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(c),c}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(a),a}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 a=[],c=Array.from(this.stateChangeEmitters.values()).map(async h=>{try{await h.callback(e,t)}catch(f){a.push(f)}});if(await Promise.all(c),a.length>0){for(let h=0;h<a.length;h+=1)console.error(a[h]);throw a[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await zg(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Ju(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Rr()&&(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(),tc);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)/tc);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${tc}ms, refresh threshold is ${sI} ticks`),s<=sI&&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 ec)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Rr()||!(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[a,c]=await Es(this.storage,this.storageKey),h=new URLSearchParams({code_challenge:`${encodeURIComponent(a)}`,code_challenge_method:`${encodeURIComponent(c)}`});s.push(h.toString())}if(n!=null&&n.queryParams){let a=new URLSearchParams(n.queryParams);s.push(a.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:a}=t;return a?{data:null,error:a}:await Ee(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(ge(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var n,s;let{data:a,error:c}=t;if(c)return{data:null,error:c};let h=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:f,error:m}=await Ee(this.fetch,"POST",`${this.url}/factors`,{body:h,headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token});return m?{data:null,error:m}:(e.factorType==="totp"&&(!((s=f==null?void 0:f.totp)===null||s===void 0)&&s.qr_code)&&(f.totp.qr_code=`data:image/svg+xml;utf-8,${f.totp.qr_code}`),{data:f,error:null})})}catch(t){if(ge(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:a}=t;if(a)return{data:null,error:a};let{data:c,error:h}=await Ee(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 h?{data:null,error:h}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),{data:c,error:h})})}catch(t){if(ge(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:a}=t;return a?{data:null,error:a}:await Ee(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(ge(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(c=>c.factor_type==="totp"&&c.status==="verified"),a=n.filter(c=>c.factor_type==="phone"&&c.status==="verified");return{data:{all:n,totp:s,phone:a},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,n;let{data:{session:s},error:a}=e;if(a)return{data:null,error:a};if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let c=this._decodeJWT(s.access_token),h=null;c.aal&&(h=c.aal);let f=h;((n=(t=s.user.factors)===null||t===void 0?void 0:t.filter(E=>E.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(f="aal2");let _=c.amr||[];return{data:{currentLevel:h,nextLevel:f,currentAuthenticationMethods:_},error:null}}))}};Ps.nextInstanceID=0;var CU=Ps,Qg=CU;var _f=class extends Qg{constructor(e){super(e)}};var DU=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function h(_){try{m(n.next(_))}catch(E){c(E)}}function f(_){try{m(n.throw(_))}catch(E){c(E)}}function m(_){_.done?a(_.value):s(_.value).then(h,f)}m((n=n.apply(r,e||[])).next())})},rc=class{constructor(e,t,n){var s,a,c;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let h=FE(e);this.realtimeUrl=`${h}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${h}/auth/v1`,this.storageUrl=`${h}/storage/v1`,this.functionsUrl=`${h}/functions/v1`;let f=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,m={db:NE,realtime:LE,auth:Object.assign(Object.assign({},VE),{storageKey:f}),global:kE},_=UE(n!=null?n:{},m);this.storageKey=(s=_.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(a=_.global.headers)!==null&&a!==void 0?a:{},_.accessToken?(this.accessToken=_.accessToken,this.auth=new Proxy({},{get:(E,I)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(I)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((c=_.auth)!==null&&c!==void 0?c:{},this.headers,_.global.fetch),this.fetch=ME(t,this._getAccessToken.bind(this),_.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},_.realtime)),this.rest=new yE(`${h}/rest/v1`,{headers:this.headers,schema:_.db.schema,fetch:this.fetch}),_.accessToken||this._listenForAuthEvents()}get functions(){return new Nu(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Gu(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 DU(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:a,flowType:c,lock:h,debug:f},m,_){let E={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new _f({url:this.authUrl,headers:Object.assign(Object.assign({},E),m),storageKey:a,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:s,flowType:c,lock:h,debug:f,fetch:_,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new sa(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 aI=(r,e,t)=>new rc(r,e,t);var vI=Dd(hI(),1);var fI={id:"~date",test:r=>r instanceof Date,serialize:r=>({_:"~date",v:r.toISOString()}),deserialize:r=>new Date(r.v)};var dI={id:"~function",test:r=>typeof r=="function",serialize:r=>({_:"~function",v:r.toString()}),deserialize:v=>eval(v.v.toString())};var pI={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 mI={id:"~nan",test:r=>Number.isNaN(r),serialize:r=>({_:"~nan"}),deserialize:r=>NaN};var gI={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 _I={id:"~set",test:r=>r instanceof Set,serialize:r=>({_:"~set",v:Array.from(r)}),deserialize:r=>new Set(r.v)};var yI={id:"~undefined",test:r=>r===void 0,serialize:r=>({_:"~undefined"}),deserialize:r=>{}};var da={settings:{stringify:!0,destringify:!0,clone:!1,depth:0,modules:[fI,dI,pI,mI,gI,_I,yI],circular:!0,symetric:!1},loadedModules:{},loadModules(r){return r.map(e=>{if(De(e)){if(!e.id)throw new Error("Provided custom module does not expose an `id` property");return da.loadedModules[e.id]=e}else throw new Error("Unknown module type")})},serialize(r,e){let t=zl(e,da.settings),n=da.loadModules(t.modules),s=t.symetric?(0,vI.keyArrangeDeep)(r):t.clone?qr(r):r,a=new Map,c=(h,f)=>{let m=De(h);if(m&&t.circular){let I=a.get(h);if(I)return pi(s,f,{_:"~circular",p:I.join(".")});a.set(h,f)}let _=n.find(I=>I.test(h)),E=(!t.depth||f.length<t.depth)&&m;if(_){let I=_.serialize(h);if(_.recursive&&E){let k=At(h);t.symetric&&k.sort(),pi(s,f,I),k.forEach(B=>c(h[B],f.concat(B)))}else f.length?pi(s,f,I):s=I}else if(E){let I=At(h);t.symetric&&I.sort(),I.forEach(k=>c(h[k],f.concat(k)))}};return c(s,[]),t.stringify?JSON.stringify(s):s},deserialize(r,e){let t=zl(e,da.settings),n=da.loadModules(t.modules),s=Bd(n,"id"),a=t.destringify?JSON.parse(r):t.clone?qr(r):r,c=(h,f)=>{if(De(h)&&h._&&typeof h._=="string"&&h._.startsWith("~")&&s[h._]){let m=s[h._].deserialize(h);f.length?s[h._].recursive&&De(m)?(pi(a,f,m),At(m).forEach(_=>c(h[_],[...f,_]))):pi(a,f,m):a=m}else t.circular&&De(h)&&h._&&h._=="~circular"?pi(a,f,ru(a,h.p)):(!t.depth||f.length<t.depth)&&De(h)&&At(h).forEach(m=>c(h[m],f.concat(m)))};return c(a,[]),a}},ic=da;var wI="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var bI=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=wI[t[r]&63];return e};var $e=class $e{constructor(e,t){gt(this,"path");gt(this,"docRef");gt(this,"value");gt(this,"throttle",250);gt(this,"heartbeatInterval",3e4);gt(this,"_destroyActions",[]);gt(this,"_heartbeatTimer");this.path=e,Object.assign(this,t),$e.session||($e.session=`syncro_${bI()}`)}debug(...e){}destroy(){return this.debug("Destroy!"),Promise.all(this._destroyActions.map(e=>e())).then(()=>this._destroyActions=[])}getReactive(e){console.warn("Syncro.getReactive has not been subclassed, assuming a POJO response");let t={...e};return{doc:t,setState(n){Object.entries(n||{}).forEach(([s,a])=>t[s]=a)},getState(){return qr(t)},watch(n){}}}static pathSplit(e){var n;let t={...(n=/^(?<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+?))?$/.exec(e))==null?void 0:n.groups};if(!t)throw new Error(`Invalid session path syntax "${e}"`);if(!(t.entity in Yg))throw new Error(`Unsupported entity "${e}" -> Entity="${t.entity}"`);return{...t,fsCollection:t.entity,fsId:t.relation?`${t.id}::${t.relation}`:t.id}}static toFirestore(e={}){return ic.serialize(e,{circular:!1,clone:!0,modules:[TI,...ic.settings.modules],stringify:!1})}static fromFirestore(e={}){return ic.deserialize(e,{circular:!1,clone:!0,modules:[TI,...ic.settings.modules],destringify:!1})}static fromFirestoreFields(e={}){let t={};for(let n in e){let s=e[n];if(["stringValue","booleanValue","doubleValue","integerValue","timestampValue","mapValue","arrayValue"].find(c=>c===n)){if(["stringValue","booleanValue","doubleValue","integerValue","timestampValue"].find(h=>h===n))return s;if(n=="mapValue")return $e.fromFirestoreFields(s.fields||{});if(n=="arrayValue"){let h=s.values;return h?h.map(f=>$e.fromFirestoreFields(f)):[]}}else t[n]=$e.fromFirestoreFields(s)}return t}static getSnapshot(e){let{fsCollection:t,fsId:n}=$e.pathSplit(e);return Promise.resolve().then(async()=>{let s=Ou($e.firestore,t,n);return Jh(s)}).then(s=>s?$e.fromFirestore(snapshot.data()):null)}static setSnapshot(e,t,n){let s={method:"merge",...n},{fsCollection:a,fsId:c}=$e.pathSplit(e);return Promise.resolve().then(()=>(s.method=="merge"?"FirestoreUpdateDoc":"FirestoreSetDoc")(Ou($e.firestore,a,c),$e.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(){let{fsCollection:e,fsId:t,entity:n,id:s,relation:a}=$e.pathSplit(this.path),c,h;return Promise.resolve().then(()=>this.setHeartbeat(!1)).then(async()=>{this.docRef=Ou($e.firestore,e,t);let f=$e.fromFirestore((await Jh(this.docRef)).data());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(tE(this.docRef,m=>{let _=$e.fromFirestore(m.data());this.debug("Incoming snapshot",{snapshotData:_}),c.setState(_)}))}).then(()=>{if(Fd(h))return this.debug("Populate initial state"),Promise.resolve().then(()=>Yg[n]||Promise.reject(`Unknown Sync entity "${n}"`)).then(()=>Yg[n].initState({supabase:$e.supabase,fsCollection:e,fsId:t,entity:n,id:s,relation:a})).then(f=>bg(this.docRef,$e.toFirestore(f)))}).then(()=>{c.watch(jd(f=>{this.debug("Local change",{newState:f}),eE(this.docRef,$e.toFirestore(f))},this.throttle))}).then(()=>this.setHeartbeat(!0,{immediate:!0})).then(()=>this)}setHeartbeat(e=!0,t){let n={immediate:!0,...t};clearTimeout(this._heartbeatTimer),e&&(this._heartbeatTimer=setTimeout(async()=>{await this.heartbeat(),e&&this.setHeartbeat(!0)},this.heartbeatInterval),n.immediate&&this.heartbeat())}async heartbeat(){this.debug("heartbeat!");let e=new Date().toISOString(),t=Ou($e.firestore,"presence",this.path),n=await Jh(t);await bg(t,{latest:e,...!n.exists()&&{created:e,lastFlush:null},sessions:{[$e.session]:e}},{merge:!0})}flush(e){let t={destroy:!1,...e};return fetch(`https://tera-tools.com/api/sync/${this.path}/flush`+(t.destroy?"?destroy=1":""),{method:"post"}).then(n=>n.ok?null:Promise.reject(n.statusText||"An error occured"))}};gt($e,"firebase"),gt($e,"firestore"),gt($e,"supabase"),gt($e,"session");var Tt=$e;var Yg={projects:{singular:"project",initState({supabase:r,id:e}){return Tt.wrapSupabase(r.from("projects").select("data").limit(1).eq("id",e)).then(t=>t.length==1?t[0]:Promise.reject(`Syncro project "${e}" not found`)).then(t=>t.data)},flushState({supabase:r,state:e,fsId:t}){return Tt.wrapSupabase(r.rpc("syncro_merge_data",{table_name:"projects",entity_id:t,new_data:e}))}},project_namespaces:{singular:"project namespace",initState({supabase:r,id:e,relation:t}){if(!t)throw new Error('Project namespace relation missing, path should resemble "project_namespaces::${PROJECT}::${RELATION}"');return Tt.wrapSupabase(r.from("project_namespaces").select("data").limit(1).eq("project",e).eq("name",t)).then(n=>n.length==1?n[0]:Tt.wrapSupabase(r.from("project_namespaces").insert({project:e,name:t,data:{}}).select("data"))).then(n=>n.data)},flushState({supabase:r,state:e,id:t,relation:n}){return Tt.wrapSupabase(r.from("project_namespaces").update({edited_at:new Date,data:e}).eq("project",t).eq("name",n))}},test:{singular:"test",initState({supabase:r,id:e}){return Tt.wrapSupabase(r.from("test").select("data").limit(1).eq("id",e)).then(t=>t.length==1?t[0]:Promise.reject(`Syncro test item "${e}" not found`)).then(t=>t.data)},flushState({supabase:r,state:e,fsId:t}){return Tt.wrapSupabase(r.rpc("syncro_merge_data",{table_name:"test",entity_id:t,new_data:e}))}},users:{singular:"user",initState({supabase:r,id:e}){return Tt.wrapSupabase(r.from("users").select("data").limit(1).eq("id",e)).then(t=>t.length==1?t[0]:Promise.reject(`Syncro user "${e}" not found`)).then(t=>t.data)},flushState({supabase:r,state:e,fsId:t}){return Tt.wrapSupabase(r.rpc("syncro_merge_data",{table_name:"users",entity_id:t,new_data:e}))}}},TI={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 sc=class{init(){}constructor(e,t){}};var oc=class extends sc{constructor(){super(...arguments);gt(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(a=>a===null);if(s.length>0)throw new Error("Firebase plugin requires mandatory options: "+s.join(", "));Tt.firebase=op({apiKey:n.firebaseApiKey,authDomain:n.firebaseAuthDomain,projectId:n.firebaseProjectId,appId:n.firebaseAppId}),Tt.firestore=WT(this.firebase),Tt.supabase=aI(n.supabaseUrl,n.supabaseKey)}_mountNamespace(t){let n;return Promise.resolve().then(()=>this.requireProject()).then(s=>{let a=t=="_PROJECT"?`projects::${s.id}`:`project_namespaces::${s.id}::${t}`;return n=this.syncros[t]=new Tt(a,{debug:(...c)=>this.debug(`SYNCRO://${a}`,...c),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 Xg=class extends oc{constructor(){super(...arguments);gt(this,"Vue");gt(this,"project",null);gt(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(a){Object.entries(a||{}).filter(([c])=>!Ud(n[c],a[c])).forEach(([c,h])=>n[c]=h)},getState(){return qr(n)},watch:a=>{this.app.$watch(s,a,{deep:!0})}}}bindProjectState(t){let n={component:null,componentKey:null,autoRequire:!0,read:!0,write:!0,throttle:{wait:200,maxWait:2e3,leading:!1,trailing:!0},...t};return Promise.resolve().then(()=>Promise.all([this.getProjectState({autoRequire:n.autoRequire}),(()=>{if(!n.componentKey){for(let s=0;s<50;s++){let a=`terafy_${s}`;if(!Object.hasOwnProperty(n.component,a)){n.componentKey=a;return}}throw new Error("Unable to find unique key to allocate against Vue2 component")}})()])).then(([s])=>{this.debug("INFO",2,"Got project snapshot",s);let a=this.Vue.observable(s);if(n.component[n.componentKey]=a,n.read&&this.events.on(`update:projects/${a.id}`,c=>{var h;(h=c==null?void 0:c.lastPatch)!=null&&h.session&&c.lastPatch.session==this.settings.session||(this.debug("INFO",5,"Update Vue2 Remote->Local",{new:c,old:a}),this.merge(a,c))}),n.write){if(!n.component)throw new Error("bindProjectState requires a VueComponent specified as `component`");let c=qr(s),h=()=>{let f=qr(s);this.debug("INFO",5,"Update Vue2 Local->Remote",{new:f,old:c}),this.createProjectStatePatch(f,c),c=f};n.component.$watch(n.componentKey,n.throttle?debounce(h,n.throttle.wait,n.throttle):h,{deep:!0})}return a})}merge(t,...n){return n.forEach(s=>Object.keys(s).forEach(a=>{isPlainObject(s[a])?(a in t||this.Vue.set(t,a,{}),this.merge(t[a],s[a])):this.Vue.set(t,a,s[a])})),t}};export{Xg as default};
|
|
46
|
+
});`,sa=class{constructor(e,t){var n;this.accessTokenValue=null,this.apiKey=null,this.channels=[],this.endPoint="",this.httpEndpoint="",this.headers=wE,this.params={},this.timeout=of,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=iU,this.conn=null,this.sendBuffer=[],this.serializer=new ju,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=a=>{let c;return a?c=a:typeof fetch=="undefined"?c=(...h)=>Promise.resolve().then(()=>(Ei(),gs)).then(({default:f})=>f(...h)):c=fetch,(...h)=>c(...h)},this.endPoint=`${e}/${sf.websocket}`,this.httpEndpoint=af(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:a=>[1e3,2e3,5e3,1e4][a-1]||1e4,this.encode=t!=null&&t.encode?t.encode:(a,c)=>c(JSON.stringify(a)),this.decode=t!=null&&t.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new ys(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(sU){this.conn=new WebSocket(this.endpointURL()),this.setupConnection();return}this.conn=new Bg(this.endpointURL(),void 0,{close:()=>{this.conn=null}}),Promise.resolve().then(()=>Dd(xE())).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:bE}))}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 _s.connecting:return Ii.Connecting;case _s.open:return Ii.Open;case _s.closing:return Ii.Closing;default:return Ii.Closed}}isConnected(){return this.connectionState()===Ii.Open}channel(e,t={config:{}}){let n=new ia(`realtime:${e}`,t,this);return this.channels.push(n),n}push(e){let{topic:t,event:n,payload:s,ref:a}=e,c=()=>{this.encode(e,h=>{var f;(f=this.conn)===null||f===void 0||f.send(h)})};this.log("push",`${t} ${n} (${a})`,s),this.isConnected()?c():this.sendBuffer.push(c)}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(rr.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(TE,"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:a,ref:c}=t;c&&c===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${a.status||""} ${n} ${s} ${c&&"("+c+")"||""}`,a),this.channels.filter(h=>h._isMember(n)).forEach(h=>h._trigger(s,a,c)),this.stateChangeCallbacks.message.forEach(h=>h(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(rr.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([oU],{type:"application/javascript"});t=URL.createObjectURL(n)}return t}},Bg=class{constructor(e,t,n){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=_s.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=n.close}};var oa=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function at(r){return typeof r=="object"&&r!==null&&"__isStorageError"in r}var uf=class extends oa{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}},ws=class extends oa{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};var aU=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function h(_){try{m(n.next(_))}catch(E){c(E)}}function f(_){try{m(n.throw(_))}catch(E){c(E)}}function m(_){_.done?a(_.value):s(_.value).then(h,f)}m((n=n.apply(r,e||[])).next())})},lf=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(Ei(),gs)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},AE=()=>aU(void 0,void 0,void 0,function*(){return typeof Response=="undefined"?(yield Promise.resolve().then(()=>(Ei(),gs))).Response:Response}),cf=r=>{if(Array.isArray(r))return r.map(t=>cf(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,a=>a.toUpperCase().replace(/[-_]/g,""));e[s]=cf(n)}),e};var bs=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function h(_){try{m(n.next(_))}catch(E){c(E)}}function f(_){try{m(n.throw(_))}catch(E){c(E)}}function m(_){_.done?a(_.value):s(_.value).then(h,f)}m((n=n.apply(r,e||[])).next())})},jg=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),uU=(r,e,t)=>bs(void 0,void 0,void 0,function*(){let n=yield AE();r instanceof n&&!(t!=null&&t.noResolveJson)?r.json().then(s=>{e(new uf(jg(s),r.status||500))}).catch(s=>{e(new ws(jg(s),s))}):e(new ws(jg(r),r))}),cU=(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 $u(r,e,t,n,s,a){return bs(this,void 0,void 0,function*(){return new Promise((c,h)=>{r(t,cU(e,n,s,a)).then(f=>{if(!f.ok)throw f;return n!=null&&n.noResolveJson?f:f.json()}).then(f=>c(f)).catch(f=>uU(f,h,n))})})}function aa(r,e,t,n){return bs(this,void 0,void 0,function*(){return $u(r,"GET",e,t,n)})}function en(r,e,t,n,s){return bs(this,void 0,void 0,function*(){return $u(r,"POST",e,n,s,t)})}function SE(r,e,t,n,s){return bs(this,void 0,void 0,function*(){return $u(r,"PUT",e,n,s,t)})}function RE(r,e,t,n){return bs(this,void 0,void 0,function*(){return $u(r,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),n)})}function hf(r,e,t,n,s){return bs(this,void 0,void 0,function*(){return $u(r,"DELETE",e,n,s,t)})}var Kt=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function h(_){try{m(n.next(_))}catch(E){c(E)}}function f(_){try{m(n.throw(_))}catch(E){c(E)}}function m(_){_.done?a(_.value):s(_.value).then(h,f)}m((n=n.apply(r,e||[])).next())})},lU={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},PE={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},qu=class{constructor(e,t={},n,s){this.url=e,this.headers=t,this.bucketId=n,this.fetch=lf(s)}uploadOrUpdate(e,t,n,s){return Kt(this,void 0,void 0,function*(){try{let a,c=Object.assign(Object.assign({},PE),s),h=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(c.upsert)}),f=c.metadata;typeof Blob!="undefined"&&n instanceof Blob?(a=new FormData,a.append("cacheControl",c.cacheControl),f&&a.append("metadata",this.encodeMetadata(f)),a.append("",n)):typeof FormData!="undefined"&&n instanceof FormData?(a=n,a.append("cacheControl",c.cacheControl),f&&a.append("metadata",this.encodeMetadata(f))):(a=n,h["cache-control"]=`max-age=${c.cacheControl}`,h["content-type"]=c.contentType,f&&(h["x-metadata"]=this.toBase64(this.encodeMetadata(f)))),s!=null&&s.headers&&(h=Object.assign(Object.assign({},h),s.headers));let m=this._removeEmptyFolders(t),_=this._getFinalPath(m),E=yield this.fetch(`${this.url}/object/${_}`,Object.assign({method:e,body:a,headers:h},c!=null&&c.duplex?{duplex:c.duplex}:{})),I=yield E.json();return E.ok?{data:{path:m,id:I.Id,fullPath:I.Key},error:null}:{data:null,error:I}}catch(a){if(at(a))return{data:null,error:a};throw a}})}upload(e,t,n){return Kt(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,n)})}uploadToSignedUrl(e,t,n,s){return Kt(this,void 0,void 0,function*(){let a=this._removeEmptyFolders(e),c=this._getFinalPath(a),h=new URL(this.url+`/object/upload/sign/${c}`);h.searchParams.set("token",t);try{let f,m=Object.assign({upsert:PE.upsert},s),_=Object.assign(Object.assign({},this.headers),{"x-upsert":String(m.upsert)});typeof Blob!="undefined"&&n instanceof Blob?(f=new FormData,f.append("cacheControl",m.cacheControl),f.append("",n)):typeof FormData!="undefined"&&n instanceof FormData?(f=n,f.append("cacheControl",m.cacheControl)):(f=n,_["cache-control"]=`max-age=${m.cacheControl}`,_["content-type"]=m.contentType);let E=yield this.fetch(h.toString(),{method:"PUT",body:f,headers:_}),I=yield E.json();return E.ok?{data:{path:a,fullPath:I.Key},error:null}:{data:null,error:I}}catch(f){if(at(f))return{data:null,error:f};throw f}})}createSignedUploadUrl(e,t){return Kt(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 a=yield en(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:s}),c=new URL(this.url+a.url),h=c.searchParams.get("token");if(!h)throw new oa("No token returned by API");return{data:{signedUrl:c.toString(),path:e,token:h},error:null}}catch(n){if(at(n))return{data:null,error:n};throw n}})}update(e,t,n){return Kt(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,n)})}move(e,t,n){return Kt(this,void 0,void 0,function*(){try{return{data:yield en(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(at(s))return{data:null,error:s};throw s}})}copy(e,t,n){return Kt(this,void 0,void 0,function*(){try{return{data:{path:(yield en(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(at(s))return{data:null,error:s};throw s}})}createSignedUrl(e,t,n){return Kt(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),a=yield en(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},n!=null&&n.transform?{transform:n.transform}:{}),{headers:this.headers}),c=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return a={signedUrl:encodeURI(`${this.url}${a.signedURL}${c}`)},{data:a,error:null}}catch(s){if(at(s))return{data:null,error:s};throw s}})}createSignedUrls(e,t,n){return Kt(this,void 0,void 0,function*(){try{let s=yield en(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),a=n!=null&&n.download?`&download=${n.download===!0?"":n.download}`:"";return{data:s.map(c=>Object.assign(Object.assign({},c),{signedUrl:c.signedURL?encodeURI(`${this.url}${c.signedURL}${a}`):null})),error:null}}catch(s){if(at(s))return{data:null,error:s};throw s}})}download(e,t){return Kt(this,void 0,void 0,function*(){let s=typeof(t==null?void 0:t.transform)!="undefined"?"render/image/authenticated":"object",a=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),c=a?`?${a}`:"";try{let h=this._getFinalPath(e);return{data:yield(yield aa(this.fetch,`${this.url}/${s}/${h}${c}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(h){if(at(h))return{data:null,error:h};throw h}})}info(e){return Kt(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{let n=yield aa(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:cf(n),error:null}}catch(n){if(at(n))return{data:null,error:n};throw n}})}exists(e){return Kt(this,void 0,void 0,function*(){let t=this._getFinalPath(e);try{return yield RE(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(n){if(at(n)&&n instanceof ws){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=[],a=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";a!==""&&s.push(a);let h=typeof(t==null?void 0:t.transform)!="undefined"?"render/image":"object",f=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});f!==""&&s.push(f);let m=s.join("&");return m!==""&&(m=`?${m}`),{data:{publicUrl:encodeURI(`${this.url}/${h}/public/${n}${m}`)}}}remove(e){return Kt(this,void 0,void 0,function*(){try{return{data:yield hf(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(at(t))return{data:null,error:t};throw t}})}list(e,t,n){return Kt(this,void 0,void 0,function*(){try{let s=Object.assign(Object.assign(Object.assign({},lU),t),{prefix:e||""});return{data:yield en(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},n),error:null}}catch(s){if(at(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 CE="2.7.1";var DE={"X-Client-Info":`storage-js/${CE}`};var ua=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function h(_){try{m(n.next(_))}catch(E){c(E)}}function f(_){try{m(n.throw(_))}catch(E){c(E)}}function m(_){_.done?a(_.value):s(_.value).then(h,f)}m((n=n.apply(r,e||[])).next())})},zu=class{constructor(e,t={},n){this.url=e,this.headers=Object.assign(Object.assign({},DE),t),this.fetch=lf(n)}listBuckets(){return ua(this,void 0,void 0,function*(){try{return{data:yield aa(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(at(e))return{data:null,error:e};throw e}})}getBucket(e){return ua(this,void 0,void 0,function*(){try{return{data:yield aa(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(at(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return ua(this,void 0,void 0,function*(){try{return{data:yield en(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(at(n))return{data:null,error:n};throw n}})}updateBucket(e,t){return ua(this,void 0,void 0,function*(){try{return{data:yield SE(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(at(n))return{data:null,error:n};throw n}})}emptyBucket(e){return ua(this,void 0,void 0,function*(){try{return{data:yield en(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(at(t))return{data:null,error:t};throw t}})}deleteBucket(e){return ua(this,void 0,void 0,function*(){try{return{data:yield hf(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(at(t))return{data:null,error:t};throw t}})}};var Gu=class extends zu{constructor(e,t={},n){super(e,t,n)}from(e){return new qu(this.url,this.headers,e,this.fetch)}};var OE="2.48.1";var Ku="";typeof Deno!="undefined"?Ku="deno":typeof document!="undefined"?Ku="web":typeof navigator!="undefined"&&navigator.product==="ReactNative"?Ku="react-native":Ku="node";var hU={"X-Client-Info":`supabase-js-${Ku}/${OE}`},kE={headers:hU},NE={schema:"public"},VE={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},LE={};Ei();var fU=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function h(_){try{m(n.next(_))}catch(E){c(E)}}function f(_){try{m(n.throw(_))}catch(E){c(E)}}function m(_){_.done?a(_.value):s(_.value).then(h,f)}m((n=n.apply(r,e||[])).next())})},dU=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=Tg:e=fetch,(...t)=>e(...t)},pU=()=>typeof Headers=="undefined"?Eg:Headers,ME=(r,e,t)=>{let n=dU(t),s=pU();return(a,c)=>fU(void 0,void 0,void 0,function*(){var h;let f=(h=yield e())!==null&&h!==void 0?h:r,m=new s(c==null?void 0:c.headers);return m.has("apikey")||m.set("apikey",r),m.has("Authorization")||m.set("Authorization",`Bearer ${f}`),n(a,Object.assign(Object.assign({},c),{headers:m}))})};var mU=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function h(_){try{m(n.next(_))}catch(E){c(E)}}function f(_){try{m(n.throw(_))}catch(E){c(E)}}function m(_){_.done?a(_.value):s(_.value).then(h,f)}m((n=n.apply(r,e||[])).next())})};function FE(r){return r.replace(/\/$/,"")}function UE(r,e){let{db:t,auth:n,realtime:s,global:a}=r,{db:c,auth:h,realtime:f,global:m}=e,_={db:Object.assign(Object.assign({},c),t),auth:Object.assign(Object.assign({},h),n),realtime:Object.assign(Object.assign({},f),s),global:Object.assign(Object.assign({},m),a),accessToken:()=>mU(this,void 0,void 0,function*(){return""})};return r.accessToken?_.accessToken=r.accessToken:delete _.accessToken,_}var ff="2.67.3";var BE="http://localhost:9999",jE="supabase.auth.token";var $E={"X-Client-Info":`gotrue-js/${ff}`},$g=10;var Wu="X-Supabase-Api-Version",qg={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};function qE(r){return Math.round(Date.now()/1e3)+r}function zE(){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 Rr=()=>typeof window!="undefined"&&typeof document!="undefined",Ts={tested:!1,writable:!1},xi=()=>{if(!Rr())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Ts.tested)return Ts.writable;let r=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(r,r),globalThis.localStorage.removeItem(r),Ts.tested=!0,Ts.writable=!0}catch{Ts.tested=!0,Ts.writable=!1}return Ts.writable};function GE(r){let e={},t=new URL(r);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((s,a)=>{e[a]=s})}catch{}return t.searchParams.forEach((n,s)=>{e[s]=n}),e}var df=r=>{let e;return r?e=r:typeof fetch=="undefined"?e=(...t)=>Promise.resolve().then(()=>(Ei(),gs)).then(({default:n})=>n(...t)):e=fetch,(...t)=>e(...t)},KE=r=>typeof r=="object"&&r!==null&&"status"in r&&"ok"in r&&"json"in r&&typeof r.json=="function",zg=async(r,e,t)=>{await r.setItem(e,JSON.stringify(t))},Qu=async(r,e)=>{let t=await r.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Ju=async(r,e)=>{await r.removeItem(e)};function gU(r){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",n,s,a,c,h,f,m,_=0;for(r=r.replace("-","+").replace("_","/");_<r.length;)c=e.indexOf(r.charAt(_++)),h=e.indexOf(r.charAt(_++)),f=e.indexOf(r.charAt(_++)),m=e.indexOf(r.charAt(_++)),n=c<<2|h>>4,s=(h&15)<<4|f>>2,a=(f&3)<<6|m,t=t+String.fromCharCode(n),f!=64&&s!=0&&(t=t+String.fromCharCode(s)),m!=64&&a!=0&&(t=t+String.fromCharCode(a));return t}var Hu=class r{constructor(){this.promise=new r.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};Hu.promiseConstructor=Promise;function Gg(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(gU(n))}async function WE(r){return await new Promise(e=>{setTimeout(()=>e(null),r)})}function HE(r,e){return new Promise((n,s)=>{(async()=>{for(let a=0;a<1/0;a++)try{let c=await r(a);if(!e(a,null,c)){n(c);return}}catch(c){if(!e(a,c)){s(c);return}}})()})}function _U(r){return("0"+r.toString(16)).substr(-2)}function yU(){let e=new Uint32Array(56);if(typeof crypto=="undefined"){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=t.length,s="";for(let a=0;a<56;a++)s+=t.charAt(Math.floor(Math.random()*n));return s}return crypto.getRandomValues(e),Array.from(e,_U).join("")}async function vU(r){let t=new TextEncoder().encode(r),n=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(n);return Array.from(s).map(a=>String.fromCharCode(a)).join("")}function wU(r){return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function bU(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 vU(r);return wU(t)}async function Es(r,e,t=!1){let n=yU(),s=n;t&&(s+="/PASSWORD_RECOVERY"),await zg(r,`${e}-code-verifier`,s);let a=await bU(n);return[a,n===a?"plain":"s256"]}var TU=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function QE(r){let e=r.headers.get(Wu);if(!e||!e.match(TU))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}var Yu=class extends Error{constructor(e,t,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=n}};function ge(r){return typeof r=="object"&&r!==null&&"__isAuthError"in r}var pf=class extends Yu{constructor(e,t,n){super(e,t,n),this.name="AuthApiError",this.status=t,this.code=n}};function JE(r){return ge(r)&&r.name==="AuthApiError"}var ca=class extends Yu{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},Nn=class extends Yu{constructor(e,t,n,s){super(e,n,s),this.name=t,this.status=n}},fr=class extends Nn{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function YE(r){return ge(r)&&r.name==="AuthSessionMissingError"}var la=class extends Nn{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}},Is=class extends Nn{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},xs=class extends Nn{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 XE(r){return ge(r)&&r.name==="AuthImplicitGrantRedirectError"}var Xu=class extends Nn{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}}},ha=class extends Nn{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function mf(r){return ge(r)&&r.name==="AuthRetryableFetchError"}var Zu=class extends Nn{constructor(e,t,n){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=n}};var EU=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},As=r=>r.msg||r.message||r.error_description||r.error||JSON.stringify(r),IU=[502,503,504];async function ZE(r){var e;if(!KE(r))throw new ha(As(r),0);if(IU.includes(r.status))throw new ha(As(r),r.status);let t;try{t=await r.json()}catch(a){throw new ca(As(a),a)}let n,s=QE(r);if(s&&s.getTime()>=qg["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 Zu(As(t),r.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new fr}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((a,c)=>a&&typeof c=="string",!0))throw new Zu(As(t),r.status,t.weak_password.reasons);throw new pf(As(t),r.status||500,n)}var xU=(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 Ee(r,e,t,n){var s;let a=Object.assign({},n==null?void 0:n.headers);a[Wu]||(a[Wu]=qg["2024-01-01"].name),n!=null&&n.jwt&&(a.Authorization=`Bearer ${n.jwt}`);let c=(s=n==null?void 0:n.query)!==null&&s!==void 0?s:{};n!=null&&n.redirectTo&&(c.redirect_to=n.redirectTo);let h=Object.keys(c).length?"?"+new URLSearchParams(c).toString():"",f=await AU(r,e,t+h,{headers:a,noResolveJson:n==null?void 0:n.noResolveJson},{},n==null?void 0:n.body);return n!=null&&n.xform?n==null?void 0:n.xform(f):{data:Object.assign({},f),error:null}}async function AU(r,e,t,n,s,a){let c=xU(e,n,s,a),h;try{h=await r(t,Object.assign({},c))}catch(f){throw console.error(f),new ha(As(f),0)}if(h.ok||await ZE(h),n!=null&&n.noResolveJson)return h;try{return await h.json()}catch(f){await ZE(f)}}function Vn(r){var e;let t=null;SU(r)&&(t=Object.assign({},r),r.expires_at||(t.expires_at=qE(r.expires_in)));let n=(e=r.user)!==null&&e!==void 0?e:r;return{data:{session:t,user:n},error:null}}function Kg(r){let e=Vn(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 tn(r){var e;return{data:{user:(e=r.user)!==null&&e!==void 0?e:r},error:null}}function eI(r){return{data:r,error:null}}function tI(r){let{action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:a}=r,c=EU(r,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),h={action_link:e,email_otp:t,hashed_token:n,redirect_to:s,verification_type:a},f=Object.assign({},c);return{data:{properties:h,user:f},error:null}}function rI(r){return r}function SU(r){return r.access_token&&r.refresh_token&&r.expires_in}var RU=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},Ss=class{constructor({url:e="",headers:t={},fetch:n}){this.url=e,this.headers=t,this.fetch=df(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await Ee(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(ge(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,t={}){try{return await Ee(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:tn})}catch(n){if(ge(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:t}=e,n=RU(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 Ee(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:tI,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(ge(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await Ee(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:tn})}catch(t){if(ge(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,n,s,a,c,h,f;try{let m={nextPage:null,lastPage:0,total:0},_=await Ee(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:(a=(s=e==null?void 0:e.perPage)===null||s===void 0?void 0:s.toString())!==null&&a!==void 0?a:""},xform:rI});if(_.error)throw _.error;let E=await _.json(),I=(c=_.headers.get("x-total-count"))!==null&&c!==void 0?c:0,k=(f=(h=_.headers.get("link"))===null||h===void 0?void 0:h.split(","))!==null&&f!==void 0?f:[];return k.length>0&&(k.forEach(B=>{let G=parseInt(B.split(";")[0].split("=")[1].substring(0,1)),j=JSON.parse(B.split(";")[1].split("=")[1]);m[`${j}Page`]=G}),m.total=parseInt(I)),{data:Object.assign(Object.assign({},E),m),error:null}}catch(m){if(ge(m))return{data:{users:[]},error:m};throw m}}async getUserById(e){try{return await Ee(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:tn})}catch(t){if(ge(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await Ee(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:tn})}catch(n){if(ge(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,t=!1){try{return await Ee(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:tn})}catch(n){if(ge(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){try{let{data:t,error:n}=await Ee(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(ge(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await Ee(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(ge(t))return{data:null,error:t};throw t}}};var nI={getItem:r=>xi()?globalThis.localStorage.getItem(r):null,setItem:(r,e)=>{xi()&&globalThis.localStorage.setItem(r,e)},removeItem:r=>{xi()&&globalThis.localStorage.removeItem(r)}};function Wg(r={}){return{getItem:e=>r[e]||null,setItem:(e,t)=>{r[e]=t},removeItem:e=>{delete r[e]}}}function iI(){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 Rs={debug:!!(globalThis&&xi()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},ec=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}},gf=class extends ec{};async function Hg(r,e,t){Rs.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",r,e);let n=new globalThis.AbortController;return e>0&&setTimeout(()=>{n.abort(),Rs.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){Rs.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",r,s.name);try{return await t()}finally{Rs.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",r,s.name)}}else{if(e===0)throw Rs.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",r),new gf(`Acquiring an exclusive Navigator LockManager lock "${r}" immediately failed`);if(Rs.debug)try{let a=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(a,null," "))}catch(a){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",a)}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()}}))}iI();var PU={url:BE,storageKey:jE,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:$E,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1},tc=30*1e3,sI=3;async function oI(r,e,t){return await t()}var Ps=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&&Rr()&&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({},PU),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 Ss({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=df(s.fetch),this.lock=s.lock||oI,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,s.lock?this.lock=s.lock:Rr()&&(!((t=globalThis==null?void 0:globalThis.navigator)===null||t===void 0)&&t.locks)?this.lock=Hg:this.lock=oI,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:xi()?this.storage=nI:(this.memoryStorage={},this.storage=Wg(this.memoryStorage)):(this.memoryStorage={},this.storage=Wg(this.memoryStorage)),Rr()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a),await this._notifyAllSubscribers(a.data.event,a.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${ff}) ${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=GE(window.location.href),n="none";if(this._isImplicitGrantCallback(t)?n="implicit":await this._isPKCECallback(t)&&(n="pkce"),Rr()&&this.detectSessionInUrl&&n!=="none"){let{data:s,error:a}=await this._getSessionFromURL(t,n);if(a){if(this._debug("#_initialize()","error detecting session from URL",a),XE(a)){let f=(e=a.details)===null||e===void 0?void 0:e.code;if(f==="identity_already_exists"||f==="identity_not_found"||f==="single_identity_not_deletable")return{error:a}}return await this._removeSession(),{error:a}}let{session:c,redirectType:h}=s;return this._debug("#_initialize()","detected session in URL",c,"redirect type",h),await this._saveSession(c),setTimeout(async()=>{h==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",c):await this._notifyAllSubscribers("SIGNED_IN",c)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return ge(t)?{error:t}:{error:new ca("Unexpected error during initialization",t)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,n,s;try{let a=await Ee(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:Vn}),{data:c,error:h}=a;if(h||!c)return{data:{user:null,session:null},error:h};let f=c.session,m=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",f)),{data:{user:m,session:f},error:null}}catch(a){if(ge(a))return{data:{user:null,session:null},error:a};throw a}}async signUp(e){var t,n,s;try{let a;if("email"in e){let{email:_,password:E,options:I}=e,k=null,B=null;this.flowType==="pkce"&&([k,B]=await Es(this.storage,this.storageKey)),a=await Ee(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:I==null?void 0:I.emailRedirectTo,body:{email:_,password:E,data:(t=I==null?void 0:I.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:I==null?void 0:I.captchaToken},code_challenge:k,code_challenge_method:B},xform:Vn})}else if("phone"in e){let{phone:_,password:E,options:I}=e;a=await Ee(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:_,password:E,data:(n=I==null?void 0:I.data)!==null&&n!==void 0?n:{},channel:(s=I==null?void 0:I.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:I==null?void 0:I.captchaToken}},xform:Vn})}else throw new Is("You must provide either an email or phone number and a password");let{data:c,error:h}=a;if(h||!c)return{data:{user:null,session:null},error:h};let f=c.session,m=c.user;return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",f)),{data:{user:m,session:f},error:null}}catch(a){if(ge(a))return{data:{user:null,session:null},error:a};throw a}}async signInWithPassword(e){try{let t;if("email"in e){let{email:a,password:c,options:h}=e;t=await Ee(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:a,password:c,gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken}},xform:Kg})}else if("phone"in e){let{phone:a,password:c,options:h}=e;t=await Ee(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:a,password:c,gotrue_meta_security:{captcha_token:h==null?void 0:h.captchaToken}},xform:Kg})}else throw new Is("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 la}:(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(ge(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,n,s,a;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:(a=e.options)===null||a===void 0?void 0:a.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await Qu(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(t!=null?t:"").split("/");try{let{data:a,error:c}=await Ee(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:Vn});if(await Ju(this.storage,`${this.storageKey}-code-verifier`),c)throw c;return!a||!a.session||!a.user?{data:{user:null,session:null,redirectType:null},error:new la}:(a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),{data:Object.assign(Object.assign({},a),{redirectType:s!=null?s:null}),error:c})}catch(a){if(ge(a))return{data:{user:null,session:null,redirectType:null},error:a};throw a}}async signInWithIdToken(e){try{let{options:t,provider:n,token:s,access_token:a,nonce:c}=e,h=await Ee(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:s,access_token:a,nonce:c,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:Vn}),{data:f,error:m}=h;return m?{data:{user:null,session:null},error:m}:!f||!f.session||!f.user?{data:{user:null,session:null},error:new la}:(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("SIGNED_IN",f.session)),{data:f,error:m})}catch(t){if(ge(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,n,s,a,c;try{if("email"in e){let{email:h,options:f}=e,m=null,_=null;this.flowType==="pkce"&&([m,_]=await Es(this.storage,this.storageKey));let{error:E}=await Ee(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:h,data:(t=f==null?void 0:f.data)!==null&&t!==void 0?t:{},create_user:(n=f==null?void 0:f.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:m,code_challenge_method:_},redirectTo:f==null?void 0:f.emailRedirectTo});return{data:{user:null,session:null},error:E}}if("phone"in e){let{phone:h,options:f}=e,{data:m,error:_}=await Ee(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:h,data:(s=f==null?void 0:f.data)!==null&&s!==void 0?s:{},create_user:(a=f==null?void 0:f.shouldCreateUser)!==null&&a!==void 0?a:!0,gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},channel:(c=f==null?void 0:f.channel)!==null&&c!==void 0?c:"sms"}});return{data:{user:null,session:null,messageId:m==null?void 0:m.message_id},error:_}}throw new Is("You must provide either an email or phone number.")}catch(h){if(ge(h))return{data:{user:null,session:null},error:h};throw h}}async verifyOtp(e){var t,n;try{let s,a;"options"in e&&(s=(t=e.options)===null||t===void 0?void 0:t.redirectTo,a=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:c,error:h}=await Ee(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:a}}),redirectTo:s,xform:Vn});if(h)throw h;if(!c)throw new Error("An error occurred on token verification.");let f=c.session,m=c.user;return f!=null&&f.access_token&&(await this._saveSession(f),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",f)),{data:{user:m,session:f},error:null}}catch(s){if(ge(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithSSO(e){var t,n,s;try{let a=null,c=null;return this.flowType==="pkce"&&([a,c]=await Es(this.storage,this.storageKey)),await Ee(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:a,code_challenge_method:c}),headers:this.headers,xform:eI})}catch(a){if(ge(a))return{data:null,error:a};throw a}}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 fr;let{error:s}=await Ee(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:s}})}catch(e){if(ge(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:a}=e,{error:c}=await Ee(this.fetch,"POST",t,{headers:this.headers,body:{email:n,type:s,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},redirectTo:a==null?void 0:a.emailRedirectTo});return{data:{user:null,session:null},error:c}}else if("phone"in e){let{phone:n,type:s,options:a}=e,{data:c,error:h}=await Ee(this.fetch,"POST",t,{headers:this.headers,body:{phone:n,type:s,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}}});return{data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:h}}throw new Is("You must provide either an email or phone number and a type")}catch(t){if(ge(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 Qu(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 c=this.suppressGetSessionWarning;e=new Proxy(e,{get:(f,m,_)=>(!c&&m==="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."),c=!0,this.suppressGetSessionWarning=!0),Reflect.get(f,m,_))})}return{data:{session:e},error:null}}let{session:s,error:a}=await this._callRefreshToken(e.refresh_token);return a?{data:{session:null},error:a}:{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 Ee(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:tn}):await this._useSession(async t=>{var n,s,a;let{data:c,error:h}=t;if(h)throw h;return!(!((n=c.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new fr}:await Ee(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(a=(s=c.session)===null||s===void 0?void 0:s.access_token)!==null&&a!==void 0?a:void 0,xform:tn})})}catch(t){if(ge(t))return YE(t)&&(await this._removeSession(),await Ju(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:a}=n;if(a)throw a;if(!s.session)throw new fr;let c=s.session,h=null,f=null;this.flowType==="pkce"&&e.email!=null&&([h,f]=await Es(this.storage,this.storageKey));let{data:m,error:_}=await Ee(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:h,code_challenge_method:f}),jwt:c.access_token,xform:tn});if(_)throw _;return c.user=m.user,await this._saveSession(c),await this._notifyAllSubscribers("USER_UPDATED",c),{data:{user:c.user},error:null}})}catch(n){if(ge(n))return{data:{user:null},error:n};throw n}}_decodeJWT(e){return Gg(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 fr;let t=Date.now()/1e3,n=t,s=!0,a=null,c=Gg(e.access_token);if(c.exp&&(n=c.exp,s=n<=t),s){let{session:h,error:f}=await this._callRefreshToken(e.refresh_token);if(f)return{data:{user:null,session:null},error:f};if(!h)return{data:{user:null,session:null},error:null};a=h}else{let{data:h,error:f}=await this._getUser(e.access_token);if(f)throw f;a={access_token:e.access_token,refresh_token:e.refresh_token,user:h.user,token_type:"bearer",expires_in:n-t,expires_at:n},await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)}return{data:{user:a.user,session:a},error:null}}catch(t){if(ge(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:c,error:h}=t;if(h)throw h;e=(n=c.session)!==null&&n!==void 0?n:void 0}if(!(e!=null&&e.refresh_token))throw new fr;let{session:s,error:a}=await this._callRefreshToken(e.refresh_token);return a?{data:{user:null,session:null},error:a}:s?{data:{user:s.user,session:s},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(ge(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e,t){try{if(!Rr())throw new xs("No browser detected.");if(e.error||e.error_description||e.error_code)throw new xs(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 Xu("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new xs("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 Xu("No code detected.");let{data:ee,error:re}=await this._exchangeCodeForSession(e.code);if(re)throw re;let le=new URL(window.location.href);return le.searchParams.delete("code"),window.history.replaceState(window.history.state,"",le.toString()),{data:{session:ee.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:s,access_token:a,refresh_token:c,expires_in:h,expires_at:f,token_type:m}=e;if(!a||!h||!c||!m)throw new xs("No session defined in URL");let _=Math.round(Date.now()/1e3),E=parseInt(h),I=_+E;f&&(I=parseInt(f));let k=I-_;k*1e3<=tc&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${k}s, should have been closer to ${E}s`);let B=I-E;_-B>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",B,I,_):_-B<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",B,I,_);let{data:G,error:j}=await this._getUser(a);if(j)throw j;let J={provider_token:n,provider_refresh_token:s,access_token:a,expires_in:E,expires_at:I,refresh_token:c,token_type:m,user:G.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:J,redirectType:e.type},error:null}}catch(n){if(ge(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 Qu(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:a}=t;if(a)return{error:a};let c=(n=s.session)===null||n===void 0?void 0:n.access_token;if(c){let{error:h}=await this.admin.signOut(c,e);if(h&&!(JE(h)&&(h.status===404||h.status===401||h.status===403)))return{error:h}}return e!=="others"&&(await this._removeSession(),await Ju(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(e){let t=zE(),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:a},error:c}=t;if(c)throw c;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",a)),this._debug("INITIAL_SESSION","callback id",e,"session",a)}catch(a){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",a),console.error(a)}})}async resetPasswordForEmail(e,t={}){let n=null,s=null;this.flowType==="pkce"&&([n,s]=await Es(this.storage,this.storageKey,!0));try{return await Ee(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(a){if(ge(a))return{data:null,error:a};throw a}}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(ge(t))return{data:null,error:t};throw t}}async linkIdentity(e){var t;try{let{data:n,error:s}=await this._useSession(async a=>{var c,h,f,m,_;let{data:E,error:I}=a;if(I)throw I;let k=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(c=e.options)===null||c===void 0?void 0:c.redirectTo,scopes:(h=e.options)===null||h===void 0?void 0:h.scopes,queryParams:(f=e.options)===null||f===void 0?void 0:f.queryParams,skipBrowserRedirect:!0});return await Ee(this.fetch,"GET",k,{headers:this.headers,jwt:(_=(m=E.session)===null||m===void 0?void 0:m.access_token)!==null&&_!==void 0?_:void 0})});if(s)throw s;return Rr()&&!(!((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(ge(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:a,error:c}=t;if(c)throw c;return await Ee(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(n=a.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0})})}catch(t){if(ge(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 HE(async s=>(s>0&&await WE(200*Math.pow(2,s-1)),this._debug(t,"refreshing attempt",s),await Ee(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Vn})),(s,a)=>{let c=200*Math.pow(2,s);return a&&mf(a)&&Date.now()+c-n<tc})}catch(n){if(this._debug(t,"error",n),ge(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),Rr()&&!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 Qu(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),a=((e=n.expires_at)!==null&&e!==void 0?e:1/0)<s+$g;if(this._debug(t,`session has${a?"":" not"} expired with margin of ${$g}s`),a){if(this.autoRefreshToken&&n.refresh_token){let{error:c}=await this._callRefreshToken(n.refresh_token);c&&(console.error(c),mf(c)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",c),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 fr;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new Hu;let{data:a,error:c}=await this._refreshAccessToken(e);if(c)throw c;if(!a.session)throw new fr;await this._saveSession(a.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",a.session);let h={session:a.session,error:null};return this.refreshingDeferred.resolve(h),h}catch(a){if(this._debug(s,"error",a),ge(a)){let c={session:null,error:a};return mf(a)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(c),c}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(a),a}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 a=[],c=Array.from(this.stateChangeEmitters.values()).map(async h=>{try{await h.callback(e,t)}catch(f){a.push(f)}});if(await Promise.all(c),a.length>0){for(let h=0;h<a.length;h+=1)console.error(a[h]);throw a[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await zg(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await Ju(this.storage,this.storageKey),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Rr()&&(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(),tc);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)/tc);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${tc}ms, refresh threshold is ${sI} ticks`),s<=sI&&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 ec)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Rr()||!(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[a,c]=await Es(this.storage,this.storageKey),h=new URLSearchParams({code_challenge:`${encodeURIComponent(a)}`,code_challenge_method:`${encodeURIComponent(c)}`});s.push(h.toString())}if(n!=null&&n.queryParams){let a=new URLSearchParams(n.queryParams);s.push(a.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:a}=t;return a?{data:null,error:a}:await Ee(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(ge(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var n,s;let{data:a,error:c}=t;if(c)return{data:null,error:c};let h=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:{issuer:e.issuer}),{data:f,error:m}=await Ee(this.fetch,"POST",`${this.url}/factors`,{body:h,headers:this.headers,jwt:(n=a==null?void 0:a.session)===null||n===void 0?void 0:n.access_token});return m?{data:null,error:m}:(e.factorType==="totp"&&(!((s=f==null?void 0:f.totp)===null||s===void 0)&&s.qr_code)&&(f.totp.qr_code=`data:image/svg+xml;utf-8,${f.totp.qr_code}`),{data:f,error:null})})}catch(t){if(ge(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:a}=t;if(a)return{data:null,error:a};let{data:c,error:h}=await Ee(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 h?{data:null,error:h}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),{data:c,error:h})})}catch(t){if(ge(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:a}=t;return a?{data:null,error:a}:await Ee(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(ge(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(c=>c.factor_type==="totp"&&c.status==="verified"),a=n.filter(c=>c.factor_type==="phone"&&c.status==="verified");return{data:{all:n,totp:s,phone:a},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,n;let{data:{session:s},error:a}=e;if(a)return{data:null,error:a};if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let c=this._decodeJWT(s.access_token),h=null;c.aal&&(h=c.aal);let f=h;((n=(t=s.user.factors)===null||t===void 0?void 0:t.filter(E=>E.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(f="aal2");let _=c.amr||[];return{data:{currentLevel:h,nextLevel:f,currentAuthenticationMethods:_},error:null}}))}};Ps.nextInstanceID=0;var CU=Ps,Qg=CU;var _f=class extends Qg{constructor(e){super(e)}};var DU=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function h(_){try{m(n.next(_))}catch(E){c(E)}}function f(_){try{m(n.throw(_))}catch(E){c(E)}}function m(_){_.done?a(_.value):s(_.value).then(h,f)}m((n=n.apply(r,e||[])).next())})},rc=class{constructor(e,t,n){var s,a,c;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");let h=FE(e);this.realtimeUrl=`${h}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${h}/auth/v1`,this.storageUrl=`${h}/storage/v1`,this.functionsUrl=`${h}/functions/v1`;let f=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,m={db:NE,realtime:LE,auth:Object.assign(Object.assign({},VE),{storageKey:f}),global:kE},_=UE(n!=null?n:{},m);this.storageKey=(s=_.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(a=_.global.headers)!==null&&a!==void 0?a:{},_.accessToken?(this.accessToken=_.accessToken,this.auth=new Proxy({},{get:(E,I)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(I)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((c=_.auth)!==null&&c!==void 0?c:{},this.headers,_.global.fetch),this.fetch=ME(t,this._getAccessToken.bind(this),_.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},_.realtime)),this.rest=new yE(`${h}/rest/v1`,{headers:this.headers,schema:_.db.schema,fetch:this.fetch}),_.accessToken||this._listenForAuthEvents()}get functions(){return new Nu(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Gu(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 DU(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:a,flowType:c,lock:h,debug:f},m,_){let E={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new _f({url:this.authUrl,headers:Object.assign(Object.assign({},E),m),storageKey:a,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:s,flowType:c,lock:h,debug:f,fetch:_,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(e){return new sa(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 aI=(r,e,t)=>new rc(r,e,t);var vI=Dd(hI(),1);var fI={id:"~date",test:r=>r instanceof Date,serialize:r=>({_:"~date",v:r.toISOString()}),deserialize:r=>new Date(r.v)};var dI={id:"~function",test:r=>typeof r=="function",serialize:r=>({_:"~function",v:r.toString()}),deserialize:v=>eval(v.v.toString())};var pI={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 mI={id:"~nan",test:r=>Number.isNaN(r),serialize:r=>({_:"~nan"}),deserialize:r=>NaN};var gI={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 _I={id:"~set",test:r=>r instanceof Set,serialize:r=>({_:"~set",v:Array.from(r)}),deserialize:r=>new Set(r.v)};var yI={id:"~undefined",test:r=>r===void 0,serialize:r=>({_:"~undefined"}),deserialize:r=>{}};var da={settings:{stringify:!0,destringify:!0,clone:!1,depth:0,modules:[fI,dI,pI,mI,gI,_I,yI],circular:!0,symetric:!1},loadedModules:{},loadModules(r){return r.map(e=>{if(De(e)){if(!e.id)throw new Error("Provided custom module does not expose an `id` property");return da.loadedModules[e.id]=e}else throw new Error("Unknown module type")})},serialize(r,e){let t=zl(e,da.settings),n=da.loadModules(t.modules),s=t.symetric?(0,vI.keyArrangeDeep)(r):t.clone?qr(r):r,a=new Map,c=(h,f)=>{let m=De(h);if(m&&t.circular){let I=a.get(h);if(I)return pi(s,f,{_:"~circular",p:I.join(".")});a.set(h,f)}let _=n.find(I=>I.test(h)),E=(!t.depth||f.length<t.depth)&&m;if(_){let I=_.serialize(h);if(_.recursive&&E){let k=At(h);t.symetric&&k.sort(),pi(s,f,I),k.forEach(B=>c(h[B],f.concat(B)))}else f.length?pi(s,f,I):s=I}else if(E){let I=At(h);t.symetric&&I.sort(),I.forEach(k=>c(h[k],f.concat(k)))}};return c(s,[]),t.stringify?JSON.stringify(s):s},deserialize(r,e){let t=zl(e,da.settings),n=da.loadModules(t.modules),s=Bd(n,"id"),a=t.destringify?JSON.parse(r):t.clone?qr(r):r,c=(h,f)=>{if(De(h)&&h._&&typeof h._=="string"&&h._.startsWith("~")&&s[h._]){let m=s[h._].deserialize(h);f.length?s[h._].recursive&&De(m)?(pi(a,f,m),At(m).forEach(_=>c(h[_],[...f,_]))):pi(a,f,m):a=m}else t.circular&&De(h)&&h._&&h._=="~circular"?pi(a,f,ru(a,h.p)):(!t.depth||f.length<t.depth)&&De(h)&&At(h).forEach(m=>c(h[m],f.concat(m)))};return c(a,[]),a}},ic=da;var wI="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var bI=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=wI[t[r]&63];return e};var $e=class $e{constructor(e,t){gt(this,"path");gt(this,"docRef");gt(this,"value");gt(this,"throttle",250);gt(this,"heartbeatInterval",3e4);gt(this,"_destroyActions",[]);gt(this,"_heartbeatTimer");this.path=e,Object.assign(this,t),$e.session||($e.session=`syncro_${bI()}`)}debug(...e){}destroy(){return this.debug("Destroy!"),Promise.all(this._destroyActions.map(e=>e())).then(()=>this._destroyActions=[])}getReactive(e){console.warn("Syncro.getReactive has not been subclassed, assuming a POJO response");let t={...e};return{doc:t,setState(n){Object.entries(n||{}).forEach(([s,a])=>t[s]=a)},getState(){return qr(t)},watch(n){}}}static pathSplit(e){var n;let t={...(n=/^(?<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+?))?$/.exec(e))==null?void 0:n.groups};if(!t)throw new Error(`Invalid session path syntax "${e}"`);if(!(t.entity in Yg))throw new Error(`Unsupported entity "${e}" -> Entity="${t.entity}"`);return{...t,fsCollection:t.entity,fsId:t.relation?`${t.id}::${t.relation}`:t.id}}static toFirestore(e={}){return ic.serialize(e,{circular:!1,clone:!0,modules:[TI,...ic.settings.modules],stringify:!1})}static fromFirestore(e={}){return ic.deserialize(e,{circular:!1,clone:!0,modules:[TI,...ic.settings.modules],destringify:!1})}static fromFirestoreFields(e={}){let t={};for(let n in e){let s=e[n];if(["stringValue","booleanValue","doubleValue","integerValue","timestampValue","mapValue","arrayValue"].find(c=>c===n)){if(["stringValue","booleanValue","doubleValue","integerValue","timestampValue"].find(h=>h===n))return s;if(n=="mapValue")return $e.fromFirestoreFields(s.fields||{});if(n=="arrayValue"){let h=s.values;return h?h.map(f=>$e.fromFirestoreFields(f)):[]}}else t[n]=$e.fromFirestoreFields(s)}return t}static getSnapshot(e){let{fsCollection:t,fsId:n}=$e.pathSplit(e);return Promise.resolve().then(async()=>Jh(Ou($e.firestore,t,n))).then(s=>s?$e.fromFirestore(s.data()):null)}static setSnapshot(e,t,n){let s={method:"merge",...n},{fsCollection:a,fsId:c}=$e.pathSplit(e);return Promise.resolve().then(()=>(s.method=="merge"?"FirestoreUpdateDoc":"FirestoreSetDoc")(Ou($e.firestore,a,c),$e.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(){let{fsCollection:e,fsId:t,entity:n,id:s,relation:a}=$e.pathSplit(this.path),c,h;return Promise.resolve().then(()=>this.setHeartbeat(!1)).then(async()=>{this.docRef=Ou($e.firestore,e,t);let f=$e.fromFirestore((await Jh(this.docRef)).data());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(tE(this.docRef,m=>{let _=$e.fromFirestore(m.data());this.debug("Incoming snapshot",{snapshotData:_}),c.setState(_)}))}).then(()=>{if(Fd(h))return this.debug("Populate initial state"),Promise.resolve().then(()=>Yg[n]||Promise.reject(`Unknown Sync entity "${n}"`)).then(()=>Yg[n].initState({supabase:$e.supabase,fsCollection:e,fsId:t,entity:n,id:s,relation:a})).then(f=>bg(this.docRef,$e.toFirestore(f)))}).then(()=>{c.watch(jd(f=>{this.debug("Local change",{newState:f}),eE(this.docRef,$e.toFirestore(f))},this.throttle))}).then(()=>this.setHeartbeat(!0,{immediate:!0})).then(()=>this)}setHeartbeat(e=!0,t){let n={immediate:!0,...t};clearTimeout(this._heartbeatTimer),e&&(this._heartbeatTimer=setTimeout(async()=>{await this.heartbeat(),e&&this.setHeartbeat(!0)},this.heartbeatInterval),n.immediate&&this.heartbeat())}async heartbeat(){this.debug("heartbeat!");let e=new Date().toISOString(),t=Ou($e.firestore,"presence",this.path),n=await Jh(t);await bg(t,{latest:e,...!n.exists()&&{created:e,lastFlush:null},sessions:{[$e.session]:e}},{merge:!0})}flush(e){let t={destroy:!1,...e};return fetch(`https://tera-tools.com/api/sync/${this.path}/flush`+(t.destroy?"?destroy=1":""),{method:"post"}).then(n=>n.ok?null:Promise.reject(n.statusText||"An error occured"))}};gt($e,"firebase"),gt($e,"firestore"),gt($e,"supabase"),gt($e,"session");var Tt=$e;var Yg={projects:{singular:"project",initState({supabase:r,id:e}){return Tt.wrapSupabase(r.from("projects").select("data").limit(1).eq("id",e)).then(t=>t.length==1?t[0]:Promise.reject(`Syncro project "${e}" not found`)).then(t=>t.data)},flushState({supabase:r,state:e,fsId:t}){return Tt.wrapSupabase(r.rpc("syncro_merge_data",{table_name:"projects",entity_id:t,new_data:e}))}},project_namespaces:{singular:"project namespace",initState({supabase:r,id:e,relation:t}){if(!t)throw new Error('Project namespace relation missing, path should resemble "project_namespaces::${PROJECT}::${RELATION}"');return Tt.wrapSupabase(r.from("project_namespaces").select("data").limit(1).eq("project",e).eq("name",t)).then(n=>n.length==1?n[0]:Tt.wrapSupabase(r.from("project_namespaces").insert({project:e,name:t,data:{}}).select("data"))).then(n=>n.data)},flushState({supabase:r,state:e,id:t,relation:n}){return Tt.wrapSupabase(r.from("project_namespaces").update({edited_at:new Date,data:e}).eq("project",t).eq("name",n))}},test:{singular:"test",initState({supabase:r,id:e}){return Tt.wrapSupabase(r.from("test").select("data").limit(1).eq("id",e)).then(t=>t.length==1?t[0]:Promise.reject(`Syncro test item "${e}" not found`)).then(t=>t.data)},flushState({supabase:r,state:e,fsId:t}){return Tt.wrapSupabase(r.rpc("syncro_merge_data",{table_name:"test",entity_id:t,new_data:e}))}},users:{singular:"user",initState({supabase:r,id:e}){return Tt.wrapSupabase(r.from("users").select("data").limit(1).eq("id",e)).then(t=>t.length==1?t[0]:Promise.reject(`Syncro user "${e}" not found`)).then(t=>t.data)},flushState({supabase:r,state:e,fsId:t}){return Tt.wrapSupabase(r.rpc("syncro_merge_data",{table_name:"users",entity_id:t,new_data:e}))}}},TI={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 sc=class{init(){}constructor(e,t){}};var oc=class extends sc{constructor(){super(...arguments);gt(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(a=>a===null);if(s.length>0)throw new Error("Firebase plugin requires mandatory options: "+s.join(", "));Tt.firebase=op({apiKey:n.firebaseApiKey,authDomain:n.firebaseAuthDomain,projectId:n.firebaseProjectId,appId:n.firebaseAppId}),Tt.firestore=WT(this.firebase),Tt.supabase=aI(n.supabaseUrl,n.supabaseKey)}_mountNamespace(t){let n;return Promise.resolve().then(()=>this.requireProject()).then(s=>{let a=t=="_PROJECT"?`projects::${s.id}`:`project_namespaces::${s.id}::${t}`;return n=this.syncros[t]=new Tt(a,{debug:(...c)=>this.debug(`SYNCRO://${a}`,...c),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 Xg=class extends oc{constructor(){super(...arguments);gt(this,"Vue");gt(this,"project",null);gt(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(a){Object.entries(a||{}).filter(([c])=>!Ud(n[c],a[c])).forEach(([c,h])=>n[c]=h)},getState(){return qr(n)},watch:a=>{this.app.$watch(s,a,{deep:!0})}}}bindProjectState(t){let n={component:null,componentKey:null,autoRequire:!0,read:!0,write:!0,throttle:{wait:200,maxWait:2e3,leading:!1,trailing:!0},...t};return Promise.resolve().then(()=>Promise.all([this.getProjectState({autoRequire:n.autoRequire}),(()=>{if(!n.componentKey){for(let s=0;s<50;s++){let a=`terafy_${s}`;if(!Object.hasOwnProperty(n.component,a)){n.componentKey=a;return}}throw new Error("Unable to find unique key to allocate against Vue2 component")}})()])).then(([s])=>{this.debug("INFO",2,"Got project snapshot",s);let a=this.Vue.observable(s);if(n.component[n.componentKey]=a,n.read&&this.events.on(`update:projects/${a.id}`,c=>{var h;(h=c==null?void 0:c.lastPatch)!=null&&h.session&&c.lastPatch.session==this.settings.session||(this.debug("INFO",5,"Update Vue2 Remote->Local",{new:c,old:a}),this.merge(a,c))}),n.write){if(!n.component)throw new Error("bindProjectState requires a VueComponent specified as `component`");let c=qr(s),h=()=>{let f=qr(s);this.debug("INFO",5,"Update Vue2 Local->Remote",{new:f,old:c}),this.createProjectStatePatch(f,c),c=f};n.component.$watch(n.componentKey,n.throttle?debounce(h,n.throttle.wait,n.throttle):h,{deep:!0})}return a})}merge(t,...n){return n.forEach(s=>Object.keys(s).forEach(a=>{isPlainObject(s[a])?(a in t||this.Vue.set(t,a,{}),this.merge(t[a],s[a])):this.Vue.set(t,a,s[a])})),t}};export{Xg as default};
|
|
47
47
|
/*! Bundled license information:
|
|
48
48
|
|
|
49
49
|
lodash/lodash.js:
|
package/lib/syncro.js
CHANGED
|
@@ -306,12 +306,11 @@ export default class Syncro {
|
|
|
306
306
|
let {fsCollection, fsId} = Syncro.pathSplit(path);
|
|
307
307
|
|
|
308
308
|
return Promise.resolve()
|
|
309
|
-
.then(async ()=>
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
})
|
|
309
|
+
.then(async ()=> FirestoreGetDoc( // Set up binding and wait for it to come ready
|
|
310
|
+
FirestoreDocRef(Syncro.firestore, fsCollection, fsId)
|
|
311
|
+
))
|
|
313
312
|
.then(doc => doc
|
|
314
|
-
? Syncro.fromFirestore(
|
|
313
|
+
? Syncro.fromFirestore(doc.data())
|
|
315
314
|
: null
|
|
316
315
|
)
|
|
317
316
|
}
|
package/lib/terafy.server.js
CHANGED
|
@@ -758,7 +758,7 @@ export default class TeraFyServer {
|
|
|
758
758
|
getNamespace(name) {
|
|
759
759
|
if (!/^[\w-]+$/.test(name)) throw new Error('Namespaces must be alphanumeric + hyphens + underscores');
|
|
760
760
|
|
|
761
|
-
return
|
|
761
|
+
return app.service('$sync').getSnapshot(`project_namespaces::${app.service('$projects').active.id}::${name}`);
|
|
762
762
|
}
|
|
763
763
|
|
|
764
764
|
|
|
@@ -777,7 +777,7 @@ export default class TeraFyServer {
|
|
|
777
777
|
if (!/^[\w--]+$/.test(name)) throw new Error('Namespaces must be alphanumeric + hyphens + underscores');
|
|
778
778
|
if (typeof state != 'object') throw new Error('State must be an object');
|
|
779
779
|
|
|
780
|
-
return
|
|
780
|
+
return app.service('$sync').setSnapshot(`project_namespaces::${app.service('$projects').active.id}}::${name}`, state, {
|
|
781
781
|
method: options.method,
|
|
782
782
|
});
|
|
783
783
|
}
|
package/package.json
CHANGED