@hlmr/sdk-js 1.10.1 → 1.11.2

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.
Files changed (62) hide show
  1. package/dist/cjs/client/HlmrClient.d.ts +2 -0
  2. package/dist/cjs/client/HlmrClient.d.ts.map +1 -1
  3. package/dist/cjs/client/HlmrClient.js +2 -0
  4. package/dist/cjs/client/HlmrClient.js.map +1 -1
  5. package/dist/cjs/index.d.ts +3 -1
  6. package/dist/cjs/index.d.ts.map +1 -1
  7. package/dist/cjs/index.js +3 -1
  8. package/dist/cjs/index.js.map +1 -1
  9. package/dist/cjs/modules/booking.d.ts +2 -2
  10. package/dist/cjs/modules/booking.d.ts.map +1 -1
  11. package/dist/cjs/modules/booking.js +2 -2
  12. package/dist/cjs/modules/booking.js.map +1 -1
  13. package/dist/cjs/modules/promo.d.ts +11 -0
  14. package/dist/cjs/modules/promo.d.ts.map +1 -0
  15. package/dist/cjs/modules/promo.js +34 -0
  16. package/dist/cjs/modules/promo.js.map +1 -0
  17. package/dist/cjs/types/booking.d.ts +10 -0
  18. package/dist/cjs/types/booking.d.ts.map +1 -1
  19. package/dist/cjs/types/promo.d.ts +46 -0
  20. package/dist/cjs/types/promo.d.ts.map +1 -0
  21. package/dist/cjs/types/promo.js +3 -0
  22. package/dist/cjs/types/promo.js.map +1 -0
  23. package/dist/esm/client/HlmrClient.d.ts +2 -0
  24. package/dist/esm/client/HlmrClient.d.ts.map +1 -1
  25. package/dist/esm/client/HlmrClient.js +17 -15
  26. package/dist/esm/client/HlmrClient.js.map +1 -1
  27. package/dist/esm/index.d.ts +3 -1
  28. package/dist/esm/index.d.ts.map +1 -1
  29. package/dist/esm/index.js +16 -15
  30. package/dist/esm/index.js.map +1 -1
  31. package/dist/esm/modules/booking.d.ts +2 -2
  32. package/dist/esm/modules/booking.d.ts.map +1 -1
  33. package/dist/esm/modules/booking.js +2 -2
  34. package/dist/esm/modules/booking.js.map +1 -1
  35. package/dist/esm/modules/promo.d.ts +11 -0
  36. package/dist/esm/modules/promo.d.ts.map +1 -0
  37. package/dist/esm/modules/promo.js +30 -0
  38. package/dist/esm/modules/promo.js.map +1 -0
  39. package/dist/esm/types/booking.d.ts +10 -0
  40. package/dist/esm/types/booking.d.ts.map +1 -1
  41. package/dist/esm/types/promo.d.ts +46 -0
  42. package/dist/esm/types/promo.d.ts.map +1 -0
  43. package/dist/esm/types/promo.js +2 -0
  44. package/dist/esm/types/promo.js.map +1 -0
  45. package/dist/esm/utils/http.js +3 -3
  46. package/dist/types/client/HlmrClient.d.ts +2 -0
  47. package/dist/types/client/HlmrClient.d.ts.map +1 -1
  48. package/dist/types/index.d.ts +3 -1
  49. package/dist/types/index.d.ts.map +1 -1
  50. package/dist/types/modules/booking.d.ts +2 -2
  51. package/dist/types/modules/booking.d.ts.map +1 -1
  52. package/dist/types/modules/promo.d.ts +11 -0
  53. package/dist/types/modules/promo.d.ts.map +1 -0
  54. package/dist/types/types/booking.d.ts +10 -0
  55. package/dist/types/types/booking.d.ts.map +1 -1
  56. package/dist/types/types/promo.d.ts +46 -0
  57. package/dist/types/types/promo.d.ts.map +1 -0
  58. package/dist/umd/hlmr-sdk.js +34 -2
  59. package/dist/umd/hlmr-sdk.js.map +1 -1
  60. package/dist/umd/hlmr-sdk.min.js +1 -1
  61. package/dist/umd/hlmr-sdk.min.js.map +1 -1
  62. package/package.json +2 -2
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).HlmrSDK={})}(this,function(e){"use strict";const t={production:{name:"production",url:"https://api.hlmr.io",description:"Environnement de production"},development:{name:"development",url:"https://api.dev.hlmr.io",description:"Environnement de développement"},staging:{name:"staging",url:"https://api.stg.hlmr.io",description:"Environnement de staging"}};class r extends Error{constructor(e,t,s,n,i){super(e),this.name="HlmrApiError",this.statusCode=t,this.code=s,this.response=n,this.originalError=i,Error.captureStackTrace&&Error.captureStackTrace(this,r)}static fromJSendResponse(e,t){if("fail"===e.status){return new r(e.data.detail||"Validation failed",t,"VALIDATION_ERROR",e)}if("error"===e.status){const s=e;return new r(s.message||"Server error",t,s.code||"SERVER_ERROR",e)}return new r("Unknown API error",t,"UNKNOWN_ERROR",e)}static networkError(e){return new r(`Network error: ${e.message}`,0,"NETWORK_ERROR",void 0,e)}static timeoutError(e){return new r(`Request timeout after ${e}ms`,0,"TIMEOUT_ERROR")}static configError(e){return new r(`Configuration error: ${e}`,0,"CONFIG_ERROR")}isAuthError(){return 401===this.statusCode}isPermissionError(){return 403===this.statusCode}isValidationError(){return this.statusCode>=400&&this.statusCode<500&&"VALIDATION_ERROR"===this.code}isServerError(){return this.statusCode>=500}isNetworkError(){return"NETWORK_ERROR"===this.code}isTimeoutError(){return"TIMEOUT_ERROR"===this.code}getInsufficientBalanceDetail(){var e,t,r,s;if(402!==this.statusCode)return null;const n=null!==(r=null===(t=null===(e=this.response)||void 0===e?void 0:e.data)||void 0===t?void 0:t.detail)&&void 0!==r?r:null===(s=this.response)||void 0===s?void 0:s.detail;return n&&"object"==typeof n&&"min_amount"in n?{min_amount:n.min_amount,wallet_balance:n.wallet_balance}:null}}function s(e){return"object"==typeof e&&null!==e&&"string"==typeof e.status&&["success","fail","error"].includes(e.status)}function n(e){return"success"===e.status&&"data"in e}const i="1.1.0";class a{constructor(e){this.config=e}updateConfig(e){this.config={...this.config,...e}}setBearerToken(e){this.config.bearerToken=e}clearBearerToken(){delete this.config.bearerToken}setAppSecret(e){this.config.appSecret=e}clearAppSecret(){delete this.config.appSecret}buildUrl(e,t="v1"){if(e.startsWith("http://")||e.startsWith("https://"))return e;const r=this.config.baseUrl.replace(/\/$/,""),s=e.replace(/^\//,"");return s.match(/^v\d+\//)?`${r}/${s}`:t?`${r}/${t}/${s}`:`${r}/${s}`}buildHeaders(e={}){const t={"Content-Type":"application/json","X-App-ID":this.config.appId,"X-SDK-Referrer":`hlmr-sdk-js@${i}`,...this.config.customHeaders,...e.headers};return this.config.appSecret&&!e.skipAuth?t["X-App-Secret"]=this.config.appSecret:this.config.bearerToken&&!e.skipAuth&&(t.Authorization=`Bearer ${this.config.bearerToken}`),t}createTimeoutController(e){const t=new AbortController;return setTimeout(()=>t.abort(),e),t}async processResponse(e){const t={};let i;e.headers.forEach((e,r)=>{t[r]=e});const a=e.headers.get("content-type");if(a&&a.includes("application/json"))try{i=await e.json()}catch(t){i=await e.text()}else i=await e.text();if(s(i)){if(!e.ok)throw r.fromJSendResponse(i,e.status);if(n(i))return{status:e.status,statusText:e.statusText,headers:t,data:i.data}}if(!e.ok)throw new r(`HTTP ${e.status}: ${e.statusText}`,e.status,"HTTP_ERROR");return{status:e.status,statusText:e.statusText,headers:t,data:i}}async request(e,t,s,n={}){const i=this.buildUrl(t,n.apiVersion),a=this.buildHeaders(n),o=n.timeout||this.config.timeout||3e4;this.config.debug&&console.log(`[HlmrSDK] ${e} ${i}`,{headers:a,body:s});const c={method:e,headers:a,signal:this.createTimeoutController(o).signal};s&&["POST","PUT","PATCH"].includes(e.toUpperCase())&&(c.body="string"==typeof s?s:JSON.stringify(s));try{let e=await fetch(i,c);if(307===e.status||301===e.status||302===e.status){const t=e.headers.get("location");if(t){console.warn(`[HlmrSDK] Received ${e.status} redirect for ${i}. Following redirect to ${t}. Please update your code to use the correct URL with trailing slash.`);const r=t.startsWith("http")?t:new URL(t,i).toString();e=await fetch(r,c)}}const t=await this.processResponse(e);return this.config.debug&&console.log("[HlmrSDK] Response:",t),t}catch(e){if(e instanceof r)throw e;if(e instanceof Error){if("AbortError"===e.name)throw r.timeoutError(o);throw r.networkError(e)}throw new r("Unknown error occurred",0,"UNKNOWN_ERROR")}}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,r){return this.request("POST",e,t,r)}async put(e,t,r){return this.request("PUT",e,t,r)}async patch(e,t,r){return this.request("PATCH",e,t,r)}async delete(e,t){return this.request("DELETE",e,void 0,t)}async directRequest(e,t="GET",s,n={}){const i={"Content-Type":"application/json",...n.headers},a=n.timeout||this.config.timeout||3e4,o=this.createTimeoutController(a);this.config.debug&&console.log(`[HlmrSDK] Direct ${t} ${e}`,{headers:i,body:s});const c={method:t,headers:i,signal:o.signal};s&&["POST","PUT","PATCH"].includes(t)&&(c.body="string"==typeof s?s:JSON.stringify(s));try{const t=await fetch(e,c),r=await this.processResponse(t);return this.config.debug&&console.log("[HlmrSDK] Direct Response:",r),r}catch(e){if(e instanceof r)throw e;if(e instanceof Error){if("AbortError"===e.name)throw r.timeoutError(a);throw r.networkError(e)}throw new r("Unknown error occurred",0,"UNKNOWN_ERROR")}}}class o{constructor(e){this.http=e}async validateRedirect(e,t){const r={app_id:e,redirect_uri:t};return(await this.http.post(`apps/${e}/validate-redirect`,r,{skipAuth:!0})).data}async exchangeRedirectToken(e){const t=await this.http.post("auth/exchange",{redirect_token:e},{skipAuth:!0});return{...t.data,scopes_refreshed:!0===t.data.scopes_refreshed}}}class c{constructor(e){this.http=e}async getProfile(){const e=(await this.http.get("users/me")).data.user;return{id:e.user_id,email:e.email||"",full_name:e.display_name||e.public_name,avatar_url:e.avatar_url,user_metadata:e.user_metadata||{},created_at:e.created_at||"",updated_at:e.updated_at||"",last_sign_in_at:e.last_sign_in_at,email_confirmed_at:e.email_verified?e.email_confirmed_at||e.updated_at:void 0}}async updateProfile(e){const t=(await this.http.patch("users/me/profile",e)).data.user;return{id:t.user_id,email:t.email||"",full_name:t.display_name||t.public_name,avatar_url:t.avatar_url,user_metadata:t.user_metadata||{},created_at:t.created_at||"",updated_at:t.updated_at||"",last_sign_in_at:t.last_sign_in_at,email_confirmed_at:t.email_verified?t.email_confirmed_at||t.updated_at:void 0}}async getSettings(e){const t=e||"default";try{const e=await this.http.get(`users/me/settings/${t}`);if(e.data&&e.data.settings)return e.data}catch(t){if(404===t.status&&e)try{const e=await this.http.get("users/me/settings/default");if(e.data&&e.data.settings)return e.data}catch(e){}}return null}async updateSettings(e,t,r){const s={...t};"default"===e&&(null==r?void 0:r.applyAll)&&(s.apply_all=!0);const n=await this.http.patch(`users/me/settings/${e}`,s),i={success:!0};return void 0!==n.data.updated_apps&&(i.updated_apps=n.data.updated_apps),i}async getLocale(e){var t;const r=await this.getSettings(e);return(null===(t=null==r?void 0:r.settings)||void 0===t?void 0:t.locale)||null}}class l{constructor(e){this.http=e}async ping(e){let t="ping";if(e){const r=new URLSearchParams;void 0!==e.idle&&r.append("idle",String(e.idle)),void 0!==e.app&&r.append("app",String(e.app)),void 0!==e.lat&&r.append("lat",String(e.lat)),void 0!==e.lng&&r.append("lng",String(e.lng)),void 0!==e.device&&r.append("device",String(e.device));const s=r.toString();s&&(t=`${t}?${s}`)}return(await this.http.get(t,{apiVersion:""})).data}async version(){return(await this.http.get("version",{apiVersion:"",skipAuth:!0})).data}async checkServiceReady(e){return(await this.http.get(`ready/${e}`,{apiVersion:"",skipAuth:!0})).data}}class h{constructor(e){this.http=e}async logSession(e,t){return(await this.http.post(`apps/${e}/sessions`,t||{})).data}}const u={pingInterval:3e4,autoReconnect:!0,maxReconnectAttempts:5,reconnectDelay:1e3,maxReconnectDelay:3e4,debug:!1};class d{setBearerToken(e){this.bearerToken=e}constructor(e,t){this.ws=null,this.pingIntervalId=null,this.reconnectAttempts=0,this.reconnectTimeoutId=null,this.isConnecting=!1,this.isManualDisconnect=!1,this.subscriptions=new Map,this.pendingSubscriptions=new Map,this.listeners=new Map,this.userId=null,this.bearerToken=null,this.authResolve=null,this.authReject=null,this.http=e,this.config={...u,...t};const r=e.config;this.bearerToken=r.bearerToken||null}async connect(){if(this.ws&&this.ws.readyState===WebSocket.OPEN)throw new Error("Already connected");if(this.isConnecting)throw new Error("Connection in progress");return this.isConnecting=!0,this.isManualDisconnect=!1,this.reconnectAttempts=0,this._connect()}async _connect(){return new Promise((e,t)=>{try{this.authResolve=e,this.authReject=t;const r=this._buildWebSocketUrl();this.config.debug&&console.log("[EventsModule] Connecting to:",r),this.ws=new WebSocket(r);const s=setTimeout(()=>{this.ws&&this.ws.readyState!==WebSocket.OPEN&&(this.ws.close(),this.isConnecting=!1,this.authResolve=null,this.authReject=null,t(new Error("Connection timeout")))},1e4);this.ws.onopen=()=>{if(this.config.debug&&console.log("[EventsModule] WebSocket connected, sending auth..."),clearTimeout(s),this.bearerToken){const e={type:"auth",token:this.bearerToken};this.ws.send(JSON.stringify(e)),this.config.debug&&console.log("[EventsModule] Sent auth message")}else this.isConnecting=!1,this.authResolve=null,this.authReject=null,this.ws.close(4008,"Missing authentication token"),t(new Error("Missing authentication token"))},this.ws.onmessage=e=>{try{const t=JSON.parse(e.data);this._handleMessage(t)}catch(e){this.config.debug&&console.error("[EventsModule] Failed to parse message:",e)}},this.ws.onerror=e=>{this.config.debug&&console.error("[EventsModule] WebSocket error:",e),clearTimeout(s),this.isConnecting=!1,this.authResolve=null,this.authReject=null,this._emit("error",new Error("WebSocket error")),t(new Error("WebSocket error"))},this.ws.onclose=e=>{this.config.debug&&console.log("[EventsModule] WebSocket closed:",e.code,e.reason),clearTimeout(s),this._stopPingInterval(),this.isConnecting=!1,this.authReject&&(this.authReject(new Error(e.reason||"Connection closed before authentication")),this.authResolve=null,this.authReject=null),this._emit("disconnect",e.reason||"Connection closed"),!this.isManualDisconnect&&this.config.autoReconnect&&this._scheduleReconnect()}}catch(e){this.isConnecting=!1,this.authResolve=null,this.authReject=null,t(e)}})}disconnect(){this.isManualDisconnect=!0,this._cleanup(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.config.debug&&console.log("[EventsModule] Disconnected")}async subscribe(e,t,r){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("Not connected");const s=this._generateId();return new Promise((n,i)=>{const a=r?{domain:e,resource:t,options:r}:{domain:e,resource:t},o={resolve:e=>{this.subscriptions.set(e.id,a),n(e)},reject:i,...a};this.pendingSubscriptions.set(s,o);const c={type:"subscribe",subscription_id:s,domain:e,resource:t,options:{filters:(null==r?void 0:r.filters)||{},include_data:(null==r?void 0:r.include_data)||!1}};this.ws.send(JSON.stringify(c)),this.config.debug&&console.log("[EventsModule] Subscribing:",c),setTimeout(()=>{this.pendingSubscriptions.has(s)&&(this.pendingSubscriptions.delete(s),i(new Error("Subscription timeout")))},1e4)})}async unsubscribe(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("Not connected");return new Promise((t,r)=>{const s={type:"unsubscribe",subscription_id:e};this.ws.send(JSON.stringify(s)),this.subscriptions.delete(e),this.config.debug&&console.log("[EventsModule] Unsubscribing:",e),t()})}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){const r=this.listeners.get(e);r&&r.delete(t)}sendTypingEvent(e,t){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return void(this.config.debug&&console.warn("[EventsModule] Cannot send typing event: not connected"));const r={type:"typing_event",chat_id:e,event:t};this.ws.send(JSON.stringify(r)),this.config.debug&&console.log("[EventsModule] Sent typing event:",r)}get isConnected(){return null!==this.ws&&this.ws.readyState===WebSocket.OPEN}get currentUserId(){return this.userId}getSubscriptions(){return new Map(this.subscriptions)}ping(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}updateConfig(e){this.config={...this.config,...e},this.ws&&this.ws.readyState===WebSocket.OPEN&&(this._stopPingInterval(),this._startPingInterval())}_buildWebSocketUrl(){return`${this.http.config.baseUrl.replace("https://","wss://").replace("http://","ws://")}/v1/events/ws`}_handleMessage(e){var t;switch(this.config.debug&&console.log("[EventsModule] Message received:",e),e.type){case"connected":this.isConnecting=!1,this.userId=e.user_id,this._emit("connect",e),this.authResolve&&(this.authResolve(e),this.authResolve=null,this.authReject=null),this._startPingInterval(),this.reconnectAttempts>0&&this._resubscribeAll(),this.reconnectAttempts=0;break;case"auth_error":this.isConnecting=!1;const r=e.error||"Authentication failed";this.authReject&&(this.authReject(new Error(r)),this.authResolve=null,this.authReject=null),null===(t=this.ws)||void 0===t||t.close(1008,r);break;case"subscription_confirmed":this._handleSubscriptionConfirmed(e);break;case"unsubscribed":this.subscriptions.delete(e.subscription_id);break;case"notification":this._emit("notification",e);break;case"system_notification":this._emit("system_notification",e);break;case"pong":break;case"error":this._emit("error",e);break;default:this.config.debug&&console.warn("[EventsModule] Unknown message type:",e.type)}}_handleSubscriptionConfirmed(e){const t=this.pendingSubscriptions.get(e.subscription_id);if(t){this.pendingSubscriptions.delete(e.subscription_id);const r={id:e.subscription_id,domain:e.domain,resource:e.resource,filters:e.filters};t.resolve(r)}this._emit("subscription_confirmed",e)}_emit(e,...t){const r=this.listeners.get(e);r&&r.forEach(r=>{try{r(...t)}catch(t){console.error(`[EventsModule] Error in ${e} listener:`,t)}})}_startPingInterval(){this.config.pingInterval>0&&(this.pingIntervalId=setInterval(()=>{this.ping()},this.config.pingInterval),this.config.debug&&console.log("[EventsModule] Ping interval started:",this.config.pingInterval))}_stopPingInterval(){this.pingIntervalId&&(clearInterval(this.pingIntervalId),this.pingIntervalId=null)}_scheduleReconnect(){if(this.reconnectAttempts>=this.config.maxReconnectAttempts)return this.config.debug&&console.log("[EventsModule] Max reconnect attempts reached"),void this._emit("error",new Error("Max reconnect attempts reached"));this.reconnectAttempts++;const e=Math.min(this.config.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),this.config.maxReconnectDelay);this.config.debug&&console.log(`[EventsModule] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts})`),this._emit("reconnecting",this.reconnectAttempts),this.reconnectTimeoutId=setTimeout(async()=>{try{await this._connect()}catch(e){this.config.debug&&console.error("[EventsModule] Reconnect failed:",e)}},e)}async _resubscribeAll(){this.config.debug&&console.log("[EventsModule] Re-subscribing to",this.subscriptions.size,"subscriptions");const e=new Map(this.subscriptions);this.subscriptions.clear();for(const[t,r]of e)try{await this.subscribe(r.domain,r.resource,r.options),this.config.debug&&console.log("[EventsModule] Re-subscribed:",r.domain,r.resource)}catch(e){this.config.debug&&console.error("[EventsModule] Failed to re-subscribe:",e)}}_cleanup(){this._stopPingInterval(),this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=null);for(const e of this.pendingSubscriptions.values())e.reject(new Error("Connection closed"));this.pendingSubscriptions.clear()}_generateId(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}}class p{constructor(e){this.http=e}async listOffers(e){const t=f(e),r=t?`offers/public/offers?${t}`:"offers/public/offers";return(await this.http.get(r,{skipAuth:!0})).data}async searchOffers(e){const t=f(e),r=t?`offers/public/offers/search?${t}`:"offers/public/offers/search";return(await this.http.get(r,{skipAuth:!0})).data}async getOffer(e){return(await this.http.get(`offers/public/offers/${e}`,{skipAuth:!0})).data}async getOfferAvailability(e,t){const r=f(t);return(await this.http.get(`offers/public/offers/${e}/availability?${r}`,{skipAuth:!0})).data.days}async listDestinations(e){const t=f(e),r=t?`geo/public/destinations?${t}`:"geo/public/destinations";return(await this.http.get(r,{skipAuth:!0})).data}async listCities(e){const t=f(e),r=t?`geo/public/cities?${t}`:"geo/public/cities";return(await this.http.get(r,{skipAuth:!0})).data}async listDocuments(e){const t=f(e),r=t?`terms/public/documents?${t}`:"terms/public/documents";return(await this.http.get(r,{skipAuth:!0})).data}async getDocument(e){return(await this.http.get(`terms/public/documents/${e}`,{skipAuth:!0})).data}}function f(e){if(!e)return"";const t=new URLSearchParams;for(const[r,s]of Object.entries(e))null!=s&&t.append(r,String(s));return t.toString()}class g{constructor(e){this.http=e}async list(e){const t=function(e){if(!e)return"";const t=new URLSearchParams;for(const[r,s]of Object.entries(e))null!=s&&t.append(r,String(s));return t.toString()}(e),r=t?`offers/offers?${t}`:"offers/offers";return(await this.http.get(r)).data}}class w{constructor(e){this.http=e}async estimate(e){return(await this.http.post("pricing/estimate",e)).data}}class m{constructor(e){this.http=e}async create(e){return(await this.http.post("booking/bookings",e)).data.booking}async quote(e){return(await this.http.post(`booking/bookings/${e}/quote`)).data.quote}async updateOptions(e,t){return(await this.http.put(`booking/bookings/${e}/options`,t)).data.booking}async confirmQuote(e,t){return(await this.http.post(`booking/bookings/${e}/confirm-quote`,t)).data.booking}async checkRequirement(e,t){return(await this.http.post(`booking/bookings/${e}/requirements/${t}/check`)).data.requirement}async list(e){const t=function(e){if(!e)return"";const t=new URLSearchParams;for(const[r,s]of Object.entries(e))null!=s&&t.append(r,String(s));return t.toString()}(e),r=t?`booking/bookings?${t}`:"booking/bookings";return(await this.http.get(r)).data}async get(e){return(await this.http.get(`booking/bookings/${e}`)).data.booking}async getRequirements(e){return(await this.http.get(`booking/bookings/${e}/requirements`)).data.requirements}async acknowledgeRequirement(e,t){return(await this.http.post(`booking/bookings/${e}/requirements/${t}/acknowledge`)).data.requirement}async cancelPreview(e){return(await this.http.post(`booking/bookings/${e}/cancel-preview`)).data}async cancel(e,t){return(await this.http.post(`booking/bookings/${e}/cancel`,t)).data.booking}async extend(e,t){return(await this.http.post(`booking/bookings/${e}/extend`,t)).data.booking}async confirmExtension(e){return(await this.http.post(`booking/bookings/${e}/confirm-extension`)).data.booking}async pay(e,t){return(await this.http.post(`booking/bookings/${e}/pay`,null!=t?t:{scope:"all"})).data}async renewPaymentLink(e){return(await this.http.post(`payment/links/${e}/renew`)).data}async listAvailableOptions(e){return(await this.http.get(`booking/bookings/${e}/available-options`)).data.masterclasses}async listBookingOptions(e){return(await this.http.get(`booking/bookings/${e}/options`)).data.options}async createOption(e,t){return(await this.http.post(`booking/bookings/${e}/options`,t)).data.option}async acceptOption(e,t){return(await this.http.post(`booking/bookings/${e}/options/${t}/accept`)).data.option}async cancelOption(e,t){return(await this.http.post(`booking/bookings/${e}/options/${t}/cancel`)).data.option}async payOption(e,t){return(await this.http.post(`booking/bookings/${e}/options/${t}/pay`)).data.option}async detach(e){return(await this.http.post(`booking/bookings/${e}/detach`)).data.booking}}class y{constructor(e){this.http=e}async getWallets(e){const t=b(e),r=t?`ledger/wallets?${t}`:"ledger/wallets";return(await this.http.get(r)).data}async getWallet(e){return(await this.http.get(`ledger/wallets/${e}`)).data.wallet}async getBalanceHistory(e,t){const r=b(t),s=r?`ledger/wallets/${e}/balance-history?${r}`:`ledger/wallets/${e}/balance-history`;return(await this.http.get(s)).data}async getTransactions(e){const t=b(e),r=t?`ledger/transactions?${t}`:"ledger/transactions";return(await this.http.get(r)).data}async getTransaction(e){return(await this.http.get(`ledger/transactions/${e}`)).data.transaction}}function b(e){if(!e)return"";const t=new URLSearchParams;for(const[r,s]of Object.entries(e))null!=s&&t.append(r,String(s));return t.toString()}class v{constructor(e){this.http=e}async getLink(e){return(await this.http.get(`payment/public/links/${e}`,{skipAuth:!0})).data}async getLinkStatus(e){return(await this.http.get(`payment/public/links/${e}/status`,{skipAuth:!0})).data}async createIntent(e,t){return(await this.http.post(`payment/public/links/${e}/intent`,t,{skipAuth:!0})).data}async confirmPayment(e,t){return(await this.http.post(`payment/public/links/${e}/confirm`,t,{skipAuth:!0})).data}async createLink(e={}){return(await this.http.post("payment/links/free",e)).data}async cancelLink(e){return(await this.http.post(`payment/links/${e}/cancel`)).data}async listLinks(e={}){const t=new URLSearchParams;e.status&&t.set("status",e.status),void 0!==e.limit&&t.set("limit",String(e.limit)),void 0!==e.offset&&t.set("offset",String(e.offset));const r=t.toString(),s=r?`payment/links?${r}`:"payment/links";return(await this.http.get(s)).data}}const _="terms/documents",k="terms/signatures";class S{constructor(e){this.http=e}async getDocument(e){return(await this.http.get(`${_}/${e}`)).data.document}async getDocumentByGroup(e,t){const r=t?`?lang=${t}`:"";return(await this.http.get(`${_}/by-group/${e}${r}`)).data}async getDiffSummary(e,t,r){const s=new URLSearchParams({from_version_id:t});r&&s.append("lang",r);return(await this.http.get(`${_}/${e}/diff-summary?${s}`)).data}async sign(e){return(await this.http.post(k,e)).data.signature}async listSignatures(e){const t=E(e),r=t?`${k}?${t}`:k;return(await this.http.get(r)).data}async getSignature(e){return(await this.http.get(`${k}/${e}`)).data.signature}async getPendingDocuments(e){const t=E(e),r=t?`${k}/pending?${t}`:`${k}/pending`;return(await this.http.get(r)).data}async getCompliance(e){const t=e?`?geo_zone=${e}`:"";return(await this.http.get(`${k}/compliance${t}`)).data}async checkSignature(e){return(await this.http.get(`${k}/check/${e}`)).data}async getDocumentSignatureHistory(e){return(await this.http.get(`${k}/document/${e}/history`)).data}}function E(e){if(!e)return"";const t=new URLSearchParams;for(const[r,s]of Object.entries(e))null!=s&&t.append(r,String(s));return t.toString()}class T{constructor(e){const t=this.buildConfig(e);this.httpClient=new a(t),this.auth=new o(this.httpClient),this.user=new c(this.httpClient),this.system=new l(this.httpClient),this.apps=new h(this.httpClient),this.events=new d(this.httpClient,e.eventsConfig),this.publicApi=new p(this.httpClient),this.offers=new g(this.httpClient),this.pricing=new w(this.httpClient),this.booking=new m(this.httpClient),this.ledger=new y(this.httpClient),this.payment=new v(this.httpClient),this.terms=new S(this.httpClient)}buildConfig(e){var s,n,i;let a;if("string"==typeof e.environment){const s=t[e.environment];if(!s)throw r.configError(`Unknown environment: ${e.environment}`);a=s.url}else a=e.environment&&"object"==typeof e.environment?e.environment.url:t.production.url;if(!e.appId||"string"!=typeof e.appId)throw r.configError("appId is required and must be a string");return{baseUrl:a,appId:e.appId,bearerToken:e.bearerToken,appSecret:e.appSecret,timeout:(null===(s=e.config)||void 0===s?void 0:s.timeout)||3e4,customHeaders:(null===(n=e.config)||void 0===n?void 0:n.customHeaders)||{},debug:(null===(i=e.config)||void 0===i?void 0:i.debug)||!1}}setBearerToken(e){if(!e||"string"!=typeof e)throw r.configError("Bearer token must be a non-empty string");this.httpClient.setBearerToken(e),this.events.setBearerToken(e)}clearBearerToken(){this.httpClient.clearBearerToken(),this.events.setBearerToken(null)}setAppSecret(e){if(!e||"string"!=typeof e)throw r.configError("App secret must be a non-empty string");this.httpClient.setAppSecret(e)}clearAppSecret(){this.httpClient.clearAppSecret()}getConfig(){return{baseUrl:this.httpClient.config.baseUrl,appId:this.httpClient.config.appId,timeout:this.httpClient.config.timeout,customHeaders:{...this.httpClient.config.customHeaders},debug:this.httpClient.config.debug}}updateConfig(e){this.httpClient.updateConfig(e)}setDebug(e){this.httpClient.updateConfig({debug:e})}static forEnvironment(e,t,r){return new T({environment:e,appId:t,bearerToken:r})}static forProduction(e="default",t){return T.forEnvironment("production",e,t)}static forDevelopment(e="default",t){return T.forEnvironment("development",e,t)}static forStaging(e="default",t){return T.forEnvironment("staging",e,t)}async directRequest(e,t="GET",r,s){return this.httpClient.directRequest(e,t,r,s)}async get(e,t){return this.httpClient.get(e,t)}async post(e,t,r){return this.httpClient.post(e,t,r)}async put(e,t,r){return this.httpClient.put(e,t,r)}async patch(e,t,r){return this.httpClient.patch(e,t,r)}async delete(e,t){return this.httpClient.delete(e,t)}}function R(e){if(e)try{e()}catch(e){console.warn("[AuthUtils] Error clearing app-specific cache:",e)}try{localStorage.clear()}catch(e){}try{sessionStorage.clear()}catch(e){}try{document.cookie.split(";").forEach(e=>{const t=e.indexOf("="),r=t>-1?e.substr(0,t).trim():e.trim();document.cookie=`${r}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`,document.cookie=`${r}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;domain=${window.location.hostname}`,document.cookie=`${r}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;domain=.${window.location.hostname}`})}catch(e){}}function O(){window.history.pushState(null,"",window.location.href);const e=()=>{window.history.pushState(null,"",window.location.href)};window.addEventListener("popstate",e),setTimeout(()=>{window.removeEventListener("popstate",e)},5e3)}function $(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);n<s.length;n++)t.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(e,s[n])&&(r[s[n]]=e[s[n]])}return r}function A(e,t,r,s){return new(r||(r=Promise))(function(n,i){function a(e){try{c(s.next(e))}catch(e){i(e)}}function o(e){try{c(s.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(a,o)}c((s=s.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class I extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class C extends I{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class j extends I{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class P extends I{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var x;!function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"}(x||(x={}));class N{constructor(e,{headers:t={},customFetch:r,region:s=x.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return A(this,arguments,void 0,function*(e,t={}){var r;let s,n;try{const{headers:i,method:a,body:o,signal:c,timeout:l}=t;let h={},{region:u}=t;u||(u=this.region);const d=new URL(`${this.url}/${e}`);let p;u&&"any"!==u&&(h["x-region"]=u,d.searchParams.set("forceFunctionRegion",u)),o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)?"undefined"!=typeof Blob&&o instanceof Blob||o instanceof ArrayBuffer?(h["Content-Type"]="application/octet-stream",p=o):"string"==typeof o?(h["Content-Type"]="text/plain",p=o):"undefined"!=typeof FormData&&o instanceof FormData?p=o:(h["Content-Type"]="application/json",p=JSON.stringify(o)):p=!o||"string"==typeof o||"undefined"!=typeof Blob&&o instanceof Blob||o instanceof ArrayBuffer||"undefined"!=typeof FormData&&o instanceof FormData?o:JSON.stringify(o);let f=c;l&&(n=new AbortController,s=setTimeout(()=>n.abort(),l),c?(f=n.signal,c.addEventListener("abort",()=>n.abort())):f=n.signal);const g=yield this.fetch(d.toString(),{method:a||"POST",headers:Object.assign(Object.assign(Object.assign({},h),this.headers),i),body:p,signal:f}).catch(e=>{throw new C(e)}),w=g.headers.get("x-relay-error");if(w&&"true"===w)throw new j(g);if(!g.ok)throw new P(g);let m,y=(null!==(r=g.headers.get("Content-Type"))&&void 0!==r?r:"text/plain").split(";")[0].trim();return m="application/json"===y?yield g.json():"application/octet-stream"===y||"application/pdf"===y?yield g.blob():"text/event-stream"===y?g:"multipart/form-data"===y?yield g.formData():yield g.text(),{data:m,error:null,response:g}}catch(e){return{data:null,error:e,response:e instanceof P||e instanceof j?e.context:void 0}}finally{s&&clearTimeout(s)}})}}var U=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}},D=class{constructor(e){var t,r;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!==(t=e.shouldThrowOnError)&&void 0!==t&&t,this.signal=e.signal,this.isMaybeSingle=null!==(r=e.isMaybeSingle)&&void 0!==r&&r,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){var r=this;void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json");let s=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{let t=null,s=null,n=null,i=e.status,a=e.statusText;if(e.ok){var o,c;if("HEAD"!==r.method){var l;const t=await e.text();""===t||(s="text/csv"===r.headers.get("Accept")||r.headers.get("Accept")&&(null===(l=r.headers.get("Accept"))||void 0===l?void 0:l.includes("application/vnd.pgrst.plan+text"))?t:JSON.parse(t))}const h=null===(o=r.headers.get("Prefer"))||void 0===o?void 0:o.match(/count=(exact|planned|estimated)/),u=null===(c=e.headers.get("content-range"))||void 0===c?void 0:c.split("/");h&&u&&u.length>1&&(n=parseInt(u[1])),r.isMaybeSingle&&"GET"===r.method&&Array.isArray(s)&&(s.length>1?(t={code:"PGRST116",details:`Results contain ${s.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},s=null,n=null,i=406,a="Not Acceptable"):s=1===s.length?s[0]:null)}else{var h;const n=await e.text();try{t=JSON.parse(n),Array.isArray(t)&&404===e.status&&(s=[],t=null,i=200,a="OK")}catch(r){404===e.status&&""===n?(i=204,a="No Content"):t={message:n}}if(t&&r.isMaybeSingle&&(null==t||null===(h=t.details)||void 0===h?void 0:h.includes("0 rows"))&&(t=null,i=200,a="OK"),t&&r.shouldThrowOnError)throw new U(t)}return{error:t,data:s,count:n,status:i,statusText:a}});return this.shouldThrowOnError||(s=s.catch(e=>{var t;let r="";const s=null==e?void 0:e.cause;if(s){var n,i,a,o;const t=null!==(n=null==s?void 0:s.message)&&void 0!==n?n:"",c=null!==(i=null==s?void 0:s.code)&&void 0!==i?i:"";r=`${null!==(a=null==e?void 0:e.name)&&void 0!==a?a:"FetchError"}: ${null==e?void 0:e.message}`,r+=`\n\nCaused by: ${null!==(o=null==s?void 0:s.name)&&void 0!==o?o:"Error"}: ${t}`,c&&(r+=` (${c})`),(null==s?void 0:s.stack)&&(r+=`\n${s.stack}`)}else{var c;r=null!==(c=null==e?void 0:e.stack)&&void 0!==c?c:""}return{error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:r,hint:"",code:""},data:null,count:null,status:0,statusText:""}})),s.then(e,t)}returns(){return this}overrideTypes(){return this}},L=class extends D{select(e){let t=!1;const r=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){const i=n?`${n}.order`:"order",a=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){const s=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:s=r}={}){const n=void 0===s?"offset":`${s}.offset`,i=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(i,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return"GET"===this.method?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:n=!1,format:i="text"}={}){var a;const o=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),c=null!==(a=this.headers.get("Accept"))&&void 0!==a?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${c}"; options=${o};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};const B=new RegExp("[,()]");var q=class extends L{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){const r=Array.from(new Set(t)).map(e=>"string"==typeof e&&B.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){const r=Array.from(new Set(t)).map(e=>"string"==typeof e&&B.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`not.in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let n="";"plain"===s?n="pl":"phrase"===s?n="ph":"websearch"===s&&(n="w");const i=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${i}.${t}`),this}match(e){return Object.entries(e).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}},M=class{constructor(e,{headers:t={},schema:r,fetch:s}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){const{head:r=!1,count:s}=null!=t?t:{},n=r?"HEAD":"GET";let i=!1;const a=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!i?"":('"'===e&&(i=!i),e)).join(""),{url:o,headers:c}=this.cloneRequestState();return o.searchParams.set("select",a),s&&c.append("Prefer",`count=${s}`),new q({method:n,url:o,headers:c,schema:this.schema,fetch:this.fetch})}insert(e,{count:t,defaultToNull:r=!0}={}){var s;const{url:n,headers:i}=this.cloneRequestState();if(t&&i.append("Prefer",`count=${t}`),r||i.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);n.searchParams.set("columns",e.join(","))}}return new q({method:"POST",url:n,headers:i,schema:this.schema,body:e,fetch:null!==(s=this.fetch)&&void 0!==s?s:fetch})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){var i;const{url:a,headers:o}=this.cloneRequestState();if(o.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&a.searchParams.set("on_conflict",t),s&&o.append("Prefer",`count=${s}`),n||o.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);a.searchParams.set("columns",e.join(","))}}return new q({method:"POST",url:a,headers:o,schema:this.schema,body:e,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch})}update(e,{count:t}={}){var r;const{url:s,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new q({method:"PATCH",url:s,headers:n,schema:this.schema,body:e,fetch:null!==(r=this.fetch)&&void 0!==r?r:fetch})}delete({count:e}={}){var t;const{url:r,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new q({method:"DELETE",url:r,headers:s,schema:this.schema,fetch:null!==(t=this.fetch)&&void 0!==t?t:fetch})}},W=class e{constructor(e,{headers:t={},schema:r,fetch:s}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.fetch=s}from(e){if(!e||"string"!=typeof e||""===e.trim())throw new Error("Invalid relation name: relation must be a non-empty string.");return new M(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:s=!1,count:n}={}){var i;let a;const o=new URL(`${this.url}/rpc/${e}`);let c;const l=e=>null!==e&&"object"==typeof e&&(!Array.isArray(e)||e.some(l)),h=r&&Object.values(t).some(l);h?(a="POST",c=t):r||s?(a=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{o.searchParams.append(e,t)})):(a="POST",c=t);const u=new Headers(this.headers);return h?u.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&u.set("Prefer",`count=${n}`),new q({method:a,url:o,headers:u,schema:this.schemaName,body:c,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch})}};class K{constructor(){}static detectEnvironment(){var e;if("undefined"!=typeof WebSocket)return{type:"native",constructor:WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocket)return{type:"native",constructor:globalThis.WebSocket};if("undefined"!=typeof global&&void 0!==global.WebSocket)return{type:"native",constructor:global.WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("undefined"!=typeof globalThis&&globalThis.EdgeRuntime||"undefined"!=typeof navigator&&(null===(e=navigator.userAgent)||void 0===e?void 0:e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const t=globalThis.process;if(t){const e=t.versions;if(e&&e.node){const t=e.node,r=parseInt(t.replace(/^v/,"").split(".")[0]);return r>=22?void 0!==globalThis.WebSocket?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${r} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${r} detected without native WebSocket support.`,workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}}const J="2.0.0",H=J,V=1e4;var F,G,z,Y,X,Q;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(F||(F={})),function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"}(G||(G={})),function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"}(z||(z={})),function(e){e.websocket="websocket"}(Y||(Y={})),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(X||(X={}));class Z{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=null!=e?e:[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&"string"==typeof e.payload.event)return t(this._binaryEncodeUserBroadcastPush(e));let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer(null===(t=e.payload)||void 0===t?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;const s=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(e){var t,r;const s=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:{},n=(new TextEncoder).encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,n)}_encodeUserBroadcastPush(e,t,r){var s,n;const i=e.topic,a=null!==(s=e.ref)&&void 0!==s?s:"",o=null!==(n=e.join_ref)&&void 0!==n?n:"",c=e.payload.event,l=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},h=0===Object.keys(l).length?"":JSON.stringify(l);if(o.length>255)throw new Error(`joinRef length ${o.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`metadata length ${h.length} exceeds maximum of 255`);const u=this.USER_BROADCAST_PUSH_META_LENGTH+o.length+a.length+i.length+c.length+h.length,d=new ArrayBuffer(this.HEADER_LENGTH+u);let p=new DataView(d),f=0;p.setUint8(f++,this.KINDS.userBroadcastPush),p.setUint8(f++,o.length),p.setUint8(f++,a.length),p.setUint8(f++,i.length),p.setUint8(f++,c.length),p.setUint8(f++,h.length),p.setUint8(f++,t),Array.from(o,e=>p.setUint8(f++,e.charCodeAt(0))),Array.from(a,e=>p.setUint8(f++,e.charCodeAt(0))),Array.from(i,e=>p.setUint8(f++,e.charCodeAt(0))),Array.from(c,e=>p.setUint8(f++,e.charCodeAt(0))),Array.from(h,e=>p.setUint8(f++,e.charCodeAt(0)));var g=new Uint8Array(d.byteLength+r.byteLength);return g.set(new Uint8Array(d),0),g.set(new Uint8Array(r),d.byteLength),g.buffer}decode(e,t){if(this._isArrayBuffer(e)){return t(this._binaryDecode(e))}if("string"==typeof e){const r=JSON.parse(e),[s,n,i,a,o]=r;return t({join_ref:s,ref:n,topic:i,event:a,payload:o})}return t({})}_binaryDecode(e){const t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;if(r===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,s)}_decodeUserBroadcast(e,t,r){const s=t.getUint8(1),n=t.getUint8(2),i=t.getUint8(3),a=t.getUint8(4);let o=this.HEADER_LENGTH+4;const c=r.decode(e.slice(o,o+s));o+=s;const l=r.decode(e.slice(o,o+n));o+=n;const h=r.decode(e.slice(o,o+i));o+=i;const u=e.slice(o,e.byteLength),d=a===this.JSON_ENCODING?JSON.parse(r.decode(u)):u,p={type:this.BROADCAST_EVENT,event:l,payload:d};return i>0&&(p.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||"ArrayBuffer"===(null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e))):{}}}class ee{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}!function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"}(Q||(Q={}));const te=(e,t,r={})=>{var s;const n=null!==(s=r.skipTypes)&&void 0!==s?s:[];return t?Object.keys(t).reduce((r,s)=>(r[s]=re(s,e,t,n),r),{}):{}},re=(e,t,r,s)=>{const n=t.find(t=>t.name===e),i=null==n?void 0:n.type,a=r[e];return i&&!s.includes(i)?se(i,a):ne(a)},se=(e,t)=>{if("_"===e.charAt(0)){const r=e.slice(1,e.length);return ce(t,r)}switch(e){case Q.bool:return ie(t);case Q.float4:case Q.float8:case Q.int2:case Q.int4:case Q.int8:case Q.numeric:case Q.oid:return ae(t);case Q.json:case Q.jsonb:return oe(t);case Q.timestamp:return le(t);case Q.abstime:case Q.date:case Q.daterange:case Q.int4range:case Q.int8range:case Q.money:case Q.reltime:case Q.text:case Q.time:case Q.timestamptz:case Q.timetz:case Q.tsrange:case Q.tstzrange:default:return ne(t)}},ne=e=>e,ie=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},ae=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},oe=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return e}return e},ce=(e,t)=>{if("string"!=typeof e)return e;const r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s;const n=e.slice(1,r);try{s=JSON.parse("["+n+"]")}catch(e){s=n?n.split(","):[]}return s.map(e=>se(t,e))}return e},le=e=>"string"==typeof e?e.replace(" ","T"):e,he=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};class ue{constructor(e,t,r={},s=1e4){this.channel=e,this.event=t,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t(null===(r=this.receivedResp)||void 0===r?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);this.channel._on(this.refEvent,{},e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var de,pe,fe,ge;!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(de||(de={}));class we{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},e=>{const{onJoin:t,onLeave:r,onSync:s}=this.caller;this.joinRef=this.channel._joinRef(),this.state=we.syncState(this.state,e,t,r),this.pendingDiffs.forEach(e=>{this.state=we.syncDiff(this.state,e,t,r)}),this.pendingDiffs=[],s()}),this.channel._on(r.diff,{},e=>{const{onJoin:t,onLeave:r,onSync:s}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=we.syncDiff(this.state,e,t,r),s())}),this.onJoin((e,t,r)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:r})}),this.onLeave((e,t,r)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:r})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,s){const n=this.cloneDeep(e),i=this.transformState(t),a={},o={};return this.map(n,(e,t)=>{i[e]||(o[e]=t)}),this.map(i,(e,t)=>{const r=n[e];if(r){const s=t.map(e=>e.presence_ref),n=r.map(e=>e.presence_ref),i=t.filter(e=>n.indexOf(e.presence_ref)<0),c=r.filter(e=>s.indexOf(e.presence_ref)<0);i.length>0&&(a[e]=i),c.length>0&&(o[e]=c)}else a[e]=t}),this.syncDiff(n,{joins:a,leaves:o},r,s)}static syncDiff(e,t,r,s){const{joins:n,leaves:i}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(n,(t,s)=>{var n;const i=null!==(n=e[t])&&void 0!==n?n:[];if(e[t]=this.cloneDeep(s),i.length>0){const r=e[t].map(e=>e.presence_ref),s=i.filter(e=>r.indexOf(e.presence_ref)<0);e[t].unshift(...s)}r(t,i,s)}),this.map(i,(t,r)=>{let n=e[t];if(!n)return;const i=r.map(e=>e.presence_ref);n=n.filter(e=>i.indexOf(e.presence_ref)<0),e[t]=n,s(t,n,r),0===n.length&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{const s=e[r];return t[r]="metas"in s?s.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):s,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}!function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(pe||(pe={})),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"}(fe||(fe={})),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(ge||(ge={}));class me{constructor(e,t={config:{}},r){var s,n;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=G.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new ue(this,z.join,this.params,this.timeout),this.rejoinTimer=new ee(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=G.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=G.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=G.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=G.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=G.errored,this.rejoinTimer.scheduleTimeout())}),this._on(z.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new we(this),this.broadcastEndpointURL=he(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(null===(n=null===(s=this.params.config)||void 0===s?void 0:s.broadcast)||void 0===n?void 0:n.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var r,s,n;if(this.socket.isConnected()||this.socket.connect(),this.state==G.closed){const{config:{broadcast:i,presence:a,private:o}}=this.params,c=null!==(s=null===(r=this.bindings.postgres_changes)||void 0===r?void 0:r.map(e=>e.filter))&&void 0!==s?s:[],l=!!this.bindings[fe.PRESENCE]&&this.bindings[fe.PRESENCE].length>0||!0===(null===(n=this.params.config.presence)||void 0===n?void 0:n.enabled),h={},u={broadcast:i,presence:Object.assign(Object.assign({},a),{enabled:l}),postgres_changes:c,private:o};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(t=>null==e?void 0:e(ge.CHANNEL_ERROR,t)),this._onClose(()=>null==e?void 0:e(ge.CLOSED)),this.updateJoinPayload(Object.assign({config:u},h)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:t})=>{var r;if(this.socket._isManualToken()||this.socket.setAuth(),void 0!==t){const s=this.bindings.postgres_changes,n=null!==(r=null==s?void 0:s.length)&&void 0!==r?r:0,i=[];for(let r=0;r<n;r++){const n=s[r],{filter:{event:a,schema:o,table:c,filter:l}}=n,h=t&&t[r];if(!(h&&h.event===a&&me.isFilterValueEqual(h.schema,o)&&me.isFilterValueEqual(h.table,c)&&me.isFilterValueEqual(h.filter,l)))return this.unsubscribe(),this.state=G.errored,void(null==e||e(ge.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes")));i.push(Object.assign(Object.assign({},n),{id:h.id}))}return this.bindings.postgres_changes=i,void(e&&e(ge.SUBSCRIBED))}null==e||e(ge.SUBSCRIBED)}).receive("error",t=>{this.state=G.errored,null==e||e(ge.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(ge.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this.state===G.joined&&e===fe.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,t,r)}async httpSend(e,t,r={}){var s;if(null==t)return Promise.reject("Payload is required for httpSend()");const n={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(n.Authorization=`Bearer ${this.socket.accessTokenValue}`);const i={method:"POST",headers:n,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,i,null!==(s=r.timeout)&&void 0!==s?s:this.timeout);if(202===a.status)return{success:!0};let o=a.statusText;try{const e=await a.json();o=e.error||e.message||o}catch(e){}return Promise.reject(new Error(o))}async send(e,t={}){var r,s;if(this._canPush()||"broadcast"!==e.type)return new Promise(r=>{var s,n,i;const a=this._push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null===(i=null===(n=null===(s=this.params)||void 0===s?void 0:s.config)||void 0===n?void 0:n.broadcast)||void 0===i?void 0:i.ack)||r("ok"),a.receive("ok",()=>r("ok")),a.receive("error",()=>r("error")),a.receive("timeout",()=>r("timed out"))});{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:n,payload:i}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);const o={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:i,private:this.private}]})};try{const e=await this._fetchWithTimeout(this.broadcastEndpointURL,o,null!==(r=t.timeout)&&void 0!==r?r:this.timeout);return await(null===(s=e.body)||void 0===s?void 0:s.cancel()),e.ok?"ok":"error"}catch(e){return"AbortError"===e.name?"timed out":"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=G.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(z.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(s=>{r=new ue(this,z.leave,{},e),r.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{null==r||r.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=G.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){const s=new AbortController,n=setTimeout(()=>s.abort(),r),i=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(n),i}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new ue(this,e,t,r);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>100){const e=this.pushBuffer.shift();e&&(e.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload))}}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var s,n;const i=e.toLocaleLowerCase(),{close:a,error:o,leave:c,join:l}=z;if(r&&[a,o,c,l].indexOf(i)>=0&&r!==this._joinRef())return;let h=this._onMessage(i,t,r);if(t&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(i)?null===(s=this.bindings.postgres_changes)||void 0===s||s.filter(e=>{var t,r,s;return"*"===(null===(t=e.filter)||void 0===t?void 0:t.event)||(null===(s=null===(r=e.filter)||void 0===r?void 0:r.event)||void 0===s?void 0:s.toLocaleLowerCase())===i}).map(e=>e.callback(h,r)):null===(n=this.bindings[i])||void 0===n||n.filter(e=>{var r,s,n,a,o,c,l,h;if(["broadcast","presence","postgres_changes"].includes(i)){if("id"in e){const i=e.id,c=null===(r=e.filter)||void 0===r?void 0:r.event;return i&&(null===(s=t.ids)||void 0===s?void 0:s.includes(i))&&("*"===c||(null==c?void 0:c.toLocaleLowerCase())===(null===(n=t.data)||void 0===n?void 0:n.type.toLocaleLowerCase()))&&(!(null===(a=e.filter)||void 0===a?void 0:a.table)||e.filter.table===(null===(o=t.data)||void 0===o?void 0:o.table))}{const r=null===(l=null===(c=null==e?void 0:e.filter)||void 0===c?void 0:c.event)||void 0===l?void 0:l.toLocaleLowerCase();return"*"===r||r===(null===(h=null==t?void 0:t.event)||void 0===h?void 0:h.toLocaleLowerCase())}}return e.type.toLocaleLowerCase()===i}).map(e=>{if("object"==typeof h&&"ids"in h){const e=h.data,{schema:t,table:r,commit_timestamp:s,type:n,errors:i}=e,a={schema:t,table:r,commit_timestamp:s,eventType:n,new:{},old:{},errors:i};h=Object.assign(Object.assign({},a),this._getPayloadRecords(e))}e.callback(h,r)})}_isClosed(){return this.state===G.closed}_isJoined(){return this.state===G.joined}_isJoining(){return this.state===G.joining}_isLeaving(){return this.state===G.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const s=e.toLocaleLowerCase(),n={type:s,filter:t,callback:r};return this.bindings[s]?this.bindings[s].push(n):this.bindings[s]=[n],this}_off(e,t){const r=e.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(e=>{var s;return!((null===(s=e.type)||void 0===s?void 0:s.toLocaleLowerCase())===r&&me.isEqual(e.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}static isFilterValueEqual(e,t){return(null!=e?e:void 0)===(null!=t?t:void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(z.close,{},e)}_onError(e){this._on(z.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=G.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=te(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=te(e.columns,e.old_record)),t}}const ye=()=>{},be=25e3,ve=10,_e=100,ke=[1e3,2e3,5e3,1e4];class Se{constructor(e,t){var r;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=V,this.transport=null,this.heartbeatIntervalMs=be,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=ye,this.ref=0,this.reconnectTimer=null,this.vsn=H,this.logger=ye,this.conn=null,this.sendBuffer=[],this.serializer=new Z,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!(null===(r=null==t?void 0:t.params)||void 0===r?void 0:r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${Y.websocket}`,this.httpEndpoint=he(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||null!==this.conn&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=K.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;if(t.includes("Node.js"))throw new Error(`${t}\n\nTo use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n npm install ws\n\n import ws from "ws"\n const client = new RealtimeClient(url, {\n ...options,\n transport: ws\n })`);throw new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const r=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(r),this._setConnectionState("disconnected")},"function"==typeof this.conn.close&&(e?this.conn.close(e,null!=t?t:""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case F.connecting:return X.Connecting;case F.open:return X.Open;case F.closing:return X.Closing;default:return X.Closed}}isConnected(){return this.connectionState()===X.Open}isConnecting(){return"connecting"===this._connectionState}isDisconnecting(){return"disconnecting"===this._connectionState}channel(e,t={config:{}}){const r=`realtime:${e}`,s=this.getChannels().find(e=>e.topic===r);if(s)return s;{const r=new me(`realtime:${e}`,t,this);return this.channels.push(r),r}}push(e){const{topic:t,event:r,payload:s,ref:n}=e,i=()=>{this.encode(e,e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)})};this.log("push",`${t} ${r} (${n})`,s),this.isConnected()?i():this.sendBuffer.push(i)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}return this._wasManualDisconnect=!1,null===(e=this.conn)||void 0===e||e.close(1e3,"heartbeat timeout"),void setTimeout(()=>{var e;this.isConnected()||null===(e=this.reconnectTimer)||void 0===e||e.scheduleTimeout()},_e)}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this._setAuthSafely("heartbeat")}else try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}}onHeartbeat(e){this.heartbeatCallback=e}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(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,e=>{if("phoenix"===e.topic&&"phx_reply"===e.event&&e.ref&&e.ref===this.pendingHeartbeatRef){const t=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback("ok"===e.payload.status?"ok":"error",t)}catch(e){this.log("error","error in heartbeat callback",e)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}const{topic:t,event:r,payload:s,ref:n}=e,i=n?`(${n})`:"",a=s.status||"";this.log("receive",`${a} ${t} ${r} ${i}`.trim(),s),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(r,s,n)),this._triggerStateCallbacks("message",e)})}_clearTimer(e){var t;"heartbeat"===e&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):"reconnect"===e&&(null===(t=this.reconnectTimer)||void 0===t||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in 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),this.conn.readyState===F.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===F.open||this.conn.readyState===F.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`);(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(e=>{this.log("error","error waiting for auth on connect",e),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this._terminateWorker()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||null===(t=this.reconnectTimer)||void 0===t||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(z.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const r=e.match(/\?/)?"&":"?";return`${e}${r}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{const e=new Blob(['\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_setConnectionState(e,t=!1){this._connectionState=e,"connecting"===e?this._wasManualDisconnect=!1:"disconnecting"===e&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t,r=!1;if(e)t=e,r=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(e){this.log("error","Error fetching access token from callback",e),t=this.accessTokenValue}else t=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{const r={access_token:t,version:"realtime-js/2.91.0"};t&&e.updateJoinPayload(r),e.joinedOnce&&e._isJoined()&&e._push(z.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(t=>{this.log("error",`Error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(r=>{try{r(t)}catch(t){this.log("error",`error in ${e} callback`,t)}})}catch(t){this.log("error",`error triggering ${e} callbacks`,t)}}_setupReconnectionTimer(){this.reconnectTimer=new ee(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},ve)},this.reconnectAfterMs)}_initializeOptions(e){var t,r,s,n,i,a,o,c,l,h,u,d;switch(this.transport=null!==(t=null==e?void 0:e.transport)&&void 0!==t?t:null,this.timeout=null!==(r=null==e?void 0:e.timeout)&&void 0!==r?r:V,this.heartbeatIntervalMs=null!==(s=null==e?void 0:e.heartbeatIntervalMs)&&void 0!==s?s:be,this.worker=null!==(n=null==e?void 0:e.worker)&&void 0!==n&&n,this.accessToken=null!==(i=null==e?void 0:e.accessToken)&&void 0!==i?i:null,this.heartbeatCallback=null!==(a=null==e?void 0:e.heartbeatCallback)&&void 0!==a?a:ye,this.vsn=null!==(o=null==e?void 0:e.vsn)&&void 0!==o?o:H,(null==e?void 0:e.params)&&(this.params=e.params),(null==e?void 0:e.logger)&&(this.logger=e.logger),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=null!==(c=null==e?void 0:e.reconnectAfterMs)&&void 0!==c?c:e=>ke[e-1]||1e4,this.vsn){case"1.0.0":this.encode=null!==(l=null==e?void 0:e.encode)&&void 0!==l?l:(e,t)=>t(JSON.stringify(e)),this.decode=null!==(h=null==e?void 0:e.decode)&&void 0!==h?h:(e,t)=>t(JSON.parse(e));break;case J:this.encode=null!==(u=null==e?void 0:e.encode)&&void 0!==u?u:this.serializer.encode.bind(this.serializer),this.decode=null!==(d=null==e?void 0:e.decode)&&void 0!==d?d:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if("undefined"!=typeof window&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl}}}var Ee=class extends Error{constructor(e,t){super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown="CommitStateUnknownException"===t.icebergType||[500,502,504].includes(t.status)&&!0===t.icebergType?.includes("CommitState")}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};function Te(e){const t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:a}){const o=function(e,t,r){const s=new URL(t,e);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&s.searchParams.set(e,t);return s.toString()}(e.baseUrl,s,n),c=await async function(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:`Bearer ${e.token}`}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}(e.auth),l=await t(o,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...c,...a},body:i?JSON.stringify(i):void 0}),h=await l.text(),u=(l.headers.get("content-type")||"").includes("application/json"),d=u&&h?JSON.parse(h):h;if(!l.ok){const e=u?d:void 0,t=e?.error;throw new Ee(t?.message??`Request failed with status ${l.status}`,{status:l.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:l.status,headers:l.headers,data:d}}}}function Re(e){return e.join("")}var Oe=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){const t=e?{parent:Re(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){const r={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Re(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Re(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Re(e.namespace)}`}),!0}catch(e){if(e instanceof Ee&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof Ee&&409===e.status)return;throw e}}};function $e(e){return e.join("")}var Ae=class{constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${$e(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){const r={};this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${$e(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${$e(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${$e(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${$e(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${$e(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof Ee&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof Ee&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},Ie=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=Te({baseUrl:r,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new Oe(this.client,t),this.tableOps=new Ae(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}},Ce=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function je(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}var Pe=class extends Ce{constructor(e,t,r){super(e),this.name="StorageApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},xe=class extends Ce{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};const Ne=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Ue=e=>{if(Array.isArray(e))return e.map(e=>Ue(e));if("function"==typeof e||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([e,r])=>{const s=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""));t[s]=Ue(r)}),t};function De(e){return(De="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function Le(e){var t=function(e,t){if("object"!=De(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=De(s))return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==De(t)?t:t+""}function Be(e,t,r){return(t=Le(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function qe(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function Me(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?qe(Object(r),!0).forEach(function(t){Be(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):qe(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}const We=e=>{var t;return e.msg||e.message||e.error_description||("string"==typeof e.error?e.error:null===(t=e.error)||void 0===t?void 0:t.message)||JSON.stringify(e)},Ke=async(e,t,r)=>{e instanceof await Response&&!(null==r?void 0:r.noResolveJson)?e.json().then(r=>{const s=e.status||500,n=(null==r?void 0:r.statusCode)||s+"";t(new Pe(We(r),s,n))}).catch(e=>{t(new xe(We(e),e))}):t(new xe(We(e),e))},Je=(e,t,r,s)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&s?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(s)?(n.headers=Me({"Content-Type":"application/json"},null==t?void 0:t.headers),n.body=JSON.stringify(s)):n.body=s,(null==t?void 0:t.duplex)&&(n.duplex=t.duplex),Me(Me({},n),r)):n};async function He(e,t,r,s,n,i){return new Promise((a,o)=>{e(r,Je(t,s,n,i)).then(e=>{if(!e.ok)throw e;return(null==s?void 0:s.noResolveJson)?e:e.json()}).then(e=>a(e)).catch(e=>Ke(e,o,s))})}async function Ve(e,t,r,s){return He(e,"GET",t,r,s)}async function Fe(e,t,r,s,n){return He(e,"POST",t,s,n,r)}async function Ge(e,t,r,s,n){return He(e,"PUT",t,s,n,r)}async function ze(e,t,r,s,n){return He(e,"DELETE",t,s,n,r)}var Ye=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}};let Xe;Xe=Symbol.toStringTag;var Qe=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[Xe]="BlobDownloadBuilder",this.promise=null}asStream(){return new Ye(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:await(await this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}};const Ze={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},et={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var tt=class{constructor(e,t={},r,s){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=r,this.fetch=Ne(s)}throwOnError(){return this.shouldThrowOnError=!0,this}async uploadOrUpdate(e,t,r,s){var n=this;try{let i;const a=Me(Me({},et),s);let o=Me(Me({},n.headers),"POST"===e&&{"x-upsert":String(a.upsert)});const c=a.metadata;"undefined"!=typeof Blob&&r instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),c&&i.append("metadata",n.encodeMetadata(c)),i.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",a.cacheControl),c&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(c))):(i=r,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,c&&(o["x-metadata"]=n.toBase64(n.encodeMetadata(c))),("undefined"!=typeof ReadableStream&&i instanceof ReadableStream||i&&"object"==typeof i&&"pipe"in i&&"function"==typeof i.pipe)&&!a.duplex&&(a.duplex="half")),(null==s?void 0:s.headers)&&(o=Me(Me({},o),s.headers));const l=n._removeEmptyFolders(t),h=n._getFinalPath(l),u=await("PUT"==e?Ge:Fe)(n.fetch,`${n.url}/object/${h}`,i,Me({headers:o},(null==a?void 0:a.duplex)?{duplex:a.duplex}:{}));return{data:{path:l,id:u.Id,fullPath:u.Key},error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,s){var n=this;const i=n._removeEmptyFolders(e),a=n._getFinalPath(i),o=new URL(n.url+`/object/upload/sign/${a}`);o.searchParams.set("token",t);try{let e;const t=Me({upsert:et.upsert},s),a=Me(Me({},n.headers),{"x-upsert":String(t.upsert)});return"undefined"!=typeof Blob&&r instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),e.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(e=r,e.append("cacheControl",t.cacheControl)):(e=r,a["cache-control"]=`max-age=${t.cacheControl}`,a["content-type"]=t.contentType),{data:{path:i,fullPath:(await Ge(n.fetch,o.toString(),e,{headers:a})).Key},error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}async createSignedUploadUrl(e,t){var r=this;try{let s=r._getFinalPath(e);const n=Me({},r.headers);(null==t?void 0:t.upsert)&&(n["x-upsert"]="true");const i=await Fe(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),a=new URL(r.url+i.url),o=a.searchParams.get("token");if(!o)throw new Ce("No token returned by API");return{data:{signedUrl:a.toString(),path:e,token:o},error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var s=this;try{return{data:await Fe(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers}),error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}async copy(e,t,r){var s=this;try{return{data:{path:(await Fe(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers})).Key},error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}async createSignedUrl(e,t,r){var s=this;try{let n=s._getFinalPath(e),i=await Fe(s.fetch,`${s.url}/object/sign/${n}`,Me({expiresIn:t},(null==r?void 0:r.transform)?{transform:r.transform}:{}),{headers:s.headers});const a=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return i={signedUrl:encodeURI(`${s.url}${i.signedURL}${a}`)},{data:i,error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}async createSignedUrls(e,t,r){var s=this;try{const n=await Fe(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:t,paths:e},{headers:s.headers}),i=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return{data:n.map(e=>Me(Me({},e),{},{signedUrl:e.signedURL?encodeURI(`${s.url}${e.signedURL}${i}`):null})),error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}download(e,t){const r=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",s=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),n=s?`?${s}`:"",i=this._getFinalPath(e);return new Qe(()=>Ve(this.fetch,`${this.url}/${r}/${i}${n}`,{headers:this.headers,noResolveJson:!0}),this.shouldThrowOnError)}async info(e){var t=this;const r=t._getFinalPath(e);try{return{data:Ue(await Ve(t.fetch,`${t.url}/object/info/${r}`,{headers:t.headers})),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}async exists(e){var t=this;const r=t._getFinalPath(e);try{return await async function(e,t,r,s){return He(e,"HEAD",t,Me(Me({},r),{},{noResolveJson:!0}),s)}(t.fetch,`${t.url}/object/${r}`,{headers:t.headers}),{data:!0,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(je(e)&&e instanceof xe){const t=e.originalError;if([400,404].includes(null==t?void 0:t.status))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){const r=this._getFinalPath(e),s=[],n=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==n&&s.push(n);const i=void 0!==(null==t?void 0:t.transform)?"render/image":"object",a=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==a&&s.push(a);let o=s.join("&");return""!==o&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}${o}`)}}}async remove(e){var t=this;try{return{data:await ze(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}async list(e,t,r){var s=this;try{const n=Me(Me(Me({},Ze),t),{},{prefix:e||""});return{data:await Fe(s.fetch,`${s.url}/object/list/${s.bucketId}`,n,{headers:s.headers},r),error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}async listV2(e,t){var r=this;try{const s=Me({},e);return{data:await Fe(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},t),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const 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("&")}};const rt="2.91.0",st={"X-Client-Info":`storage-js/${rt}`};var nt=class{constructor(e,t={},r,s){this.shouldThrowOnError=!1;const n=new URL(e);(null==s?void 0:s.useNewHostname)&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase.")),this.url=n.href.replace(/\/$/,""),this.headers=Me(Me({},st),t),this.fetch=Ne(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async listBuckets(e){var t=this;try{const r=t.listBucketOptionsToQueryString(e);return{data:await Ve(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}async getBucket(e){var t=this;try{return{data:await Ve(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}async createBucket(e,t={public:!1}){var r=this;try{return{data:await Fe(r.fetch,`${r.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}async updateBucket(e,t){var r=this;try{return{data:await Ge(r.fetch,`${r.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}async emptyBucket(e){var t=this;try{return{data:await Fe(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await ze(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},it=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Me(Me({},st),t),this.fetch=Ne(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(e){var t=this;try{return{data:await Fe(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}async listBuckets(e){var t=this;try{const r=new URLSearchParams;void 0!==(null==e?void 0:e.limit)&&r.set("limit",e.limit.toString()),void 0!==(null==e?void 0:e.offset)&&r.set("offset",e.offset.toString()),(null==e?void 0:e.sortColumn)&&r.set("sortColumn",e.sortColumn),(null==e?void 0:e.sortOrder)&&r.set("sortOrder",e.sortOrder),(null==e?void 0:e.search)&&r.set("search",e.search);const s=r.toString(),n=s?`${t.url}/bucket?${s}`:`${t.url}/bucket`;return{data:await Ve(t.fetch,n,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await ze(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(je(e))return{data:null,error:e};throw e}}from(e){var t=this;if(!(e=>!(!e||"string"!=typeof e)&&!(0===e.length||e.length>100)&&e.trim()===e&&!e.includes("/")&&!e.includes("\\")&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e))(e))throw new Ce("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new Ie({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(e,t){const r=e[t];return"function"!=typeof r?r:async(...t)=>{try{return{data:await r.apply(e,t),error:null}}catch(e){if(s)throw e;return{data:null,error:e}}}}})}};const at={"X-Client-Info":`storage-js/${rt}`,"Content-Type":"application/json"};var ot=class extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}};function ct(e){return"object"==typeof e&&null!==e&&"__isStorageVectorsError"in e}var lt=class extends ot{constructor(e,t,r){super(e),this.name="StorageVectorsApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},ht=class extends ot{constructor(e,t){super(e),this.name="StorageVectorsUnknownError",this.originalError=t}};const ut=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),dt=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),pt=(e,t,r,s)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&s?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(s)?(n.headers=Me({"Content-Type":"application/json"},null==t?void 0:t.headers),n.body=JSON.stringify(s)):n.body=s,Me(Me({},n),r)):n};async function ft(e,t,r,s,n,i){return new Promise((a,o)=>{e(r,pt(t,s,n,i)).then(e=>{if(!e.ok)throw e;if(null==s?void 0:s.noResolveJson)return e;const t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():{}}).then(e=>a(e)).catch(e=>(async(e,t,r)=>{if(e&&"object"==typeof e&&"status"in e&&"ok"in e&&"number"==typeof e.status&&!(null==r?void 0:r.noResolveJson)){const r=e.status||500,s=e;if("function"==typeof s.json)s.json().then(e=>{const s=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||r+"";t(new lt(dt(e),r,s))}).catch(()=>{const e=r+"";t(new lt(s.statusText||`HTTP ${r} error`,r,e))});else{const e=r+"";t(new lt(s.statusText||`HTTP ${r} error`,r,e))}}else t(new ht(dt(e),e))})(e,o,s))})}async function gt(e,t,r,s,n){return ft(e,"POST",t,s,n,r)}var wt=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Me(Me({},at),t),this.fetch=ut(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createIndex(e){var t=this;try{return{data:await gt(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ct(e))return{data:null,error:e};throw e}}async getIndex(e,t){var r=this;try{return{data:await gt(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(ct(e))return{data:null,error:e};throw e}}async listIndexes(e){var t=this;try{return{data:await gt(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ct(e))return{data:null,error:e};throw e}}async deleteIndex(e,t){var r=this;try{return{data:await gt(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{},error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(ct(e))return{data:null,error:e};throw e}}},mt=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Me(Me({},at),t),this.fetch=ut(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async putVectors(e){var t=this;try{if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return{data:await gt(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ct(e))return{data:null,error:e};throw e}}async getVectors(e){var t=this;try{return{data:await gt(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ct(e))return{data:null,error:e};throw e}}async listVectors(e){var t=this;try{if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error("segmentIndex must be between 0 and "+(e.segmentCount-1))}return{data:await gt(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ct(e))return{data:null,error:e};throw e}}async queryVectors(e){var t=this;try{return{data:await gt(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ct(e))return{data:null,error:e};throw e}}async deleteVectors(e){var t=this;try{if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return{data:await gt(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ct(e))return{data:null,error:e};throw e}}},yt=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Me(Me({},at),t),this.fetch=ut(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(e){var t=this;try{return{data:await gt(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ct(e))return{data:null,error:e};throw e}}async getBucket(e){var t=this;try{return{data:await gt(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ct(e))return{data:null,error:e};throw e}}async listBuckets(e={}){var t=this;try{return{data:await gt(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ct(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await gt(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(ct(e))return{data:null,error:e};throw e}}},bt=class extends yt{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new vt(this.url,this.headers,e,this.fetch)}async createBucket(e){return(()=>super.createBucket)().call(this,e)}async getBucket(e){return(()=>super.getBucket)().call(this,e)}async listBuckets(e={}){return(()=>super.listBuckets)().call(this,e)}async deleteBucket(e){return(()=>super.deleteBucket)().call(this,e)}},vt=class extends wt{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}async createIndex(e){return(()=>super.createIndex)().call(this,Me(Me({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(e={}){return(()=>super.listIndexes)().call(this,Me(Me({},e),{},{vectorBucketName:this.vectorBucketName}))}async getIndex(e){return(()=>super.getIndex)().call(this,this.vectorBucketName,e)}async deleteIndex(e){return(()=>super.deleteIndex)().call(this,this.vectorBucketName,e)}index(e){return new _t(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},_t=class extends mt{constructor(e,t,r,s,n){super(e,t,n),this.vectorBucketName=r,this.indexName=s}async putVectors(e){var t=this;return(()=>super.putVectors)().call(t,Me(Me({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async getVectors(e){var t=this;return(()=>super.getVectors)().call(t,Me(Me({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async listVectors(e={}){var t=this;return(()=>super.listVectors)().call(t,Me(Me({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async queryVectors(e){var t=this;return(()=>super.queryVectors)().call(t,Me(Me({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async deleteVectors(e){var t=this;return(()=>super.deleteVectors)().call(t,Me(Me({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}},kt=class extends nt{constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new tt(this.url,this.headers,e,this.fetch)}get vectors(){return new bt(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new it(this.url+"/iceberg",this.headers,this.fetch)}};const St="2.91.0",Et=3e4,Tt=9e4,Rt={"X-Client-Info":`gotrue-js/${St}`},Ot="X-Supabase-Api-Version",$t={timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"},At=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class It extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function Ct(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class jt extends It{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}class Pt extends It{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class xt extends It{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class Nt extends xt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class Ut extends xt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Dt extends xt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Lt extends xt{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}}}class Bt extends xt{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}}}class qt extends xt{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class Mt extends xt{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function Wt(e){return Ct(e)&&"AuthRetryableFetchError"===e.name}class Kt extends xt{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}class Jt extends xt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Ht="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Vt=" \t\n\r=".split(""),Ft=(()=>{const e=new Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<Vt.length;t+=1)e[Vt[t].charCodeAt(0)]=-2;for(let t=0;t<Ht.length;t+=1)e[Ht[t].charCodeAt(0)]=t;return e})();function Gt(e,t,r){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;r(Ht[e]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;r(Ht[e]),t.queuedBits-=6}}function zt(e,t,r){const s=Ft[e];if(!(s>-1)){if(-2===s)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}for(t.queue=t.queue<<6|s,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}function Yt(e){const t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=e=>{!function(e,t,r){if(0===t.utf8seq){if(e<=127)return void r(e);for(let r=1;r<6;r+=1)if(!(e>>7-r&1)){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else{if(4!==t.utf8seq)throw new Error("Invalid UTF-8 sequence");t.codepoint=7&e}t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}}(e,s,r)};for(let t=0;t<e.length;t+=1)zt(e.charCodeAt(t),n,i);return t.join("")}function Xt(e,t){if(!(e<=127)){if(e<=2047)return t(192|e>>6),void t(128|63&e);if(e<=65535)return t(224|e>>12),t(128|e>>6&63),void t(128|63&e);if(e<=1114111)return t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),void t(128|63&e);throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}t(e)}function Qt(e){const t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)zt(e.charCodeAt(t),r,s);return new Uint8Array(t)}function Zt(e){const t=[];return function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){const t=1024*(s-55296)&65535;s=65536+(e.charCodeAt(r+1)-56320&65535|t),r+=1}Xt(s,t)}}(e,e=>t.push(e)),new Uint8Array(t)}function er(e){const t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};return e.forEach(e=>Gt(e,r,s)),Gt(null,r,s),t.join("")}const tr=()=>"undefined"!=typeof window&&"undefined"!=typeof document,rr={tested:!1,writable:!1},sr=()=>{if(!tr())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(rr.tested)return rr.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),rr.tested=!0,rr.writable=!0}catch(e){rr.tested=!0,rr.writable=!1}return rr.writable};const nr=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),ir=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},ar=async(e,t)=>{const r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return r}},or=async(e,t)=>{await e.removeItem(t)};class cr{constructor(){this.promise=new cr.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function lr(e){const t=e.split(".");if(3!==t.length)throw new Jt("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!At.test(t[e]))throw new Jt("JWT not in base64url format");return{header:JSON.parse(Yt(t[0])),payload:JSON.parse(Yt(t[1])),signature:Qt(t[2]),raw:{header:t[0],payload:t[1]}}}function hr(e){return("0"+e.toString(16)).substr(-2)}async function ur(e){if(!("undefined"!=typeof crypto&&void 0!==crypto.subtle&&"undefined"!=typeof TextEncoder))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;const t=await async function(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map(e=>String.fromCharCode(e)).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function dr(e,t,r=!1){const s=function(){const e=new Uint32Array(56);if("undefined"==typeof crypto){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length;let r="";for(let s=0;s<56;s++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,hr).join("")}();let n=s;r&&(n+="/PASSWORD_RECOVERY"),await ir(e,`${t}-code-verifier`,n);const i=await ur(s);return[i,s===i?"plain":"s256"]}cr.promiseConstructor=Promise;const pr=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;const fr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function gr(e){if(!fr.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function wr(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){const e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function mr(e){return JSON.parse(JSON.stringify(e))}const yr=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),br=[502,503,504];async function vr(e){var t,r;if(!("object"==typeof(r=e)&&null!==r&&"status"in r&&"ok"in r&&"json"in r&&"function"==typeof r.json))throw new Mt(yr(e),0);if(br.includes(e.status))throw new Mt(yr(e),e.status);let s,n;try{s=await e.json()}catch(e){throw new Pt(yr(e),e)}const i=function(e){const t=e.headers.get(Ot);if(!t)return null;if(!t.match(pr))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(e){return null}}(e);if(i&&i.getTime()>=$t.timestamp&&"object"==typeof s&&s&&"string"==typeof s.code?n=s.code:"object"==typeof s&&s&&"string"==typeof s.error_code&&(n=s.error_code),n){if("weak_password"===n)throw new Kt(yr(s),e.status,(null===(t=s.weak_password)||void 0===t?void 0:t.reasons)||[]);if("session_not_found"===n)throw new Nt}else if("object"==typeof s&&s&&"object"==typeof s.weak_password&&s.weak_password&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new Kt(yr(s),e.status,s.weak_password.reasons);throw new jt(yr(s),e.status||500,n)}async function _r(e,t,r,s){var n;const i=Object.assign({},null==s?void 0:s.headers);i[Ot]||(i[Ot]=$t.name),(null==s?void 0:s.jwt)&&(i.Authorization=`Bearer ${s.jwt}`);const a=null!==(n=null==s?void 0:s.query)&&void 0!==n?n:{};(null==s?void 0:s.redirectTo)&&(a.redirect_to=s.redirectTo);const o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",c=await async function(e,t,r,s,n,i){const a=((e,t,r,s)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))})(t,s,n,i);let o;try{o=await e(r,Object.assign({},a))}catch(e){throw console.error(e),new Mt(yr(e),0)}o.ok||await vr(o);if(null==s?void 0:s.noResolveJson)return o;try{return await o.json()}catch(e){await vr(e)}}(e,t,r+o,{headers:i,noResolveJson:null==s?void 0:s.noResolveJson},{},null==s?void 0:s.body);return(null==s?void 0:s.xform)?null==s?void 0:s.xform(c):{data:Object.assign({},c),error:null}}function kr(e){var t;let r=null;var s;(function(e){return e.access_token&&e.refresh_token&&e.expires_in})(e)&&(r=Object.assign({},e),e.expires_at||(r.expires_at=(s=e.expires_in,Math.round(Date.now()/1e3)+s)));return{data:{session:r,user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function Sr(e){const t=kr(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function Er(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function Tr(e){return{data:e,error:null}}function Rr(e){const{action_link:t,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=e,a=$(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]);return{data:{properties:{action_link:t,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i},user:Object.assign({},a)},error:null}}function Or(e){return e}const $r=["global","local","others"];class Ar{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=nr(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut(e,t=$r[0]){if($r.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${$r.join(", ")}`);try{return await _r(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(Ct(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await _r(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Er})}catch(e){if(Ct(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{const{options:t}=e,r=$(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=null==r?void 0:r.newEmail,delete s.newEmail),await _r(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:Rr,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(Ct(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await _r(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Er})}catch(e){if(Ct(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,r,s,n,i,a,o;try{const c={nextPage:null,lastPage:0,total:0},l=await _r(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(n=null===(s=null==e?void 0:e.perPage)||void 0===s?void 0:s.toString())&&void 0!==n?n:""},xform:Or});if(l.error)throw l.error;const h=await l.json(),u=null!==(i=l.headers.get("x-total-count"))&&void 0!==i?i:0,d=null!==(o=null===(a=l.headers.get("link"))||void 0===a?void 0:a.split(","))&&void 0!==o?o:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);c[`${r}Page`]=t}),c.total=parseInt(u)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(e){if(Ct(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){gr(e);try{return await _r(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Er})}catch(e){if(Ct(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){gr(e);try{return await _r(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Er})}catch(e){if(Ct(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){gr(e);try{return await _r(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Er})}catch(e){if(Ct(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){gr(e.userId);try{const{data:t,error:r}=await _r(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if(Ct(e))return{data:null,error:e};throw e}}async _deleteFactor(e){gr(e.userId),gr(e.id);try{return{data:await _r(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(Ct(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){var t,r,s,n,i,a,o;try{const c={nextPage:null,lastPage:0,total:0},l=await _r(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(n=null===(s=null==e?void 0:e.perPage)||void 0===s?void 0:s.toString())&&void 0!==n?n:""},xform:Or});if(l.error)throw l.error;const h=await l.json(),u=null!==(i=l.headers.get("x-total-count"))&&void 0!==i?i:0,d=null!==(o=null===(a=l.headers.get("link"))||void 0===a?void 0:a.split(","))&&void 0!==o?o:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);c[`${r}Page`]=t}),c.total=parseInt(u)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(e){if(Ct(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await _r(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Ct(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await _r(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Ct(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await _r(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Ct(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await _r(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(Ct(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await _r(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(Ct(e))return{data:null,error:e};throw e}}}function Ir(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}const Cr=!!(globalThis&&sr()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"));class jr extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class Pr extends jr{}async function xr(e,t,r){Cr&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const s=new globalThis.AbortController;return t>0&&setTimeout(()=>{s.abort(),Cr&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async s=>{if(!s){if(0===t)throw Cr&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new Pr(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(Cr)try{const e=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(e,null," "))}catch(e){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",e)}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 r()}Cr&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,s.name);try{return await r()}finally{Cr&&console.log("@supabase/gotrue-js: navigatorLock: released",e,s.name)}}))}function Nr(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function Ur(e){const t=(new TextEncoder).encode(e);return"0x"+Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}class Dr extends Error{constructor({message:e,code:t,cause:r,name:s}){var n;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=null!==(n=null!=s?s:r instanceof Error?r.name:void 0)&&void 0!==n?n:"Unknown Error",this.code=t}}class Lr extends Dr{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function Br({error:e,options:t}){var r,s,n;const{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new Dr({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===(null===(r=i.authenticatorSelection)||void 0===r?void 0:r.requireResidentKey))return new Dr({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===(null===(s=i.authenticatorSelection)||void 0===s?void 0:s.userVerification))return new Dr({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===(null===(n=i.authenticatorSelection)||void 0===n?void 0:n.userVerification))return new Dr({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new Dr({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new Dr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name){return 0===i.pubKeyCredParams.filter(e=>"public-key"===e.type).length?new Dr({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new Dr({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e})}if("SecurityError"===e.name){const t=window.location.hostname;if(!Vr(t))return new Dr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(i.rp.id!==t)return new Dr({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new Dr({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new Dr({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new Dr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function qr({error:e,options:t}){const{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new Dr({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new Dr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!Vr(t))return new Dr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new Dr({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new Dr({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new Dr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}const Mr=new class{createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function Wr(e){if(!e)throw new Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:t,user:r,excludeCredentials:s}=e,n=$(e,["challenge","user","excludeCredentials"]),i=Qt(t).buffer,a=Object.assign(Object.assign({},r),{id:Qt(r.id).buffer}),o=Object.assign(Object.assign({},n),{challenge:i,user:a});if(s&&s.length>0){o.excludeCredentials=new Array(s.length);for(let e=0;e<s.length;e++){const t=s[e];o.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:Qt(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return o}function Kr(e){if(!e)throw new Error("Credential request options are required");if("undefined"!=typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);const{challenge:t,allowCredentials:r}=e,s=$(e,["challenge","allowCredentials"]),n=Qt(t).buffer,i=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let e=0;e<r.length;e++){const t=r[e];i.allowCredentials[e]=Object.assign(Object.assign({},t),{id:Qt(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return i}function Jr(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const r=e;return{id:e.id,rawId:e.id,response:{attestationObject:er(new Uint8Array(e.response.attestationObject)),clientDataJSON:er(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:null!==(t=r.authenticatorAttachment)&&void 0!==t?t:void 0}}function Hr(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const r=e,s=e.getClientExtensionResults(),n=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:er(new Uint8Array(n.authenticatorData)),clientDataJSON:er(new Uint8Array(n.clientDataJSON)),signature:er(new Uint8Array(n.signature)),userHandle:n.userHandle?er(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:null!==(t=r.authenticatorAttachment)&&void 0!==t?t:void 0}}function Vr(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function Fr(){var e,t;return!!(tr()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null===(e=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===e?void 0:e.create)&&"function"==typeof(null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.get))}const Gr={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},zr={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Yr(...e){const t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),r=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),s={};for(const n of e)if(n)for(const e in n){const i=n[e];if(void 0!==i)if(Array.isArray(i))s[e]=i;else if(r(i))s[e]=i;else if(t(i)){const r=s[e];t(r)?s[e]=Yr(r,i):s[e]=Yr(i)}else s[e]=i}return s}class Xr{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},n){try{const{data:i,error:a}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!i)return{data:null,error:a};const o=null!=s?s:Mr.createNewAbortSignal();if("create"===i.webauthn.type){const{user:e}=i.webauthn.credential_options.publicKey;e.name||(e.name=`${e.id}:${r}`),e.displayName||(e.displayName=e.name)}switch(i.webauthn.type){case"create":{const t=function(e,t){return Yr(Gr,e,t||{})}(i.webauthn.credential_options.publicKey,null==n?void 0:n.create),{data:r,error:s}=await async function(e){try{const t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new Lr("Browser returned unexpected credential type",t)}:{data:null,error:new Lr("Empty credential response",t)}}catch(t){return{data:null,error:Br({error:t,options:e})}}}({publicKey:t,signal:o});return r?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:r}},error:null}:{data:null,error:s}}case"request":{const t=function(e,t){return Yr(zr,e,t||{})}(i.webauthn.credential_options.publicKey,null==n?void 0:n.request),{data:r,error:s}=await async function(e){try{const t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new Lr("Browser returned unexpected credential type",t)}:{data:null,error:new Lr("Empty credential response",t)}}catch(t){return{data:null,error:qr({error:t,options:e})}}}(Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:t,signal:o}));return r?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:r}},error:null}:{data:null,error:s}}}}catch(e){return Ct(e)?{data:null,error:e}:{data:null,error:new Pt("Unexpected error in challenge",e)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:s}={}},n){if(!t)return{data:null,error:new It("rpId is required for WebAuthn authentication")};try{if(!Fr())return{data:null,error:new Pt("Browser does not support WebAuthn",null)};const{data:i,error:a}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:n});if(!i)return{data:null,error:a};const{webauthn:o}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:o.type,rpId:t,rpOrigins:r,credential_response:o.credential_response}})}catch(e){return Ct(e)?{data:null,error:e}:{data:null,error:new Pt("Unexpected error in authenticate",e)}}}async _register({friendlyName:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:s}={}},n){if(!t)return{data:null,error:new It("rpId is required for WebAuthn registration")};try{if(!Fr())return{data:null,error:new Pt("Browser does not support WebAuthn",null)};const{data:i,error:a}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(t=>{var r;return null===(r=t.data)||void 0===r?void 0:r.all.find(t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:a};const{data:o,error:c}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:n});return o?this._verify({factorId:i.id,challengeId:o.challengeId,webauthn:{rpId:t,rpOrigins:r,type:o.webauthn.type,credential_response:o.webauthn.credential_response}}):{data:null,error:c}}catch(e){return Ct(e)?{data:null,error:e}:{data:null,error:new Pt("Unexpected error in register",e)}}}}!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();const Qr={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Rt,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4};async function Zr(e,t,r){return await r()}const es={};class ts{get jwks(){var e,t;return null!==(t=null===(e=es[this.storageKey])||void 0===e?void 0:e.jwks)&&void 0!==t?t:{keys:[]}}set jwks(e){es[this.storageKey]=Object.assign(Object.assign({},es[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!==(t=null===(e=es[this.storageKey])||void 0===e?void 0:e.cachedAt)&&void 0!==t?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){es[this.storageKey]=Object.assign(Object.assign({},es[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=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;const n=Object.assign(Object.assign({},Qr),e);if(this.storageKey=n.storageKey,this.instanceID=null!==(t=ts.nextInstanceID[this.storageKey])&&void 0!==t?t:0,ts.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!n.debug,"function"==typeof n.debug&&(this.logger=n.debug),this.instanceID>0&&tr()){const e=`${this._logPrefix()} 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.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=n.persistSession,this.autoRefreshToken=n.autoRefreshToken,this.admin=new Ar({url:n.url,headers:n.headers,fetch:n.fetch}),this.url=n.url,this.headers=n.headers,this.fetch=nr(n.fetch),this.lock=n.lock||Zr,this.detectSessionInUrl=n.detectSessionInUrl,this.flowType=n.flowType,this.hasCustomAuthorizationHeader=n.hasCustomAuthorizationHeader,this.throwOnError=n.throwOnError,this.lockAcquireTimeout=n.lockAcquireTimeout,n.lock?this.lock=n.lock:this.persistSession&&tr()&&(null===(r=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===r?void 0:r.locks)?this.lock=xr:this.lock=Zr,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),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),webauthn:new Xr(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(n.storage?this.storage=n.storage:sr()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Ir(this.memoryStorage)),n.userStorage&&(this.userStorage=n.userStorage)):(this.memoryStorage={},this.storage=Ir(this.memoryStorage)),tr()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null===(s=this.broadcastChannel)||void 0===s||s.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)})}this.initialize()}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${St}) ${(new Date).toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{let t={},r="none";if(tr()&&(t=function(e){const t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach((e,r)=>{t[r]=e})}catch(e){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),tr()&&this.detectSessionInUrl&&"none"!==r){const{data:s,error:n}=await this._getSessionFromURL(t,r);if(n){if(this._debug("#_initialize()","error detecting session from URL",n),function(e){return Ct(e)&&"AuthImplicitGrantRedirectError"===e.name}(n)){const t=null===(e=n.details)||void 0===e?void 0:e.code;if("identity_already_exists"===t||"identity_not_found"===t||"single_identity_not_deletable"===t)return{error:n}}return{error:n}}const{session:i,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",i,"redirect type",a),await this._saveSession(i),setTimeout(async()=>{"recovery"===a?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return Ct(e)?this._returnResult({error:e}):this._returnResult({error:new Pt("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{const n=await _r(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(r=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==r?r:{},gotrue_meta_security:{captcha_token:null===(s=null==e?void 0:e.options)||void 0===s?void 0:s.captchaToken}},xform:kr}),{data:i,error:a}=n;if(a||!i)return this._returnResult({data:{user:null,session:null},error:a});const o=i.session,c=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:c,session:o},error:null})}catch(e){if(Ct(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){var t,r,s;try{let n;if("email"in e){const{email:r,password:s,options:i}=e;let a=null,o=null;"pkce"===this.flowType&&([a,o]=await dr(this.storage,this.storageKey)),n=await _r(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==i?void 0:i.emailRedirectTo,body:{email:r,password:s,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:a,code_challenge_method:o},xform:kr})}else{if(!("phone"in e))throw new Dt("You must provide either an email or phone number and a password");{const{phone:t,password:i,options:a}=e;n=await _r(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:i,data:null!==(r=null==a?void 0:a.data)&&void 0!==r?r:{},channel:null!==(s=null==a?void 0:a.channel)&&void 0!==s?s:"sms",gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}},xform:kr})}}const{data:i,error:a}=n;if(a||!i)return await or(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});const o=i.session,c=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:c,session:o},error:null})}catch(e){if(await or(this.storage,`${this.storageKey}-code-verifier`),Ct(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if("email"in e){const{email:r,password:s,options:n}=e;t=await _r(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:Sr})}else{if(!("phone"in e))throw new Dt("You must provide either an email or phone number and a password");{const{phone:r,password:s,options:n}=e;t=await _r(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:Sr})}}const{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){const e=new Ut;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(e){if(Ct(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){var t,r,s,n;return await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(s=e.options)||void 0===s?void 0:s.queryParams,skipBrowserRedirect:null===(n=e.options)||void 0===n?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,n,i,a,o,c,l,h,u;let d,p;if("message"in e)d=e.message,p=e.signature;else{const{chain:h,wallet:u,statement:f,options:g}=e;let w;if(tr())if("object"==typeof u)w=u;else{const e=window;if(!("ethereum"in e)||"object"!=typeof e.ethereum||!("request"in e.ethereum)||"function"!=typeof e.ethereum.request)throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.");w=e.ethereum}else{if("object"!=typeof u||!(null==g?void 0:g.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=u}const m=new URL(null!==(t=null==g?void 0:g.url)&&void 0!==t?t:window.location.href),y=await w.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!y||0===y.length)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const b=Nr(y[0]);let v=null===(r=null==g?void 0:g.signInWithEthereum)||void 0===r?void 0:r.chainId;if(!v){const e=await w.request({method:"eth_chainId"});v=parseInt(e,16)}d=function(e){var t;const{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:a,notBefore:o,requestId:c,resources:l,scheme:h,uri:u,version:d}=e;if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!u)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==d)throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(null===(t=e.statement)||void 0===t?void 0:t.includes("\n"))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);const p=`${h?`${h}://${s}`:s} wants you to sign in with your Ethereum account:\n${Nr(e.address)}\n\n${e.statement?`${e.statement}\n`:""}`;let f=`URI: ${u}\nVersion: ${d}\nChain ID: ${r}${a?`\nNonce: ${a}`:""}\nIssued At: ${i.toISOString()}`;if(n&&(f+=`\nExpiration Time: ${n.toISOString()}`),o&&(f+=`\nNot Before: ${o.toISOString()}`),c&&(f+=`\nRequest ID: ${c}`),l){let e="\nResources:";for(const t of l){if(!t||"string"!=typeof t)throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}f+=e}return`${p}\n${f}`}({domain:m.host,address:b,statement:f,uri:m.href,version:"1",chainId:v,nonce:null===(s=null==g?void 0:g.signInWithEthereum)||void 0===s?void 0:s.nonce,issuedAt:null!==(i=null===(n=null==g?void 0:g.signInWithEthereum)||void 0===n?void 0:n.issuedAt)&&void 0!==i?i:new Date,expirationTime:null===(a=null==g?void 0:g.signInWithEthereum)||void 0===a?void 0:a.expirationTime,notBefore:null===(o=null==g?void 0:g.signInWithEthereum)||void 0===o?void 0:o.notBefore,requestId:null===(c=null==g?void 0:g.signInWithEthereum)||void 0===c?void 0:c.requestId,resources:null===(l=null==g?void 0:g.signInWithEthereum)||void 0===l?void 0:l.resources}),p=await w.request({method:"personal_sign",params:[Ur(d),b]})}try{const{data:t,error:r}=await _r(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:d,signature:p},(null===(h=e.options)||void 0===h?void 0:h.captchaToken)?{gotrue_meta_security:{captcha_token:null===(u=e.options)||void 0===u?void 0:u.captchaToken}}:null),xform:kr});if(r)throw r;if(!t||!t.session||!t.user){const e=new Ut;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(Ct(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){var t,r,s,n,i,a,o,c,l,h,u,d;let p,f;if("message"in e)p=e.message,f=e.signature;else{const{chain:u,wallet:d,statement:g,options:w}=e;let m;if(tr())if("object"==typeof d)m=d;else{const e=window;if(!("solana"in e)||"object"!=typeof e.solana||!("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.");m=e.solana}else{if("object"!=typeof d||!(null==w?void 0:w.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");m=d}const y=new URL(null!==(t=null==w?void 0:w.url)&&void 0!==t?t:window.location.href);if("signIn"in m&&m.signIn){const e=await m.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},null==w?void 0:w.signInWithSolana),{version:"1",domain:y.host,uri:y.href}),g?{statement:g}:null));let t;if(Array.isArray(e)&&e[0]&&"object"==typeof e[0])t=e[0];else{if(!(e&&"object"==typeof e&&"signedMessage"in e&&"signature"in e))throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");t=e}if(!("signedMessage"in t&&"signature"in t&&("string"==typeof t.signedMessage||t.signedMessage instanceof Uint8Array)&&t.signature instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");p="string"==typeof t.signedMessage?t.signedMessage:(new TextDecoder).decode(t.signedMessage),f=t.signature}else{if(!("signMessage"in m&&"function"==typeof m.signMessage&&"publicKey"in m&&"object"==typeof m&&m.publicKey&&"toBase58"in m.publicKey&&"function"==typeof m.publicKey.toBase58))throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${y.host} wants you to sign in with your Solana account:`,m.publicKey.toBase58(),...g?["",g,""]:[""],"Version: 1",`URI: ${y.href}`,`Issued At: ${null!==(s=null===(r=null==w?void 0:w.signInWithSolana)||void 0===r?void 0:r.issuedAt)&&void 0!==s?s:(new Date).toISOString()}`,...(null===(n=null==w?void 0:w.signInWithSolana)||void 0===n?void 0:n.notBefore)?[`Not Before: ${w.signInWithSolana.notBefore}`]:[],...(null===(i=null==w?void 0:w.signInWithSolana)||void 0===i?void 0:i.expirationTime)?[`Expiration Time: ${w.signInWithSolana.expirationTime}`]:[],...(null===(a=null==w?void 0:w.signInWithSolana)||void 0===a?void 0:a.chainId)?[`Chain ID: ${w.signInWithSolana.chainId}`]:[],...(null===(o=null==w?void 0:w.signInWithSolana)||void 0===o?void 0:o.nonce)?[`Nonce: ${w.signInWithSolana.nonce}`]:[],...(null===(c=null==w?void 0:w.signInWithSolana)||void 0===c?void 0:c.requestId)?[`Request ID: ${w.signInWithSolana.requestId}`]:[],...(null===(h=null===(l=null==w?void 0:w.signInWithSolana)||void 0===l?void 0:l.resources)||void 0===h?void 0:h.length)?["Resources",...w.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");const e=await m.signMessage((new TextEncoder).encode(p),"utf8");if(!(e&&e instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");f=e}}try{const{data:t,error:r}=await _r(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:er(f)},(null===(u=e.options)||void 0===u?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null===(d=e.options)||void 0===d?void 0:d.captchaToken}}:null),xform:kr});if(r)throw r;if(!t||!t.session||!t.user){const e=new Ut;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(Ct(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){const t=await ar(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(null!=t?t:"").split("/");try{if(!r&&"pkce"===this.flowType)throw new qt;const{data:t,error:n}=await _r(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:kr});if(await or(this.storage,`${this.storageKey}-code-verifier`),n)throw n;if(!t||!t.session||!t.user){const e=new Ut;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),setTimeout(async()=>{await this._notifyAllSubscribers("SIGNED_IN",t.session)},0)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:null!=s?s:null}),error:n})}catch(e){if(await or(this.storage,`${this.storageKey}-code-verifier`),Ct(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{const{options:t,provider:r,token:s,access_token:n,nonce:i}=e,a=await _r(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:n,nonce:i,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:kr}),{data:o,error:c}=a;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!o||!o.session||!o.user){const e=new Ut;return this._returnResult({data:{user:null,session:null},error:e})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:o,error:c})}catch(e){if(Ct(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){var t,r,s,n,i;try{if("email"in e){const{email:s,options:n}=e;let i=null,a=null;"pkce"===this.flowType&&([i,a]=await dr(this.storage,this.storageKey));const{error:o}=await _r(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:s,data:null!==(t=null==n?void 0:n.data)&&void 0!==t?t:{},create_user:null===(r=null==n?void 0:n.shouldCreateUser)||void 0===r||r,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:i,code_challenge_method:a},redirectTo:null==n?void 0:n.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}if("phone"in e){const{phone:t,options:r}=e,{data:a,error:o}=await _r(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(s=null==r?void 0:r.data)&&void 0!==s?s:{},create_user:null===(n=null==r?void 0:r.shouldCreateUser)||void 0===n||n,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!==(i=null==r?void 0:r.channel)&&void 0!==i?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==a?void 0:a.message_id},error:o})}throw new Dt("You must provide either an email or phone number.")}catch(e){if(await or(this.storage,`${this.storageKey}-code-verifier`),Ct(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){var t,r;try{let s,n;"options"in e&&(s=null===(t=e.options)||void 0===t?void 0:t.redirectTo,n=null===(r=e.options)||void 0===r?void 0:r.captchaToken);const{data:i,error:a}=await _r(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:s,xform:kr});if(a)throw a;if(!i){throw new Error("An error occurred on token verification.")}const o=i.session,c=i.user;return(null==o?void 0:o.access_token)&&(await this._saveSession(o),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",o)),this._returnResult({data:{user:c,session:o},error:null})}catch(e){if(Ct(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){var t,r,s,n,i;try{let a=null,o=null;"pkce"===this.flowType&&([a,o]=await dr(this.storage,this.storageKey));const c=await _r(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:null!==(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==r?r:void 0}),(null===(s=null==e?void 0:e.options)||void 0===s?void 0:s.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:o}),headers:this.headers,xform:Tr});return(null===(n=c.data)||void 0===n?void 0:n.url)&&tr()&&!(null===(i=e.options)||void 0===i?void 0:i.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(e){if(await or(this.storage,`${this.storageKey}-code-verifier`),Ct(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new Nt;const{error:s}=await _r(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(Ct(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:r,type:s,options:n}=e,{error:i}=await _r(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},redirectTo:null==n?void 0:n.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}if("phone"in e){const{phone:r,type:s,options:n}=e,{data:i,error:a}=await _r(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==i?void 0:i.message_id},error:a})}throw new Dt("You must provide either an email or phone number and a type")}catch(e){if(Ct(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){await this.initializePromise;return await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(e){}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){const e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}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{const 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;const t=await ar(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=!!e.expires_at&&1e3*e.expires_at-Date.now()<Tt;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){const t=await ar(this.userStorage,this.storageKey+"-user");(null==t?void 0:t.user)?e.user=t.user:e.user=wr()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const t={value:this.suppressGetSessionWarning};e.user=function(e,t){return new Proxy(e,{get:(e,r,s)=>{if("__isInsecureUserWarningProxy"===r)return!0;if("symbol"==typeof r){const t=r.toString();if("Symbol(Symbol.toPrimitive)"===t||"Symbol(Symbol.toStringTag)"===t||"Symbol(util.inspect.custom)"===t||"Symbol(nodejs.util.inspect.custom)"===t)return Reflect.get(e,r,s)}return t.value||"string"!=typeof r||(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."),t.value=!0),Reflect.get(e,r,s)}})}(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?this._returnResult({data:{session:null},error:n}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await _r(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Er}):await this._useSession(async e=>{var t,r,s;const{data:n,error:i}=e;if(i)throw i;return(null===(t=n.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await _r(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(s=null===(r=n.session)||void 0===r?void 0:r.access_token)&&void 0!==s?s:void 0,xform:Er}):{data:{user:null},error:new Nt}})}catch(e){if(Ct(e))return function(e){return Ct(e)&&"AuthSessionMissingError"===e.name}(e)&&(await this._removeSession(),await or(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{const{data:s,error:n}=r;if(n)throw n;if(!s.session)throw new Nt;const i=s.session;let a=null,o=null;"pkce"===this.flowType&&null!=e.email&&([a,o]=await dr(this.storage,this.storageKey));const{data:c,error:l}=await _r(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:o}),jwt:i.access_token,xform:Er});if(l)throw l;return i.user=c.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(e){if(await or(this.storage,`${this.storageKey}-code-verifier`),Ct(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new Nt;const t=Date.now()/1e3;let r=t,s=!0,n=null;const{payload:i}=lr(e.access_token);if(i.exp&&(r=i.exp,s=r<=t),s){const{data:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!t)return{data:{user:null,session:null},error:null};n=t}else{const{data:s,error:i}=await this._getUser(e.access_token);if(i)throw i;n={access_token:e.access_token,refresh_token:e.refresh_token,user:s.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return this._returnResult({data:{user:n.user,session:n},error:null})}catch(e){if(Ct(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){const{data:s,error:n}=t;if(n)throw n;e=null!==(r=s.session)&&void 0!==r?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new Nt;const{data:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?this._returnResult({data:{user:null,session:null},error:n}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if(Ct(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!tr())throw new Lt("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Lt(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("pkce"===this.flowType)throw new Bt("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new Lt("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new Bt("No code detected.");const{data:t,error:r}=await this._exchangeCodeForSession(e.code);if(r)throw r;const s=new URL(window.location.href);return s.searchParams.delete("code"),window.history.replaceState(window.history.state,"",s.toString()),{data:{session:t.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:s,access_token:n,refresh_token:i,expires_in:a,expires_at:o,token_type:c}=e;if(!(n&&a&&i&&c))throw new Lt("No session defined in URL");const l=Math.round(Date.now()/1e3),h=parseInt(a);let u=l+h;o&&(u=parseInt(o));const d=u-l;1e3*d<=Et&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${d}s, should have been closer to ${h}s`);const p=u-h;l-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,u,l):l-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,u,l);const{data:f,error:g}=await this._getUser(n);if(g)throw g;const w={provider_token:r,provider_refresh_token:s,access_token:n,expires_in:h,expires_at:u,refresh_token:i,token_type:c,user:f.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:w,redirectType:e.type},error:null})}catch(e){if(Ct(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await ar(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return this._returnResult({error:n});const i=null===(r=s.session)||void 0===r?void 0:r.access_token;if(i){const{error:t}=await this.admin.signOut(i,e);if(t&&(!function(e){return Ct(e)&&"AuthApiError"===e.name}(t)||404!==t.status&&401!==t.status&&403!==t.status))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await or(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const t=Symbol("auth-callback"),r={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,r),(async()=>{await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{const{data:{session:s},error:n}=t;if(n)throw n;await(null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(t){await(null===(s=this.stateChangeEmitters.get(e))||void 0===s?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null;"pkce"===this.flowType&&([r,s]=await dr(this.storage,this.storageKey,!0));try{return await _r(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(await or(this.storage,`${this.storageKey}-code-verifier`),Ct(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){var e;try{const{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null})}catch(e){if(Ct(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:r,error:s}=await this._useSession(async t=>{var r,s,n,i,a;const{data:o,error:c}=t;if(c)throw c;const l=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(r=e.options)||void 0===r?void 0:r.redirectTo,scopes:null===(s=e.options)||void 0===s?void 0:s.scopes,queryParams:null===(n=e.options)||void 0===n?void 0:n.queryParams,skipBrowserRedirect:!0});return await _r(this.fetch,"GET",l,{headers:this.headers,jwt:null!==(a=null===(i=o.session)||void 0===i?void 0:i.access_token)&&void 0!==a?a:void 0})});if(s)throw s;return tr()&&!(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)&&window.location.assign(null==r?void 0:r.url),this._returnResult({data:{provider:e.provider,url:null==r?void 0:r.url},error:null})}catch(t){if(Ct(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{const{error:s,data:{session:n}}=t;if(s)throw s;const{options:i,provider:a,token:o,access_token:c,nonce:l}=e,h=await _r(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!==(r=null==n?void 0:n.access_token)&&void 0!==r?r:void 0,body:{provider:a,id_token:o,access_token:c,nonce:l,link_identity:!0,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:kr}),{data:u,error:d}=h;return d?this._returnResult({data:{user:null,session:null},error:d}):u&&u.session&&u.user?(u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("USER_UPDATED",u.session)),this._returnResult({data:u,error:d})):this._returnResult({data:{user:null,session:null},error:new Ut})}catch(e){if(await or(this.storage,`${this.storageKey}-code-verifier`),Ct(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;const{data:n,error:i}=t;if(i)throw i;return await _r(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(s=null===(r=n.session)||void 0===r?void 0:r.access_token)&&void 0!==s?s:void 0})})}catch(e){if(Ct(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const n=Date.now();return await(r=async r=>(r>0&&await async function(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await _r(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:kr})),s=(e,t)=>{const r=200*Math.pow(2,e);return t&&Wt(t)&&Date.now()+r-n<Et},new Promise((e,t)=>{(async()=>{for(let n=0;n<1/0;n++)try{const t=await r(n);if(!s(n,null,t))return void e(t)}catch(e){if(!s(n,e))return void t(e)}})()}))}catch(e){if(this._debug(t,"error",e),Ct(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,"end")}var r,s}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const r=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",r),tr()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const s=await ar(this.storage,this.storageKey);if(s&&this.userStorage){let t=await ar(this.userStorage,this.storageKey+"-user");this.storage.isServer||!Object.is(this.storage,this.userStorage)||t||(t={user:s.user},await ir(this.userStorage,this.storageKey+"-user",t)),s.user=null!==(e=null==t?void 0:t.user)&&void 0!==e?e:wr()}else if(s&&!s.user&&!s.user){const e=await ar(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(s.user=e.user,await or(this.storage,this.storageKey+"-user"),await ir(this.storage,this.storageKey,s)):s.user=wr()}if(this._debug(r,"session from storage",s),!this._isValidSession(s))return this._debug(r,"session is not valid"),void(null!==s&&await this._removeSession());const n=1e3*(null!==(t=s.expires_at)&&void 0!==t?t:1/0)-Date.now()<Tt;if(this._debug(r,`session has${n?"":" not"} expired with margin of 90000s`),n){if(this.autoRefreshToken&&s.refresh_token){const{error:e}=await this._callRefreshToken(s.refresh_token);e&&(console.error(e),Wt(e)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else if(s.user&&!0===s.user.__isUserNotAvailableProxy)try{const{data:e,error:t}=await this._getUser(s.access_token);!t&&(null==e?void 0:e.user)?(s.user=e.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(e){console.error("Error getting user data:",e),this._debug(r,"error getting user data, skipping SIGNED_IN notification",e)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(e){return this._debug(r,"error",e),void console.error(e)}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new Nt;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new cr;const{data:t,error:r}=await this._refreshAccessToken(e);if(r)throw r;if(!t.session)throw new Nt;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);const s={data:t.session,error:null};return this.refreshingDeferred.resolve(s),s}catch(e){if(this._debug(s,"error",e),Ct(e)){const r={data:null,error:e};return Wt(e)||await this._removeSession(),null===(t=this.refreshingDeferred)||void 0===t||t.resolve(r),r}throw null===(r=this.refreshingDeferred)||void 0===r||r.reject(e),e}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){const s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});const s=[],n=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(e){s.push(e)}});if(await Promise.all(n),s.length>0){for(let e=0;e<s.length;e+=1)console.error(s[e]);throw s[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await or(this.storage,`${this.storageKey}-code-verifier`);const t=Object.assign({},e),r=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!r&&t.user&&await ir(this.userStorage,this.storageKey+"-user",{user:t.user});const e=Object.assign({},t);delete e.user;const s=mr(e);await ir(this.storage,this.storageKey,s)}else{const e=mr(t);await ir(this.storage,this.storageKey,e)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await or(this.storage,this.storageKey),await or(this.storage,this.storageKey+"-code-verifier"),await or(this.storage,this.storageKey+"-user"),this.userStorage&&await or(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&tr()&&(null===window||void 0===window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Et);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);const t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}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{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");const s=Math.floor((1e3*r.expires_at-e)/Et);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(!(e.isAcquireTimeout||e instanceof jr))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!tr()||!(null===window||void 0===window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null===window||void 0===window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{"visible"===document.visibilityState?await this._recoverAndRefresh():this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting")}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){const s=[`provider=${encodeURIComponent(t)}`];if((null==r?void 0:r.redirectTo)&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),(null==r?void 0:r.scopes)&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),"pkce"===this.flowType){const[e,t]=await dr(this.storage,this.storageKey),r=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});s.push(r.toString())}if(null==r?void 0:r.queryParams){const e=new URLSearchParams(r.queryParams);s.push(e.toString())}return(null==r?void 0:r.skipBrowserRedirect)&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;return n?this._returnResult({data:null,error:n}):await _r(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token})})}catch(e){if(Ct(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;const{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:o,error:c}=await _r(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:null===(r=null==n?void 0:n.session)||void 0===r?void 0:r.access_token});return c?this._returnResult({data:null,error:c}):("totp"===e.factorType&&"totp"===o.type&&(null===(s=null==o?void 0:o.totp)||void 0===s?void 0:s.qr_code)&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),this._returnResult({data:o,error:null}))})}catch(e){if(Ct(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return this._returnResult({data:null,error:n});const i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?Jr(e.webauthn.credential_response):Hr(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:o}=await _r(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});return o?this._returnResult({data:null,error:o}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:o}))})}catch(e){if(Ct(e))return this._returnResult({data:null,error:e});throw e}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return this._returnResult({data:null,error:n});const i=await _r(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});if(i.error)return i;const{data:a}=i;if("webauthn"!==a.type)return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:Wr(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:Kr(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(Ct(e))return this._returnResult({data:null,error:e});throw e}})}async _challengeAndVerify(e){const{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;const{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};const s={all:[],phone:[],totp:[],webauthn:[]};for(const r of null!==(e=null==t?void 0:t.factors)&&void 0!==e?e:[])s.all.push(r),"verified"===r.status&&s[r.factor_type].push(r);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(){var e,t;const{data:{session:r},error:s}=await this.getSession();if(s)return this._returnResult({data:null,error:s});if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:n}=lr(r.access_token);let i=null;n.aal&&(i=n.aal);let a=i;(null!==(t=null===(e=r.user.factors)||void 0===e?void 0:e.filter(e=>"verified"===e.status))&&void 0!==t?t:[]).length>0&&(a="aal2");return{data:{currentLevel:i,nextLevel:a,currentAuthenticationMethods:n.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{const{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await _r(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new Nt})})}catch(e){if(Ct(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new Nt});const i=await _r(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return i.data&&i.data.redirect_url&&tr()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(Ct(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new Nt});const i=await _r(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return i.data&&i.data.redirect_url&&tr()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(Ct(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await _r(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new Nt})})}catch(e){if(Ct(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{const{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await _r(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Nt})})}catch(e){if(Ct(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(t=>t.kid===e);if(r)return r;const s=Date.now();if(r=this.jwks.keys.find(t=>t.kid===e),r&&this.jwks_cached_at+6e5>s)return r;const{data:n,error:i}=await _r(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return n.keys&&0!==n.keys.length?(this.jwks=n,this.jwks_cached_at=s,r=n.keys.find(t=>t.kid===e),r||null):null}async getClaims(e,t={}){try{let r=e;if(!r){const{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});r=e.session.access_token}const{header:s,payload:n,signature:i,raw:{header:a,payload:o}}=lr(r);(null==t?void 0:t.allowExpired)||function(e){if(!e)throw new Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw new Error("JWT has expired")}(n.exp);const c=s.alg&&!s.alg.startsWith("HS")&&s.kid&&"crypto"in globalThis&&"subtle"in globalThis.crypto?await this.fetchJwk(s.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks):null;if(!c){const{error:e}=await this.getUser(r);if(e)throw e;return{data:{claims:n,header:s,signature:i},error:null}}const l=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}(s.alg),h=await crypto.subtle.importKey("jwk",c,l,!0,["verify"]);if(!await crypto.subtle.verify(l,h,i,Zt(`${a}.${o}`)))throw new Jt("Invalid JWT signature");return{data:{claims:n,header:s,signature:i},error:null}}catch(e){if(Ct(e))return this._returnResult({data:null,error:e});throw e}}}ts.nextInstanceID={};const rs=ts;let ss="";ss="undefined"!=typeof Deno?"deno":"undefined"!=typeof document?"web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";const ns={headers:{"X-Client-Info":`supabase-js-${ss}/2.91.0`}},is={schema:"public"},as={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},os={};function cs(e){return(cs="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function ls(e){var t=function(e,t){if("object"!=cs(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=cs(s))return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==cs(t)?t:t+""}function hs(e,t,r){return(t=ls(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function us(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function ds(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?us(Object(r),!0).forEach(function(t){hs(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):us(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}const ps=(e,t,r)=>{const s=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r),n=Headers;return async(r,i)=>{var a;const o=null!==(a=await t())&&void 0!==a?a:e;let c=new n(null==i?void 0:i.headers);return c.has("apikey")||c.set("apikey",e),c.has("Authorization")||c.set("Authorization",`Bearer ${o}`),s(r,ds(ds({},i),{},{headers:c}))}};var fs=class extends rs{constructor(e){super(e)}},gs=class{constructor(e,t,r){var s,n;this.supabaseUrl=e,this.supabaseKey=t;const i=function(e){const t=null==e?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL((r=t).endsWith("/")?r:r+"/")}catch(e){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}var r}(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const a=`sb-${i.hostname.split(".")[0]}-auth-token`,o=function(e,t){var r,s;const{db:n,auth:i,realtime:a,global:o}=e,{db:c,auth:l,realtime:h,global:u}=t,d={db:ds(ds({},c),n),auth:ds(ds({},l),i),realtime:ds(ds({},h),a),storage:{},global:ds(ds(ds({},u),o),{},{headers:ds(ds({},null!==(r=null==u?void 0:u.headers)&&void 0!==r?r:{}),null!==(s=null==o?void 0:o.headers)&&void 0!==s?s:{})}),accessToken:async()=>""};return e.accessToken?d.accessToken=e.accessToken:delete d.accessToken,d}(null!=r?r:{},{db:is,realtime:os,auth:ds(ds({},as),{},{storageKey:a}),global:ns});var c;(this.storageKey=null!==(s=o.auth.storageKey)&&void 0!==s?s:"",this.headers=null!==(n=o.global.headers)&&void 0!==n?n:{},o.accessToken)?(this.accessToken=o.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!==(c=o.auth)&&void 0!==c?c:{},this.headers,o.global.fetch);this.fetch=ps(t,this._getAccessToken.bind(this),o.global.fetch),this.realtime=this._initRealtimeClient(ds({headers:this.headers,accessToken:this._getAccessToken.bind(this)},o.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(e=>this.realtime.setAuth(e)).catch(e=>console.warn("Failed to set initial Realtime auth token:",e)),this.rest=new W(new URL("rest/v1",i).href,{headers:this.headers,schema:o.db.schema,fetch:this.fetch}),this.storage=new kt(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),o.accessToken||this._listenForAuthEvents()}get functions(){return new N(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}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()}async _getAccessToken(){var e,t,r=this;if(r.accessToken)return await r.accessToken();const{data:s}=await r.auth.getSession();return null!==(e=null===(t=s.session)||void 0===t?void 0:t.access_token)&&void 0!==e?e:r.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:a,lock:o,debug:c,throwOnError:l},h,u){const d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new fs({url:this.authUrl.href,headers:ds(ds({},d),h),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:n,flowType:a,lock:o,debug:c,throwOnError:l,fetch:u,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new Se(this.realtimeUrl.href,ds(ds({},e),{},{params:ds(ds({},{apikey:this.supabaseKey}),null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){"TOKEN_REFRESHED"!==e&&"SIGNED_IN"!==e||this.changedAccessToken===r?"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.changedAccessToken=r,this.realtime.setAuth(r))}};(function(){if("undefined"!=typeof window)return!1;const e=globalThis.process;if(!e)return!1;const t=e.version;if(null==t)return!1;const r=t.match(/^v(\d+)\./);return!!r&&parseInt(r[1],10)<=18})()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");let ws=null,ms=null;e.AppsModule=h,e.BookingModule=m,e.EventsModule=d,e.HlmrApiError=r,e.HlmrClient=T,e.LedgerModule=y,e.OffersModule=g,e.PaymentModule=v,e.PricingModule=w,e.PublicModule=p,e.SDK_NAME="hlmr-sdk-js",e.SDK_VERSION=i,e.TermsModule=S,e.clearAllCache=R,e.getSupabaseClient=function(e,t,r){var s,n,i;if(ws)return ws;if(!e)throw new Error("Supabase URL is required. Pass import.meta.env.VITE_SUPABASE_URL");if(!t)throw new Error("Supabase anon key is required. Pass import.meta.env.VITE_SUPABASE_ANON_KEY");const a={detectSessionInUrl:null!==(s=null==r?void 0:r.detectSessionInUrl)&&void 0!==s&&s,persistSession:null===(n=null==r?void 0:r.persistSession)||void 0===n||n,autoRefreshToken:null===(i=null==r?void 0:r.autoRefreshToken)||void 0===i||i};return ws=((e,t,r)=>new gs(e,t,r))(e,t,{auth:{detectSessionInUrl:a.detectSessionInUrl,persistSession:a.persistSession,autoRefreshToken:a.autoRefreshToken}}),ms={url:e,options:a},ws},e.getSupabaseClientConfig=function(){return ms?{...ms}:null},e.isJSendError=function(e){return"error"===e.status&&"message"in e},e.isJSendFail=function(e){return"fail"===e.status&&"data"in e},e.isJSendResponse=s,e.isJSendSuccess=n,e.performLogout=function(e={}){const{redirectUrl:t,onClearCache:r,idpBaseUrl:s,clientId:n,callbackPath:i}=e;let a;if(R(r),O(),t)a=t;else if(s&&n&&i){const e=`${s}/login?client_id=${n}&redirect_uri=${encodeURIComponent(window.location.origin+i)}`;a=`${s}/logout?redirect_uri=${encodeURIComponent(e)}`}else a="/login";window.location.replace(a)},e.preventBackNavigation=O,e.resetSupabaseClient=function(){ws=null,ms=null}});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).HlmrSDK={})}(this,function(e){"use strict";const t={production:{name:"production",url:"https://api.hlmr.io",description:"Environnement de production"},development:{name:"development",url:"https://api.dev.hlmr.io",description:"Environnement de développement"},staging:{name:"staging",url:"https://api.stg.hlmr.io",description:"Environnement de staging"}};class r extends Error{constructor(e,t,s,n,i){super(e),this.name="HlmrApiError",this.statusCode=t,this.code=s,this.response=n,this.originalError=i,Error.captureStackTrace&&Error.captureStackTrace(this,r)}static fromJSendResponse(e,t){if("fail"===e.status){return new r(e.data.detail||"Validation failed",t,"VALIDATION_ERROR",e)}if("error"===e.status){const s=e;return new r(s.message||"Server error",t,s.code||"SERVER_ERROR",e)}return new r("Unknown API error",t,"UNKNOWN_ERROR",e)}static networkError(e){return new r(`Network error: ${e.message}`,0,"NETWORK_ERROR",void 0,e)}static timeoutError(e){return new r(`Request timeout after ${e}ms`,0,"TIMEOUT_ERROR")}static configError(e){return new r(`Configuration error: ${e}`,0,"CONFIG_ERROR")}isAuthError(){return 401===this.statusCode}isPermissionError(){return 403===this.statusCode}isValidationError(){return this.statusCode>=400&&this.statusCode<500&&"VALIDATION_ERROR"===this.code}isServerError(){return this.statusCode>=500}isNetworkError(){return"NETWORK_ERROR"===this.code}isTimeoutError(){return"TIMEOUT_ERROR"===this.code}getInsufficientBalanceDetail(){var e,t,r,s;if(402!==this.statusCode)return null;const n=null!==(r=null===(t=null===(e=this.response)||void 0===e?void 0:e.data)||void 0===t?void 0:t.detail)&&void 0!==r?r:null===(s=this.response)||void 0===s?void 0:s.detail;return n&&"object"==typeof n&&"min_amount"in n?{min_amount:n.min_amount,wallet_balance:n.wallet_balance}:null}}function s(e){return"object"==typeof e&&null!==e&&"string"==typeof e.status&&["success","fail","error"].includes(e.status)}function n(e){return"success"===e.status&&"data"in e}const i="1.1.0";class a{constructor(e){this.config=e}updateConfig(e){this.config={...this.config,...e}}setBearerToken(e){this.config.bearerToken=e}clearBearerToken(){delete this.config.bearerToken}setAppSecret(e){this.config.appSecret=e}clearAppSecret(){delete this.config.appSecret}buildUrl(e,t="v1"){if(e.startsWith("http://")||e.startsWith("https://"))return e;const r=this.config.baseUrl.replace(/\/$/,""),s=e.replace(/^\//,"");return s.match(/^v\d+\//)?`${r}/${s}`:t?`${r}/${t}/${s}`:`${r}/${s}`}buildHeaders(e={}){const t={"Content-Type":"application/json","X-App-ID":this.config.appId,"X-SDK-Referrer":`hlmr-sdk-js@${i}`,...this.config.customHeaders,...e.headers};return this.config.appSecret&&!e.skipAuth?t["X-App-Secret"]=this.config.appSecret:this.config.bearerToken&&!e.skipAuth&&(t.Authorization=`Bearer ${this.config.bearerToken}`),t}createTimeoutController(e){const t=new AbortController;return setTimeout(()=>t.abort(),e),t}async processResponse(e){const t={};let i;e.headers.forEach((e,r)=>{t[r]=e});const a=e.headers.get("content-type");if(a&&a.includes("application/json"))try{i=await e.json()}catch(t){i=await e.text()}else i=await e.text();if(s(i)){if(!e.ok)throw r.fromJSendResponse(i,e.status);if(n(i))return{status:e.status,statusText:e.statusText,headers:t,data:i.data}}if(!e.ok)throw new r(`HTTP ${e.status}: ${e.statusText}`,e.status,"HTTP_ERROR");return{status:e.status,statusText:e.statusText,headers:t,data:i}}async request(e,t,s,n={}){const i=this.buildUrl(t,n.apiVersion),a=this.buildHeaders(n),o=n.timeout||this.config.timeout||3e4;this.config.debug&&console.log(`[HlmrSDK] ${e} ${i}`,{headers:a,body:s});const c={method:e,headers:a,signal:this.createTimeoutController(o).signal};s&&["POST","PUT","PATCH"].includes(e.toUpperCase())&&(c.body="string"==typeof s?s:JSON.stringify(s));try{let e=await fetch(i,c);if(307===e.status||301===e.status||302===e.status){const t=e.headers.get("location");if(t){console.warn(`[HlmrSDK] Received ${e.status} redirect for ${i}. Following redirect to ${t}. Please update your code to use the correct URL with trailing slash.`);const r=t.startsWith("http")?t:new URL(t,i).toString();e=await fetch(r,c)}}const t=await this.processResponse(e);return this.config.debug&&console.log("[HlmrSDK] Response:",t),t}catch(e){if(e instanceof r)throw e;if(e instanceof Error){if("AbortError"===e.name)throw r.timeoutError(o);throw r.networkError(e)}throw new r("Unknown error occurred",0,"UNKNOWN_ERROR")}}async get(e,t){return this.request("GET",e,void 0,t)}async post(e,t,r){return this.request("POST",e,t,r)}async put(e,t,r){return this.request("PUT",e,t,r)}async patch(e,t,r){return this.request("PATCH",e,t,r)}async delete(e,t){return this.request("DELETE",e,void 0,t)}async directRequest(e,t="GET",s,n={}){const i={"Content-Type":"application/json",...n.headers},a=n.timeout||this.config.timeout||3e4,o=this.createTimeoutController(a);this.config.debug&&console.log(`[HlmrSDK] Direct ${t} ${e}`,{headers:i,body:s});const c={method:t,headers:i,signal:o.signal};s&&["POST","PUT","PATCH"].includes(t)&&(c.body="string"==typeof s?s:JSON.stringify(s));try{const t=await fetch(e,c),r=await this.processResponse(t);return this.config.debug&&console.log("[HlmrSDK] Direct Response:",r),r}catch(e){if(e instanceof r)throw e;if(e instanceof Error){if("AbortError"===e.name)throw r.timeoutError(a);throw r.networkError(e)}throw new r("Unknown error occurred",0,"UNKNOWN_ERROR")}}}class o{constructor(e){this.http=e}async validateRedirect(e,t){const r={app_id:e,redirect_uri:t};return(await this.http.post(`apps/${e}/validate-redirect`,r,{skipAuth:!0})).data}async exchangeRedirectToken(e){const t=await this.http.post("auth/exchange",{redirect_token:e},{skipAuth:!0});return{...t.data,scopes_refreshed:!0===t.data.scopes_refreshed}}}class c{constructor(e){this.http=e}async getProfile(){const e=(await this.http.get("users/me")).data.user;return{id:e.user_id,email:e.email||"",full_name:e.display_name||e.public_name,avatar_url:e.avatar_url,user_metadata:e.user_metadata||{},created_at:e.created_at||"",updated_at:e.updated_at||"",last_sign_in_at:e.last_sign_in_at,email_confirmed_at:e.email_verified?e.email_confirmed_at||e.updated_at:void 0}}async updateProfile(e){const t=(await this.http.patch("users/me/profile",e)).data.user;return{id:t.user_id,email:t.email||"",full_name:t.display_name||t.public_name,avatar_url:t.avatar_url,user_metadata:t.user_metadata||{},created_at:t.created_at||"",updated_at:t.updated_at||"",last_sign_in_at:t.last_sign_in_at,email_confirmed_at:t.email_verified?t.email_confirmed_at||t.updated_at:void 0}}async getSettings(e){const t=e||"default";try{const e=await this.http.get(`users/me/settings/${t}`);if(e.data&&e.data.settings)return e.data}catch(t){if(404===t.status&&e)try{const e=await this.http.get("users/me/settings/default");if(e.data&&e.data.settings)return e.data}catch(e){}}return null}async updateSettings(e,t,r){const s={...t};"default"===e&&(null==r?void 0:r.applyAll)&&(s.apply_all=!0);const n=await this.http.patch(`users/me/settings/${e}`,s),i={success:!0};return void 0!==n.data.updated_apps&&(i.updated_apps=n.data.updated_apps),i}async getLocale(e){var t;const r=await this.getSettings(e);return(null===(t=null==r?void 0:r.settings)||void 0===t?void 0:t.locale)||null}}class l{constructor(e){this.http=e}async ping(e){let t="ping";if(e){const r=new URLSearchParams;void 0!==e.idle&&r.append("idle",String(e.idle)),void 0!==e.app&&r.append("app",String(e.app)),void 0!==e.lat&&r.append("lat",String(e.lat)),void 0!==e.lng&&r.append("lng",String(e.lng)),void 0!==e.device&&r.append("device",String(e.device));const s=r.toString();s&&(t=`${t}?${s}`)}return(await this.http.get(t,{apiVersion:""})).data}async version(){return(await this.http.get("version",{apiVersion:"",skipAuth:!0})).data}async checkServiceReady(e){return(await this.http.get(`ready/${e}`,{apiVersion:"",skipAuth:!0})).data}}class h{constructor(e){this.http=e}async logSession(e,t){return(await this.http.post(`apps/${e}/sessions`,t||{})).data}}const u={pingInterval:3e4,autoReconnect:!0,maxReconnectAttempts:5,reconnectDelay:1e3,maxReconnectDelay:3e4,debug:!1};class d{setBearerToken(e){this.bearerToken=e}constructor(e,t){this.ws=null,this.pingIntervalId=null,this.reconnectAttempts=0,this.reconnectTimeoutId=null,this.isConnecting=!1,this.isManualDisconnect=!1,this.subscriptions=new Map,this.pendingSubscriptions=new Map,this.listeners=new Map,this.userId=null,this.bearerToken=null,this.authResolve=null,this.authReject=null,this.http=e,this.config={...u,...t};const r=e.config;this.bearerToken=r.bearerToken||null}async connect(){if(this.ws&&this.ws.readyState===WebSocket.OPEN)throw new Error("Already connected");if(this.isConnecting)throw new Error("Connection in progress");return this.isConnecting=!0,this.isManualDisconnect=!1,this.reconnectAttempts=0,this._connect()}async _connect(){return new Promise((e,t)=>{try{this.authResolve=e,this.authReject=t;const r=this._buildWebSocketUrl();this.config.debug&&console.log("[EventsModule] Connecting to:",r),this.ws=new WebSocket(r);const s=setTimeout(()=>{this.ws&&this.ws.readyState!==WebSocket.OPEN&&(this.ws.close(),this.isConnecting=!1,this.authResolve=null,this.authReject=null,t(new Error("Connection timeout")))},1e4);this.ws.onopen=()=>{if(this.config.debug&&console.log("[EventsModule] WebSocket connected, sending auth..."),clearTimeout(s),this.bearerToken){const e={type:"auth",token:this.bearerToken};this.ws.send(JSON.stringify(e)),this.config.debug&&console.log("[EventsModule] Sent auth message")}else this.isConnecting=!1,this.authResolve=null,this.authReject=null,this.ws.close(4008,"Missing authentication token"),t(new Error("Missing authentication token"))},this.ws.onmessage=e=>{try{const t=JSON.parse(e.data);this._handleMessage(t)}catch(e){this.config.debug&&console.error("[EventsModule] Failed to parse message:",e)}},this.ws.onerror=e=>{this.config.debug&&console.error("[EventsModule] WebSocket error:",e),clearTimeout(s),this.isConnecting=!1,this.authResolve=null,this.authReject=null,this._emit("error",new Error("WebSocket error")),t(new Error("WebSocket error"))},this.ws.onclose=e=>{this.config.debug&&console.log("[EventsModule] WebSocket closed:",e.code,e.reason),clearTimeout(s),this._stopPingInterval(),this.isConnecting=!1,this.authReject&&(this.authReject(new Error(e.reason||"Connection closed before authentication")),this.authResolve=null,this.authReject=null),this._emit("disconnect",e.reason||"Connection closed"),!this.isManualDisconnect&&this.config.autoReconnect&&this._scheduleReconnect()}}catch(e){this.isConnecting=!1,this.authResolve=null,this.authReject=null,t(e)}})}disconnect(){this.isManualDisconnect=!0,this._cleanup(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.config.debug&&console.log("[EventsModule] Disconnected")}async subscribe(e,t,r){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("Not connected");const s=this._generateId();return new Promise((n,i)=>{const a=r?{domain:e,resource:t,options:r}:{domain:e,resource:t},o={resolve:e=>{this.subscriptions.set(e.id,a),n(e)},reject:i,...a};this.pendingSubscriptions.set(s,o);const c={type:"subscribe",subscription_id:s,domain:e,resource:t,options:{filters:(null==r?void 0:r.filters)||{},include_data:(null==r?void 0:r.include_data)||!1}};this.ws.send(JSON.stringify(c)),this.config.debug&&console.log("[EventsModule] Subscribing:",c),setTimeout(()=>{this.pendingSubscriptions.has(s)&&(this.pendingSubscriptions.delete(s),i(new Error("Subscription timeout")))},1e4)})}async unsubscribe(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("Not connected");return new Promise((t,r)=>{const s={type:"unsubscribe",subscription_id:e};this.ws.send(JSON.stringify(s)),this.subscriptions.delete(e),this.config.debug&&console.log("[EventsModule] Unsubscribing:",e),t()})}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){const r=this.listeners.get(e);r&&r.delete(t)}sendTypingEvent(e,t){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return void(this.config.debug&&console.warn("[EventsModule] Cannot send typing event: not connected"));const r={type:"typing_event",chat_id:e,event:t};this.ws.send(JSON.stringify(r)),this.config.debug&&console.log("[EventsModule] Sent typing event:",r)}get isConnected(){return null!==this.ws&&this.ws.readyState===WebSocket.OPEN}get currentUserId(){return this.userId}getSubscriptions(){return new Map(this.subscriptions)}ping(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}updateConfig(e){this.config={...this.config,...e},this.ws&&this.ws.readyState===WebSocket.OPEN&&(this._stopPingInterval(),this._startPingInterval())}_buildWebSocketUrl(){return`${this.http.config.baseUrl.replace("https://","wss://").replace("http://","ws://")}/v1/events/ws`}_handleMessage(e){var t;switch(this.config.debug&&console.log("[EventsModule] Message received:",e),e.type){case"connected":this.isConnecting=!1,this.userId=e.user_id,this._emit("connect",e),this.authResolve&&(this.authResolve(e),this.authResolve=null,this.authReject=null),this._startPingInterval(),this.reconnectAttempts>0&&this._resubscribeAll(),this.reconnectAttempts=0;break;case"auth_error":this.isConnecting=!1;const r=e.error||"Authentication failed";this.authReject&&(this.authReject(new Error(r)),this.authResolve=null,this.authReject=null),null===(t=this.ws)||void 0===t||t.close(1008,r);break;case"subscription_confirmed":this._handleSubscriptionConfirmed(e);break;case"unsubscribed":this.subscriptions.delete(e.subscription_id);break;case"notification":this._emit("notification",e);break;case"system_notification":this._emit("system_notification",e);break;case"pong":break;case"error":this._emit("error",e);break;default:this.config.debug&&console.warn("[EventsModule] Unknown message type:",e.type)}}_handleSubscriptionConfirmed(e){const t=this.pendingSubscriptions.get(e.subscription_id);if(t){this.pendingSubscriptions.delete(e.subscription_id);const r={id:e.subscription_id,domain:e.domain,resource:e.resource,filters:e.filters};t.resolve(r)}this._emit("subscription_confirmed",e)}_emit(e,...t){const r=this.listeners.get(e);r&&r.forEach(r=>{try{r(...t)}catch(t){console.error(`[EventsModule] Error in ${e} listener:`,t)}})}_startPingInterval(){this.config.pingInterval>0&&(this.pingIntervalId=setInterval(()=>{this.ping()},this.config.pingInterval),this.config.debug&&console.log("[EventsModule] Ping interval started:",this.config.pingInterval))}_stopPingInterval(){this.pingIntervalId&&(clearInterval(this.pingIntervalId),this.pingIntervalId=null)}_scheduleReconnect(){if(this.reconnectAttempts>=this.config.maxReconnectAttempts)return this.config.debug&&console.log("[EventsModule] Max reconnect attempts reached"),void this._emit("error",new Error("Max reconnect attempts reached"));this.reconnectAttempts++;const e=Math.min(this.config.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),this.config.maxReconnectDelay);this.config.debug&&console.log(`[EventsModule] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts})`),this._emit("reconnecting",this.reconnectAttempts),this.reconnectTimeoutId=setTimeout(async()=>{try{await this._connect()}catch(e){this.config.debug&&console.error("[EventsModule] Reconnect failed:",e)}},e)}async _resubscribeAll(){this.config.debug&&console.log("[EventsModule] Re-subscribing to",this.subscriptions.size,"subscriptions");const e=new Map(this.subscriptions);this.subscriptions.clear();for(const[t,r]of e)try{await this.subscribe(r.domain,r.resource,r.options),this.config.debug&&console.log("[EventsModule] Re-subscribed:",r.domain,r.resource)}catch(e){this.config.debug&&console.error("[EventsModule] Failed to re-subscribe:",e)}}_cleanup(){this._stopPingInterval(),this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=null);for(const e of this.pendingSubscriptions.values())e.reject(new Error("Connection closed"));this.pendingSubscriptions.clear()}_generateId(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}}class p{constructor(e){this.http=e}async listOffers(e){const t=f(e),r=t?`offers/public/offers?${t}`:"offers/public/offers";return(await this.http.get(r,{skipAuth:!0})).data}async searchOffers(e){const t=f(e),r=t?`offers/public/offers/search?${t}`:"offers/public/offers/search";return(await this.http.get(r,{skipAuth:!0})).data}async getOffer(e){return(await this.http.get(`offers/public/offers/${e}`,{skipAuth:!0})).data}async getOfferAvailability(e,t){const r=f(t);return(await this.http.get(`offers/public/offers/${e}/availability?${r}`,{skipAuth:!0})).data.days}async listDestinations(e){const t=f(e),r=t?`geo/public/destinations?${t}`:"geo/public/destinations";return(await this.http.get(r,{skipAuth:!0})).data}async listCities(e){const t=f(e),r=t?`geo/public/cities?${t}`:"geo/public/cities";return(await this.http.get(r,{skipAuth:!0})).data}async listDocuments(e){const t=f(e),r=t?`terms/public/documents?${t}`:"terms/public/documents";return(await this.http.get(r,{skipAuth:!0})).data}async getDocument(e){return(await this.http.get(`terms/public/documents/${e}`,{skipAuth:!0})).data}}function f(e){if(!e)return"";const t=new URLSearchParams;for(const[r,s]of Object.entries(e))null!=s&&t.append(r,String(s));return t.toString()}class g{constructor(e){this.http=e}async list(e){const t=function(e){if(!e)return"";const t=new URLSearchParams;for(const[r,s]of Object.entries(e))null!=s&&t.append(r,String(s));return t.toString()}(e),r=t?`offers/offers?${t}`:"offers/offers";return(await this.http.get(r)).data}}class w{constructor(e){this.http=e}async estimate(e){return(await this.http.post("pricing/estimate",e)).data}}class m{constructor(e){this.http=e}async create(e){return(await this.http.post("booking/bookings",e)).data.booking}async quote(e,t){return(await this.http.post(`booking/bookings/${e}/quote`,t)).data.quote}async updateOptions(e,t){return(await this.http.put(`booking/bookings/${e}/options`,t)).data.booking}async confirmQuote(e,t){return(await this.http.post(`booking/bookings/${e}/confirm-quote`,t)).data.booking}async checkRequirement(e,t){return(await this.http.post(`booking/bookings/${e}/requirements/${t}/check`)).data.requirement}async list(e){const t=function(e){if(!e)return"";const t=new URLSearchParams;for(const[r,s]of Object.entries(e))null!=s&&t.append(r,String(s));return t.toString()}(e),r=t?`booking/bookings?${t}`:"booking/bookings";return(await this.http.get(r)).data}async get(e){return(await this.http.get(`booking/bookings/${e}`)).data.booking}async getRequirements(e){return(await this.http.get(`booking/bookings/${e}/requirements`)).data.requirements}async acknowledgeRequirement(e,t){return(await this.http.post(`booking/bookings/${e}/requirements/${t}/acknowledge`)).data.requirement}async cancelPreview(e){return(await this.http.post(`booking/bookings/${e}/cancel-preview`)).data}async cancel(e,t){return(await this.http.post(`booking/bookings/${e}/cancel`,t)).data.booking}async extend(e,t){return(await this.http.post(`booking/bookings/${e}/extend`,t)).data.booking}async confirmExtension(e){return(await this.http.post(`booking/bookings/${e}/confirm-extension`)).data.booking}async pay(e,t){return(await this.http.post(`booking/bookings/${e}/pay`,null!=t?t:{scope:"all"})).data}async renewPaymentLink(e){return(await this.http.post(`payment/links/${e}/renew`)).data}async listAvailableOptions(e){return(await this.http.get(`booking/bookings/${e}/available-options`)).data.masterclasses}async listBookingOptions(e){return(await this.http.get(`booking/bookings/${e}/options`)).data.options}async createOption(e,t){return(await this.http.post(`booking/bookings/${e}/options`,t)).data.option}async acceptOption(e,t){return(await this.http.post(`booking/bookings/${e}/options/${t}/accept`)).data.option}async cancelOption(e,t){return(await this.http.post(`booking/bookings/${e}/options/${t}/cancel`)).data.option}async payOption(e,t){return(await this.http.post(`booking/bookings/${e}/options/${t}/pay`)).data.option}async detach(e){return(await this.http.post(`booking/bookings/${e}/detach`)).data.booking}}class y{constructor(e){this.http=e}async getWallets(e){const t=b(e),r=t?`ledger/wallets?${t}`:"ledger/wallets";return(await this.http.get(r)).data}async getWallet(e){return(await this.http.get(`ledger/wallets/${e}`)).data.wallet}async getBalanceHistory(e,t){const r=b(t),s=r?`ledger/wallets/${e}/balance-history?${r}`:`ledger/wallets/${e}/balance-history`;return(await this.http.get(s)).data}async getTransactions(e){const t=b(e),r=t?`ledger/transactions?${t}`:"ledger/transactions";return(await this.http.get(r)).data}async getTransaction(e){return(await this.http.get(`ledger/transactions/${e}`)).data.transaction}}function b(e){if(!e)return"";const t=new URLSearchParams;for(const[r,s]of Object.entries(e))null!=s&&t.append(r,String(s));return t.toString()}class v{constructor(e){this.http=e}async getLink(e){return(await this.http.get(`payment/public/links/${e}`,{skipAuth:!0})).data}async getLinkStatus(e){return(await this.http.get(`payment/public/links/${e}/status`,{skipAuth:!0})).data}async createIntent(e,t){return(await this.http.post(`payment/public/links/${e}/intent`,t,{skipAuth:!0})).data}async confirmPayment(e,t){return(await this.http.post(`payment/public/links/${e}/confirm`,t,{skipAuth:!0})).data}async createLink(e={}){return(await this.http.post("payment/links/free",e)).data}async cancelLink(e){return(await this.http.post(`payment/links/${e}/cancel`)).data}async listLinks(e={}){const t=new URLSearchParams;e.status&&t.set("status",e.status),void 0!==e.limit&&t.set("limit",String(e.limit)),void 0!==e.offset&&t.set("offset",String(e.offset));const r=t.toString(),s=r?`payment/links?${r}`:"payment/links";return(await this.http.get(s)).data}}const _="terms/documents",k="terms/signatures";class S{constructor(e){this.http=e}async getDocument(e){return(await this.http.get(`${_}/${e}`)).data.document}async getDocumentByGroup(e,t){const r=t?`?lang=${t}`:"";return(await this.http.get(`${_}/by-group/${e}${r}`)).data}async getDiffSummary(e,t,r){const s=new URLSearchParams({from_version_id:t});r&&s.append("lang",r);return(await this.http.get(`${_}/${e}/diff-summary?${s}`)).data}async sign(e){return(await this.http.post(k,e)).data.signature}async listSignatures(e){const t=E(e),r=t?`${k}?${t}`:k;return(await this.http.get(r)).data}async getSignature(e){return(await this.http.get(`${k}/${e}`)).data.signature}async getPendingDocuments(e){const t=E(e),r=t?`${k}/pending?${t}`:`${k}/pending`;return(await this.http.get(r)).data}async getCompliance(e){const t=e?`?geo_zone=${e}`:"";return(await this.http.get(`${k}/compliance${t}`)).data}async checkSignature(e){return(await this.http.get(`${k}/check/${e}`)).data}async getDocumentSignatureHistory(e){return(await this.http.get(`${k}/document/${e}/history`)).data}}function E(e){if(!e)return"";const t=new URLSearchParams;for(const[r,s]of Object.entries(e))null!=s&&t.append(r,String(s));return t.toString()}class T{constructor(e){this.http=e}async checkVoucher(e,t){const r=new URLSearchParams({code:e});(null==t?void 0:t.offer_id)&&r.set("offer_id",t.offer_id),void 0!==(null==t?void 0:t.amount)&&r.set("amount",String(t.amount)),(null==t?void 0:t.booking_type)&&r.set("booking_type",t.booking_type);return(await this.http.get(`promo/vouchers/check?${r.toString()}`)).data}async getMyReferralCode(e){const t=e?`?first_name=${encodeURIComponent(e)}`:"";return(await this.http.get(`promo/referral/my-code${t}`)).data}async getMyRewards(){return(await this.http.get("promo/referral/my-rewards")).data}async enrollWithReferralCode(e){return(await this.http.post("promo/referral/enroll",{code:e})).data}}class R{constructor(e){const t=this.buildConfig(e);this.httpClient=new a(t),this.auth=new o(this.httpClient),this.user=new c(this.httpClient),this.system=new l(this.httpClient),this.apps=new h(this.httpClient),this.events=new d(this.httpClient,e.eventsConfig),this.publicApi=new p(this.httpClient),this.offers=new g(this.httpClient),this.pricing=new w(this.httpClient),this.booking=new m(this.httpClient),this.ledger=new y(this.httpClient),this.payment=new v(this.httpClient),this.terms=new S(this.httpClient),this.promo=new T(this.httpClient)}buildConfig(e){var s,n,i;let a;if("string"==typeof e.environment){const s=t[e.environment];if(!s)throw r.configError(`Unknown environment: ${e.environment}`);a=s.url}else a=e.environment&&"object"==typeof e.environment?e.environment.url:t.production.url;if(!e.appId||"string"!=typeof e.appId)throw r.configError("appId is required and must be a string");return{baseUrl:a,appId:e.appId,bearerToken:e.bearerToken,appSecret:e.appSecret,timeout:(null===(s=e.config)||void 0===s?void 0:s.timeout)||3e4,customHeaders:(null===(n=e.config)||void 0===n?void 0:n.customHeaders)||{},debug:(null===(i=e.config)||void 0===i?void 0:i.debug)||!1}}setBearerToken(e){if(!e||"string"!=typeof e)throw r.configError("Bearer token must be a non-empty string");this.httpClient.setBearerToken(e),this.events.setBearerToken(e)}clearBearerToken(){this.httpClient.clearBearerToken(),this.events.setBearerToken(null)}setAppSecret(e){if(!e||"string"!=typeof e)throw r.configError("App secret must be a non-empty string");this.httpClient.setAppSecret(e)}clearAppSecret(){this.httpClient.clearAppSecret()}getConfig(){return{baseUrl:this.httpClient.config.baseUrl,appId:this.httpClient.config.appId,timeout:this.httpClient.config.timeout,customHeaders:{...this.httpClient.config.customHeaders},debug:this.httpClient.config.debug}}updateConfig(e){this.httpClient.updateConfig(e)}setDebug(e){this.httpClient.updateConfig({debug:e})}static forEnvironment(e,t,r){return new R({environment:e,appId:t,bearerToken:r})}static forProduction(e="default",t){return R.forEnvironment("production",e,t)}static forDevelopment(e="default",t){return R.forEnvironment("development",e,t)}static forStaging(e="default",t){return R.forEnvironment("staging",e,t)}async directRequest(e,t="GET",r,s){return this.httpClient.directRequest(e,t,r,s)}async get(e,t){return this.httpClient.get(e,t)}async post(e,t,r){return this.httpClient.post(e,t,r)}async put(e,t,r){return this.httpClient.put(e,t,r)}async patch(e,t,r){return this.httpClient.patch(e,t,r)}async delete(e,t){return this.httpClient.delete(e,t)}}function O(e){if(e)try{e()}catch(e){console.warn("[AuthUtils] Error clearing app-specific cache:",e)}try{localStorage.clear()}catch(e){}try{sessionStorage.clear()}catch(e){}try{document.cookie.split(";").forEach(e=>{const t=e.indexOf("="),r=t>-1?e.substr(0,t).trim():e.trim();document.cookie=`${r}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`,document.cookie=`${r}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;domain=${window.location.hostname}`,document.cookie=`${r}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;domain=.${window.location.hostname}`})}catch(e){}}function $(){window.history.pushState(null,"",window.location.href);const e=()=>{window.history.pushState(null,"",window.location.href)};window.addEventListener("popstate",e),setTimeout(()=>{window.removeEventListener("popstate",e)},5e3)}function A(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(e);n<s.length;n++)t.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(e,s[n])&&(r[s[n]]=e[s[n]])}return r}function I(e,t,r,s){return new(r||(r=Promise))(function(n,i){function a(e){try{c(s.next(e))}catch(e){i(e)}}function o(e){try{c(s.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(a,o)}c((s=s.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class C extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class j extends C{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class P extends C{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class x extends C{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var N;!function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"}(N||(N={}));class U{constructor(e,{headers:t={},customFetch:r,region:s=N.Any}={}){this.url=e,this.headers=t,this.region=s,this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return I(this,arguments,void 0,function*(e,t={}){var r;let s,n;try{const{headers:i,method:a,body:o,signal:c,timeout:l}=t;let h={},{region:u}=t;u||(u=this.region);const d=new URL(`${this.url}/${e}`);let p;u&&"any"!==u&&(h["x-region"]=u,d.searchParams.set("forceFunctionRegion",u)),o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)?"undefined"!=typeof Blob&&o instanceof Blob||o instanceof ArrayBuffer?(h["Content-Type"]="application/octet-stream",p=o):"string"==typeof o?(h["Content-Type"]="text/plain",p=o):"undefined"!=typeof FormData&&o instanceof FormData?p=o:(h["Content-Type"]="application/json",p=JSON.stringify(o)):p=!o||"string"==typeof o||"undefined"!=typeof Blob&&o instanceof Blob||o instanceof ArrayBuffer||"undefined"!=typeof FormData&&o instanceof FormData?o:JSON.stringify(o);let f=c;l&&(n=new AbortController,s=setTimeout(()=>n.abort(),l),c?(f=n.signal,c.addEventListener("abort",()=>n.abort())):f=n.signal);const g=yield this.fetch(d.toString(),{method:a||"POST",headers:Object.assign(Object.assign(Object.assign({},h),this.headers),i),body:p,signal:f}).catch(e=>{throw new j(e)}),w=g.headers.get("x-relay-error");if(w&&"true"===w)throw new P(g);if(!g.ok)throw new x(g);let m,y=(null!==(r=g.headers.get("Content-Type"))&&void 0!==r?r:"text/plain").split(";")[0].trim();return m="application/json"===y?yield g.json():"application/octet-stream"===y||"application/pdf"===y?yield g.blob():"text/event-stream"===y?g:"multipart/form-data"===y?yield g.formData():yield g.text(),{data:m,error:null,response:g}}catch(e){return{data:null,error:e,response:e instanceof x||e instanceof P?e.context:void 0}}finally{s&&clearTimeout(s)}})}}var D=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}},L=class{constructor(e){var t,r;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!==(t=e.shouldThrowOnError)&&void 0!==t&&t,this.signal=e.signal,this.isMaybeSingle=null!==(r=e.isMaybeSingle)&&void 0!==r&&r,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(e,t){var r=this;void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json");let s=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{let t=null,s=null,n=null,i=e.status,a=e.statusText;if(e.ok){var o,c;if("HEAD"!==r.method){var l;const t=await e.text();""===t||(s="text/csv"===r.headers.get("Accept")||r.headers.get("Accept")&&(null===(l=r.headers.get("Accept"))||void 0===l?void 0:l.includes("application/vnd.pgrst.plan+text"))?t:JSON.parse(t))}const h=null===(o=r.headers.get("Prefer"))||void 0===o?void 0:o.match(/count=(exact|planned|estimated)/),u=null===(c=e.headers.get("content-range"))||void 0===c?void 0:c.split("/");h&&u&&u.length>1&&(n=parseInt(u[1])),r.isMaybeSingle&&"GET"===r.method&&Array.isArray(s)&&(s.length>1?(t={code:"PGRST116",details:`Results contain ${s.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},s=null,n=null,i=406,a="Not Acceptable"):s=1===s.length?s[0]:null)}else{var h;const n=await e.text();try{t=JSON.parse(n),Array.isArray(t)&&404===e.status&&(s=[],t=null,i=200,a="OK")}catch(r){404===e.status&&""===n?(i=204,a="No Content"):t={message:n}}if(t&&r.isMaybeSingle&&(null==t||null===(h=t.details)||void 0===h?void 0:h.includes("0 rows"))&&(t=null,i=200,a="OK"),t&&r.shouldThrowOnError)throw new D(t)}return{error:t,data:s,count:n,status:i,statusText:a}});return this.shouldThrowOnError||(s=s.catch(e=>{var t;let r="";const s=null==e?void 0:e.cause;if(s){var n,i,a,o;const t=null!==(n=null==s?void 0:s.message)&&void 0!==n?n:"",c=null!==(i=null==s?void 0:s.code)&&void 0!==i?i:"";r=`${null!==(a=null==e?void 0:e.name)&&void 0!==a?a:"FetchError"}: ${null==e?void 0:e.message}`,r+=`\n\nCaused by: ${null!==(o=null==s?void 0:s.name)&&void 0!==o?o:"Error"}: ${t}`,c&&(r+=` (${c})`),(null==s?void 0:s.stack)&&(r+=`\n${s.stack}`)}else{var c;r=null!==(c=null==e?void 0:e.stack)&&void 0!==c?c:""}return{error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:r,hint:"",code:""},data:null,count:null,status:0,statusText:""}})),s.then(e,t)}returns(){return this}overrideTypes(){return this}},B=class extends L{select(e){let t=!1;const r=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){const i=n?`${n}.order`:"order",a=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){const s=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:s=r}={}){const n=void 0===s?"offset":`${s}.offset`,i=void 0===s?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${e}`),this.url.searchParams.set(i,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return"GET"===this.method?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:n=!1,format:i="text"}={}){var a;const o=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,n?"wal":null].filter(Boolean).join("|"),c=null!==(a=this.headers.get("Accept"))&&void 0!==a?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${c}"; options=${o};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};const q=new RegExp("[,()]");var M=class extends B{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){const r=Array.from(new Set(t)).map(e=>"string"==typeof e&&q.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}notIn(e,t){const r=Array.from(new Set(t)).map(e=>"string"==typeof e&&q.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`not.in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let n="";"plain"===s?n="pl":"phrase"===s?n="ph":"websearch"===s&&(n="w");const i=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${n}fts${i}.${t}`),this}match(e){return Object.entries(e).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){const s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}},W=class{constructor(e,{headers:t={},schema:r,fetch:s}){this.url=e,this.headers=new Headers(t),this.schema=r,this.fetch=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){const{head:r=!1,count:s}=null!=t?t:{},n=r?"HEAD":"GET";let i=!1;const a=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!i?"":('"'===e&&(i=!i),e)).join(""),{url:o,headers:c}=this.cloneRequestState();return o.searchParams.set("select",a),s&&c.append("Prefer",`count=${s}`),new M({method:n,url:o,headers:c,schema:this.schema,fetch:this.fetch})}insert(e,{count:t,defaultToNull:r=!0}={}){var s;const{url:n,headers:i}=this.cloneRequestState();if(t&&i.append("Prefer",`count=${t}`),r||i.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);n.searchParams.set("columns",e.join(","))}}return new M({method:"POST",url:n,headers:i,schema:this.schema,body:e,fetch:null!==(s=this.fetch)&&void 0!==s?s:fetch})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!0}={}){var i;const{url:a,headers:o}=this.cloneRequestState();if(o.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==t&&a.searchParams.set("on_conflict",t),s&&o.append("Prefer",`count=${s}`),n||o.append("Prefer","missing=default"),Array.isArray(e)){const t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){const e=[...new Set(t)].map(e=>`"${e}"`);a.searchParams.set("columns",e.join(","))}}return new M({method:"POST",url:a,headers:o,schema:this.schema,body:e,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch})}update(e,{count:t}={}){var r;const{url:s,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new M({method:"PATCH",url:s,headers:n,schema:this.schema,body:e,fetch:null!==(r=this.fetch)&&void 0!==r?r:fetch})}delete({count:e}={}){var t;const{url:r,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new M({method:"DELETE",url:r,headers:s,schema:this.schema,fetch:null!==(t=this.fetch)&&void 0!==t?t:fetch})}},K=class e{constructor(e,{headers:t={},schema:r,fetch:s}={}){this.url=e,this.headers=new Headers(t),this.schemaName=r,this.fetch=s}from(e){if(!e||"string"!=typeof e||""===e.trim())throw new Error("Invalid relation name: relation must be a non-empty string.");return new W(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:s=!1,count:n}={}){var i;let a;const o=new URL(`${this.url}/rpc/${e}`);let c;const l=e=>null!==e&&"object"==typeof e&&(!Array.isArray(e)||e.some(l)),h=r&&Object.values(t).some(l);h?(a="POST",c=t):r||s?(a=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{o.searchParams.append(e,t)})):(a="POST",c=t);const u=new Headers(this.headers);return h?u.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&u.set("Prefer",`count=${n}`),new M({method:a,url:o,headers:u,schema:this.schemaName,body:c,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch})}};class J{constructor(){}static detectEnvironment(){var e;if("undefined"!=typeof WebSocket)return{type:"native",constructor:WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocket)return{type:"native",constructor:globalThis.WebSocket};if("undefined"!=typeof global&&void 0!==global.WebSocket)return{type:"native",constructor:global.WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("undefined"!=typeof globalThis&&globalThis.EdgeRuntime||"undefined"!=typeof navigator&&(null===(e=navigator.userAgent)||void 0===e?void 0:e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const t=globalThis.process;if(t){const e=t.versions;if(e&&e.node){const t=e.node,r=parseInt(t.replace(/^v/,"").split(".")[0]);return r>=22?void 0!==globalThis.WebSocket?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${r} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${r} detected without native WebSocket support.`,workaround:'For Node.js < 22, install "ws" package and provide it via the transport option:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}}const H="2.0.0",V=H,F=1e4;var G,z,Y,X,Q,Z;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(G||(G={})),function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"}(z||(z={})),function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"}(Y||(Y={})),function(e){e.websocket="websocket"}(X||(X={})),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(Q||(Q={}));class ee{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=null!=e?e:[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&"string"==typeof e.payload.event)return t(this._binaryEncodeUserBroadcastPush(e));let r=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer(null===(t=e.payload)||void 0===t?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;const s=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(e){var t,r;const s=null!==(r=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==r?r:{},n=(new TextEncoder).encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,n)}_encodeUserBroadcastPush(e,t,r){var s,n;const i=e.topic,a=null!==(s=e.ref)&&void 0!==s?s:"",o=null!==(n=e.join_ref)&&void 0!==n?n:"",c=e.payload.event,l=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},h=0===Object.keys(l).length?"":JSON.stringify(l);if(o.length>255)throw new Error(`joinRef length ${o.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(i.length>255)throw new Error(`topic length ${i.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(h.length>255)throw new Error(`metadata length ${h.length} exceeds maximum of 255`);const u=this.USER_BROADCAST_PUSH_META_LENGTH+o.length+a.length+i.length+c.length+h.length,d=new ArrayBuffer(this.HEADER_LENGTH+u);let p=new DataView(d),f=0;p.setUint8(f++,this.KINDS.userBroadcastPush),p.setUint8(f++,o.length),p.setUint8(f++,a.length),p.setUint8(f++,i.length),p.setUint8(f++,c.length),p.setUint8(f++,h.length),p.setUint8(f++,t),Array.from(o,e=>p.setUint8(f++,e.charCodeAt(0))),Array.from(a,e=>p.setUint8(f++,e.charCodeAt(0))),Array.from(i,e=>p.setUint8(f++,e.charCodeAt(0))),Array.from(c,e=>p.setUint8(f++,e.charCodeAt(0))),Array.from(h,e=>p.setUint8(f++,e.charCodeAt(0)));var g=new Uint8Array(d.byteLength+r.byteLength);return g.set(new Uint8Array(d),0),g.set(new Uint8Array(r),d.byteLength),g.buffer}decode(e,t){if(this._isArrayBuffer(e)){return t(this._binaryDecode(e))}if("string"==typeof e){const r=JSON.parse(e),[s,n,i,a,o]=r;return t({join_ref:s,ref:n,topic:i,event:a,payload:o})}return t({})}_binaryDecode(e){const t=new DataView(e),r=t.getUint8(0),s=new TextDecoder;if(r===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,s)}_decodeUserBroadcast(e,t,r){const s=t.getUint8(1),n=t.getUint8(2),i=t.getUint8(3),a=t.getUint8(4);let o=this.HEADER_LENGTH+4;const c=r.decode(e.slice(o,o+s));o+=s;const l=r.decode(e.slice(o,o+n));o+=n;const h=r.decode(e.slice(o,o+i));o+=i;const u=e.slice(o,e.byteLength),d=a===this.JSON_ENCODING?JSON.parse(r.decode(u)):u,p={type:this.BROADCAST_EVENT,event:l,payload:d};return i>0&&(p.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||"ArrayBuffer"===(null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e))):{}}}class te{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}!function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"}(Z||(Z={}));const re=(e,t,r={})=>{var s;const n=null!==(s=r.skipTypes)&&void 0!==s?s:[];return t?Object.keys(t).reduce((r,s)=>(r[s]=se(s,e,t,n),r),{}):{}},se=(e,t,r,s)=>{const n=t.find(t=>t.name===e),i=null==n?void 0:n.type,a=r[e];return i&&!s.includes(i)?ne(i,a):ie(a)},ne=(e,t)=>{if("_"===e.charAt(0)){const r=e.slice(1,e.length);return le(t,r)}switch(e){case Z.bool:return ae(t);case Z.float4:case Z.float8:case Z.int2:case Z.int4:case Z.int8:case Z.numeric:case Z.oid:return oe(t);case Z.json:case Z.jsonb:return ce(t);case Z.timestamp:return he(t);case Z.abstime:case Z.date:case Z.daterange:case Z.int4range:case Z.int8range:case Z.money:case Z.reltime:case Z.text:case Z.time:case Z.timestamptz:case Z.timetz:case Z.tsrange:case Z.tstzrange:default:return ie(t)}},ie=e=>e,ae=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},oe=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},ce=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return e}return e},le=(e,t)=>{if("string"!=typeof e)return e;const r=e.length-1,s=e[r];if("{"===e[0]&&"}"===s){let s;const n=e.slice(1,r);try{s=JSON.parse("["+n+"]")}catch(e){s=n?n.split(","):[]}return s.map(e=>ne(t,e))}return e},he=e=>"string"==typeof e?e.replace(" ","T"):e,ue=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};class de{constructor(e,t,r={},s=1e4){this.channel=e,this.event=t,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t(null===(r=this.receivedResp)||void 0===r?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);this.channel._on(this.refEvent,{},e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var pe,fe,ge,we;!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(pe||(pe={}));class me{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},e=>{const{onJoin:t,onLeave:r,onSync:s}=this.caller;this.joinRef=this.channel._joinRef(),this.state=me.syncState(this.state,e,t,r),this.pendingDiffs.forEach(e=>{this.state=me.syncDiff(this.state,e,t,r)}),this.pendingDiffs=[],s()}),this.channel._on(r.diff,{},e=>{const{onJoin:t,onLeave:r,onSync:s}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=me.syncDiff(this.state,e,t,r),s())}),this.onJoin((e,t,r)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:r})}),this.onLeave((e,t,r)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:r})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,s){const n=this.cloneDeep(e),i=this.transformState(t),a={},o={};return this.map(n,(e,t)=>{i[e]||(o[e]=t)}),this.map(i,(e,t)=>{const r=n[e];if(r){const s=t.map(e=>e.presence_ref),n=r.map(e=>e.presence_ref),i=t.filter(e=>n.indexOf(e.presence_ref)<0),c=r.filter(e=>s.indexOf(e.presence_ref)<0);i.length>0&&(a[e]=i),c.length>0&&(o[e]=c)}else a[e]=t}),this.syncDiff(n,{joins:a,leaves:o},r,s)}static syncDiff(e,t,r,s){const{joins:n,leaves:i}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(n,(t,s)=>{var n;const i=null!==(n=e[t])&&void 0!==n?n:[];if(e[t]=this.cloneDeep(s),i.length>0){const r=e[t].map(e=>e.presence_ref),s=i.filter(e=>r.indexOf(e.presence_ref)<0);e[t].unshift(...s)}r(t,i,s)}),this.map(i,(t,r)=>{let n=e[t];if(!n)return;const i=r.map(e=>e.presence_ref);n=n.filter(e=>i.indexOf(e.presence_ref)<0),e[t]=n,s(t,n,r),0===n.length&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{const s=e[r];return t[r]="metas"in s?s.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):s,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}!function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(fe||(fe={})),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"}(ge||(ge={})),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(we||(we={}));class ye{constructor(e,t={config:{}},r){var s,n;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=z.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},t.config),this.timeout=this.socket.timeout,this.joinPush=new de(this,Y.join,this.params,this.timeout),this.rejoinTimer=new te(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=z.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=z.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=z.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=z.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=z.errored,this.rejoinTimer.scheduleTimeout())}),this._on(Y.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new me(this),this.broadcastEndpointURL=ue(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(null===(n=null===(s=this.params.config)||void 0===s?void 0:s.broadcast)||void 0===n?void 0:n.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var r,s,n;if(this.socket.isConnected()||this.socket.connect(),this.state==z.closed){const{config:{broadcast:i,presence:a,private:o}}=this.params,c=null!==(s=null===(r=this.bindings.postgres_changes)||void 0===r?void 0:r.map(e=>e.filter))&&void 0!==s?s:[],l=!!this.bindings[ge.PRESENCE]&&this.bindings[ge.PRESENCE].length>0||!0===(null===(n=this.params.config.presence)||void 0===n?void 0:n.enabled),h={},u={broadcast:i,presence:Object.assign(Object.assign({},a),{enabled:l}),postgres_changes:c,private:o};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(t=>null==e?void 0:e(we.CHANNEL_ERROR,t)),this._onClose(()=>null==e?void 0:e(we.CLOSED)),this.updateJoinPayload(Object.assign({config:u},h)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:t})=>{var r;if(this.socket._isManualToken()||this.socket.setAuth(),void 0!==t){const s=this.bindings.postgres_changes,n=null!==(r=null==s?void 0:s.length)&&void 0!==r?r:0,i=[];for(let r=0;r<n;r++){const n=s[r],{filter:{event:a,schema:o,table:c,filter:l}}=n,h=t&&t[r];if(!(h&&h.event===a&&ye.isFilterValueEqual(h.schema,o)&&ye.isFilterValueEqual(h.table,c)&&ye.isFilterValueEqual(h.filter,l)))return this.unsubscribe(),this.state=z.errored,void(null==e||e(we.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes")));i.push(Object.assign(Object.assign({},n),{id:h.id}))}return this.bindings.postgres_changes=i,void(e&&e(we.SUBSCRIBED))}null==e||e(we.SUBSCRIBED)}).receive("error",t=>{this.state=z.errored,null==e||e(we.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(we.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this.state===z.joined&&e===ge.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,t,r)}async httpSend(e,t,r={}){var s;if(null==t)return Promise.reject("Payload is required for httpSend()");const n={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(n.Authorization=`Bearer ${this.socket.accessTokenValue}`);const i={method:"POST",headers:n,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,i,null!==(s=r.timeout)&&void 0!==s?s:this.timeout);if(202===a.status)return{success:!0};let o=a.statusText;try{const e=await a.json();o=e.error||e.message||o}catch(e){}return Promise.reject(new Error(o))}async send(e,t={}){var r,s;if(this._canPush()||"broadcast"!==e.type)return new Promise(r=>{var s,n,i;const a=this._push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null===(i=null===(n=null===(s=this.params)||void 0===s?void 0:s.config)||void 0===n?void 0:n.broadcast)||void 0===i?void 0:i.ack)||r("ok"),a.receive("ok",()=>r("ok")),a.receive("error",()=>r("error")),a.receive("timeout",()=>r("timed out"))});{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:n,payload:i}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);const o={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:n,payload:i,private:this.private}]})};try{const e=await this._fetchWithTimeout(this.broadcastEndpointURL,o,null!==(r=t.timeout)&&void 0!==r?r:this.timeout);return await(null===(s=e.body)||void 0===s?void 0:s.cancel()),e.ok?"ok":"error"}catch(e){return"AbortError"===e.name?"timed out":"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=z.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(Y.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(s=>{r=new de(this,Y.leave,{},e),r.receive("ok",()=>{t(),s("ok")}).receive("timeout",()=>{t(),s("timed out")}).receive("error",()=>{s("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{null==r||r.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=z.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){const s=new AbortController,n=setTimeout(()=>s.abort(),r),i=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:s.signal}));return clearTimeout(n),i}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new de(this,e,t,r);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>100){const e=this.pushBuffer.shift();e&&(e.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload))}}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var s,n;const i=e.toLocaleLowerCase(),{close:a,error:o,leave:c,join:l}=Y;if(r&&[a,o,c,l].indexOf(i)>=0&&r!==this._joinRef())return;let h=this._onMessage(i,t,r);if(t&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(i)?null===(s=this.bindings.postgres_changes)||void 0===s||s.filter(e=>{var t,r,s;return"*"===(null===(t=e.filter)||void 0===t?void 0:t.event)||(null===(s=null===(r=e.filter)||void 0===r?void 0:r.event)||void 0===s?void 0:s.toLocaleLowerCase())===i}).map(e=>e.callback(h,r)):null===(n=this.bindings[i])||void 0===n||n.filter(e=>{var r,s,n,a,o,c,l,h;if(["broadcast","presence","postgres_changes"].includes(i)){if("id"in e){const i=e.id,c=null===(r=e.filter)||void 0===r?void 0:r.event;return i&&(null===(s=t.ids)||void 0===s?void 0:s.includes(i))&&("*"===c||(null==c?void 0:c.toLocaleLowerCase())===(null===(n=t.data)||void 0===n?void 0:n.type.toLocaleLowerCase()))&&(!(null===(a=e.filter)||void 0===a?void 0:a.table)||e.filter.table===(null===(o=t.data)||void 0===o?void 0:o.table))}{const r=null===(l=null===(c=null==e?void 0:e.filter)||void 0===c?void 0:c.event)||void 0===l?void 0:l.toLocaleLowerCase();return"*"===r||r===(null===(h=null==t?void 0:t.event)||void 0===h?void 0:h.toLocaleLowerCase())}}return e.type.toLocaleLowerCase()===i}).map(e=>{if("object"==typeof h&&"ids"in h){const e=h.data,{schema:t,table:r,commit_timestamp:s,type:n,errors:i}=e,a={schema:t,table:r,commit_timestamp:s,eventType:n,new:{},old:{},errors:i};h=Object.assign(Object.assign({},a),this._getPayloadRecords(e))}e.callback(h,r)})}_isClosed(){return this.state===z.closed}_isJoined(){return this.state===z.joined}_isJoining(){return this.state===z.joining}_isLeaving(){return this.state===z.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const s=e.toLocaleLowerCase(),n={type:s,filter:t,callback:r};return this.bindings[s]?this.bindings[s].push(n):this.bindings[s]=[n],this}_off(e,t){const r=e.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(e=>{var s;return!((null===(s=e.type)||void 0===s?void 0:s.toLocaleLowerCase())===r&&ye.isEqual(e.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}static isFilterValueEqual(e,t){return(null!=e?e:void 0)===(null!=t?t:void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(Y.close,{},e)}_onError(e){this._on(Y.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=z.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=re(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=re(e.columns,e.old_record)),t}}const be=()=>{},ve=25e3,_e=10,ke=100,Se=[1e3,2e3,5e3,1e4];class Ee{constructor(e,t){var r;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=F,this.transport=null,this.heartbeatIntervalMs=ve,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=be,this.ref=0,this.reconnectTimer=null,this.vsn=V,this.logger=be,this.conn=null,this.sendBuffer=[],this.serializer=new ee,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!(null===(r=null==t?void 0:t.params)||void 0===r?void 0:r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${X.websocket}`,this.httpEndpoint=ue(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||null!==this.conn&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=J.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;if(t.includes("Node.js"))throw new Error(`${t}\n\nTo use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n npm install ws\n\n import ws from "ws"\n const client = new RealtimeClient(url, {\n ...options,\n transport: ws\n })`);throw new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const r=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(r),this._setConnectionState("disconnected")},"function"==typeof this.conn.close&&(e?this.conn.close(e,null!=t?t:""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case G.connecting:return Q.Connecting;case G.open:return Q.Open;case G.closing:return Q.Closing;default:return Q.Closed}}isConnected(){return this.connectionState()===Q.Open}isConnecting(){return"connecting"===this._connectionState}isDisconnecting(){return"disconnecting"===this._connectionState}channel(e,t={config:{}}){const r=`realtime:${e}`,s=this.getChannels().find(e=>e.topic===r);if(s)return s;{const r=new ye(`realtime:${e}`,t,this);return this.channels.push(r),r}}push(e){const{topic:t,event:r,payload:s,ref:n}=e,i=()=>{this.encode(e,e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)})};this.log("push",`${t} ${r} (${n})`,s),this.isConnected()?i():this.sendBuffer.push(i)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}return this._wasManualDisconnect=!1,null===(e=this.conn)||void 0===e||e.close(1e3,"heartbeat timeout"),void setTimeout(()=>{var e;this.isConnected()||null===(e=this.reconnectTimer)||void 0===e||e.scheduleTimeout()},ke)}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this._setAuthSafely("heartbeat")}else try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}}onHeartbeat(e){this.heartbeatCallback=e}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(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,e=>{if("phoenix"===e.topic&&"phx_reply"===e.event&&e.ref&&e.ref===this.pendingHeartbeatRef){const t=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback("ok"===e.payload.status?"ok":"error",t)}catch(e){this.log("error","error in heartbeat callback",e)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}const{topic:t,event:r,payload:s,ref:n}=e,i=n?`(${n})`:"",a=s.status||"";this.log("receive",`${a} ${t} ${r} ${i}`.trim(),s),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(r,s,n)),this._triggerStateCallbacks("message",e)})}_clearTimer(e){var t;"heartbeat"===e&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):"reconnect"===e&&(null===(t=this.reconnectTimer)||void 0===t||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in 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),this.conn.readyState===G.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===G.open||this.conn.readyState===G.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`);(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(e=>{this.log("error","error waiting for auth on connect",e),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this._terminateWorker()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||null===(t=this.reconnectTimer)||void 0===t||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(Y.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const r=e.match(/\?/)?"&":"?";return`${e}${r}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{const e=new Blob(['\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_setConnectionState(e,t=!1){this._connectionState=e,"connecting"===e?this._wasManualDisconnect=!1:"disconnecting"===e&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t,r=!1;if(e)t=e,r=!0;else if(this.accessToken)try{t=await this.accessToken()}catch(e){this.log("error","Error fetching access token from callback",e),t=this.accessTokenValue}else t=this.accessTokenValue;r?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{const r={access_token:t,version:"realtime-js/2.91.0"};t&&e.updateJoinPayload(r),e.joinedOnce&&e._isJoined()&&e._push(Y.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(t=>{this.log("error",`Error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(r=>{try{r(t)}catch(t){this.log("error",`error in ${e} callback`,t)}})}catch(t){this.log("error",`error triggering ${e} callbacks`,t)}}_setupReconnectionTimer(){this.reconnectTimer=new te(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},_e)},this.reconnectAfterMs)}_initializeOptions(e){var t,r,s,n,i,a,o,c,l,h,u,d;switch(this.transport=null!==(t=null==e?void 0:e.transport)&&void 0!==t?t:null,this.timeout=null!==(r=null==e?void 0:e.timeout)&&void 0!==r?r:F,this.heartbeatIntervalMs=null!==(s=null==e?void 0:e.heartbeatIntervalMs)&&void 0!==s?s:ve,this.worker=null!==(n=null==e?void 0:e.worker)&&void 0!==n&&n,this.accessToken=null!==(i=null==e?void 0:e.accessToken)&&void 0!==i?i:null,this.heartbeatCallback=null!==(a=null==e?void 0:e.heartbeatCallback)&&void 0!==a?a:be,this.vsn=null!==(o=null==e?void 0:e.vsn)&&void 0!==o?o:V,(null==e?void 0:e.params)&&(this.params=e.params),(null==e?void 0:e.logger)&&(this.logger=e.logger),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=null!==(c=null==e?void 0:e.reconnectAfterMs)&&void 0!==c?c:e=>Se[e-1]||1e4,this.vsn){case"1.0.0":this.encode=null!==(l=null==e?void 0:e.encode)&&void 0!==l?l:(e,t)=>t(JSON.stringify(e)),this.decode=null!==(h=null==e?void 0:e.decode)&&void 0!==h?h:(e,t)=>t(JSON.parse(e));break;case H:this.encode=null!==(u=null==e?void 0:e.encode)&&void 0!==u?u:this.serializer.encode.bind(this.serializer),this.decode=null!==(d=null==e?void 0:e.decode)&&void 0!==d?d:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if("undefined"!=typeof window&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl}}}var Te=class extends Error{constructor(e,t){super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown="CommitStateUnknownException"===t.icebergType||[500,502,504].includes(t.status)&&!0===t.icebergType?.includes("CommitState")}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};function Re(e){const t=e.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:a}){const o=function(e,t,r){const s=new URL(t,e);if(r)for(const[e,t]of Object.entries(r))void 0!==t&&s.searchParams.set(e,t);return s.toString()}(e.baseUrl,s,n),c=await async function(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:`Bearer ${e.token}`}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}(e.auth),l=await t(o,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...c,...a},body:i?JSON.stringify(i):void 0}),h=await l.text(),u=(l.headers.get("content-type")||"").includes("application/json"),d=u&&h?JSON.parse(h):h;if(!l.ok){const e=u?d:void 0,t=e?.error;throw new Te(t?.message??`Request failed with status ${l.status}`,{status:l.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:l.status,headers:l.headers,data:d}}}}function Oe(e){return e.join("")}var $e=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){const t=e?{parent:Oe(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){const r={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Oe(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Oe(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Oe(e.namespace)}`}),!0}catch(e){if(e instanceof Te&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof Te&&409===e.status)return;throw e}}};function Ae(e){return e.join("")}var Ie=class{constructor(e,t="",r){this.client=e,this.prefix=t,this.accessDelegation=r}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ae(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){const r={};this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Ae(e.namespace)}/tables`,body:t,headers:r})).data.metadata}async updateTable(e,t){const r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Ae(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Ae(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ae(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Ae(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof Te&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(r){if(r instanceof Te&&409===r.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw r}}},Ce=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const r=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=Re({baseUrl:r,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new $e(this.client,t),this.tableOps=new Ie(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}},je=class extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}};function Pe(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}var xe=class extends je{constructor(e,t,r){super(e),this.name="StorageApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},Ne=class extends je{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}};const Ue=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),De=e=>{if(Array.isArray(e))return e.map(e=>De(e));if("function"==typeof e||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([e,r])=>{const s=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""));t[s]=De(r)}),t};function Le(e){return(Le="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function Be(e){var t=function(e,t){if("object"!=Le(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=Le(s))return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==Le(t)?t:t+""}function qe(e,t,r){return(t=Be(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Me(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function We(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?Me(Object(r),!0).forEach(function(t){qe(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Me(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}const Ke=e=>{var t;return e.msg||e.message||e.error_description||("string"==typeof e.error?e.error:null===(t=e.error)||void 0===t?void 0:t.message)||JSON.stringify(e)},Je=async(e,t,r)=>{e instanceof await Response&&!(null==r?void 0:r.noResolveJson)?e.json().then(r=>{const s=e.status||500,n=(null==r?void 0:r.statusCode)||s+"";t(new xe(Ke(r),s,n))}).catch(e=>{t(new Ne(Ke(e),e))}):t(new Ne(Ke(e),e))},He=(e,t,r,s)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&s?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(s)?(n.headers=We({"Content-Type":"application/json"},null==t?void 0:t.headers),n.body=JSON.stringify(s)):n.body=s,(null==t?void 0:t.duplex)&&(n.duplex=t.duplex),We(We({},n),r)):n};async function Ve(e,t,r,s,n,i){return new Promise((a,o)=>{e(r,He(t,s,n,i)).then(e=>{if(!e.ok)throw e;return(null==s?void 0:s.noResolveJson)?e:e.json()}).then(e=>a(e)).catch(e=>Je(e,o,s))})}async function Fe(e,t,r,s){return Ve(e,"GET",t,r,s)}async function Ge(e,t,r,s,n){return Ve(e,"POST",t,s,n,r)}async function ze(e,t,r,s,n){return Ve(e,"PUT",t,s,n,r)}async function Ye(e,t,r,s,n){return Ve(e,"DELETE",t,s,n,r)}var Xe=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}async execute(){try{return{data:(await this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}};let Qe;Qe=Symbol.toStringTag;var Ze=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[Qe]="BlobDownloadBuilder",this.promise=null}asStream(){return new Xe(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){try{return{data:await(await this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}};const et={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},tt={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var rt=class{constructor(e,t={},r,s){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=r,this.fetch=Ue(s)}throwOnError(){return this.shouldThrowOnError=!0,this}async uploadOrUpdate(e,t,r,s){var n=this;try{let i;const a=We(We({},tt),s);let o=We(We({},n.headers),"POST"===e&&{"x-upsert":String(a.upsert)});const c=a.metadata;"undefined"!=typeof Blob&&r instanceof Blob?(i=new FormData,i.append("cacheControl",a.cacheControl),c&&i.append("metadata",n.encodeMetadata(c)),i.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",a.cacheControl),c&&!i.has("metadata")&&i.append("metadata",n.encodeMetadata(c))):(i=r,o["cache-control"]=`max-age=${a.cacheControl}`,o["content-type"]=a.contentType,c&&(o["x-metadata"]=n.toBase64(n.encodeMetadata(c))),("undefined"!=typeof ReadableStream&&i instanceof ReadableStream||i&&"object"==typeof i&&"pipe"in i&&"function"==typeof i.pipe)&&!a.duplex&&(a.duplex="half")),(null==s?void 0:s.headers)&&(o=We(We({},o),s.headers));const l=n._removeEmptyFolders(t),h=n._getFinalPath(l),u=await("PUT"==e?ze:Ge)(n.fetch,`${n.url}/object/${h}`,i,We({headers:o},(null==a?void 0:a.duplex)?{duplex:a.duplex}:{}));return{data:{path:l,id:u.Id,fullPath:u.Key},error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async upload(e,t,r){return this.uploadOrUpdate("POST",e,t,r)}async uploadToSignedUrl(e,t,r,s){var n=this;const i=n._removeEmptyFolders(e),a=n._getFinalPath(i),o=new URL(n.url+`/object/upload/sign/${a}`);o.searchParams.set("token",t);try{let e;const t=We({upsert:tt.upsert},s),a=We(We({},n.headers),{"x-upsert":String(t.upsert)});return"undefined"!=typeof Blob&&r instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),e.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(e=r,e.append("cacheControl",t.cacheControl)):(e=r,a["cache-control"]=`max-age=${t.cacheControl}`,a["content-type"]=t.contentType),{data:{path:i,fullPath:(await ze(n.fetch,o.toString(),e,{headers:a})).Key},error:null}}catch(e){if(n.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async createSignedUploadUrl(e,t){var r=this;try{let s=r._getFinalPath(e);const n=We({},r.headers);(null==t?void 0:t.upsert)&&(n["x-upsert"]="true");const i=await Ge(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),a=new URL(r.url+i.url),o=a.searchParams.get("token");if(!o)throw new je("No token returned by API");return{data:{signedUrl:a.toString(),path:e,token:o},error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async update(e,t,r){return this.uploadOrUpdate("PUT",e,t,r)}async move(e,t,r){var s=this;try{return{data:await Ge(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers}),error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async copy(e,t,r){var s=this;try{return{data:{path:(await Ge(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==r?void 0:r.destinationBucket},{headers:s.headers})).Key},error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async createSignedUrl(e,t,r){var s=this;try{let n=s._getFinalPath(e),i=await Ge(s.fetch,`${s.url}/object/sign/${n}`,We({expiresIn:t},(null==r?void 0:r.transform)?{transform:r.transform}:{}),{headers:s.headers});const a=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return i={signedUrl:encodeURI(`${s.url}${i.signedURL}${a}`)},{data:i,error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async createSignedUrls(e,t,r){var s=this;try{const n=await Ge(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:t,paths:e},{headers:s.headers}),i=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return{data:n.map(e=>We(We({},e),{},{signedUrl:e.signedURL?encodeURI(`${s.url}${e.signedURL}${i}`):null})),error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}download(e,t){const r=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",s=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),n=s?`?${s}`:"",i=this._getFinalPath(e);return new Ze(()=>Fe(this.fetch,`${this.url}/${r}/${i}${n}`,{headers:this.headers,noResolveJson:!0}),this.shouldThrowOnError)}async info(e){var t=this;const r=t._getFinalPath(e);try{return{data:De(await Fe(t.fetch,`${t.url}/object/info/${r}`,{headers:t.headers})),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async exists(e){var t=this;const r=t._getFinalPath(e);try{return await async function(e,t,r,s){return Ve(e,"HEAD",t,We(We({},r),{},{noResolveJson:!0}),s)}(t.fetch,`${t.url}/object/${r}`,{headers:t.headers}),{data:!0,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e)&&e instanceof Ne){const t=e.originalError;if([400,404].includes(null==t?void 0:t.status))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){const r=this._getFinalPath(e),s=[],n=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==n&&s.push(n);const i=void 0!==(null==t?void 0:t.transform)?"render/image":"object",a=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==a&&s.push(a);let o=s.join("&");return""!==o&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}${o}`)}}}async remove(e){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async list(e,t,r){var s=this;try{const n=We(We(We({},et),t),{},{prefix:e||""});return{data:await Ge(s.fetch,`${s.url}/object/list/${s.bucketId}`,n,{headers:s.headers},r),error:null}}catch(e){if(s.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async listV2(e,t){var r=this;try{const s=We({},e);return{data:await Ge(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{headers:r.headers},t),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const 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("&")}};const st="2.91.0",nt={"X-Client-Info":`storage-js/${st}`};var it=class{constructor(e,t={},r,s){this.shouldThrowOnError=!1;const n=new URL(e);(null==s?void 0:s.useNewHostname)&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase.")),this.url=n.href.replace(/\/$/,""),this.headers=We(We({},nt),t),this.fetch=Ue(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async listBuckets(e){var t=this;try{const r=t.listBucketOptionsToQueryString(e);return{data:await Fe(t.fetch,`${t.url}/bucket${r}`,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async getBucket(e){var t=this;try{return{data:await Fe(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async createBucket(e,t={public:!1}){var r=this;try{return{data:await Ge(r.fetch,`${r.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async updateBucket(e,t){var r=this;try{return{data:await ze(r.fetch,`${r.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async emptyBucket(e){var t=this;try{return{data:await Ge(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},at=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=We(We({},nt),t),this.fetch=Ue(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(e){var t=this;try{return{data:await Ge(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async listBuckets(e){var t=this;try{const r=new URLSearchParams;void 0!==(null==e?void 0:e.limit)&&r.set("limit",e.limit.toString()),void 0!==(null==e?void 0:e.offset)&&r.set("offset",e.offset.toString()),(null==e?void 0:e.sortColumn)&&r.set("sortColumn",e.sortColumn),(null==e?void 0:e.sortOrder)&&r.set("sortOrder",e.sortOrder),(null==e?void 0:e.search)&&r.set("search",e.search);const s=r.toString(),n=s?`${t.url}/bucket?${s}`:`${t.url}/bucket`;return{data:await Fe(t.fetch,n,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await Ye(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Pe(e))return{data:null,error:e};throw e}}from(e){var t=this;if(!(e=>!(!e||"string"!=typeof e)&&!(0===e.length||e.length>100)&&e.trim()===e&&!e.includes("/")&&!e.includes("\\")&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e))(e))throw new je("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");const r=new Ce({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(e,t){const r=e[t];return"function"!=typeof r?r:async(...t)=>{try{return{data:await r.apply(e,t),error:null}}catch(e){if(s)throw e;return{data:null,error:e}}}}})}};const ot={"X-Client-Info":`storage-js/${st}`,"Content-Type":"application/json"};var ct=class extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}};function lt(e){return"object"==typeof e&&null!==e&&"__isStorageVectorsError"in e}var ht=class extends ct{constructor(e,t,r){super(e),this.name="StorageVectorsApiError",this.status=t,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},ut=class extends ct{constructor(e,t){super(e),this.name="StorageVectorsUnknownError",this.originalError=t}};const dt=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),pt=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),ft=(e,t,r,s)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&s?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(s)?(n.headers=We({"Content-Type":"application/json"},null==t?void 0:t.headers),n.body=JSON.stringify(s)):n.body=s,We(We({},n),r)):n};async function gt(e,t,r,s,n,i){return new Promise((a,o)=>{e(r,ft(t,s,n,i)).then(e=>{if(!e.ok)throw e;if(null==s?void 0:s.noResolveJson)return e;const t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():{}}).then(e=>a(e)).catch(e=>(async(e,t,r)=>{if(e&&"object"==typeof e&&"status"in e&&"ok"in e&&"number"==typeof e.status&&!(null==r?void 0:r.noResolveJson)){const r=e.status||500,s=e;if("function"==typeof s.json)s.json().then(e=>{const s=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||r+"";t(new ht(pt(e),r,s))}).catch(()=>{const e=r+"";t(new ht(s.statusText||`HTTP ${r} error`,r,e))});else{const e=r+"";t(new ht(s.statusText||`HTTP ${r} error`,r,e))}}else t(new ut(pt(e),e))})(e,o,s))})}async function wt(e,t,r,s,n){return gt(e,"POST",t,s,n,r)}var mt=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=We(We({},ot),t),this.fetch=dt(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createIndex(e){var t=this;try{return{data:await wt(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(lt(e))return{data:null,error:e};throw e}}async getIndex(e,t){var r=this;try{return{data:await wt(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers}),error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(lt(e))return{data:null,error:e};throw e}}async listIndexes(e){var t=this;try{return{data:await wt(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(lt(e))return{data:null,error:e};throw e}}async deleteIndex(e,t){var r=this;try{return{data:await wt(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:r.headers})||{},error:null}}catch(e){if(r.shouldThrowOnError)throw e;if(lt(e))return{data:null,error:e};throw e}}},yt=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=We(We({},ot),t),this.fetch=dt(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async putVectors(e){var t=this;try{if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return{data:await wt(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(lt(e))return{data:null,error:e};throw e}}async getVectors(e){var t=this;try{return{data:await wt(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(lt(e))return{data:null,error:e};throw e}}async listVectors(e){var t=this;try{if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error("segmentIndex must be between 0 and "+(e.segmentCount-1))}return{data:await wt(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(lt(e))return{data:null,error:e};throw e}}async queryVectors(e){var t=this;try{return{data:await wt(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(lt(e))return{data:null,error:e};throw e}}async deleteVectors(e){var t=this;try{if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return{data:await wt(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(lt(e))return{data:null,error:e};throw e}}},bt=class{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=We(We({},ot),t),this.fetch=dt(r)}throwOnError(){return this.shouldThrowOnError=!0,this}async createBucket(e){var t=this;try{return{data:await wt(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(lt(e))return{data:null,error:e};throw e}}async getBucket(e){var t=this;try{return{data:await wt(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(lt(e))return{data:null,error:e};throw e}}async listBuckets(e={}){var t=this;try{return{data:await wt(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(lt(e))return{data:null,error:e};throw e}}async deleteBucket(e){var t=this;try{return{data:await wt(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{},error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(lt(e))return{data:null,error:e};throw e}}},vt=class extends bt{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new _t(this.url,this.headers,e,this.fetch)}async createBucket(e){return(()=>super.createBucket)().call(this,e)}async getBucket(e){return(()=>super.getBucket)().call(this,e)}async listBuckets(e={}){return(()=>super.listBuckets)().call(this,e)}async deleteBucket(e){return(()=>super.deleteBucket)().call(this,e)}},_t=class extends mt{constructor(e,t,r,s){super(e,t,s),this.vectorBucketName=r}async createIndex(e){return(()=>super.createIndex)().call(this,We(We({},e),{},{vectorBucketName:this.vectorBucketName}))}async listIndexes(e={}){return(()=>super.listIndexes)().call(this,We(We({},e),{},{vectorBucketName:this.vectorBucketName}))}async getIndex(e){return(()=>super.getIndex)().call(this,this.vectorBucketName,e)}async deleteIndex(e){return(()=>super.deleteIndex)().call(this,this.vectorBucketName,e)}index(e){return new kt(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},kt=class extends yt{constructor(e,t,r,s,n){super(e,t,n),this.vectorBucketName=r,this.indexName=s}async putVectors(e){var t=this;return(()=>super.putVectors)().call(t,We(We({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async getVectors(e){var t=this;return(()=>super.getVectors)().call(t,We(We({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async listVectors(e={}){var t=this;return(()=>super.listVectors)().call(t,We(We({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async queryVectors(e){var t=this;return(()=>super.queryVectors)().call(t,We(We({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}async deleteVectors(e){var t=this;return(()=>super.deleteVectors)().call(t,We(We({},e),{},{vectorBucketName:t.vectorBucketName,indexName:t.indexName}))}},St=class extends it{constructor(e,t={},r,s){super(e,t,r,s)}from(e){return new rt(this.url,this.headers,e,this.fetch)}get vectors(){return new vt(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new at(this.url+"/iceberg",this.headers,this.fetch)}};const Et="2.91.0",Tt=3e4,Rt=9e4,Ot={"X-Client-Info":`gotrue-js/${Et}`},$t="X-Supabase-Api-Version",At={timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"},It=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class Ct extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function jt(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class Pt extends Ct{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}class xt extends Ct{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class Nt extends Ct{constructor(e,t,r,s){super(e,r,s),this.name=t,this.status=r}}class Ut extends Nt{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class Dt extends Nt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Lt extends Nt{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class Bt extends Nt{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}}}class qt extends Nt{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}}}class Mt extends Nt{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}}class Wt extends Nt{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function Kt(e){return jt(e)&&"AuthRetryableFetchError"===e.name}class Jt extends Nt{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}class Ht extends Nt{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const Vt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Ft=" \t\n\r=".split(""),Gt=(()=>{const e=new Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<Ft.length;t+=1)e[Ft[t].charCodeAt(0)]=-2;for(let t=0;t<Vt.length;t+=1)e[Vt[t].charCodeAt(0)]=t;return e})();function zt(e,t,r){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;r(Vt[e]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;r(Vt[e]),t.queuedBits-=6}}function Yt(e,t,r){const s=Gt[e];if(!(s>-1)){if(-2===s)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}for(t.queue=t.queue<<6|s,t.queuedBits+=6;t.queuedBits>=8;)r(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}function Xt(e){const t=[],r=e=>{t.push(String.fromCodePoint(e))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=e=>{!function(e,t,r){if(0===t.utf8seq){if(e<=127)return void r(e);for(let r=1;r<6;r+=1)if(!(e>>7-r&1)){t.utf8seq=r;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else{if(4!==t.utf8seq)throw new Error("Invalid UTF-8 sequence");t.codepoint=7&e}t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&r(t.codepoint)}}(e,s,r)};for(let t=0;t<e.length;t+=1)Yt(e.charCodeAt(t),n,i);return t.join("")}function Qt(e,t){if(!(e<=127)){if(e<=2047)return t(192|e>>6),void t(128|63&e);if(e<=65535)return t(224|e>>12),t(128|e>>6&63),void t(128|63&e);if(e<=1114111)return t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),void t(128|63&e);throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}t(e)}function Zt(e){const t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)Yt(e.charCodeAt(t),r,s);return new Uint8Array(t)}function er(e){const t=[];return function(e,t){for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);if(s>55295&&s<=56319){const t=1024*(s-55296)&65535;s=65536+(e.charCodeAt(r+1)-56320&65535|t),r+=1}Qt(s,t)}}(e,e=>t.push(e)),new Uint8Array(t)}function tr(e){const t=[],r={queue:0,queuedBits:0},s=e=>{t.push(e)};return e.forEach(e=>zt(e,r,s)),zt(null,r,s),t.join("")}const rr=()=>"undefined"!=typeof window&&"undefined"!=typeof document,sr={tested:!1,writable:!1},nr=()=>{if(!rr())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(sr.tested)return sr.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),sr.tested=!0,sr.writable=!0}catch(e){sr.tested=!0,sr.writable=!1}return sr.writable};const ir=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),ar=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},or=async(e,t)=>{const r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return r}},cr=async(e,t)=>{await e.removeItem(t)};class lr{constructor(){this.promise=new lr.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function hr(e){const t=e.split(".");if(3!==t.length)throw new Ht("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!It.test(t[e]))throw new Ht("JWT not in base64url format");return{header:JSON.parse(Xt(t[0])),payload:JSON.parse(Xt(t[1])),signature:Zt(t[2]),raw:{header:t[0],payload:t[1]}}}function ur(e){return("0"+e.toString(16)).substr(-2)}async function dr(e){if(!("undefined"!=typeof crypto&&void 0!==crypto.subtle&&"undefined"!=typeof TextEncoder))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;const t=await async function(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t),s=new Uint8Array(r);return Array.from(s).map(e=>String.fromCharCode(e)).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function pr(e,t,r=!1){const s=function(){const e=new Uint32Array(56);if("undefined"==typeof crypto){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length;let r="";for(let s=0;s<56;s++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,ur).join("")}();let n=s;r&&(n+="/PASSWORD_RECOVERY"),await ar(e,`${t}-code-verifier`,n);const i=await dr(s);return[i,s===i?"plain":"s256"]}lr.promiseConstructor=Promise;const fr=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;const gr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function wr(e){if(!gr.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function mr(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){const e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function yr(e){return JSON.parse(JSON.stringify(e))}const br=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),vr=[502,503,504];async function _r(e){var t,r;if(!("object"==typeof(r=e)&&null!==r&&"status"in r&&"ok"in r&&"json"in r&&"function"==typeof r.json))throw new Wt(br(e),0);if(vr.includes(e.status))throw new Wt(br(e),e.status);let s,n;try{s=await e.json()}catch(e){throw new xt(br(e),e)}const i=function(e){const t=e.headers.get($t);if(!t)return null;if(!t.match(fr))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(e){return null}}(e);if(i&&i.getTime()>=At.timestamp&&"object"==typeof s&&s&&"string"==typeof s.code?n=s.code:"object"==typeof s&&s&&"string"==typeof s.error_code&&(n=s.error_code),n){if("weak_password"===n)throw new Jt(br(s),e.status,(null===(t=s.weak_password)||void 0===t?void 0:t.reasons)||[]);if("session_not_found"===n)throw new Ut}else if("object"==typeof s&&s&&"object"==typeof s.weak_password&&s.weak_password&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new Jt(br(s),e.status,s.weak_password.reasons);throw new Pt(br(s),e.status||500,n)}async function kr(e,t,r,s){var n;const i=Object.assign({},null==s?void 0:s.headers);i[$t]||(i[$t]=At.name),(null==s?void 0:s.jwt)&&(i.Authorization=`Bearer ${s.jwt}`);const a=null!==(n=null==s?void 0:s.query)&&void 0!==n?n:{};(null==s?void 0:s.redirectTo)&&(a.redirect_to=s.redirectTo);const o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",c=await async function(e,t,r,s,n,i){const a=((e,t,r,s)=>{const n={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))})(t,s,n,i);let o;try{o=await e(r,Object.assign({},a))}catch(e){throw console.error(e),new Wt(br(e),0)}o.ok||await _r(o);if(null==s?void 0:s.noResolveJson)return o;try{return await o.json()}catch(e){await _r(e)}}(e,t,r+o,{headers:i,noResolveJson:null==s?void 0:s.noResolveJson},{},null==s?void 0:s.body);return(null==s?void 0:s.xform)?null==s?void 0:s.xform(c):{data:Object.assign({},c),error:null}}function Sr(e){var t;let r=null;var s;(function(e){return e.access_token&&e.refresh_token&&e.expires_in})(e)&&(r=Object.assign({},e),e.expires_at||(r.expires_at=(s=e.expires_in,Math.round(Date.now()/1e3)+s)));return{data:{session:r,user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function Er(e){const t=Sr(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function Tr(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function Rr(e){return{data:e,error:null}}function Or(e){const{action_link:t,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=e,a=A(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]);return{data:{properties:{action_link:t,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i},user:Object.assign({},a)},error:null}}function $r(e){return e}const Ar=["global","local","others"];class Ir{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=ir(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)}}async signOut(e,t=Ar[0]){if(Ar.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Ar.join(", ")}`);try{return await kr(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(jt(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await kr(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Tr})}catch(e){if(jt(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{const{options:t}=e,r=A(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=null==r?void 0:r.newEmail,delete s.newEmail),await kr(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:Or,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(jt(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await kr(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Tr})}catch(e){if(jt(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,r,s,n,i,a,o;try{const c={nextPage:null,lastPage:0,total:0},l=await kr(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(n=null===(s=null==e?void 0:e.perPage)||void 0===s?void 0:s.toString())&&void 0!==n?n:""},xform:$r});if(l.error)throw l.error;const h=await l.json(),u=null!==(i=l.headers.get("x-total-count"))&&void 0!==i?i:0,d=null!==(o=null===(a=l.headers.get("link"))||void 0===a?void 0:a.split(","))&&void 0!==o?o:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);c[`${r}Page`]=t}),c.total=parseInt(u)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(e){if(jt(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){wr(e);try{return await kr(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Tr})}catch(e){if(jt(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){wr(e);try{return await kr(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Tr})}catch(e){if(jt(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){wr(e);try{return await kr(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Tr})}catch(e){if(jt(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){wr(e.userId);try{const{data:t,error:r}=await kr(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if(jt(e))return{data:null,error:e};throw e}}async _deleteFactor(e){wr(e.userId),wr(e.id);try{return{data:await kr(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(jt(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){var t,r,s,n,i,a,o;try{const c={nextPage:null,lastPage:0,total:0},l=await kr(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(n=null===(s=null==e?void 0:e.perPage)||void 0===s?void 0:s.toString())&&void 0!==n?n:""},xform:$r});if(l.error)throw l.error;const h=await l.json(),u=null!==(i=l.headers.get("x-total-count"))&&void 0!==i?i:0,d=null!==(o=null===(a=l.headers.get("link"))||void 0===a?void 0:a.split(","))&&void 0!==o?o:[];return d.length>0&&(d.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);c[`${r}Page`]=t}),c.total=parseInt(u)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(e){if(jt(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await kr(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(jt(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await kr(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(jt(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await kr(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(jt(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await kr(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(jt(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await kr(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(jt(e))return{data:null,error:e};throw e}}}function Cr(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}const jr=!!(globalThis&&nr()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"));class Pr extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class xr extends Pr{}async function Nr(e,t,r){jr&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const s=new globalThis.AbortController;return t>0&&setTimeout(()=>{s.abort(),jr&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:s.signal},async s=>{if(!s){if(0===t)throw jr&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new xr(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(jr)try{const e=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(e,null," "))}catch(e){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",e)}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 r()}jr&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,s.name);try{return await r()}finally{jr&&console.log("@supabase/gotrue-js: navigatorLock: released",e,s.name)}}))}function Ur(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function Dr(e){const t=(new TextEncoder).encode(e);return"0x"+Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}class Lr extends Error{constructor({message:e,code:t,cause:r,name:s}){var n;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=null!==(n=null!=s?s:r instanceof Error?r.name:void 0)&&void 0!==n?n:"Unknown Error",this.code=t}}class Br extends Lr{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function qr({error:e,options:t}){var r,s,n;const{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new Lr({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===(null===(r=i.authenticatorSelection)||void 0===r?void 0:r.requireResidentKey))return new Lr({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===(null===(s=i.authenticatorSelection)||void 0===s?void 0:s.userVerification))return new Lr({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===(null===(n=i.authenticatorSelection)||void 0===n?void 0:n.userVerification))return new Lr({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new Lr({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new Lr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name){return 0===i.pubKeyCredParams.filter(e=>"public-key"===e.type).length?new Lr({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new Lr({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e})}if("SecurityError"===e.name){const t=window.location.hostname;if(!Fr(t))return new Lr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(i.rp.id!==t)return new Lr({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new Lr({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new Lr({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new Lr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function Mr({error:e,options:t}){const{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new Lr({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new Lr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!Fr(t))return new Lr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(r.rpId!==t)return new Lr({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new Lr({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new Lr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}const Wr=new class{createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function Kr(e){if(!e)throw new Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:t,user:r,excludeCredentials:s}=e,n=A(e,["challenge","user","excludeCredentials"]),i=Zt(t).buffer,a=Object.assign(Object.assign({},r),{id:Zt(r.id).buffer}),o=Object.assign(Object.assign({},n),{challenge:i,user:a});if(s&&s.length>0){o.excludeCredentials=new Array(s.length);for(let e=0;e<s.length;e++){const t=s[e];o.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:Zt(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return o}function Jr(e){if(!e)throw new Error("Credential request options are required");if("undefined"!=typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);const{challenge:t,allowCredentials:r}=e,s=A(e,["challenge","allowCredentials"]),n=Zt(t).buffer,i=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let e=0;e<r.length;e++){const t=r[e];i.allowCredentials[e]=Object.assign(Object.assign({},t),{id:Zt(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return i}function Hr(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const r=e;return{id:e.id,rawId:e.id,response:{attestationObject:tr(new Uint8Array(e.response.attestationObject)),clientDataJSON:tr(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:null!==(t=r.authenticatorAttachment)&&void 0!==t?t:void 0}}function Vr(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const r=e,s=e.getClientExtensionResults(),n=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:tr(new Uint8Array(n.authenticatorData)),clientDataJSON:tr(new Uint8Array(n.clientDataJSON)),signature:tr(new Uint8Array(n.signature)),userHandle:n.userHandle?tr(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:null!==(t=r.authenticatorAttachment)&&void 0!==t?t:void 0}}function Fr(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function Gr(){var e,t;return!!(rr()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null===(e=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===e?void 0:e.create)&&"function"==typeof(null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.get))}const zr={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Yr={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Xr(...e){const t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),r=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),s={};for(const n of e)if(n)for(const e in n){const i=n[e];if(void 0!==i)if(Array.isArray(i))s[e]=i;else if(r(i))s[e]=i;else if(t(i)){const r=s[e];t(r)?s[e]=Xr(r,i):s[e]=Xr(i)}else s[e]=i}return s}class Qr{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:t,friendlyName:r,signal:s},n){try{const{data:i,error:a}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!i)return{data:null,error:a};const o=null!=s?s:Wr.createNewAbortSignal();if("create"===i.webauthn.type){const{user:e}=i.webauthn.credential_options.publicKey;e.name||(e.name=`${e.id}:${r}`),e.displayName||(e.displayName=e.name)}switch(i.webauthn.type){case"create":{const t=function(e,t){return Xr(zr,e,t||{})}(i.webauthn.credential_options.publicKey,null==n?void 0:n.create),{data:r,error:s}=await async function(e){try{const t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new Br("Browser returned unexpected credential type",t)}:{data:null,error:new Br("Empty credential response",t)}}catch(t){return{data:null,error:qr({error:t,options:e})}}}({publicKey:t,signal:o});return r?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:r}},error:null}:{data:null,error:s}}case"request":{const t=function(e,t){return Xr(Yr,e,t||{})}(i.webauthn.credential_options.publicKey,null==n?void 0:n.request),{data:r,error:s}=await async function(e){try{const t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new Br("Browser returned unexpected credential type",t)}:{data:null,error:new Br("Empty credential response",t)}}catch(t){return{data:null,error:Mr({error:t,options:e})}}}(Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:t,signal:o}));return r?{data:{factorId:e,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:r}},error:null}:{data:null,error:s}}}}catch(e){return jt(e)?{data:null,error:e}:{data:null,error:new xt("Unexpected error in challenge",e)}}}async _verify({challengeId:e,factorId:t,webauthn:r}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:r})}async _authenticate({factorId:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:s}={}},n){if(!t)return{data:null,error:new Ct("rpId is required for WebAuthn authentication")};try{if(!Gr())return{data:null,error:new xt("Browser does not support WebAuthn",null)};const{data:i,error:a}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:s},{request:n});if(!i)return{data:null,error:a};const{webauthn:o}=i;return this._verify({factorId:e,challengeId:i.challengeId,webauthn:{type:o.type,rpId:t,rpOrigins:r,credential_response:o.credential_response}})}catch(e){return jt(e)?{data:null,error:e}:{data:null,error:new xt("Unexpected error in authenticate",e)}}}async _register({friendlyName:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:r=("undefined"!=typeof window?[window.location.origin]:void 0),signal:s}={}},n){if(!t)return{data:null,error:new Ct("rpId is required for WebAuthn registration")};try{if(!Gr())return{data:null,error:new xt("Browser does not support WebAuthn",null)};const{data:i,error:a}=await this._enroll({friendlyName:e});if(!i)return await this.client.mfa.listFactors().then(t=>{var r;return null===(r=t.data)||void 0===r?void 0:r.all.find(t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:a};const{data:o,error:c}=await this._challenge({factorId:i.id,friendlyName:i.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:s},{create:n});return o?this._verify({factorId:i.id,challengeId:o.challengeId,webauthn:{rpId:t,rpOrigins:r,type:o.webauthn.type,credential_response:o.webauthn.credential_response}}):{data:null,error:c}}catch(e){return jt(e)?{data:null,error:e}:{data:null,error:new xt("Unexpected error in register",e)}}}}!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();const Zr={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ot,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4};async function es(e,t,r){return await r()}const ts={};class rs{get jwks(){var e,t;return null!==(t=null===(e=ts[this.storageKey])||void 0===e?void 0:e.jwks)&&void 0!==t?t:{keys:[]}}set jwks(e){ts[this.storageKey]=Object.assign(Object.assign({},ts[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!==(t=null===(e=ts[this.storageKey])||void 0===e?void 0:e.cachedAt)&&void 0!==t?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){ts[this.storageKey]=Object.assign(Object.assign({},ts[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=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;const n=Object.assign(Object.assign({},Zr),e);if(this.storageKey=n.storageKey,this.instanceID=null!==(t=rs.nextInstanceID[this.storageKey])&&void 0!==t?t:0,rs.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!n.debug,"function"==typeof n.debug&&(this.logger=n.debug),this.instanceID>0&&rr()){const e=`${this._logPrefix()} 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.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=n.persistSession,this.autoRefreshToken=n.autoRefreshToken,this.admin=new Ir({url:n.url,headers:n.headers,fetch:n.fetch}),this.url=n.url,this.headers=n.headers,this.fetch=ir(n.fetch),this.lock=n.lock||es,this.detectSessionInUrl=n.detectSessionInUrl,this.flowType=n.flowType,this.hasCustomAuthorizationHeader=n.hasCustomAuthorizationHeader,this.throwOnError=n.throwOnError,this.lockAcquireTimeout=n.lockAcquireTimeout,n.lock?this.lock=n.lock:this.persistSession&&rr()&&(null===(r=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===r?void 0:r.locks)?this.lock=Nr:this.lock=es,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),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),webauthn:new Qr(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(n.storage?this.storage=n.storage:nr()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Cr(this.memoryStorage)),n.userStorage&&(this.userStorage=n.userStorage)):(this.memoryStorage={},this.storage=Cr(this.memoryStorage)),rr()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null===(s=this.broadcastChannel)||void 0===s||s.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)})}this.initialize()}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${Et}) ${(new Date).toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{let t={},r="none";if(rr()&&(t=function(e){const t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach((e,r)=>{t[r]=e})}catch(e){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),rr()&&this.detectSessionInUrl&&"none"!==r){const{data:s,error:n}=await this._getSessionFromURL(t,r);if(n){if(this._debug("#_initialize()","error detecting session from URL",n),function(e){return jt(e)&&"AuthImplicitGrantRedirectError"===e.name}(n)){const t=null===(e=n.details)||void 0===e?void 0:e.code;if("identity_already_exists"===t||"identity_not_found"===t||"single_identity_not_deletable"===t)return{error:n}}return{error:n}}const{session:i,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",i,"redirect type",a),await this._saveSession(i),setTimeout(async()=>{"recovery"===a?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return jt(e)?this._returnResult({error:e}):this._returnResult({error:new xt("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,s;try{const n=await kr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(r=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==r?r:{},gotrue_meta_security:{captcha_token:null===(s=null==e?void 0:e.options)||void 0===s?void 0:s.captchaToken}},xform:Sr}),{data:i,error:a}=n;if(a||!i)return this._returnResult({data:{user:null,session:null},error:a});const o=i.session,c=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:c,session:o},error:null})}catch(e){if(jt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){var t,r,s;try{let n;if("email"in e){const{email:r,password:s,options:i}=e;let a=null,o=null;"pkce"===this.flowType&&([a,o]=await pr(this.storage,this.storageKey)),n=await kr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==i?void 0:i.emailRedirectTo,body:{email:r,password:s,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:a,code_challenge_method:o},xform:Sr})}else{if(!("phone"in e))throw new Lt("You must provide either an email or phone number and a password");{const{phone:t,password:i,options:a}=e;n=await kr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:i,data:null!==(r=null==a?void 0:a.data)&&void 0!==r?r:{},channel:null!==(s=null==a?void 0:a.channel)&&void 0!==s?s:"sms",gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}},xform:Sr})}}const{data:i,error:a}=n;if(a||!i)return await cr(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});const o=i.session,c=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:c,session:o},error:null})}catch(e){if(await cr(this.storage,`${this.storageKey}-code-verifier`),jt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if("email"in e){const{email:r,password:s,options:n}=e;t=await kr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:Er})}else{if(!("phone"in e))throw new Lt("You must provide either an email or phone number and a password");{const{phone:r,password:s,options:n}=e;t=await kr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},xform:Er})}}const{data:r,error:s}=t;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){const e=new Dt;return this._returnResult({data:{user:null,session:null},error:e})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(e){if(jt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){var t,r,s,n;return await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(s=e.options)||void 0===s?void 0:s.queryParams,skipBrowserRedirect:null===(n=e.options)||void 0===n?void 0:n.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:t}=e;switch(t){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){var t,r,s,n,i,a,o,c,l,h,u;let d,p;if("message"in e)d=e.message,p=e.signature;else{const{chain:h,wallet:u,statement:f,options:g}=e;let w;if(rr())if("object"==typeof u)w=u;else{const e=window;if(!("ethereum"in e)||"object"!=typeof e.ethereum||!("request"in e.ethereum)||"function"!=typeof e.ethereum.request)throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.");w=e.ethereum}else{if("object"!=typeof u||!(null==g?void 0:g.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=u}const m=new URL(null!==(t=null==g?void 0:g.url)&&void 0!==t?t:window.location.href),y=await w.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!y||0===y.length)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const b=Ur(y[0]);let v=null===(r=null==g?void 0:g.signInWithEthereum)||void 0===r?void 0:r.chainId;if(!v){const e=await w.request({method:"eth_chainId"});v=parseInt(e,16)}d=function(e){var t;const{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:a,notBefore:o,requestId:c,resources:l,scheme:h,uri:u,version:d}=e;if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!u)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==d)throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`);if(null===(t=e.statement)||void 0===t?void 0:t.includes("\n"))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);const p=`${h?`${h}://${s}`:s} wants you to sign in with your Ethereum account:\n${Ur(e.address)}\n\n${e.statement?`${e.statement}\n`:""}`;let f=`URI: ${u}\nVersion: ${d}\nChain ID: ${r}${a?`\nNonce: ${a}`:""}\nIssued At: ${i.toISOString()}`;if(n&&(f+=`\nExpiration Time: ${n.toISOString()}`),o&&(f+=`\nNot Before: ${o.toISOString()}`),c&&(f+=`\nRequest ID: ${c}`),l){let e="\nResources:";for(const t of l){if(!t||"string"!=typeof t)throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}f+=e}return`${p}\n${f}`}({domain:m.host,address:b,statement:f,uri:m.href,version:"1",chainId:v,nonce:null===(s=null==g?void 0:g.signInWithEthereum)||void 0===s?void 0:s.nonce,issuedAt:null!==(i=null===(n=null==g?void 0:g.signInWithEthereum)||void 0===n?void 0:n.issuedAt)&&void 0!==i?i:new Date,expirationTime:null===(a=null==g?void 0:g.signInWithEthereum)||void 0===a?void 0:a.expirationTime,notBefore:null===(o=null==g?void 0:g.signInWithEthereum)||void 0===o?void 0:o.notBefore,requestId:null===(c=null==g?void 0:g.signInWithEthereum)||void 0===c?void 0:c.requestId,resources:null===(l=null==g?void 0:g.signInWithEthereum)||void 0===l?void 0:l.resources}),p=await w.request({method:"personal_sign",params:[Dr(d),b]})}try{const{data:t,error:r}=await kr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:d,signature:p},(null===(h=e.options)||void 0===h?void 0:h.captchaToken)?{gotrue_meta_security:{captcha_token:null===(u=e.options)||void 0===u?void 0:u.captchaToken}}:null),xform:Sr});if(r)throw r;if(!t||!t.session||!t.user){const e=new Dt;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(jt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){var t,r,s,n,i,a,o,c,l,h,u,d;let p,f;if("message"in e)p=e.message,f=e.signature;else{const{chain:u,wallet:d,statement:g,options:w}=e;let m;if(rr())if("object"==typeof d)m=d;else{const e=window;if(!("solana"in e)||"object"!=typeof e.solana||!("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.");m=e.solana}else{if("object"!=typeof d||!(null==w?void 0:w.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");m=d}const y=new URL(null!==(t=null==w?void 0:w.url)&&void 0!==t?t:window.location.href);if("signIn"in m&&m.signIn){const e=await m.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},null==w?void 0:w.signInWithSolana),{version:"1",domain:y.host,uri:y.href}),g?{statement:g}:null));let t;if(Array.isArray(e)&&e[0]&&"object"==typeof e[0])t=e[0];else{if(!(e&&"object"==typeof e&&"signedMessage"in e&&"signature"in e))throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");t=e}if(!("signedMessage"in t&&"signature"in t&&("string"==typeof t.signedMessage||t.signedMessage instanceof Uint8Array)&&t.signature instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");p="string"==typeof t.signedMessage?t.signedMessage:(new TextDecoder).decode(t.signedMessage),f=t.signature}else{if(!("signMessage"in m&&"function"==typeof m.signMessage&&"publicKey"in m&&"object"==typeof m&&m.publicKey&&"toBase58"in m.publicKey&&"function"==typeof m.publicKey.toBase58))throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${y.host} wants you to sign in with your Solana account:`,m.publicKey.toBase58(),...g?["",g,""]:[""],"Version: 1",`URI: ${y.href}`,`Issued At: ${null!==(s=null===(r=null==w?void 0:w.signInWithSolana)||void 0===r?void 0:r.issuedAt)&&void 0!==s?s:(new Date).toISOString()}`,...(null===(n=null==w?void 0:w.signInWithSolana)||void 0===n?void 0:n.notBefore)?[`Not Before: ${w.signInWithSolana.notBefore}`]:[],...(null===(i=null==w?void 0:w.signInWithSolana)||void 0===i?void 0:i.expirationTime)?[`Expiration Time: ${w.signInWithSolana.expirationTime}`]:[],...(null===(a=null==w?void 0:w.signInWithSolana)||void 0===a?void 0:a.chainId)?[`Chain ID: ${w.signInWithSolana.chainId}`]:[],...(null===(o=null==w?void 0:w.signInWithSolana)||void 0===o?void 0:o.nonce)?[`Nonce: ${w.signInWithSolana.nonce}`]:[],...(null===(c=null==w?void 0:w.signInWithSolana)||void 0===c?void 0:c.requestId)?[`Request ID: ${w.signInWithSolana.requestId}`]:[],...(null===(h=null===(l=null==w?void 0:w.signInWithSolana)||void 0===l?void 0:l.resources)||void 0===h?void 0:h.length)?["Resources",...w.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");const e=await m.signMessage((new TextEncoder).encode(p),"utf8");if(!(e&&e instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");f=e}}try{const{data:t,error:r}=await kr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:tr(f)},(null===(u=e.options)||void 0===u?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null===(d=e.options)||void 0===d?void 0:d.captchaToken}}:null),xform:Sr});if(r)throw r;if(!t||!t.session||!t.user){const e=new Dt;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:r})}catch(e){if(jt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){const t=await or(this.storage,`${this.storageKey}-code-verifier`),[r,s]=(null!=t?t:"").split("/");try{if(!r&&"pkce"===this.flowType)throw new Mt;const{data:t,error:n}=await kr(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:Sr});if(await cr(this.storage,`${this.storageKey}-code-verifier`),n)throw n;if(!t||!t.session||!t.user){const e=new Dt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),setTimeout(async()=>{await this._notifyAllSubscribers("SIGNED_IN",t.session)},0)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:null!=s?s:null}),error:n})}catch(e){if(await cr(this.storage,`${this.storageKey}-code-verifier`),jt(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{const{options:t,provider:r,token:s,access_token:n,nonce:i}=e,a=await kr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:n,nonce:i,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:Sr}),{data:o,error:c}=a;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!o||!o.session||!o.user){const e=new Dt;return this._returnResult({data:{user:null,session:null},error:e})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:o,error:c})}catch(e){if(jt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){var t,r,s,n,i;try{if("email"in e){const{email:s,options:n}=e;let i=null,a=null;"pkce"===this.flowType&&([i,a]=await pr(this.storage,this.storageKey));const{error:o}=await kr(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:s,data:null!==(t=null==n?void 0:n.data)&&void 0!==t?t:{},create_user:null===(r=null==n?void 0:n.shouldCreateUser)||void 0===r||r,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:i,code_challenge_method:a},redirectTo:null==n?void 0:n.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}if("phone"in e){const{phone:t,options:r}=e,{data:a,error:o}=await kr(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(s=null==r?void 0:r.data)&&void 0!==s?s:{},create_user:null===(n=null==r?void 0:r.shouldCreateUser)||void 0===n||n,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!==(i=null==r?void 0:r.channel)&&void 0!==i?i:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==a?void 0:a.message_id},error:o})}throw new Lt("You must provide either an email or phone number.")}catch(e){if(await cr(this.storage,`${this.storageKey}-code-verifier`),jt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){var t,r;try{let s,n;"options"in e&&(s=null===(t=e.options)||void 0===t?void 0:t.redirectTo,n=null===(r=e.options)||void 0===r?void 0:r.captchaToken);const{data:i,error:a}=await kr(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:s,xform:Sr});if(a)throw a;if(!i){throw new Error("An error occurred on token verification.")}const o=i.session,c=i.user;return(null==o?void 0:o.access_token)&&(await this._saveSession(o),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",o)),this._returnResult({data:{user:c,session:o},error:null})}catch(e){if(jt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){var t,r,s,n,i;try{let a=null,o=null;"pkce"===this.flowType&&([a,o]=await pr(this.storage,this.storageKey));const c=await kr(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:null!==(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==r?r:void 0}),(null===(s=null==e?void 0:e.options)||void 0===s?void 0:s.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:o}),headers:this.headers,xform:Rr});return(null===(n=c.data)||void 0===n?void 0:n.url)&&rr()&&!(null===(i=e.options)||void 0===i?void 0:i.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(e){if(await cr(this.storage,`${this.storageKey}-code-verifier`),jt(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new Ut;const{error:s}=await kr(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if(jt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const t=`${this.url}/resend`;if("email"in e){const{email:r,type:s,options:n}=e,{error:i}=await kr(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}},redirectTo:null==n?void 0:n.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:i})}if("phone"in e){const{phone:r,type:s,options:n}=e,{data:i,error:a}=await kr(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==i?void 0:i.message_id},error:a})}throw new Lt("You must provide either an email or phone number and a type")}catch(e){if(jt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){await this.initializePromise;return await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(e){}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){const e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}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{const 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;const t=await or(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=!!e.expires_at&&1e3*e.expires_at-Date.now()<Rt;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){const t=await or(this.userStorage,this.storageKey+"-user");(null==t?void 0:t.user)?e.user=t.user:e.user=mr()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const t={value:this.suppressGetSessionWarning};e.user=function(e,t){return new Proxy(e,{get:(e,r,s)=>{if("__isInsecureUserWarningProxy"===r)return!0;if("symbol"==typeof r){const t=r.toString();if("Symbol(Symbol.toPrimitive)"===t||"Symbol(Symbol.toStringTag)"===t||"Symbol(util.inspect.custom)"===t||"Symbol(nodejs.util.inspect.custom)"===t)return Reflect.get(e,r,s)}return t.value||"string"!=typeof r||(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."),t.value=!0),Reflect.get(e,r,s)}})}(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?this._returnResult({data:{session:null},error:n}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const t=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await kr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Tr}):await this._useSession(async e=>{var t,r,s;const{data:n,error:i}=e;if(i)throw i;return(null===(t=n.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await kr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(s=null===(r=n.session)||void 0===r?void 0:r.access_token)&&void 0!==s?s:void 0,xform:Tr}):{data:{user:null},error:new Ut}})}catch(e){if(jt(e))return function(e){return jt(e)&&"AuthSessionMissingError"===e.name}(e)&&(await this._removeSession(),await cr(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{const{data:s,error:n}=r;if(n)throw n;if(!s.session)throw new Ut;const i=s.session;let a=null,o=null;"pkce"===this.flowType&&null!=e.email&&([a,o]=await pr(this.storage,this.storageKey));const{data:c,error:l}=await kr(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:o}),jwt:i.access_token,xform:Tr});if(l)throw l;return i.user=c.user,await this._saveSession(i),await this._notifyAllSubscribers("USER_UPDATED",i),this._returnResult({data:{user:i.user},error:null})})}catch(e){if(await cr(this.storage,`${this.storageKey}-code-verifier`),jt(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new Ut;const t=Date.now()/1e3;let r=t,s=!0,n=null;const{payload:i}=hr(e.access_token);if(i.exp&&(r=i.exp,s=r<=t),s){const{data:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!t)return{data:{user:null,session:null},error:null};n=t}else{const{data:s,error:i}=await this._getUser(e.access_token);if(i)throw i;n={access_token:e.access_token,refresh_token:e.refresh_token,user:s.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)}return this._returnResult({data:{user:n.user,session:n},error:null})}catch(e){if(jt(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){const{data:s,error:n}=t;if(n)throw n;e=null!==(r=s.session)&&void 0!==r?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new Ut;const{data:s,error:n}=await this._callRefreshToken(e.refresh_token);return n?this._returnResult({data:{user:null,session:null},error:n}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if(jt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!rr())throw new Bt("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Bt(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("pkce"===this.flowType)throw new qt("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new Bt("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new qt("No code detected.");const{data:t,error:r}=await this._exchangeCodeForSession(e.code);if(r)throw r;const s=new URL(window.location.href);return s.searchParams.delete("code"),window.history.replaceState(window.history.state,"",s.toString()),{data:{session:t.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:s,access_token:n,refresh_token:i,expires_in:a,expires_at:o,token_type:c}=e;if(!(n&&a&&i&&c))throw new Bt("No session defined in URL");const l=Math.round(Date.now()/1e3),h=parseInt(a);let u=l+h;o&&(u=parseInt(o));const d=u-l;1e3*d<=Tt&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${d}s, should have been closer to ${h}s`);const p=u-h;l-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,u,l):l-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,u,l);const{data:f,error:g}=await this._getUser(n);if(g)throw g;const w={provider_token:r,provider_refresh_token:s,access_token:n,expires_in:h,expires_at:u,refresh_token:i,token_type:c,user:f.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:w,redirectType:e.type},error:null})}catch(e){if(jt(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return"function"==typeof this.detectSessionInUrl?this.detectSessionInUrl(new URL(window.location.href),e):Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await or(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return this._returnResult({error:n});const i=null===(r=s.session)||void 0===r?void 0:r.access_token;if(i){const{error:t}=await this.admin.signOut(i,e);if(t&&(!function(e){return jt(e)&&"AuthApiError"===e.name}(t)||404!==t.status&&401!==t.status&&403!==t.status))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await cr(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const t=Symbol("auth-callback"),r={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,r),(async()=>{await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{const{data:{session:s},error:n}=t;if(n)throw n;await(null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(t){await(null===(s=this.stateChangeEmitters.get(e))||void 0===s?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null;"pkce"===this.flowType&&([r,s]=await pr(this.storage,this.storageKey,!0));try{return await kr(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(await cr(this.storage,`${this.storageKey}-code-verifier`),jt(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){var e;try{const{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null})}catch(e){if(jt(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:r,error:s}=await this._useSession(async t=>{var r,s,n,i,a;const{data:o,error:c}=t;if(c)throw c;const l=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(r=e.options)||void 0===r?void 0:r.redirectTo,scopes:null===(s=e.options)||void 0===s?void 0:s.scopes,queryParams:null===(n=e.options)||void 0===n?void 0:n.queryParams,skipBrowserRedirect:!0});return await kr(this.fetch,"GET",l,{headers:this.headers,jwt:null!==(a=null===(i=o.session)||void 0===i?void 0:i.access_token)&&void 0!==a?a:void 0})});if(s)throw s;return rr()&&!(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)&&window.location.assign(null==r?void 0:r.url),this._returnResult({data:{provider:e.provider,url:null==r?void 0:r.url},error:null})}catch(t){if(jt(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{const{error:s,data:{session:n}}=t;if(s)throw s;const{options:i,provider:a,token:o,access_token:c,nonce:l}=e,h=await kr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!==(r=null==n?void 0:n.access_token)&&void 0!==r?r:void 0,body:{provider:a,id_token:o,access_token:c,nonce:l,link_identity:!0,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:Sr}),{data:u,error:d}=h;return d?this._returnResult({data:{user:null,session:null},error:d}):u&&u.session&&u.user?(u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers("USER_UPDATED",u.session)),this._returnResult({data:u,error:d})):this._returnResult({data:{user:null,session:null},error:new Dt})}catch(e){if(await cr(this.storage,`${this.storageKey}-code-verifier`),jt(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,s;const{data:n,error:i}=t;if(i)throw i;return await kr(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(s=null===(r=n.session)||void 0===r?void 0:r.access_token)&&void 0!==s?s:void 0})})}catch(e){if(jt(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const n=Date.now();return await(r=async r=>(r>0&&await async function(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await kr(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Sr})),s=(e,t)=>{const r=200*Math.pow(2,e);return t&&Kt(t)&&Date.now()+r-n<Tt},new Promise((e,t)=>{(async()=>{for(let n=0;n<1/0;n++)try{const t=await r(n);if(!s(n,null,t))return void e(t)}catch(e){if(!s(n,e))return void t(e)}})()}))}catch(e){if(this._debug(t,"error",e),jt(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,"end")}var r,s}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const r=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",r),rr()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e,t;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const s=await or(this.storage,this.storageKey);if(s&&this.userStorage){let t=await or(this.userStorage,this.storageKey+"-user");this.storage.isServer||!Object.is(this.storage,this.userStorage)||t||(t={user:s.user},await ar(this.userStorage,this.storageKey+"-user",t)),s.user=null!==(e=null==t?void 0:t.user)&&void 0!==e?e:mr()}else if(s&&!s.user&&!s.user){const e=await or(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(s.user=e.user,await cr(this.storage,this.storageKey+"-user"),await ar(this.storage,this.storageKey,s)):s.user=mr()}if(this._debug(r,"session from storage",s),!this._isValidSession(s))return this._debug(r,"session is not valid"),void(null!==s&&await this._removeSession());const n=1e3*(null!==(t=s.expires_at)&&void 0!==t?t:1/0)-Date.now()<Rt;if(this._debug(r,`session has${n?"":" not"} expired with margin of 90000s`),n){if(this.autoRefreshToken&&s.refresh_token){const{error:e}=await this._callRefreshToken(s.refresh_token);e&&(console.error(e),Kt(e)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else if(s.user&&!0===s.user.__isUserNotAvailableProxy)try{const{data:e,error:t}=await this._getUser(s.access_token);!t&&(null==e?void 0:e.user)?(s.user=e.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(e){console.error("Error getting user data:",e),this._debug(r,"error getting user data, skipping SIGNED_IN notification",e)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(e){return this._debug(r,"error",e),void console.error(e)}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new Ut;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new lr;const{data:t,error:r}=await this._refreshAccessToken(e);if(r)throw r;if(!t.session)throw new Ut;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);const s={data:t.session,error:null};return this.refreshingDeferred.resolve(s),s}catch(e){if(this._debug(s,"error",e),jt(e)){const r={data:null,error:e};return Kt(e)||await this._removeSession(),null===(t=this.refreshingDeferred)||void 0===t||t.resolve(r),r}throw null===(r=this.refreshingDeferred)||void 0===r||r.reject(e),e}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){const s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});const s=[],n=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(e){s.push(e)}});if(await Promise.all(n),s.length>0){for(let e=0;e<s.length;e+=1)console.error(s[e]);throw s[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await cr(this.storage,`${this.storageKey}-code-verifier`);const t=Object.assign({},e),r=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!r&&t.user&&await ar(this.userStorage,this.storageKey+"-user",{user:t.user});const e=Object.assign({},t);delete e.user;const s=yr(e);await ar(this.storage,this.storageKey,s)}else{const e=yr(t);await ar(this.storage,this.storageKey,e)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await cr(this.storage,this.storageKey),await cr(this.storage,this.storageKey+"-code-verifier"),await cr(this.storage,this.storageKey+"-user"),this.userStorage&&await cr(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&rr()&&(null===window||void 0===window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),Tt);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e);const t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&"object"==typeof t&&"function"==typeof t.unref?t.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}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{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");const s=Math.floor((1e3*r.expires_at-e)/Tt);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(!(e.isAcquireTimeout||e instanceof Pr))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!rr()||!(null===window||void 0===window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null===window||void 0===window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{"visible"===document.visibilityState?await this._recoverAndRefresh():this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting")}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){const s=[`provider=${encodeURIComponent(t)}`];if((null==r?void 0:r.redirectTo)&&s.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),(null==r?void 0:r.scopes)&&s.push(`scopes=${encodeURIComponent(r.scopes)}`),"pkce"===this.flowType){const[e,t]=await pr(this.storage,this.storageKey),r=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});s.push(r.toString())}if(null==r?void 0:r.queryParams){const e=new URLSearchParams(r.queryParams);s.push(e.toString())}return(null==r?void 0:r.skipBrowserRedirect)&&s.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;return n?this._returnResult({data:null,error:n}):await kr(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token})})}catch(e){if(jt(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;const{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:o,error:c}=await kr(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:null===(r=null==n?void 0:n.session)||void 0===r?void 0:r.access_token});return c?this._returnResult({data:null,error:c}):("totp"===e.factorType&&"totp"===o.type&&(null===(s=null==o?void 0:o.totp)||void 0===s?void 0:s.qr_code)&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),this._returnResult({data:o,error:null}))})}catch(e){if(jt(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return this._returnResult({data:null,error:n});const i=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?Hr(e.webauthn.credential_response):Vr(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:o}=await kr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:i,headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});return o?this._returnResult({data:null,error:o}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:o}))})}catch(e){if(jt(e))return this._returnResult({data:null,error:e});throw e}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async t=>{var r;const{data:s,error:n}=t;if(n)return this._returnResult({data:null,error:n});const i=await kr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});if(i.error)return i;const{data:a}=i;if("webauthn"!==a.type)return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:Kr(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:Jr(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(jt(e))return this._returnResult({data:null,error:e});throw e}})}async _challengeAndVerify(e){const{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;const{data:{user:t},error:r}=await this.getUser();if(r)return{data:null,error:r};const s={all:[],phone:[],totp:[],webauthn:[]};for(const r of null!==(e=null==t?void 0:t.factors)&&void 0!==e?e:[])s.all.push(r),"verified"===r.status&&s[r.factor_type].push(r);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(){var e,t;const{data:{session:r},error:s}=await this.getSession();if(s)return this._returnResult({data:null,error:s});if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:n}=hr(r.access_token);let i=null;n.aal&&(i=n.aal);let a=i;(null!==(t=null===(e=r.user.factors)||void 0===e?void 0:e.filter(e=>"verified"===e.status))&&void 0!==t?t:[]).length>0&&(a="aal2");return{data:{currentLevel:i,nextLevel:a,currentAuthenticationMethods:n.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{const{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?await kr(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new Ut})})}catch(e){if(jt(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new Ut});const i=await kr(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return i.data&&i.data.redirect_url&&rr()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(jt(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new Ut});const i=await kr(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return i.data&&i.data.redirect_url&&rr()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(i.data.redirect_url),i})}catch(e){if(jt(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;return r?this._returnResult({data:null,error:r}):t?await kr(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new Ut})})}catch(e){if(jt(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{const{data:{session:r},error:s}=t;return s?this._returnResult({data:null,error:s}):r?(await kr(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new Ut})})}catch(e){if(jt(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(t=>t.kid===e);if(r)return r;const s=Date.now();if(r=this.jwks.keys.find(t=>t.kid===e),r&&this.jwks_cached_at+6e5>s)return r;const{data:n,error:i}=await kr(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(i)throw i;return n.keys&&0!==n.keys.length?(this.jwks=n,this.jwks_cached_at=s,r=n.keys.find(t=>t.kid===e),r||null):null}async getClaims(e,t={}){try{let r=e;if(!r){const{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});r=e.session.access_token}const{header:s,payload:n,signature:i,raw:{header:a,payload:o}}=hr(r);(null==t?void 0:t.allowExpired)||function(e){if(!e)throw new Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw new Error("JWT has expired")}(n.exp);const c=s.alg&&!s.alg.startsWith("HS")&&s.kid&&"crypto"in globalThis&&"subtle"in globalThis.crypto?await this.fetchJwk(s.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks):null;if(!c){const{error:e}=await this.getUser(r);if(e)throw e;return{data:{claims:n,header:s,signature:i},error:null}}const l=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}(s.alg),h=await crypto.subtle.importKey("jwk",c,l,!0,["verify"]);if(!await crypto.subtle.verify(l,h,i,er(`${a}.${o}`)))throw new Ht("Invalid JWT signature");return{data:{claims:n,header:s,signature:i},error:null}}catch(e){if(jt(e))return this._returnResult({data:null,error:e});throw e}}}rs.nextInstanceID={};const ss=rs;let ns="";ns="undefined"!=typeof Deno?"deno":"undefined"!=typeof document?"web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";const is={headers:{"X-Client-Info":`supabase-js-${ns}/2.91.0`}},as={schema:"public"},os={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},cs={};function ls(e){return(ls="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function hs(e){var t=function(e,t){if("object"!=ls(e)||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var s=r.call(e,t||"default");if("object"!=ls(s))return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==ls(t)?t:t+""}function us(e,t,r){return(t=hs(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function ds(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function ps(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?ds(Object(r),!0).forEach(function(t){us(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):ds(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}const fs=(e,t,r)=>{const s=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(r),n=Headers;return async(r,i)=>{var a;const o=null!==(a=await t())&&void 0!==a?a:e;let c=new n(null==i?void 0:i.headers);return c.has("apikey")||c.set("apikey",e),c.has("Authorization")||c.set("Authorization",`Bearer ${o}`),s(r,ps(ps({},i),{},{headers:c}))}};var gs=class extends ss{constructor(e){super(e)}},ws=class{constructor(e,t,r){var s,n;this.supabaseUrl=e,this.supabaseKey=t;const i=function(e){const t=null==e?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL((r=t).endsWith("/")?r:r+"/")}catch(e){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}var r}(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const a=`sb-${i.hostname.split(".")[0]}-auth-token`,o=function(e,t){var r,s;const{db:n,auth:i,realtime:a,global:o}=e,{db:c,auth:l,realtime:h,global:u}=t,d={db:ps(ps({},c),n),auth:ps(ps({},l),i),realtime:ps(ps({},h),a),storage:{},global:ps(ps(ps({},u),o),{},{headers:ps(ps({},null!==(r=null==u?void 0:u.headers)&&void 0!==r?r:{}),null!==(s=null==o?void 0:o.headers)&&void 0!==s?s:{})}),accessToken:async()=>""};return e.accessToken?d.accessToken=e.accessToken:delete d.accessToken,d}(null!=r?r:{},{db:as,realtime:cs,auth:ps(ps({},os),{},{storageKey:a}),global:is});var c;(this.storageKey=null!==(s=o.auth.storageKey)&&void 0!==s?s:"",this.headers=null!==(n=o.global.headers)&&void 0!==n?n:{},o.accessToken)?(this.accessToken=o.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!==(c=o.auth)&&void 0!==c?c:{},this.headers,o.global.fetch);this.fetch=fs(t,this._getAccessToken.bind(this),o.global.fetch),this.realtime=this._initRealtimeClient(ps({headers:this.headers,accessToken:this._getAccessToken.bind(this)},o.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(e=>this.realtime.setAuth(e)).catch(e=>console.warn("Failed to set initial Realtime auth token:",e)),this.rest=new K(new URL("rest/v1",i).href,{headers:this.headers,schema:o.db.schema,fetch:this.fetch}),this.storage=new St(this.storageUrl.href,this.headers,this.fetch,null==r?void 0:r.storage),o.accessToken||this._listenForAuthEvents()}get functions(){return new U(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,r)}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()}async _getAccessToken(){var e,t,r=this;if(r.accessToken)return await r.accessToken();const{data:s}=await r.auth.getSession();return null!==(e=null===(t=s.session)||void 0===t?void 0:t.access_token)&&void 0!==e?e:r.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:a,lock:o,debug:c,throwOnError:l},h,u){const d={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new gs({url:this.authUrl.href,headers:ps(ps({},d),h),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,userStorage:n,flowType:a,lock:o,debug:c,throwOnError:l,fetch:u,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new Ee(this.realtimeUrl.href,ps(ps({},e),{},{params:ps(ps({},{apikey:this.supabaseKey}),null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){"TOKEN_REFRESHED"!==e&&"SIGNED_IN"!==e||this.changedAccessToken===r?"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.changedAccessToken=r,this.realtime.setAuth(r))}};(function(){if("undefined"!=typeof window)return!1;const e=globalThis.process;if(!e)return!1;const t=e.version;if(null==t)return!1;const r=t.match(/^v(\d+)\./);return!!r&&parseInt(r[1],10)<=18})()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");let ms=null,ys=null;e.AppsModule=h,e.BookingModule=m,e.EventsModule=d,e.HlmrApiError=r,e.HlmrClient=R,e.LedgerModule=y,e.OffersModule=g,e.PaymentModule=v,e.PricingModule=w,e.PromoModule=T,e.PublicModule=p,e.SDK_NAME="hlmr-sdk-js",e.SDK_VERSION=i,e.TermsModule=S,e.clearAllCache=O,e.getSupabaseClient=function(e,t,r){var s,n,i;if(ms)return ms;if(!e)throw new Error("Supabase URL is required. Pass import.meta.env.VITE_SUPABASE_URL");if(!t)throw new Error("Supabase anon key is required. Pass import.meta.env.VITE_SUPABASE_ANON_KEY");const a={detectSessionInUrl:null!==(s=null==r?void 0:r.detectSessionInUrl)&&void 0!==s&&s,persistSession:null===(n=null==r?void 0:r.persistSession)||void 0===n||n,autoRefreshToken:null===(i=null==r?void 0:r.autoRefreshToken)||void 0===i||i};return ms=((e,t,r)=>new ws(e,t,r))(e,t,{auth:{detectSessionInUrl:a.detectSessionInUrl,persistSession:a.persistSession,autoRefreshToken:a.autoRefreshToken}}),ys={url:e,options:a},ms},e.getSupabaseClientConfig=function(){return ys?{...ys}:null},e.isJSendError=function(e){return"error"===e.status&&"message"in e},e.isJSendFail=function(e){return"fail"===e.status&&"data"in e},e.isJSendResponse=s,e.isJSendSuccess=n,e.performLogout=function(e={}){const{redirectUrl:t,onClearCache:r,idpBaseUrl:s,clientId:n,callbackPath:i}=e;let a;if(O(r),$(),t)a=t;else if(s&&n&&i){const e=`${s}/login?client_id=${n}&redirect_uri=${encodeURIComponent(window.location.origin+i)}`;a=`${s}/logout?redirect_uri=${encodeURIComponent(e)}`}else a="/login";window.location.replace(a)},e.preventBackNavigation=$,e.resetSupabaseClient=function(){ms=null,ys=null}});
2
2
  //# sourceMappingURL=hlmr-sdk.min.js.map