vendor: 10,113 bytes, line 1
1import{g as be,a as Es,c as te}from"./react-vendor-D8xdFElw.js";function Ss(s,e){for(var t=0;t<e.length;t++){const r=e[t];if(typeof r!="string"&&!Array.isArray(r)){for(const n in r)if(n!=="default"&&!(n in s)){const i=Object.getOwnPropertyDescriptor(r,n);i&&Object.defineProperty(s,n,i.get?i:{enumerable:!0,get:()=>r[n]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}var mt={},Ne={},nt=function(s,e){return nt=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])},nt(s,e)};function Zt(s,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");nt(s,e);function t(){this.constructor=s}s.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var De=function(){return De=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++){t=arguments[r];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])}return e},De.apply(this,arguments)};function de(s,e){var t={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,r=Object.getOwnPropertySymbols(s);n<r.length;n++)e.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(s,r[n])&&(t[r[n]]=s[r[n]]);return t}function er(s,e,t,r){var n=arguments.length,i=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(s,e,t,r);else for(var a=s.length-1;a>=0;a--)(o=s[a])&&(i=(n<3?o(i):n>3?o(e,t,i):o(e,t))||i);return n>3&&i&&Object.defineProperty(e,t,i),i}function tr(s,e){return function(t,r){e(t,r,s)}}function rr(s,e,t,r,n,i){function o(v){if(v!==void 0&&typeof v!="function")throw new TypeError("Function expected");return v}for(var a=r.kind,l=a==="getter"?"get":a==="setter"?"set":"value",c=!e&&s?r.static?s:s.prototype:null,u=e||(c?Object.getOwnPropertyDescriptor(c,r.name):{}),d,f=!1,h=t.length-1;h>=0;h--){var g={};for(var _ in r)g[_]=_==="access"?{}:r[_];for(var _ in r.access)g.access[_]=r.access[_];g.addInitializer=function(v){if(f)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(v||null))};var p=(0,t[h])(a==="accessor"?{get:u.get,set:u.set}:u[l],g);if(a==="accessor"){if(p===void 0)continue;if(p===null||typeof p!="object")throw new TypeError("Object expected");(d=o(p.get))&&(u.get=d),(d=o(p.set))&&(u.set=d),(d=o(p.init))&&n.unshift(d)}else(d=o(p))&&(a==="field"?n.unshift(d):u[l]=d)}c&&Object.defineProperty(c,r.name,u),f=!0}function sr(s,e,t){for(var r=arguments.length>2,n=0;n<e.length;n++)t=r?e[n].call(s,t):e[n].call(s);return r?t:void 0}function nr(s){return typeof s=="symbol"?s:"".concat(s)}function ir(s,e,t){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(s,"name",{configurable:!0,value:t?"".concat(t," ",e):e})}function or(s,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(s,e)}function y(s,e,t,r){function n(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function a(u){try{c(r.next(u))}catch(d){o(d)}}function l(u){try{c(r.throw(u))}catch(d){o(d)}}function c(u){u.done?i(u.value):n(u.value).then(a,l)}c((r=r.apply(s,e||[])).next())})}function ar(s,e){var t={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,n,i,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(u){return l([c,u])}}function l(c){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(t=0)),t;)try{if(r=1,n&&(i=c[0]&2?n.return:c[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,c[1])).done)return i;switch(n=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return t.label++,{value:c[1],done:!1};case 5:t.label++,n=c[1],c=[0];continue;case 7:c=t.ops.pop(),t.trys.pop();continue;default:if(i=t.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){t=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){t.label=c[1];break}if(c[0]===6&&t.label<i[1]){t.label=i[1],i=c;break}if(i&&t.label<i[2]){t.label=i[2],t.ops.push(c);break}i[2]&&t.ops.pop(),t.trys.pop();continue}c=e.call(s,t)}catch(u){c=[6,u],n=0}finally{r=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}var Ge=Object.create?function(s,e,t,r){r===void 0&&(r=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(s,r,n)}:function(s,e,t,r){r===void 0&&(r=t),s[r]=e[t]};function lr(s,e){for(var t in s)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&Ge(e,s,t)}function Le(s){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&s[e],r=0;if(t)return t.call(s);if(s&&typeof s.length=="number")return{next:function(){return s&&r>=s.length&&(s=void 0),{value:s&&s[r++],done:!s}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Et(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var r=t.call(s),n,i=[],o;try{for(;(e===void 0||e-- >0)&&!(n=r.next()).done;)i.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(t=r.return)&&t.call(r)}finally{if(o)throw o.error}}return i}function cr(){for(var s=[],e=0;e<arguments.length;e++)s=s.concat(Et(arguments[e]));return s}function ur(){for(var s=0,e=0,t=arguments.length;e<t;e++)s+=arguments[e].length;for(var r=Array(s),n=0,e=0;e<t;e++)for(var i=arguments[e],o=0,a=i.length;o<a;o++,n++)r[n]=i[o];return r}function hr(s,e,t){if(t||arguments.length===2)for(var r=0,n=e.length,i;r<n;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return s.concat(i||Array.prototype.slice.call(e))}function ue(s){return this instanceof ue?(this.v=s,this):new ue(s)}function dr(s,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(s,e||[]),n,i=[];return n=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),n[Symbol.asyncIterator]=function(){return this},n;function o(h){return function(g){return Promise.resolve(g).then(h,d)}}function a(h,g){r[h]&&(n[h]=function(_){return new Promise(function(p,v){i.push([h,_,p,v])>1||l(h,_)})},g&&(n[h]=g(n[h])))}function l(h,g){try{c(r[h](g))}catch(_){f(i[0][3],_)}}function c(h){h.value instanceof ue?Promise.resolve(h.value.v).then(u,d):f(i[0][2],h)}function u(h){l("next",h)}function d(h){l("throw",h)}function f(h,g){h(g),i.shift(),i.length&&l(i[0][0],i[0][1])}}function fr(s){var e,t;return e={},r("next"),r("throw",function(n){throw n}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(n,i){e[n]=s[n]?function(o){return(t=!t)?{value:ue(s[n](o)),done:!1}:i?i(o):o}:i}}function gr(s){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=s[Symbol.asyncIterator],t;return e?e.call(s):(s=typeof Le=="function"?Le(s):s[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(i){t[i]=s[i]&&function(o){return new Promise(function(a,l){o=s[i](o),n(a,l,o.done,o.value)})}}function n(i,o,a,l){Promise.resolve(l).then(function(c){i({value:c,done:a})},o)}}function pr(s,e){return Object.defineProperty?Object.defineProperty(s,"raw",{value:e}):s.raw=e,s}var Ts=Object.create?function(s,e){Object.defineProperty(s,"default",{enumerable:!0,value:e})}:function(s,e){s.default=e},it=function(s){return it=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},it(s)};function _r(s){if(s&&s.__esModule)return s;var e={};if(s!=null)for(var t=it(s),r=0;r<t.length;r++)t[r]!=="default"&&Ge(e,s,t[r]);return Ts(e,s),e}function wr(s){return s&&s.__esModule?s:{default:s}}function vr(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)}function yr(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t}function br(s,e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof s=="function"?e===s:s.has(e)}function mr(s,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,n;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],t&&(n=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(i){return Promise.reject(i)}}),s.stack.push({value:e,dispose:r,async:t})}else t&&s.stack.push({async:!0});return e}var Os=typeof SuppressedError=="function"?SuppressedError:function(s,e,t){var r=new Error(t);return r.name="SuppressedError",r.error=s,r.suppressed=e,r};function Er(s){function e(i){s.error=s.hasError?new Os(i,s.error,"An error was suppressed during disposal."):i,s.hasError=!0}var t,r=0;function n(){for(;t=s.stack.pop();)try{if(!t.async&&r===1)return r=0,s.stack.push(t),Promise.resolve().then(n);if(t.dispose){var i=t.dispose.call(t.value);if(t.async)return r|=2,Promise.resolve(i).then(n,function(o){return e(o),n()})}else r|=1}catch(o){e(o)}
1if(r===1)return s.hasError?Promise.reject(s.error):Promise.resolve();if(s.hasError)throw s.error}return n()}function Sr(s,e){return typeof s=="string"&&/^\.\.?\//.test(s)?s.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(t,r,n,i,o){return r?e?".jsx":".js":n&&(!i||!o)?t:n+i+"."+o.toLowerCase()+"js"}):s}const ks={__extends:Zt,__assign:De,__rest:de,__decorate:er,__param:tr,__esDecorate:rr,__runInitializers:sr,__propKey:nr,__setFunctionName:ir,__metadata:or,__awaiter:y,__generator:ar,__createBinding:Ge,__exportStar:lr,__values:Le,__read:Et,__spread:cr,__spreadArrays:ur,__spreadArray:hr,__await:ue,__asyncGenerator:dr,__asyncDelegator:fr,__asyncValues:gr,__makeTemplateObject:pr,__importStar:_r,__importDefault:wr,__classPrivateFieldGet:vr,__classPrivateFieldSet:yr,__classPrivateFieldIn:br,__addDisposableResource:mr,__disposeResources:Er,__rewriteRelativeImportExtension:Sr},As=Object.freeze(Object.defineProperty({__proto__:null,__addDisposableResource:mr,get __assign(){return De},__asyncDelegator:fr,__asyncGenerator:dr,__asyncValues:gr,__await:ue,__awaiter:y,__classPrivateFieldGet:vr,__classPrivateFieldIn:br,__classPrivateFieldSet:yr,__createBinding:Ge,__decorate:er,__disposeResources:Er,__esDecorate:rr,__exportStar:lr,__extends:Zt,__generator:ar,__importDefault:wr,__importStar:_r,__makeTemplateOb
1ject:pr,__metadata:or,__param:tr,__propKey:nr,__read:Et,__rest:de,__rewriteRelativeImportExtension:Sr,__runInitializers:sr,__setFunctionName:ir,__spread:cr,__spreadArray:hr,__spreadArrays:ur,__values:Le,default:ks},Symbol.toStringTag,{value:"Module"})),Rs=s=>s?(...e)=>s(...e):(...e)=>fetch(...e);let He=class extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}},Tr=class extends He{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}},ot=class extends He{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}},at=class extends He{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}};var Be;(function(s){s.Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2"})(Be||(Be={}));class Ps{constructor(e,{headers:t={},customFetch:r,region:n=Be.Any}={}){this.url=e,this.headers=t,this.region=n,this.fetch=Rs(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return y(this,arguments,void 0,function*(t,r={}){var n;let i,o;try{const{headers:a,method:l,body:c,signal:u,timeout:d}=r;let f={},{region:h}=r;h||(h=this.region);const g=new URL(`${this.url}/${t}`);h&&h!=="any"&&(f["x-region"]=h,g.searchParams.set("forceFunctionRegion",h));let _;c&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",_=c):typeof c=="string"?(f["Content-Type"]="text/plain",_=c):typeof FormData<"u"&&c instanceof FormData?_=c:(f["Content-Type"]="application/json",_=JSON.stringify(c)):_=c;let p=u;d&&(o=new AbortController,i=setTimeout(()=>o.abort(),d),u?(p=o.signal,u.addEventListener("abort",()=>o.abort())):p=o.signal);const v=yield this.fetch(g.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),a),body:_,signal:p}).catch(A=>{throw new Tr(A)}),m=v.headers.get("x-relay-error");if(m&&m==="true")throw new ot(v);if(!v.ok)throw new at(v);let w=((n=v.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),S;return w==="application/json"?S=yield v.json():w==="application/octet-stream"||w==="application/pdf"?S=yield v.blob():w==="text/event-stream"?S=v:w==="multipart/form-data"?S=yield v.formData():S=yield v.text(),{data:S,error:null,response:v}}catch(a){return{data:null,error:a,response:a instanceof at||a instanceof ot?a.context:void 0}}finally{i&&clearTimeout(i)}})}}const js=Object.freeze(Object.defineProperty({__proto__:null,get FunctionRegion(){return Be},FunctionsClient:Ps,FunctionsError:He,FunctionsFetchError:Tr,FunctionsHttpError:at,FunctionsRelayError:ot},Symbol.toStringTag,{value:"Module"})),Or=be(js);var I={};const fe=be(As);var Se={},Te={},Oe={},ke={},Ae={},Re={},Ct;function kr(){if(Ct)return Re;Ct=1,Object.defineProperty(Re,"__esModule",{value:!0});class s extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.co
1de=t.code}}return Re.default=s,Re}var $t;function Ar(){if($t)return Ae;$t=1,Object.defineProperty(Ae,"__esModule",{value:!0});const e=fe.__importDefault(kr());let t=class{constructor(n){var i,o;this.shouldThrowOnError=!1,this.method=n.method,this.url=n.url,this.headers=new Headers(n.headers),this.schema=n.schema,this.body=n.body,this.shouldThrowOnError=(i=n.shouldThrowOnError)!==null&&i!==void 0?i:!1,this.signal=n.signal,this.isMaybeSingle=(o=n.isMaybeSingle)!==null&&o!==void 0?o:!1,n.fetch?this.fetch=n.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(n,i){return this.headers=new Headers(this.headers),this.headers.set(n,i),this}then(n,i){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");const o=this.fetch;let a=o(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async l=>{var c,u,d,f;let h=null,g=null,_=null,p=l.status,v=l.statusText;if(l.ok){if(this.method!=="HEAD"){const A=await l.text();A===""||(this.headers.get("Accept")==="text/csv"||this.headers.get("Accept")&&(!((c=this.headers.get("Accept"))===null||c===void 0)&&c.includes("application/vnd.pgrst.plan+text"))?g=A:g=JSON.parse(A))}const w=(u=this.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),S=(d=l.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");w&&S&&S.length>1&&(_=parseInt(S[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(g)&&(g.length>1?(h={code:"PGRST116",details:`Results contain ${g.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},g=null,_=null,p=406,v="Not Acceptable"):g.length===1?g=g[0]:g=null)}else{const w=await l.text();try{h=JSON.parse(w),Array.isArray(h)&&l.status===404&&(g=[],h=null,p=200,v="OK")}catch{l.status===404&&w===""?(p=204,v="No Content"):h={message:w}}if(h&&this.isMaybeSingle&&(!((f=h==null?void 0:h.details)===null||f===void 0)&&f.includes("0 rows"))&&(h=null,p=200,v="OK"),h&&this.shouldThrowOnError)throw new e.default(h)}return{error:h,data:g,count:_,status:p,statusText:v}});return this.shouldThrowOnError||(a=a.catch(l=>{var c,u,d,f,h,g;let _="";const p=l==null?void 0:l.cause;if(p){const v=(c=p==null?void 0:p.message)!==null&&c!==void 0?c:"",m=(u=p==null?void 0:p.code)!==null&&u!==void 0?u:"";_=`${(d=l==null?void 0:l.name)!==null&&d!==void 0?d:"FetchError"}: ${l==null?void 0:l.message}`,_+=` 2 3Caused by: ${(f=p==null?void 0:p.name)!==null&&f!==void 0?f:"Error"}: ${v}`,m&&(_+=` (${m})`),p!=null&&p.stack&&(_+=` 4${p.stack}`)}else _=(h=l==null?void 0:l.stack)!==null&&h!==void 0?h:"";return{error:{message:`${(g=l==null?void 0:l.name)!==null&&g!==void 0?g:"FetchError"}: ${l==null?void 0:l.message}`,details:_,hint:"",code:""},data:null,count:null,status:0,statusText:""}})),a.then(n,i)}returns(){return this}overrideTypes(){return this}};return Ae.default=t,Ae}var It;function Rr(){if(It)return ke;It=1,Object.defineProperty(ke,"__esModule",{value:!0});const e=fe.__importDefault(Ar());let t=class extends e.default{select(n){let i=!1;const o=(n??"*").split("").map(a=>/\s/.test(a)&&!i?"":(a==='"'&&(i=!i),a)).join("");return this.url.searchParams.set("select",o),this.headers.append("Prefer","return=representation"),this}order(n,{ascending:i=!0,nullsFirst:o,foreignTable:a,referencedTable:l=a}={}){const c=l?`${l}.order`:"order",u=this.url.searchParams.get(c);return this.url.searchParams.set(c,`${u?`${u},`:""}${n}.${i?"asc":"desc"}${o===void 0?"":o?".nullsfirst":".nullslast"}`),this}limit(n,{foreignTable:i,referencedTable:o=i}={}){const a=typeof o>"u"?"limit":`${o}.limit`;return this.url.searchParams.set(a,`${n}`),this}range(n,i,{foreignTable:o,referencedTable:a=o}={}){const l=typeof a>"u"?"offset":`${a}.offset`,c=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(l,`${n}`),this.url.searchParams.set(c,`${i-n+1}`),this}abortSignal(n){return this.signal=n,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?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}
4explain({analyze:n=!1,verbose:i=!1,settings:o=!1,buffers:a=!1,wal:l=!1,format:c="text"}={}){var u;const d=[n?"analyze":null,i?"verbose":null,o?"settings":null,a?"buffers":null,l?"wal":null].filter(Boolean).join("|"),f=(u=this.headers.get("Accept"))!==null&&u!==void 0?u:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${c}; for="${f}"; options=${d};`),c==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(n){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${n}`),this}};return ke.default=t,ke}var xt;function St(){if(xt)return Oe;xt=1,Object.defineProperty(Oe,"__esModule",{value:!0});const e=fe.__importDefault(Rr()),t=new RegExp("[,()]");let r=class extends e.default{eq(i,o){return this.url.searchParams.append(i,`eq.${o}`),this}neq(i,o){return this.url.searchParams.append(i,`neq.${o}`),this}gt(i,o){return this.url.searchParams.append(i,`gt.${o}`),this}gte(i,o){return this.url.searchParams.append(i,`gte.${o}`),this}lt(i,o){return this.url.searchParams.append(i,`lt.${o}`),this}lte(i,o){return this.url.searchParams.append(i,`lte.${o}`),this}like(i,o){return this.url.searchParams.append(i,`like.${o}`),this}likeAllOf(i,o){return this.url.searchParams.append(i,`like(all).{${o.join(",")}}`),this}likeAnyOf(i,o){return this.url.searchParams.append(i,`like(any).{${o.join(",")}}`),this}ilike(i,o){return this.url.searchParams.append(i,`ilike.${o}`),this}ilikeAllOf(i,o){return this.url.searchParams.append(i,`ilike(all).{${o.join(",")}}`),this}ilikeAnyOf(i,o){return this.url.searchParams.append(i,`ilike(any).{${o.join(",")}}`),this}regexMatch(i,o){return this.url.searchParams.append(i,`match.${o}`),this}regexIMatch(i,o){return this.url.searchParams.append(i,`imatch.${o}`),this}is(i,o){return this.url.searchParams.append(i,`is.${o}`),this}isDistinct(i,o){return this.url.searchParams.append(i,`isdistinct.${o}`),this}in(i,o){const a=Array.from(new Set(o)).map(l=>typeof l=="string"&&t.test(l)?`"${l}"`:`${l}`).join(",");return this.url.searchParams.append(i,`in.(${a})`),this}contains(i,o){return typeof o=="string"?this.url.searchParams.append(i,`cs.${o}`):Array.isArray(o)?this.url.searchParams.append(i,`cs.{${o.join(",")}}`):this.url.searchParams.append(i,`cs.${JSON.stringify(o)}`),this}containedBy(i,o){return typeof o=="string"?this.url.searchParams.append(i,`cd.${o}`):Array.isArray(o)?this.url.searchParams.append(i,`cd.{${o.join(",")}}`):this.url.searchParams.append(i,`cd.${JSON.stringify(o)}`),this}rangeGt(i,o){return this.url.searchParams.append(i,`sr.${o}`),this}rangeGte(i,o){return this.url.searchParams.append(i,`nxl.${o}`),this}rangeLt(i,o){return this.url.searchParams.append(i,`sl.${o}`),this}rangeLte(i,o){return this.url.searchParams.append(i,`nxr.${o}`),this}rangeAdjacent(i,o){return this.url.searchParams.append(i,`adj.${o}`),this}overlaps(i,o){return typeof o=="string"?this.url.searchParams.append(i,`ov.${o}`):this.url.searchParams.append(i,`ov.{${o.join(",")}}`),this}textSearch(i,o,{config:a,type:l}={}){let c="";l==="plain"?c="pl":l==="phrase"?c="ph":l==="websearch"&&(c="w");const u=a===void 0?"":`(${a})`;return this.url.searchParams.append(i,`${c}fts${u}.${o}`),this}match(i){return Object.entries(i).forEach(([o,a])=>{this.url.searchParams.append(o,`eq.${a}`)}),this}not(i,o,a){return this.url.searchParams.append(i,`not.${o}.${a}`),this}or(i,{foreignTable:o,referencedTable:a=o}={}){const l=a?`${a}.or`:"or";return this.url.searchParams.append(l,`(${i})`),this}filter(i,o,a){return this.url.searchParams.append(i,`${o}.${a}`),this}};return Oe.default=r,Oe}var Ut;function Pr(){if(Ut)return Te;Ut=1,Object.defineProperty(Te,"__esModule",{value:!0});const e=fe.__importDefault(St());let t=class{constructor(n,{headers:i={},schema:o,fetch:a}){this.url=n,this.headers=new Headers(i),this.schema=o,this.fetch=a}select(n,i){const{head:o=!1,count:a}=i??{},l=o?"HEAD":"GET";let c=!1;const u=(n??"*").split("").map(d=>/\s/.test(d)&&!c?"":(d==='"'&&(c=!c),d)).join("");return this.url.searchParams.set("select",u),a&&this.headers.append("Prefer",`count=${a}`),new e.default({method:l,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(n,{count:i,defaultToNull:o=!0}={}){var a;const l="POST";if(i&&this.headers.append("Prefer",`count=${i}`),o||this.headers.append("Prefer","missing=default"),Array.isArray(n)){const c=n.reduce((u,d)=>u.concat(Object.keys(d)),[]);if(c.length>0){const u=[...new Set(c)].map(d=>`"${d}"`);this.url.searchParams.set("columns",u.join(","))}}return new e.default({method:l,url:this.url,headers:this.headers,schema:this.schema,body:n,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch})}upsert(n,{onConflict:i,ignoreDuplicates:o=!1,count:a,defaultToNull:l=!0}={}){var c;const u="POST";if(this.headers.append("Prefer",`resolution=${o?"ignore":"merge"}-duplicates`),i!==void 0&&this.url.searchParams.set("on_conflict",i),a&&this.headers.append("Prefer",`count=${a}`),l||this.headers.append("Prefer","missing=default"),Array.isArray(n)){const d=n.reduce((f,h)=>f.concat(Object.keys(h)),[]);if(d.length>0){const f=[...new Set(d)].map(h=>`"${h}"`);this.url.searchParams.set("columns",f.join(","))}}return new e.default({method:u,url:this.url,headers:this.headers,schema:this.schema,body:n,fetch:(c=this.fetch)!==null&&c!==void 0?c:fetch})}update(n,{count:i}={}){var o;const a="PATCH";return i&&this.headers.append("Prefer",`count=${i}`),new e.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:n,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch})}delete({count:n}={}){var i;const o="DELETE";return n&&this.headers.append("Prefer",`count=${n}`),new e.default({method:o,url:this.url,headers:this.headers,schema:this.schema,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch})}};return Te.default=t,Te}var Nt;function Cs(){if(Nt)return Se;
4Nt=1,Object.defineProperty(Se,"__esModule",{value:!0});const s=fe,e=s.__importDefault(Pr()),t=s.__importDefault(St());let r=class jr{constructor(i,{headers:o={},schema:a,fetch:l}={}){this.url=i,this.headers=new Headers(o),this.schemaName=a,this.fetch=l}from(i){if(!i||typeof i!="string"||i.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");const o=new URL(`${this.url}/${i}`);return new e.default(o,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(i){return new jr(this.url,{headers:this.headers,schema:i,fetch:this.fetch})}rpc(i,o={},{head:a=!1,get:l=!1,count:c}={}){var u;let d;const f=new URL(`${this.url}/rpc/${i}`);let h;a||l?(d=a?"HEAD":"GET",Object.entries(o).filter(([_,p])=>p!==void 0).map(([_,p])=>[_,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([_,p])=>{f.searchParams.append(_,p)})):(d="POST",h=o);const g=new Headers(this.headers);return c&&g.set("Prefer",`count=${c}`),new t.default({method:d,url:f,headers:g,schema:this.schemaName,body:h,fetch:(u=this.fetch)!==null&&u!==void 0?u:fetch})}};return Se.default=r,Se}Object.defineProperty(I,"__esModule",{value:!0});I.PostgrestError=I.PostgrestBuilder=I.PostgrestTransformBuilder=I.PostgrestFilterBuilder=I.PostgrestQueryBuilder=I.PostgrestClient=void 0;const ge=fe,Cr=ge.__importDefault(Cs());I.PostgrestClient=Cr.default;const $r=ge.__importDefault(Pr());I.PostgrestQueryBuilder=$r.default;const Ir=ge.__importDefault(St());I.PostgrestFilterBuilder=Ir.default;const xr=ge.__importDefault(Rr());I.PostgrestTransformBuilder=xr.default;const Ur=ge.__importDefault(Ar());I.PostgrestBuilder=Ur.default;const Nr=ge.__importDefault(kr());I.PostgrestError=Nr.default;I.default={PostgrestClient:Cr.default,PostgrestQueryBuilder:$r.default,PostgrestFilterBuilder:Ir.default,PostgrestTransformBuilder:xr.default,PostgrestBuilder:Ur.default,PostgrestError:Nr.default};class Dr{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")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(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||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."};if(typeof process<"u"){const t=process.versions;if(t&&t.node){const r=t.node,n=parseInt(r.replace(/^v/,"").split(".")[0]);return n>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${n} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${n} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option: 5import ws from "ws" 6new 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+=` 7 8Suggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){const r=this.getWebSocketConstructor();return new r(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}}const $s="2.87.1",Is=`realtime-js/${$s}`,Lr="1.0.0",xs="2.0.0",Dt=Lr,lt=1e4,Us=1e3,Ns=100;var X;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(X||(X={}));var R;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(R||(R={}));var B;(function(s){s.close="phx_close",s.error="phx_error",s.join="phx_join",s.reply="phx_reply",s.leave="phx_leave",s.access_token="access_token"})(B||(B={}));var ct;(function(s){s.websocket="websocket"})(ct||(ct={}));var Z;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(Z||(Z={}));class Ds{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=e??[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")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((t=e.payload)===null||t===void 0?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,r;const n=(r=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&r!==void 0?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var t,r;const n=(r=(t=e.payload)===null||t===void 0?void 0:t.payload)!==null&&r!==void 0?r:{},o=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,t,r){var n,i;const o=e.topic,a=(n=e.ref)!==null&&n!==void 0?n:"",l=(i=e.join_ref)!==null&&i!==void 0?i:"",c=e.payload.event,u=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(u).length===0?"":JSON.stringify(u);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`metadata length ${d.length} exceeds maximum of 255`);const f=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+o.length+c.length+d.length,h=new ArrayBuffer(this.HEADER_LENGTH+f);
8let g=new DataView(h),_=0;g.setUint8(_++,this.KINDS.userBroadcastPush),g.setUint8(_++,l.length),g.setUint8(_++,a.length),g.setUint8(_++,o.length),g.setUint8(_++,c.length),g.setUint8(_++,d.length),g.setUint8(_++,t),Array.from(l,v=>g.setUint8(_++,v.charCodeAt(0))),Array.from(a,v=>g.setUint8(_++,v.charCodeAt(0))),Array.from(o,v=>g.setUint8(_++,v.charCodeAt(0))),Array.from(c,v=>g.setUint8(_++,v.charCodeAt(0))),Array.from(d,v=>g.setUint8(_++,v.charCodeAt(0)));var p=new Uint8Array(h.byteLength+r.byteLength);return p.set(new Uint8Array(h),0),p.set(new Uint8Array(r),h.byteLength),p.buffer}decode(e,t){if(this._isArrayBuffer(e)){let r=this._binaryDecode(e);return t(r)}if(typeof e=="string"){const r=JSON.parse(e),[n,i,o,a,l]=r;return t({join_ref:n,ref:i,topic:o,event:a,payload:l})}return t({})}_binaryDecode(e){const t=new DataView(e),r=t.getUint8(0),n=new TextDecoder;switch(r){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,t,n)}}_decodeUserBroadcast(e,t,r){const n=t.getUint8(1),i=t.getUint8(2),o=t.getUint8(3),a=t.getUint8(4);let l=this.HEADER_LENGTH+4;const c=r.decode(e.slice(l,l+n));l=l+n;const u=r.decode(e.slice(l,l+i));l=l+i;const d=r.decode(e.slice(l,l+o));l=l+o;const f=e.slice(l,e.byteLength),h=a===this.JSON_ENCODING?JSON.parse(r.decode(f)):f,g={type:this.BROADCAST_EVENT,event:u,payload:h};return o>0&&(g.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:g}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||((t=e==null?void 0:e.constructor)===null||t===void 0?void 0:t.name)==="ArrayBuffer"}_pick(e,t){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([r])=>t.includes(r)))}}class Br{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))}}var O;(function(s){s.abstime="abstime",s.bool="bool",s.date="date",s.daterange="daterange",s.float4="float4",s.float8="float8",s.int2="int2",s.int4="int4",s.int4range="int4range",s.int8="int8",s.int8range="int8range",s.json="json",s.jsonb="jsonb",s.money="money",s.numeric="numeric",s.oid="oid",s.reltime="reltime",s.text="text",s.time="time",s.timestamp="timestamp",s.timestamptz="timestamptz",s.timetz="timetz",s.tsrange="tsrange",s.tstzrange="tstzrange"})(O||(O={}));const Lt=(s,e,t={})=>{var r;const n=(r=t.skipTypes)!==null&&r!==void 0?r:[];return e?Object.keys(e).reduce((i,o)=>(i[o]=Ls(o,s,e,n),i),{}):{}},Ls=(s,e,t,r)=>{const n=e.find(a=>a.name===s),i=n==null?void 0:n.type,o=t[s];return i&&!r.includes(i)?qr(i,o):ut(o)},qr=(s,e)=>{if(s.charAt(0)==="_"){const t=s.slice(1,s.length);return Ms(e,t)}switch(s){case O.bool:return Bs(e);case O.float4:case O.float8:case O.int2:case O.int4:case O.int8:case O.numeric:case O.oid:return qs(e);case O.json:case O.jsonb:return Fs(e);case O.timestamp:return Ws(e);case O.abstime:case O.date:case O.daterange:case O.int4range:case O.int8range:case O.money:case O.reltime:case O.text:case O.time:case O.timestamptz:case O.timetz:case O.tsrange:case O.tstzrange:return ut(e);default:return ut(e)}},ut=s=>s,Bs=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},qs=s=>{if(typeof s=="string"){const e=parseFloat(s);if(!Number.isNaN(e))return e}return s},Fs=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(e){return console.log(`JSON parse error: ${e}`),s}return s},Ms=(s,e)=>{if(typeof s!="string")return s;const t=s.length-1,r=s[t];if(s[0]==="{"&&r==="}"){let i;const o=s.slice(1,t);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>qr(e,a))}return s},Ws=s=>typeof s=="string"?s.replace(" ","T"):s,Fr=s=>{const e=new URL(s);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};class Xe{constructor(e,t,r={},n=lt){this.channel=e,this.event=t,this.payload=r,this.timeout=n,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHo
8oks=[],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((r=this.receivedResp)===null||r===void 0?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);const e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},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(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var ht;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(ht||(ht={}));let Mr=class $e{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(t==null?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},n=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=$e.syncState(this.state,n,i,o),this.pendingDiffs.forEach(l=>{this.state=$e.syncDiff(this.state,l,i,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},n=>{const{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=$e.syncDiff(this.state,n,i,o),a())}),this.onJoin((n,i,o)=>{this.channel._trigger("presence",{event:"join",key:n,currentPresences:i,newPresences:o})}),this.onLeave((n,i,o)=>{this.channel._trigger("presence",{event:"leave",key:n,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,n){const i=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(i,(c,u)=>{o[c]||(l[c]=u)}),this.map(o,(c,u)=>{const d=i[c];if(d){const f=u.map(p=>p.presence_ref),h=d.map(p=>p.presence_ref),g=u.filter(p=>h.indexOf(p.presence_ref)<0),_=d.filter(p=>f.indexOf(p.presence_ref)<0);g.length>0&&(a[c]=g),_.length>0&&(l[c]=_)}else a[c]=u}),this.syncDiff(i,{joins:a,leaves:l},r,n)}static syncDiff(e,t,r,n){const{joins:i,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),n||(n=()=>{}),this.map(i,(a,l)=>{var c;const u=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),u.length>0){const d=e[a].map(h=>h.presence_ref),f=u.filter(h=>d.indexOf(h.presence_ref)<0);e[a].unshift(...f)}r(a,u,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;const u=l.map(d=>d.presence_ref);c=c.filter(d=>u.indexOf(d.presence_ref)<0),e[a]=c,n(a,c,l),c.length===0&&delete e[a]}),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 n=e[r];return"metas"in n?t[r]=n.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):t[r]=n,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()}};var dt;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(dt||(dt={}));var le;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(le||(le={}));var q;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(q||(q={}));const Vs=R;let Wr=class pe{constructor(e,t={config:{}},r){var n,i;if(this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=R.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 Xe(this,B.join,this.params,this.timeout),this.rejoinTimer=new Br(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=R.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=R.closed,this.socket._remove(this)}),this._onError(o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=R.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=R.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=R.errored,this.rejoinTimer.scheduleTimeout())}),this._on(B.reply,{},(o,a)=>{this._trigger(this._replyEventName(a),o)}),this.presence=new Mr(this),this.broadcastEndpointURL=Fr(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((i=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,t=this.timeout){var r,n,i;if(this.socket.isConnected()||this.socket.connect(),this.state==R.closed){const{config:{broadcast:o,presence:a,private:l}}=this.params,c=(n=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(h=>h.filter))!==null&&n!==void 0?n:[],u=!!this.bindings[le.PRESENCE]&&this.bindings[le.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,d={},f={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:u}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(h=>e==null?void 0:e(q.CHANNEL_ERROR,h)),this._onClose(()=>e==null?void 0:e(q.CLOSED)),this.updateJoinPayload(Object.assign({config:f},d)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:h})=>{var g;if(this.socket._isManualToken()||this.socket.setAuth(),h===void 0){e==null||e(q.SUBSCRIBED);return}else{const _=this.bindings.postgres_changes,p=(g=_==null?void 0:_.length)!==null&&g!==void 0?g:0,v=[];for(let m=0;m<p;m++){const w=_[m],{filter:{event:S,schema:A,table:T,filter:j}}=w,W=h&&h[m];if(W&&W.event===S&&pe.isFilterValueEqual(W.schema,A)&&pe.isFilterValueEqual(W.table,T)&&pe.isFilterValueEqual(W.filter,j))v.push(Object.assign(Object.assign({},w),{id:W.id}));else{this.unsubscribe(),this.state=R.errored,e==null||e(q.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=v,e&&e(q.SUBSCRIBED);return}}).receive("error",h=>{this.state=R.errored,e==null||e(q.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(h).join(", ")||"error")))}).receive("timeout",()=>{e==null||e(q.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===R.joined&&e===le.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 n;const i=this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"";if(t==null)return Promise.reject("Payload is required for httpSend()");const o={method:"POST",headers:{Authorization:i,apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:t,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;
8try{const c=await a.json();l=c.error||c.message||l}catch{}return Promise.reject(new Error(l))}async send(e,t={}){var r,n;if(!this._canPush()&&e.type==="broadcast"){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:i,payload:o}=e,l={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{const c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(r=t.timeout)!==null&&r!==void 0?r:this.timeout);return await((n=c.body)===null||n===void 0?void 0:n.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,l;const c=this._push(e.type,e,t.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),c.receive("ok",()=>i("ok")),c.receive("error",()=>i("error")),c.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=R.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(B.close,"leave",this._joinRef())};this.joinPush.destroy();let r=null;return new Promise(n=>{r=new Xe(this,B.leave,{},e),r.receive("ok",()=>{t(),n("ok")}).receive("timeout",()=>{t(),n("timed out")}).receive("error",()=>{n("error")}),r.send(),this._canPush()||r.trigger("ok",{})}).finally(()=>{r==null||r.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=R.closed,this.bindings={}}async _fetchWithTimeout(e,t,r){const n=new AbortController,i=setTimeout(()=>n.abort(),r),o=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:n.signal}));return clearTimeout(i),o}_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 n=new Xe(this,e,t,r);return this._canPush()?n.send():this._addToPushBuffer(n),n}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>Ns){const t=this.pushBuffer.shift();t&&(t.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${t.event}`,t.payload))}}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var n,i;const o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:u}=B;if(r&&[a,l,c,u].indexOf(o)>=0&&r!==this._joinRef())return;let f=this._onMessage(o,t,r);if(t&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(n=this.bindings.postgres_changes)===null||n===void 0||n.filter(h=>{var g,_,p;return((g=h.filter)===null||g===void 0?void 0:g.event)==="*"||((p=(_=h.filter)===null||_===void 0?void 0:_.event)===null||p===void 0?void 0:p.toLocaleLowerCase())===o}).map(h=>h.callback(f,r)):(i=this.bindings[o])===null||i===void 0||i.filter(h=>{var g,_,p,v,m,w;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in h){const S=h.id,A=(g=h.filter)===null||g===void 0?void 0:g.event;return S&&((_=t.ids)===null||_===void 0?void 0:_.includes(S))&&(A==="*"||(A==null?void 0:A.toLocaleLowerCase())===((p=t.data)===null||p===void 0?void 0:p.type.toLocaleLowerCase()))}else{const S=(m=(v=h==null?void 0:h.filter)===null||v===void 0?void 0:v.event)===null||m===void 0?void 0:m.toLocaleLowerCase();return S==="*"||S===((w=t==null?void 0:t.event)===null||w===void 0?void 0:w.toLocaleLowerCase())}else return h.type.toLocaleLowerCase()===o}).map(h=>{if(typeof f=="object"&&"ids"in f){const g=f.data,{schema:_,table:p,commit_timestamp:v,type:m,errors:w}=g;f=Object.assign(Object.assign({},{schema:_,table:p,commit_timestamp:v,eventType:m,new:{},old:{},errors:w}),this._getPayloadRecords(g))}h.callback(f,r)}
8)}_isClosed(){return this.state===R.closed}_isJoined(){return this.state===R.joined}_isJoining(){return this.state===R.joining}_isLeaving(){return this.state===R.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const n=e.toLocaleLowerCase(),i={type:n,filter:t,callback:r};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this}_off(e,t){const r=e.toLocaleLowerCase();return this.bindings[r]&&(this.bindings[r]=this.bindings[r].filter(n=>{var i;return!(((i=n.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===r&&pe.isEqual(n.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(e??void 0)===(t??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(B.close,{},e)}_onError(e){this._on(B.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=R.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=Lt(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=Lt(e.columns,e.old_record)),t}};const Ze=()=>{},Pe={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Ks=[1e3,2e3,5e3,1e4],Gs=1e4,Hs=` 9 addEventListener("message", (e) => { 10 if (e.data.event === "start") { 11 setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); 12 } 13 });`;let Js=class{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=lt,this.transport=null,this.heartbeatIntervalMs=Pe.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Ze,this.ref=0,this.reconnectTimer=null,this.vsn=Dt,this.logger=Ze,this.conn=null,this.sendBuffer=[],this.serializer=new Ds,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=n=>n?(...i)=>n(...i):(...i)=>fetch(...i),!(!((r=t==null?void 0:t.params)===null||r===void 0)&&r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${ct.websocket}`,this.httpEndpoint=Fr(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(t==null?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&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=Dr.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;throw t.includes("Node.js")?new Error(`${t} 14 15To use Realtime in Node.js, you need to provide a WebSocket implementation: 16 17Option 1: Use Node.js 22+ which has native WebSocket support 18Option 2: Install and provide the "ws" package: 19 20 npm install ws 21 22 import ws from "ws" 23 const client = new RealtimeClient(url, { 24 ...options, 25 transport: ws 26 })`):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")},typeof this.conn.close=="function"&&(e?this.conn.close(e,t??""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(t=>t.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case X.connecting:return Z.C
26onnecting;case X.open:return Z.Open;case X.closing:return Z.Closing;default:return Z.Closed}}isConnected(){return this.connectionState()===Z.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,t={config:{}}){const r=`realtime:${e}`,n=this.getChannels().find(i=>i.topic===r);if(n)return n;{const i=new Wr(`realtime:${e}`,t,this);return this.channels.push(i),i}}push(e){const{topic:t,event:r,payload:n,ref:i}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${t} ${r} (${i})`,n),this.isConnected()?o():this.sendBuffer.push(o)}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()){try{this.heartbeatCallback("disconnected")}catch(t){this.log("error","error in heartbeat callback",t)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(t){this.log("error","error in heartbeat callback",t)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(Us,"heartbeat timeout"),setTimeout(()=>{var t;this.isConnected()||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout()},Pe.HEARTBEAT_TIMEOUT_FALLBACK);return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(t){this.log("error","error in heartbeat callback",t)}this._setAuthSafely("heartbeat")}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(r=>r.topic===e&&(r._isJoined()||r._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,t=>{if(t.topic==="phoenix"&&t.event==="phx_reply")try{this.heartbeatCallback(t.payload.status==="ok"?"ok":"error")}catch(c){this.log("error","error in heartbeat callback",c)}t.ref&&t.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:r,event:n,payload:i,ref:o}=t,a=o?`(${o})`:"",l=i.status||"";this.log("receive",`${l} ${r} ${n} ${a}`.trim(),i),this.channels.filter(c=>c._isMember(r)).forEach(c=>c._trigger(n,i,o)),this._triggerStateCallbacks("message",t)})}_clearTimer(e){var t;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((t=this.reconnectTimer)===null||t===void 0||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))}_teardownConnection(){if(this.conn){if(this.conn.readyState===X.open||this.conn.readyState===X.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.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(t=>{this.log("error","error waiting for auth on connect",t),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=t=>{this.log("worker","worker error",t.message),this.workerRef.terminate()},this.workerRef.onmessage=t=>{t.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_onConnClose(e){var t;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(t=this.reconnectTimer)===null||t===void 0||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}
26_triggerChanError(){this.channels.forEach(e=>e._trigger(B.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;const r=e.match(/\?/)?"&":"?",n=new URLSearchParams(t);return`${e}${r}${n}`}_workerObjectUrl(e){let t;if(e)t=e;else{const r=new Blob([Hs],{type:"application/javascript"});t=URL.createObjectURL(r)}return t}_setConnectionState(e,t=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(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(n){this.log("error","Error fetching access token from callback",n),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(n=>{const i={access_token:t,version:Is};t&&n.updateJoinPayload(i),n.joinedOnce&&n._isJoined()&&n._push(B.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(n){this.log("error",`error in ${e} callback`,n)}})}catch(r){this.log("error",`error triggering ${e} callbacks`,r)}}_setupReconnectionTimer(){this.reconnectTimer=new Br(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Pe.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var t,r,n,i,o,a,l,c,u,d,f,h;switch(this.transport=(t=e==null?void 0:e.transport)!==null&&t!==void 0?t:null,this.timeout=(r=e==null?void 0:e.timeout)!==null&&r!==void 0?r:lt,this.heartbeatIntervalMs=(n=e==null?void 0:e.heartbeatIntervalMs)!==null&&n!==void 0?n:Pe.HEARTBEAT_INTERVAL,this.worker=(i=e==null?void 0:e.worker)!==null&&i!==void 0?i:!1,this.accessToken=(o=e==null?void 0:e.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(a=e==null?void 0:e.heartbeatCallback)!==null&&a!==void 0?a:Ze,this.vsn=(l=e==null?void 0:e.vsn)!==null&&l!==void 0?l:Dt,e!=null&&e.params&&(this.params=e.params),e!=null&&e.logger&&(this.logger=e.logger),(e!=null&&e.logLevel||e!=null&&e.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(c=e==null?void 0:e.reconnectAfterMs)!==null&&c!==void 0?c:g=>Ks[g-1]||Gs,this.vsn){case Lr:this.encode=(u=e==null?void 0:e.encode)!==null&&u!==void 0?u:(g,_)=>_(JSON.stringify(g)),this.decode=(d=e==null?void 0:e.decode)!==null&&d!==void 0?d:(g,_)=>_(JSON.parse(g));break;case xs:this.encode=(f=e==null?void 0:e.encode)!==null&&f!==void 0?f:this.serializer.encode.bind(this.serializer),this.decode=(h=e==null?void 0:e.decode)!==null&&h!==void 0?h:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e==null?void 0:e.workerUrl}}};const zs=Object.freeze(Object.defineProperty({__proto__:null,REALTIME_CHANNEL_STATES:Vs,get REALTIME_LISTEN_TYPES(){return le},get REALTIME_POSTGRES_CHANGES_LISTEN_EVENT(){return dt},get REALTIME_PRESENCE_LISTEN_EVENTS(){return ht},get REALTIME_SUBSCRIBE_STATES(){return q},RealtimeChannel:Wr,RealtimeClient:Js,RealtimePresence:Mr,WebSocketFactory:Dr},Symbol.toStringTag,{value:"Module"})),Vr=be(zs);class me extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function k(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class Kr extends me{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}}}class qe extends me{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}const Tt=s=>s?(...e)=>s(...e):(...e)=>fetch(...e),Ys=()=>Response,ft=s=>{if(Array.isArray(s))return s.map(t=>ft(t));if(typeof s=="function"||s!==Object(s))return s;const e={};
26return Object.entries(s).forEach(([t,r])=>{const n=t.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[n]=ft(r)}),e},Qs=s=>{if(typeof s!="object"||s===null)return!1;const e=Object.getPrototypeOf(s);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in s)&&!(Symbol.iterator in s)},Xs=s=>!s||typeof s!="string"||s.length===0||s.length>100||s.trim()!==s||s.includes("/")||s.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(s),et=s=>{var e;return s.msg||s.message||s.error_description||(typeof s.error=="string"?s.error:(e=s.error)===null||e===void 0?void 0:e.message)||JSON.stringify(s)},Zs=(s,e,t)=>y(void 0,void 0,void 0,function*(){const r=yield Ys();s instanceof r&&!(t!=null&&t.noResolveJson)?s.json().then(n=>{const i=s.status||500,o=(n==null?void 0:n.statusCode)||i+"";e(new Kr(et(n),i,o))}).catch(n=>{e(new qe(et(n),n))}):e(new qe(et(s),s))}),en=(s,e,t,r)=>{const n={method:s,headers:(e==null?void 0:e.headers)||{}};return s==="GET"||!r?n:(Qs(r)?(n.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),n.body=JSON.stringify(r)):n.body=r,e!=null&&e.duplex&&(n.duplex=e.duplex),Object.assign(Object.assign({},n),t))};function Ee(s,e,t,r,n,i){return y(this,void 0,void 0,function*(){return new Promise((o,a)=>{s(t,en(e,r,n,i)).then(l=>{if(!l.ok)throw l;return r!=null&&r.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>Zs(l,a,r))})})}function ve(s,e,t,r){return y(this,void 0,void 0,function*(){return Ee(s,"GET",e,t,r)})}function L(s,e,t,r,n){return y(this,void 0,void 0,function*(){return Ee(s,"POST",e,r,n,t)})}function gt(s,e,t,r,n){return y(this,void 0,void 0,function*(){return Ee(s,"PUT",e,r,n,t)})}function tn(s,e,t,r){return y(this,void 0,void 0,function*(){return Ee(s,"HEAD",e,Object.assign(Object.assign({},t),{noResolveJson:!0}),r)})}function Ot(s,e,t,r,n){return y(this,void 0,void 0,function*(){return Ee(s,"DELETE",e,r,n,t)})}class rn{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}execute(){return y(this,void 0,void 0,function*(){try{return{data:(yield this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(k(e))return{data:null,error:e};throw e}})}}var Gr;class sn{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[Gr]="BlobDownloadBuilder",this.promise=null}asStream(){return new rn(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}execute(){return y(this,void 0,void 0,function*(){try{return{data:yield(yield this.downloadFn()).blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(k(e))return{data:null,error:e};throw e}})}}Gr=Symbol.toStringTag;const nn={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Bt={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class on{constructor(e,t={},r,n){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=r,this.fetch=Tt(n)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,t,r,n){return y(this,void 0,void 0,function*(){try{let i;const o=Object.assign(Object.assign({},Bt),n);let a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const l=o.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",this.encodeMetadata(l)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),l&&!i.has("metadata")&&i.append("metadata",this.encodeMetadata(l))):(i=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=this.toBase64(this.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),n!=null&&n.headers&&(a=Object.assign(Object.assign({},a),n.headers));const c=this._removeEmptyFolders(t),u=this._getFinalPath(c),d=yield(e=="PUT"?gt:L)(this.fetch,`${this.url}/object/${u}`,i,Object.assign({headers:a},o!=null&&o.duplex?{duplex:o.duplex}:{}));return{data:{path:c,id:d.Id,fullPath:d.Key},error:null}}catch(i){if(this.shouldThrowOnError)throw i;if(k(i))return{data:null,error:i};throw i}})}upload(e,t,r){return y(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,n){return y(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(e),o=this._getFinalPath(i),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let l;const c=Object.assign({upsert:Bt.upsert},n),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType);const d=yield gt(this.fetch,a.toString(),l,{headers:u});return{data:{path:i,fullPath:d.Key},error:null}}catch(l){if(this.shouldThrowOnError)throw l;if(k(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e,t){return y(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e);const n=Object.assign({},this.headers);t!=null&&t.upsert&&(n["x-upsert"]="true");const i=yield L(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:n}),o=new URL(this.url+i.url),a=o.searchParams.get("token");if(!a)throw new me("No token returned by API");return{data:{signedUrl:o.toString(),path:e,token:a},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(k(r))return{data:null,error:r};throw r}})}update(e,t,r){return y(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t,r){return y(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,de
26stinationBucket:r==null?void 0:r.destinationBucket},{headers:this.headers}),error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(k(n))return{data:null,error:n};throw n}})}copy(e,t,r){return y(this,void 0,void 0,function*(){try{return{data:{path:(yield L(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:r==null?void 0:r.destinationBucket},{headers:this.headers})).Key},error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(k(n))return{data:null,error:n};throw n}})}createSignedUrl(e,t,r){return y(this,void 0,void 0,function*(){try{let n=this._getFinalPath(e),i=yield L(this.fetch,`${this.url}/object/sign/${n}`,Object.assign({expiresIn:t},r!=null&&r.transform?{transform:r.transform}:{}),{headers:this.headers});const o=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${o}`)},{data:i,error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(k(n))return{data:null,error:n};throw n}})}createSignedUrls(e,t,r){return y(this,void 0,void 0,function*(){try{const n=yield L(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return{data:n.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${i}`):null})),error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(k(n))return{data:null,error:n};throw n}})}download(e,t){const n=typeof(t==null?void 0:t.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),o=i?`?${i}`:"",a=this._getFinalPath(e),l=()=>ve(this.fetch,`${this.url}/${n}/${a}${o}`,{headers:this.headers,noResolveJson:!0});return new sn(l,this.shouldThrowOnError)}info(e){return y(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const r=yield ve(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:ft(r),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(k(r))return{data:null,error:r};throw r}})}exists(e){return y(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield tn(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(k(r)&&r instanceof qe){const n=r.originalError;if([400,404].includes(n==null?void 0:n.status))return{data:!1,error:r}}throw r}})}getPublicUrl(e,t){const r=this._getFinalPath(e),n=[],i=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";i!==""&&n.push(i);const a=typeof(t==null?void 0:t.transform)<"u"?"render/image":"object",l=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});l!==""&&n.push(l);let c=n.join("&");return c!==""&&(c=`?${c}`),{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${r}${c}`)}}}remove(e){return y(this,void 0,void 0,function*(){try{return{data:yield Ot(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(k(t))return{data:null,error:t};throw t}})}list(e,t,r){return y(this,void 0,void 0,function*(){try{const n=Object.assign(Object.assign(Object.assign({},nn),t),{prefix:e||""});return{data:yield L(this.fetch,`${this.url}/object/list/${this.bucketId}`,n,{headers:this.headers},r),error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(k(n))return{data:null,error:n};throw n}})}listV2(e,t){return y(this,void 0,void 0,function*(){try{const r=Object.assign({},e);return{data:yield L(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,r,{headers:this.headers},t),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(k(r))return{data:null,error:r};throw r}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?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 Hr="2.87.1",Jr={"X-Client-Info":`storage-js/${Hr}`};class an{constructor(e,t={},r,n){this.shouldThrowOnError=!1;const i=new URL(e);n!=null&&n.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase.")),this.url=i.href.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Jr),t),this.fetch=Tt(r)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(e){return y(this,void 0,void 0,function*(){try{const t=this.listBucketOptionsToQueryString(e);return{data:yield ve(this.fetch,`${this.url}/bucket${t}`,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(k(t))return{data:null,error:t};throw t}})}getBucket(e){return y(this,void 0,void 0,function*(){try{return{data:yield ve(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(k(t))return{data:null,error:t};throw t}})}createBucket(e){return y(this,arguments,void 0,function*(t,r={public:!1}){try{return{data:yield L(this.fetch,`${this.url}/bucket`,{id:t,name:t,type:r.type,public:r.public,file_size_limit:r.fileSizeLimit,allowed_mime_types:r.allowedMimeTypes},{headers:this.headers}),error:null}}catch(n){if(this.shouldThrowOnError)throw n;if(k(n))return{data:null,error:n};throw n}})}updateBucket(e,t){return y(this,void 0,void 0,function*(){try{return{data:yield gt(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(k(r))return{data:null,error:r};throw r}})}emptyBucket(e){return y(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(k(t))return{data:null,error:t};throw t}})}deleteBucket(e){return y(this,void 0,void 0,function*(){try{return{data:yield Ot(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(k(t))return{data:null,error:t};throw t}})}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():""}}
26var ye=class extends Error{constructor(s,e){var t;super(s),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&((t=e.icebergType)==null?void 0:t.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function ln(s,e,t){const r=new URL(e,s);if(t)for(const[n,i]of Object.entries(t))i!==void 0&&r.searchParams.set(n,i);return r.toString()}async function cn(s){return!s||s.type==="none"?{}:s.type==="bearer"?{Authorization:`Bearer ${s.token}`}:s.type==="header"?{[s.name]:s.value}:s.type==="custom"?await s.getHeaders():{}}function un(s){const e=s.fetchImpl??globalThis.fetch;return{async request({method:t,path:r,query:n,body:i,headers:o}){const a=ln(s.baseUrl,r,n),l=await cn(s.auth),c=await e(a,{method:t,headers:{...i?{"Content-Type":"application/json"}:{},...l,...o},body:i?JSON.stringify(i):void 0}),u=await c.text(),d=(c.headers.get("content-type")||"").includes("application/json"),f=d&&u?JSON.parse(u):u;if(!c.ok){const h=d?f:void 0,g=h==null?void 0:h.error;throw new ye((g==null?void 0:g.message)??`Request failed with status ${c.status}`,{status:c.status,icebergType:g==null?void 0:g.type,icebergCode:g==null?void 0:g.code,details:h})}return{status:c.status,headers:c.headers,data:f}}}}function je(s){return s.join("�")}var hn=class{constructor(s,e=""){this.client=s,this.prefix=e}async listNamespaces(s){const e=s?{parent:je(s.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(r=>({namespace:r}))}async createNamespace(s,e){const t={namespace:s.namespace,properties:e==null?void 0:e.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:t})).data}async dropNamespace(s){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${je(s.namespace)}`})}async loadNamespaceMetadata(s){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${je(s.namespace)}`})).data.properties}}async namespaceExists(s){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${je(s.namespace)}`}),!0}catch(e){if(e instanceof ye&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(s,e){try{return await this.createNamespace(s,e)}catch(t){if(t instanceof ye&&t.status===409)return;throw t}}};function re(s){return s.join("�")}var dn=class{constructor(s,e="",t){this.client=s,this.prefix=e,this.accessDelegation=t}async listTables(s){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${re(s.namespace)}/tables`})).data.identifiers}async createTable(s,e){const t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${re(s.namespace)}/tables`,body:e,headers:t})).data.metadata}async updateTable(s,e){const t=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${re(s.namespace)}/tables/${s.name}`,body:e});return{"metadata-location":t.data["metadata-location"],metadata:t.data.metadata}}async dropTable(s,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${re(s.namespace)}/tables/${s.name}`,query:{purgeRequested:String((e==null?void 0:e.purge)??!1)}})}async loadTable(s){const e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${re(s.namespace)}/tables/${s.name}`,headers:e})).data.metadata}async tableExists(s){const e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${re(s.namespace)}/tables/${s.name}`,headers:e}),!0}catch(t){if(t instanceof ye&&t.status===404)return!1;throw t}}async createTableIfNotExists(s,e){try{return await this.createTable(s,e)}catch(t){if(t instanceof ye&&t.status===409)return await this.loadTable({namespace:s.namespace,name:e.name});throw t}}},fn=class{constructor(s){var r;let e="v1";s.catalogName&&(e+=`/${s.catalogName}`);const t=s.baseUrl.endsWith("/")?s.baseUrl:`${s.baseUrl}/`;this.client=un({baseUrl:t,auth:s.auth,fetchImpl:s.fetch}),this.accessDelegation=(r=s.accessDelegation)==null?void 0:r.join(","),this.namespaceOps=new hn(this.client,e),this.tableOps=new dn(this.client,e,this.accessDelegation)}async listNamespaces(s){return this.namespaceOps.listNamespaces(s)}async createNamespace(s,e){return this.namespaceOps.createNamespace(s,e)}async dropNamespace(s){await this.namespaceOps.dropNamespace(s)}async loadNamespaceMetadata(s){return this.namespaceOps.loadNamespaceMetadata(s)}async listTables(s){return this.tableOps.listTables(s)}
26async createTable(s,e){return this.tableOps.createTable(s,e)}async updateTable(s,e){return this.tableOps.updateTable(s,e)}async dropTable(s,e){await this.tableOps.dropTable(s,e)}async loadTable(s){return this.tableOps.loadTable(s)}async namespaceExists(s){return this.namespaceOps.namespaceExists(s)}async tableExists(s){return this.tableOps.tableExists(s)}async createNamespaceIfNotExists(s,e){return this.namespaceOps.createNamespaceIfNotExists(s,e)}async createTableIfNotExists(s,e){return this.tableOps.createTableIfNotExists(s,e)}};class zr{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Jr),t),this.fetch=Tt(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return y(this,void 0,void 0,function*(){try{return{data:yield L(this.fetch,`${this.url}/bucket`,{name:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(k(t))return{data:null,error:t};throw t}})}listBuckets(e){return y(this,void 0,void 0,function*(){try{const t=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&t.set("limit",e.limit.toString()),(e==null?void 0:e.offset)!==void 0&&t.set("offset",e.offset.toString()),e!=null&&e.sortColumn&&t.set("sortColumn",e.sortColumn),e!=null&&e.sortOrder&&t.set("sortOrder",e.sortOrder),e!=null&&e.search&&t.set("search",e.search);const r=t.toString(),n=r?`${this.url}/bucket?${r}`:`${this.url}/bucket`;return{data:yield ve(this.fetch,n,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(k(t))return{data:null,error:t};throw t}})}deleteBucket(e){return y(this,void 0,void 0,function*(){try{return{data:yield Ot(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(k(t))return{data:null,error:t};throw t}})}from(e){if(!Xs(e))throw new me("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 t=new fn({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:()=>y(this,void 0,void 0,function*(){return this.headers})},fetch:this.fetch}),r=this.shouldThrowOnError;return new Proxy(t,{get(i,o){const a=i[o];return typeof a!="function"?a:(...l)=>y(this,void 0,void 0,function*(){try{return{data:yield a.apply(i,l),error:null}}catch(c){if(r)throw c;return{data:null,error:c}}})}})}}const kt={"X-Client-Info":`storage-js/${Hr}`,"Content-Type":"application/json"};class At extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}}function U(s){return typeof s=="object"&&s!==null&&"__isStorageVectorsError"in s}class Ie extends At{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}}}class Yr extends At{constructor(e,t){super(e),this.name="StorageVectorsUnknownError",this.originalError=t}}var pt;(function(s){s.InternalError="InternalError",s.S3VectorConflictException="S3VectorConflictException",s.S3VectorNotFoundException="S3VectorNotFoundException",s.S3VectorBucketNotEmpty="S3VectorBucketNotEmpty",s.S3VectorMaxBucketsExceeded="S3VectorMaxBucketsExceeded",s.S3VectorMaxIndexesExceeded="S3VectorMaxIndexesExceeded"})(pt||(pt={}));const Je=s=>s?(...e)=>s(...e):(...e)=>fetch(...e),gn=()=>Response,Qr=s=>{if(typeof s!="object"||s===null)return!1;const e=Object.getPrototypeOf(s);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in s)&&!(Symbol.iterator in s)},pn=s=>Array.from(new Float32Array(s)),_n=(s,e)=>{if(e!==void 0&&s.float32.length!==e)throw new Error(`Vector dimension mismatch: expected ${e}, got ${s.float32.length}`)},qt=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),wn=(s,e,t)=>y(void 0,void 0,void 0,function*(){if(s&&typeof s=="object"&&"status"in s&&"ok"in s&&typeof s.status=="number"&&!(t!=null&&t.noResolveJson)){const n=s.status||500,i=s;if(typeof i.json=="function")i.json().then(o=>{const a=(o==null?void 0:o.statusCode)||(o==null?void 0:o.code)||n+"";e(new Ie(qt(o),n,a))}).catch(()=>{const o=n+"",a=i.statusText||`HTTP ${n} error`;e(new Ie(a,n,o))});else{const o=n+"",a=i.statusText||`HTTP ${n} error`;e(new Ie(a,n,o))}}else e(new Yr(qt(s),s))}),vn=(s,e,t,r)=>{const n={method:s,headers:(e==null?void 0:e.headers)||{}};return r?(Qr(r)?(n.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),n.body=JSON.stringify(r)):n.body=r,Object.assign(Object.assign({},n),t)):n};function yn(s,e,t,r,n,i){return y(this,void 0,void 0,function*(){return new Promise((o,a)=>
26{s(t,vn(e,r,n,i)).then(l=>{if(!l.ok)throw l;if(r!=null&&r.noResolveJson)return l;const c=l.headers.get("content-type");return!c||!c.includes("application/json")?{}:l.json()}).then(l=>o(l)).catch(l=>wn(l,a,r))})})}function N(s,e,t,r,n){return y(this,void 0,void 0,function*(){return yn(s,"POST",e,r,n,t)})}class Xr{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},kt),t),this.fetch=Je(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createIndex(e){return y(this,void 0,void 0,function*(){try{return{data:(yield N(this.fetch,`${this.url}/CreateIndex`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}getIndex(e,t){return y(this,void 0,void 0,function*(){try{return{data:yield N(this.fetch,`${this.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}),error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(U(r))return{data:null,error:r};throw r}})}listIndexes(e){return y(this,void 0,void 0,function*(){try{return{data:yield N(this.fetch,`${this.url}/ListIndexes`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}deleteIndex(e,t){return y(this,void 0,void 0,function*(){try{return{data:(yield N(this.fetch,`${this.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}))||{},error:null}}catch(r){if(this.shouldThrowOnError)throw r;if(U(r))return{data:null,error:r};throw r}})}}class Zr{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},kt),t),this.fetch=Je(r)}throwOnError(){return this.shouldThrowOnError=!0,this}putVectors(e){return y(this,void 0,void 0,function*(){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:(yield N(this.fetch,`${this.url}/PutVectors`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}getVectors(e){return y(this,void 0,void 0,function*(){try{return{data:yield N(this.fetch,`${this.url}/GetVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}listVectors(e){return y(this,void 0,void 0,function*(){try{if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return{data:yield N(this.fetch,`${this.url}/ListVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}queryVectors(e){return y(this,void 0,void 0,function*(){try{return{data:yield N(this.fetch,`${this.url}/QueryVectors`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}deleteVectors(e){return y(this,void 0,void 0,function*(){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:(yield N(this.fetch,`${this.url}/DeleteVectors`,e,{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}}class es{constructor(e,t={},r){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},kt),t),this.fetch=Je(r)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return y(this,void 0,void 0,function*(){try{return{data:(yield N(this.fetch,`${this.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}getBucket(e){return y(this,void 0,void 0,function*(){try{return{data:yield N(this.fetch,`${this.url}/GetVectorBucket`,{vectorBucketName:e},{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}listBuckets(){return y(this,arguments,void 0,function*(e={}){try{return{data:yield N(this.fetch,`${this.url}/ListVectorBuckets`,e,{headers:this.headers}),error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}deleteBucket(e){return y(this,void 0,void 0,function*(){try{return{data:(yield N(this.fetch,`${this.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(t){if(this.shouldThrowOnError)throw t;if(U(t))return{data:null,error:t};throw t}})}}class ts extends es{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new rs(this.url,this.headers,e,this.fetch)}createBucket(e){const t=Object.create(null,{createBucket:{get:()=>super.createBucket}});return y(this,void 0,void 0,function*(){return t.createBucket.call(this,e)})}getBucket(e){const t=Object.create(null,{getBucket:{get:()=>super.getBucket}});return y(this,void 0,void 0,function*(){return t.getBucket.call(this,e)})}listBuckets(){const e=Object.create(null,{listBuckets:{get:()=>super.listBuckets}});return y(this,arguments,void 0,function*(t={}
26){return e.listBuckets.call(this,t)})}deleteBucket(e){const t=Object.create(null,{deleteBucket:{get:()=>super.deleteBucket}});return y(this,void 0,void 0,function*(){return t.deleteBucket.call(this,e)})}}class rs extends Xr{constructor(e,t,r,n){super(e,t,n),this.vectorBucketName=r}createIndex(e){const t=Object.create(null,{createIndex:{get:()=>super.createIndex}});return y(this,void 0,void 0,function*(){return t.createIndex.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName}))})}listIndexes(){const e=Object.create(null,{listIndexes:{get:()=>super.listIndexes}});return y(this,arguments,void 0,function*(t={}){return e.listIndexes.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName}))})}getIndex(e){const t=Object.create(null,{getIndex:{get:()=>super.getIndex}});return y(this,void 0,void 0,function*(){return t.getIndex.call(this,this.vectorBucketName,e)})}deleteIndex(e){const t=Object.create(null,{deleteIndex:{get:()=>super.deleteIndex}});return y(this,void 0,void 0,function*(){return t.deleteIndex.call(this,this.vectorBucketName,e)})}index(e){return new ss(this.url,this.headers,this.vectorBucketName,e,this.fetch)}}class ss extends Zr{constructor(e,t,r,n,i){super(e,t,i),this.vectorBucketName=r,this.indexName=n}putVectors(e){const t=Object.create(null,{putVectors:{get:()=>super.putVectors}});return y(this,void 0,void 0,function*(){return t.putVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}getVectors(e){const t=Object.create(null,{getVectors:{get:()=>super.getVectors}});return y(this,void 0,void 0,function*(){return t.getVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}listVectors(){const e=Object.create(null,{listVectors:{get:()=>super.listVectors}});return y(this,arguments,void 0,function*(t={}){return e.listVectors.call(this,Object.assign(Object.assign({},t),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}queryVectors(e){const t=Object.create(null,{queryVectors:{get:()=>super.queryVectors}});return y(this,void 0,void 0,function*(){return t.queryVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}deleteVectors(e){const t=Object.create(null,{deleteVectors:{get:()=>super.deleteVectors}});return y(this,void 0,void 0,function*(){return t.deleteVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}}class bn extends an{constructor(e,t={},r,n){super(e,t,r,n)}from(e){return new on(this.url,this.headers,e,this.fetch)}get vectors(){return new ts(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new zr(this.url+"/iceberg",this.headers,this.fetch)}}const mn=Object.freeze(Object.defineProperty({__proto__:null,StorageAnalyticsClient:zr,StorageApiError:Kr,StorageClient:bn,StorageError:me,StorageUnknownError:qe,StorageVectorsApiError:Ie,StorageVectorsClient:ts,StorageVectorsError:At,get StorageVectorsErrorCode(){return pt},StorageVectorsUnknownError:Yr,VectorBucketApi:es,VectorBucketScope:rs,VectorDataApi:Zr,VectorIndexApi:Xr,VectorIndexScope:ss,isPlainObject:Qr,isStorageError:k,isStorageVectorsError:U,normalizeToFloat32:pn,resolveFetch:Je,resolveResponse:gn,validateVectorDimension:_n},Symbol.toStringTag,{value:"Module"})),En=be(mn);var ns={},ze={};Object.defineProperty(ze,"__esModule",{value:!0});ze.version=void 0;ze.version="2.87.1";(function(s){Object.defineProperty(s,"__esModule",{value:!0}),s.DEFAULT_REALTIME_OPTIONS=s.DEFAULT_AUTH_OPTIONS=s.DEFAULT_DB_OPTIONS=s.DEFAULT_GLOBAL_OPTIONS=s.DEFAULT_HEADERS=void 0;const e=ze;let t="";typeof Deno<"u"?t="deno":typeof document<"u"?t="web":typeof navigator<"u"&&navigator.product==="ReactNative"?t="react-native":t="node",s.DEFAULT_HEADERS={"X-Client-Info":`supabase-js-${t}/${e.version}`},s.DEFAULT_GLOBAL_OPTIONS={headers:s.DEFAULT_HEADERS},s.DEFAULT_DB_OPTIONS={schema:"public"},s.DEFAULT_AUTH_OPTIONS={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},s.DEFAULT_REALTIME_OPTIONS={}})(ns);var is={};(function(s){Object.defineProperty(s,"__esModule",{value:!0}),s.fetchWithAuth=s.resolveHeadersConstructor=s.resolveFetch=void 0;const e=n=>
26n?(...i)=>n(...i):(...i)=>fetch(...i);s.resolveFetch=e;const t=()=>Headers;s.resolveHeadersConstructor=t;const r=(n,i,o)=>{const a=(0,s.resolveFetch)(o),l=(0,s.resolveHeadersConstructor)();return async(c,u)=>{var d;const f=(d=await i())!==null&&d!==void 0?d:n;let h=new l(u==null?void 0:u.headers);return h.has("apikey")||h.set("apikey",n),h.has("Authorization")||h.set("Authorization",`Bearer ${f}`),a(c,Object.assign(Object.assign({},u),{headers:h}))}};s.fetchWithAuth=r})(is);var G={};Object.defineProperty(G,"__esModule",{value:!0});G.isBrowser=void 0;G.uuid=Sn;G.ensureTrailingSlash=os;G.applySettingDefaults=On;G.validateSupabaseUrl=kn;function Sn(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(s){var e=Math.random()*16|0,t=s=="x"?e:e&3|8;return t.toString(16)})}function os(s){return s.endsWith("/")?s:s+"/"}const Tn=()=>typeof window<"u";G.isBrowser=Tn;function On(s,e){var t,r;const{db:n,auth:i,realtime:o,global:a}=s,{db:l,auth:c,realtime:u,global:d}=e,f={db:Object.assign(Object.assign({},l),n),auth:Object.assign(Object.assign({},c),i),realtime:Object.assign(Object.assign({},u),o),storage:{},global:Object.assign(Object.assign(Object.assign({},d),a),{headers:Object.assign(Object.assign({},(t=d==null?void 0:d.headers)!==null&&t!==void 0?t:{}),(r=a==null?void 0:a.headers)!==null&&r!==void 0?r:{})}),accessToken:async()=>""};return s.accessToken?f.accessToken=s.accessToken:delete f.accessToken,f}function kn(s){const e=s==null?void 0:s.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(os(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Ye={};const as="2.87.1",oe=30*1e3,_t=3,tt=_t*oe,An="http://localhost:9999",Rn="supabase.auth.token",Pn={"X-Client-Info":`gotrue-js/${as}`},wt="X-Supabase-Api-Version",ls={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},jn=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Cn=10*60*1e3;let he=class extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}};function b(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}let cs=class extends he{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}};function us(s){return b(s)&&s.name==="AuthApiError"}let V=class extends he{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}},M=class extends he{constructor(e,t,r,n){super(e,r,n),this.name=t,this.status=r}},x=class extends M{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function hs(s){return b(s)&&s.name==="AuthSessionMissingError"}let z=class extends M{constructor(){super("Auth session or user missing","AuthInvalidToken
26ResponseError",500,void 0)}},_e=class extends M{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}},we=class extends M{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};function ds(s){return b(s)&&s.name==="AuthImplicitGrantRedirectError"}let vt=class extends M{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}}},Fe=class extends M{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}};function xe(s){return b(s)&&s.name==="AuthRetryableFetchError"}let yt=class extends M{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}};function $n(s){return b(s)&&s.name==="AuthWeakPasswordError"}let Me=class extends M{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};const We="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Ft=` 27\r=`.split(""),In=(()=>{const s=new Array(128);for(let e=0;e<s.length;e+=1)s[e]=-1;for(let e=0;e<Ft.length;e+=1)s[Ft[e].charCodeAt(0)]=-2;for(let e=0;e<We.length;e+=1)s[We[e].charCodeAt(0)]=e;return s})();function Mt(s,e,t){if(s!==null)for(e.queue=e.queue<<8|s,e.queuedBits+=8;e.queuedBits>=6;){const r=e.queue>>e.queuedBits-6&63;t(We[r]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){const r=e.queue>>e.queuedBits-6&63;t(We[r]),e.queuedBits-=6}}function fs(s,e,t){const r=In[s];if(r>-1)for(e.queue=e.queue<<6|r,e.queuedBits+=6;e.queuedBits>=8;)t(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(s)}"`)}}function Wt(s){const e=[],t=o=>{e.push(String.fromCodePoint(o))},r={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=o=>{Nn(o,r,t)};for(let o=0;o<s.length;o+=1)fs(s.charCodeAt(o),n,i);return e.join("")}function xn(s,e){if(s<=127){e(s);return}else if(s<=2047){e(192|s>>6),e(128|s&63);return}else if(s<=65535){e(224|s>>12),e(128|s>>6&63),e(128|s&63);return}else if(s<=1114111){e(240|s>>18),e(128|s>>12&63),e(128|s>>6&63),e(128|s&63);return}throw new Error(`Unrecognized Unicode codepoint: ${s.toString(16)}`)}function Un(s,e){for(let t=0;t<s.length;t+=1){let r=s.charCodeAt(t);if(r>55295&&r<=56319){const n=(r-55296)*1024&65535;r=(s.charCodeAt(t+1)-56320&65535|n)+65536,t+=1}xn(r,e)}}function Nn(s,e,t){if(e.utf8seq===0){if(s<=127){t(s);return}for(let r=1;r<6;r+=1)if(!(s>>7-r&1)){e.utf8seq=r;break}if(e.utf8seq===2)e.codepoint=s&31;else if(e.utf8seq===3)e.codepoint=s&15;else if(e.utf8seq===4)e.codepoint=s&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(s<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|s&63,e.utf8seq-=1,e.utf8seq===0&&t(e.codepoint)}}function ce(s){const e=[],t={queue:0,queuedBits:0},r=n=>{e.push(n)};for(let n=0;n<s.length;n+=1)fs(s.charCodeAt(n),t,r);return new Uint8Array(e)}function Dn(s){const e=[];return Un(s,t=>e.push(t)),new Uint8Array(e)}function ee(s){const e=[],t={queue:0,queuedBits:0},r=n=>{e.push(n)};return s.forEach(n=>Mt(n,t,r)),Mt(null,t,r),e.join("")}function Ln(s){return Math.round(Date.now()/1e3)+s}function Bn(){return Symbol("auth-callback")}const $=()=>typeof window<"u"&&typeof document<"u",H={tested:!1,writable:!1},gs=()=>{if(!$())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(H.tested)return H.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),H.tested=!0,H.writable=!0}catch{H.tested=!0,H.writable=!1}return H.writable};function qn(s){const e={},t=new URL(s);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((n,i)=>{e[i]=n})}catch{}return t.searchParams.forEach((r,n)=>{e[n]=r}),e}const ps=s=>s?(...e)=>s(...e):(...e)=>fetch(...e),Fn=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",ae=async(s,e,t)=>{await s.setItem(e,JSON.stringify(t))},J=async(s,e)=>{const t=await s.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},C=async(s,e)=>{await s.removeItem(e)};class Qe{constructor(){this.promise=new Qe.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}Qe.promiseConstructor=Promise;function rt(s){const e=s.split(".");if(e.length!==3)throw new Me("Invalid JWT structure");for(let r=0;r<e.length;r++)if(!jn.test(e[r]))throw new Me("JWT not in base64url format");return{header:JSON.parse(Wt(e[0])),payload:JSON.parse(Wt(e[1])),signature:ce(e[2]),raw:{header:e[0],payload:e[1]}}}async function Mn(s){return await new Promise(e=>{setTimeout(()=>e(null),s)})}function Wn(s,e){return new Promise((r,n)=>{(async()=>{for(let i=0;i<1/0;i++)try{const o=await s(i);if(!e(i,null,o)){r(o);return}}catch(o){if(!e(i,o)){n(o);return}}})()})}function Vn(s){return("0"+s.toString(16)).substr(-2)}function Kn(){const e=new Uint32Array(56);if(typeof crypto>"u"){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=t.length;let n="";for(let i=0;i<56;i++)n+=t.charAt(Math.floor(Math.random()*r));return n}return crypto.getRandomValues(e),Array.from(e,Vn).join("")}async function Gn(s){const t=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",t),n=new Uint8Array(r);return Array.from(n).map(i=>String.fromCharCode(i)).join("")}async function Hn(s){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code
27challenge method will default to use plain instead of sha256."),s;const t=await Gn(s);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function se(s,e,t=!1){const r=Kn();let n=r;t&&(n+="/PASSWORD_RECOVERY"),await ae(s,`${e}-code-verifier`,n);const i=await Hn(r);return[i,r===i?"plain":"s256"]}const Jn=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function zn(s){const e=s.headers.get(wt);if(!e||!e.match(Jn))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Yn(s){if(!s)throw new Error("Missing exp claim");const e=Math.floor(Date.now()/1e3);if(s<=e)throw new Error("JWT has expired")}function Qn(s){switch(s){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")}}const Xn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ne(s){if(!Xn.test(s))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function st(){const s={};return new Proxy(s,{get:(e,t)=>{if(t==="__isUserNotAvailableProxy")return!0;if(typeof t=="symbol"){const r=t.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")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 Zn(s,e){return new Proxy(s,{get:(t,r,n)=>{if(r==="__isInsecureUserWarningProxy")return!0;if(typeof r=="symbol"){const i=r.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(t,r,n)}return!e.value&&typeof r=="string"&&(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."),e.value=!0),Reflect.get(t,r,n)}})}function Vt(s){return JSON.parse(JSON.stringify(s))}const Y=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),ei=[502,503,504];async function Kt(s){var e;if(!Fn(s))throw new Fe(Y(s),0);if(ei.includes(s.status))throw new Fe(Y(s),s.status);let t;try{t=await s.json()}catch(i){throw new V(Y(i),i)}let r;const n=zn(s);if(n&&n.getTime()>=ls["2024-01-01"].timestamp&&typeof t=="object"&&t&&typeof t.code=="string"?r=t.code:typeof t=="object"&&t&&typeof t.error_code=="string"&&(r=t.error_code),r){if(r==="weak_password")throw new yt(Y(t),s.status,((e=t.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(r==="session_not_found")throw new x}else if(typeof t=="object"&&t&&typeof t.weak_password=="object"&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new yt(Y(t),s.status,t.weak_password.reasons);throw new cs(Y(t),s.status||500,r)}const ti=(s,e,t,r)=>{const n={method:s,headers:(e==null?void 0:e.headers)||{}};return s==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),n.body=JSON.stringify(r),Object.assign(Object.assign({},n),t))};async function E(s,e,t,r){var n;const i=Object.assign({},r==null?void 0:r.headers);i[wt]||(i[wt]=ls["2024-01-01"].name),r!=null&&r.jwt&&(i.Authorization=`Bearer ${r.jwt}`);const o=(n=r==null?void 0:r.query)!==null&&n!==void 0?n:{};r!=null&&r.redirectTo&&(o.redirect_to=r.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await ri(s,e,t+a,{headers:i,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(l):{data:Object.assign({},l),error:null}}async function ri(s,e,t,r,n,i){const o=ti(e,r,n,i);let a;try{a=await s(t,Object.assign({},o))}catch(l){throw console.error(l),new Fe(Y(l),0)}if(a.ok||await Kt(a),r!=null&&r.noResolveJson)return a;try{return await a.json()}catch(l){await Kt(l)}}function D(s){var e;let t=null;ii(s)&&(t=Object.assign({},s),s.expires_at||(t.expires_at=Ln(s.expires_in)));const r=(e=s.user)!==null&&e!==void 0?e:s;return{data:{session:t,user:r},error:null}}function Gt(s){const e=D(s);return!e.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((t,r)=>t&&typeof r=="string",!0)&&(e.data.weak_password=s.weak_password),e}function K(s){var e;return{data:{user:(e=s.user)!==null&&e!==void 0?e:s},error:null}}function si(s){return{data:s,error:null}}function ni(s){const{action_link:e,email_otp:t,hashed_token:r,redirect_to:n,verification_type:i}=s,o=de(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:n,verification_type:i},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Ht(s){return s}function ii(s){return s.access_token&&s.refresh_token&&s.expires_in}const Ue=["global","local","others"];let Rt=class{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=ps(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=Ue[0]){if(Ue.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Ue.join(", ")}`);try{return await E(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(b(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await E(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:K})}catch(r){if(b(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{const{options:t}=e,r=de(e,["options"]),n=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(n.new_email=r==null?void 0:r.newEmail,delete n.newEmail),await E(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:ni,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(b(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await E(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:K})}catch(t){if(b(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,n,i,o,a,l;try{const c={nextPage:null,lastPage:0,total:0},u=await E(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(n=e==null?void 0:e.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:Ht});if(u.error)throw u.error;const d=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,h=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return h.length>
270&&(h.forEach(g=>{const _=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),p=JSON.parse(g.split(";")[1].split("=")[1]);c[`${p}Page`]=_}),c.total=parseInt(f)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(b(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){ne(e);try{return await E(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:K})}catch(t){if(b(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){ne(e);try{return await E(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:K})}catch(r){if(b(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){ne(e);try{return await E(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:K})}catch(r){if(b(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){ne(e.userId);try{const{data:t,error:r}=await E(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:t,error:r}}catch(t){if(b(t))return{data:null,error:t};throw t}}async _deleteFactor(e){ne(e.userId),ne(e.id);try{return{data:await E(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}}async _listOAuthClients(e){var t,r,n,i,o,a,l;try{const c={nextPage:null,lastPage:0,total:0},u=await E(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(i=(n=e==null?void 0:e.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:Ht});if(u.error)throw u.error;const d=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,h=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return h.length>0&&(h.forEach(g=>{const _=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),p=JSON.parse(g.split(";")[1].split("=")[1]);c[`${p}Page`]=_}),c.total=parseInt(f)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(b(c))return{data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await E(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(b(t))return{data:null,error:t};throw t}}async _getOAuthClient(e){try{return await E(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(b(t))return{data:null,error:t};throw t}}async _updateOAuthClient(e,t){try{return await E(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(b(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(e){try{return await E(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(t){if(b(t))return{data:null,error:t};throw t}}async _regenerateOAuthClientSecret(e){try{return await E(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:t=>({data:t,error:null})})}catch(t){if(b(t))return{data:null,error:t};throw t}}};function Jt(s={}){return{getItem:e=>s[e]||null,setItem:(e,t)=>{s[e]=t},removeItem:e=>{delete s[e]}}}const Q={debug:!!(globalThis&&gs()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Pt extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}let _s=class extends Pt{};class oi extends Pt{}async function ws(s,e,t){Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,e);const r=new globalThis.AbortController;return e>0&&setTimeout(()=>{r.abort(),Q.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},e),await Promise.resolve().then(()=>globalThis.navigator.locks.request(s,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async n=>{if(n){Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,n.name);try{return await t()}finally{Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,n.name)}}else{if(e===0)throw Q.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new _s(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(Q.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await t()}}))}const zt={};async function ai(s,e,t){var r;const n=(r=zt[s])!==null&&r!==void 0?r:Promise.resolve(),i=Promise.race([n.catch(()=>null),e>=0?new Promise((o,a)=>{setTimeout(()=>{a(new oi(`Acquring process lock with name "${s}" timed out`))},e)}):null].filter(o=>
27o)).catch(o=>{if(o&&o.isAcquireTimeout)throw o;return null}).then(async()=>await t());return zt[s]=i.catch(async o=>{if(o&&o.isAcquireTimeout)return await n,null;throw o}),await i}function li(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function vs(s){if(!/^0x[a-fA-F0-9]{40}$/.test(s))throw new Error(`@supabase/auth-js: Address "${s}" is invalid.`);return s.toLowerCase()}function ci(s){return parseInt(s,16)}function ui(s){const e=new TextEncoder().encode(s);return"0x"+Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}function hi(s){var e;const{chainId:t,domain:r,expirationTime:n,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:u,uri:d,version:f}=s;{if(!Number.isInteger(t))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(f!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);if(!((e=s.statement)===null||e===void 0)&&e.includes(` 28`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${s.statement}`)}const h=vs(s.address),g=u?`${u}://${r}`:r,_=s.statement?`${s.statement} 29`:"",p=`${g} wants you to sign in with your Ethereum account: 30${h} 31 32${_}`;let v=`URI: ${d} 33Version: ${f} 34Chain ID: ${t}${o?` 35Nonce: ${o}`:""} 36Issued At: ${i.toISOString()}`;if(n&&(v+=` 37Expiration Time: ${n.toISOString()}`),a&&(v+=` 38Not Before: ${a.toISOString()}`),l&&(v+=` 39Request ID: ${l}`),c){let m=` 40Resources:`;for(const w of c){if(!w||typeof w!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${w}`);m+=` 41- ${w}`}v+=m}return`${p} 42${v}`}class P extends Error{constructor({message:e,code:t,cause:r,name:n}){var i;super(e,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=n??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=t}}class Ve extends P{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function di({error:s,options:e}){var t,r,n;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(s.name==="AbortError"){if(e.signal instanceof AbortSignal)return new P({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:s})}else if(s.name==="ConstraintError"){if(((t=i.authenticatorSelection)===null||t===void 0?void 0:t.requireResidentKey)===!0)return new P({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:s});if(e.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new P({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:s});if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new P({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:s})}else{if(s.name==="InvalidStateError")return new P({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:s});if(s.name==="NotAllowedError")return new P({message:s.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:s});if(s.name==="NotSupportedError")return i.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new P({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:s}):new P({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:s});if(s.name==="SecurityError"){const o=window.location.hostname;if(ys(o)){if(i.rp.id!==o)return new P({message:`The RP ID "${i.rp.id}
42" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:s})}else return new P({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:s})}else if(s.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new P({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:s})}else if(s.name==="UnknownError")return new P({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:s})}return new P({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:s})}function fi({error:s,options:e}){const{publicKey:t}=e;if(!t)throw Error("options was missing required publicKey property");if(s.name==="AbortError"){if(e.signal instanceof AbortSignal)return new P({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:s})}else{if(s.name==="NotAllowedError")return new P({message:s.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:s});if(s.name==="SecurityError"){const r=window.location.hostname;if(ys(r)){if(t.rpId!==r)return new P({message:`The RP ID "${t.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:s})}else return new P({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:s})}else if(s.name==="UnknownError")return new P({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:s})}return new P({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:s})}class gi{createNewAbortSignal(){if(this.controller){const t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}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}}}const pi=new gi;function _i(s){if(!s)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(s);const{challenge:e,user:t,excludeCredentials:r}=s,n=de(s,["challenge","user","excludeCredentials"]),i=ce(e).buffer,o=Object.assign(Object.assign({},t),{id:ce(t.id).buffer}),a=Object.assign(Object.assign({},n),{challenge:i,user:o});if(r&&r.length>0){a.excludeCredentials=new Array(r.length);for(let l=0;l<r.length;l++){const c=r[l];a.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:ce(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return a}function wi(s){if(!s)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(s);const{challenge:e,allowCredentials:t}=s,r=de(s,["challenge","allowCredentials"]),n=ce(e).buffer,i=Object.assign(Object.assign({},r),{challenge:n});if(t&&t.length>0){i.allowCredentials=new Array(t.length);for(let o=0;o<t.length;o++){const a=t[o];i.allowCredentials[o]=Object.assign(Object.assign({},a),{id:ce(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return i}function vi(s){var e;if("toJSON"in s&&typeof s.toJSON=="function")return s.toJSON();const t=s;return{id:s.id,rawId:s.id,response:{attestationObject:ee(new Uint8Array(s.response.attestationObject)),clientDataJSON:ee(new Uint8Array(s.response.clientDataJSON))},type:"public-key",clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function yi(s){var e;if("toJSON"in s&&typeof s.toJSON=="function")return s.toJSON();const t=s,r=s.getClientExtensionResults(),n=s.response;
42return{id:s.id,rawId:s.id,response:{authenticatorData:ee(new Uint8Array(n.authenticatorData)),clientDataJSON:ee(new Uint8Array(n.clientDataJSON)),signature:ee(new Uint8Array(n.signature)),userHandle:n.userHandle?ee(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:(e=t.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function ys(s){return s==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(s)}function Yt(){var s,e;return!!($()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((s=navigator==null?void 0:navigator.credentials)===null||s===void 0?void 0:s.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function bi(s){try{const e=await navigator.credentials.create(s);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ve("Browser returned unexpected credential type",e)}:{data:null,error:new Ve("Empty credential response",e)}}catch(e){return{data:null,error:di({error:e,options:s})}}}async function mi(s){try{const e=await navigator.credentials.get(s);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ve("Browser returned unexpected credential type",e)}:{data:null,error:new Ve("Empty credential response",e)}}catch(e){return{data:null,error:fi({error:e,options:s})}}}const Ei={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Si={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Ke(...s){const e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),t=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),r={};for(const n of s)if(n)for(const i in n){const o=n[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(t(o))r[i]=o;else if(e(o)){const a=r[i];e(a)?r[i]=Ke(a,o):r[i]=Ke(o)}else r[i]=o}return r}function Ti(s,e){return Ke(Ei,s,e||{})}function Oi(s,e){return Ke(Si,s,e||{})}class ki{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:n},i){try{const{data:o,error:a}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!o)return{data:null,error:a};const l=n??pi.createNewAbortSignal();if(o.webauthn.type==="create"){const{user:c}=o.webauthn.credential_options.publicKey;c.name||(c.name=`${c.id}:${r}`),c.displayName||(c.displayName=c.name)}switch(o.webauthn.type){case"create":{const c=Ti(o.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:u,error:d}=await bi({publicKey:c,signal:l});return u?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:u}},error:null}:{data:null,error:d}}case"request":{const c=Oi(o.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:u,error:d}=await mi(Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:c,signal:l}));return u?{data:{factorId:e,challengeId:o.id,webauthn:{type:o.webauthn.type,credential_response:u}},error:null}:{data:null,error:d}}}}catch(o){return b(o)?{data:null,error:o}:{data:null,error:new V("Unexpected error in challenge",o)}}}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=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!t)return{data:null,error:new he("rpId is required for WebAuthn authentication")};try{if(!Yt())return{data:null,error:new V("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:r},signal:n},{request:i});if(!o)return{data:null,error:a};const{webauthn:l}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:l.type,rpId:t,rpOrigins:r,credential_response:l.credential_response}})}catch(o){return b(o)?{data:null,error:o}:{data:null,error:new V("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!t)return{data:null,error:new he("rpId is required for WebAuthn registration")};try{if(!Yt())return{data:null,error:new V("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(u=>{var d;return(d=u.data)===null||d===void 0?void 0:d.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u==null?void 0:u.id}):void 0),{data:null,error:a};const{data:l,error:c}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:r},signal:n},{create:i});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:t,rpOrigins:r,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(o){return b(o)?{data:null,error:o}:{data:null,error:new V("Unexpected error in register",o)}}}}li();const Ai={url:An,storageKey:Rn,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Pn,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1};async function Qt(s,e,t){return await t()}const ie={};let jt=class bt{get jwks(){var e,t;return(t=(e=ie[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&t!==void 0?t:{keys:[]}}set jwks(e){ie[this.storageKey]=Object.assign(Object.assign({},ie[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return(t=(e=ie[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&t!==void 0?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){ie[this.storageKey]=Object.assign(Object.assign({},ie[this.storageKey]),{cachedAt:e})}constructor(e){var t,r,n;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},Ai),e);if(this.storageKey=i.storageKey,this.instanceID=(t=bt.nextInstanceID[this.storageKey])!==null&&t!==void 0?t:0,bt.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&$()){const o=`${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(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new Rt({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=ps(i.fetch),this.lock=i.lock||Qt,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,i.lock?this.lock=i.lock:this.persistSession&&$()&&(!((r=globalThis==null?void 0:globalThis.navigator)===null||r===void 0)&&r.locks)?this.lock=ws:this.lock=Qt,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 ki(this)}
42,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?(i.storage?this.storage=i.storage:gs()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Jt(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=Jt(this.memoryStorage)),$()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(n=this.broadcastChannel)===null||n===void 0||n.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),await this._notifyAllSubscribers(o.data.event,o.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} (${as}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let t={},r="none";if($()&&(t=qn(window.location.href),this._isImplicitGrantCallback(t)?r="implicit":await this._isPKCECallback(t)&&(r="pkce")),$()&&this.detectSessionInUrl&&r!=="none"){const{data:n,error:i}=await this._getSessionFromURL(t,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),ds(i)){const l=(e=i.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}const{session:o,redirectType:a}=n;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(t){return b(t)?this._returnResult({error:t}):this._returnResult({error:new V("Unexpected error during initialization",t)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,n;try{const i=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(t=e==null?void 0:e.options)===null||t===void 0?void 0:t.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.captchaToken}},xform:D}),{data:o,error:a}=i;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});const l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(b(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var t,r,n;try{let i;if("email"in e){const{email:u,password:d,options:f}=e;let h=null,g=null;this.flowType==="pkce"&&([h,g]=await se(this.storage,this.storageKey)),i=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f==null?void 0:f.emailRedirectTo,body:{email:u,password:d,data:(t=f==null?void 0:f.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken},code_challenge:h,code_challenge_method:g},xform:D})}else if("phone"in e){const{phone:u,password:d,options:f}=e;i=await E(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(r=f==null?void 0:f.data)!==null&&r!==void 0?r:{},channel:(n=f==null?void 0:f.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f==null?void 0:f.captchaToken}},xform:D})}else throw new _e("You must provide either an email or phone number and a password");const{data:o,error:a}=i;if(a||!o)return await C(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});const l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(await C(this.storage,`${this.storageKey}-code-verifier`),b(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let t;if("email"in e){const{email:i,password:o,options:a}=e;t=await E(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:Gt})}else if("phone"in e){const{phone:i,password:o,options:a}=e;t=await E(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:Gt})}else throw new _e("You must provide either an email or phone number and a password");const{data:r,error:n}=t;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!r||!r.session||!r.user){const i=new z;return this._returnResult({data:{user:null,session:null},error:i})}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:n})}catch(t){if(b(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOAuth(e){var t,r,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async 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,n,i,o,a,l,c,u,d,f;let h,g;if("message"in e)h=e.message,g=e.signature;else{const{chain:_,wallet:p,statement:v,options:m}=e;let w;if($())if(typeof p=="object")w=p;else{const F=window;if("ethereum"in F&&typeof F.ethereum=="object"&&"request"in F.ethereum&&typeof F.ethereum.request=="function")w=F.ethereum;else 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.")}else{if(typeof p!="object"||!(m!=null&&m.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=p}const S=new URL((t=m==null?void 0:m.url)!==null&&t!==void 0?t:window.location.href),A=await w.request({method:"eth_requestAccounts"}).then(F=>F).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!A||A.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const T=vs(A[0]);let j=(r=m==null?void 0:m.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!j){const F=await w.request({method:"eth_chainId"});j=ci(F)}const W={domain:S.host,address:T,statement:v,uri:S.href,version:"1",chainId:j,nonce:(n=m==null?void 0:m.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(o=(i=m==null?void 0:m.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=m==null?void 0:m.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=m==null?void 0:m.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=m==null?void 0:m.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(u=m==null?void 0:m.signInWithEthereum)===null||u===void 0?void 0:u.resources};h=hi(W),g=await w.request({method:"personal_sign",params:[ui(h),T]})}try{const{data:_,error:p}=await E(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:h,signature:g},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:D});if(p)throw p;if(!_||!_.session||!_.user){const v=new z;return this._returnResult({data:{user:null,session:null},error:v})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:p})}catch(_){if(b(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async signInWithSolana(e){var t,r,n,i,o,a,l,c,u,d,f,h;let g,_;if("message"in e)g=e.message,_=e.signature;else{const{chain:p,wallet:v,statement:m,options:w}=e;let S;if($())if(typeof v=="object")S=v;else{const T=window;if("solana"in T&&typeof T.solana=="object"&&("signIn"in T.solana&&typeof T.solana.signIn=="function"||"signMessage"in T.solana&&typeof T.solana.signMessage=="function"))S=T.solana;else 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.")}else{if(typeof v!="object"||!(w!=null&&w.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");S=v}const A=new URL((t=w==null?void 0:w.url)!==null&&t!==void 0?t:window.location.href);if("signIn"in S&&S.signIn){const T=await S.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},w==null?void 0:w.signInWithSolana),{version:"1",domain:A.host,uri:A.href}),m?{statement:m}:null));let j;if(Array.isArray(T)&&T[0]&&typeof T[0]=="object")j=T[0];else if(T&&typeof T=="object"&&"signedMessage"in T&&"signature"in T)j=T;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in j&&"signature"in j&&(typeof j.signedMessage=="string"||j.signedMessage instanceof Uint8Array)&&j.signature instanceof Uint8Array)g=typeof j.signedMessage=="string"?j.signedMessage:new TextDecoder().decode(j.signedMessage),_=j.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in S)||typeof S.signMessage!="function"||!("publicKey"in S)||typeof S!="object"||!S.publicKey||!("toBase58"in S.publicKey)||typeof S.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");g=[`${A.host} wants you to sign in with your Solana account:`,S.publicKey.toBase58(),...m?["",m,""]:[""],"Version: 1",`URI: ${A.href}`,`Issued At: ${(n=(r=w==null?void 0:w.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=w==null?void 0:w.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${w.signInWithSolana.notBefore}`]:[],...!((o=w==null?void 0:w.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${w.signInWithSolana.expirationTime}`]:[],...!((a=w==null?void 0:w.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${w.signInWithSolana.chainId}`]:[],...!((l=w==null?void 0:w.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${w.signInWithSolana.nonce}`]:[],...!((c=w==null?void 0:w.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${w.signInWithSolana.requestId}`]:[],...!((d=(u=w==null?void 0:w.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||d===void 0)&&d.length?["Resources",...w.sign
42InWithSolana.resources.map(j=>`- ${j}`)]:[]].join(` 43`);const T=await S.signMessage(new TextEncoder().encode(g),"utf8");if(!T||!(T instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");_=T}}try{const{data:p,error:v}=await E(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:g,signature:ee(_)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:D});if(v)throw v;if(!p||!p.session||!p.user){const m=new z;return this._returnResult({data:{user:null,session:null},error:m})}return p.session&&(await this._saveSession(p.session),await this._notifyAllSubscribers("SIGNED_IN",p.session)),this._returnResult({data:Object.assign({},p),error:v})}catch(p){if(b(p))return this._returnResult({data:{user:null,session:null},error:p});throw p}}async _exchangeCodeForSession(e){const t=await J(this.storage,`${this.storageKey}-code-verifier`),[r,n]=(t??"").split("/");try{const{data:i,error:o}=await E(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:D});if(await C(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){const a=new z;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:o})}catch(i){if(await C(this.storage,`${this.storageKey}-code-verifier`),b(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{const{options:t,provider:r,token:n,access_token:i,nonce:o}=e,a=await E(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:n,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:D}),{data:l,error:c}=a;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){const u=new z;return this._returnResult({data:{user:null,session:null},error:u})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:c})}catch(t){if(b(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async signInWithOtp(e){var t,r,n,i,o;try{if("email"in e){const{email:a,options:l}=e;let c=null,u=null;this.flowType==="pkce"&&([c,u]=await se(this.storage,this.storageKey));const{error:d}=await E(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l==null?void 0:l.data)!==null&&t!==void 0?t:{},create_user:(r=l==null?void 0:l.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l==null?void 0:l.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){const{phone:a,options:l}=e,{data:c,error:u}=await E(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=l==null?void 0:l.data)!==null&&n!==void 0?n:{},create_user:(i=l==null?void 0:l.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(o=l==null?void 0:l.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:u})}throw new _e("You must provide either an email or phone number.")}catch(a){if(await C(this.storage,`${this.storageKey}-code-verifier`),b(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var t,r;try{let n,i;"options"in e&&(n=(t=e.options)===null||t===void 0?void 0:t.redirectTo,i=(r=e.options)===null||r===void 0?void 0:r.captchaToken);const{data:o,error:a}=await E(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:D});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,c=o.user;return l!=null&&l.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(n){if(b(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var t,r,n,i,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await se(this.storage,this.storageKey));const c=await E(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:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((n=e==null?void 0:e.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:si});return!((i=c.data)===null||i===void 0)&&i.url&&$()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(a){if(await C(this.storage,`${this.storageKey}-code-verifier`),b(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new x;const{error:n}=await E(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(b(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:n,options:i}=e,{error:o}=await E(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){const{phone:r,type:n,options:i}=e,{data:o,error:a}=await E(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:a})}throw new _e("You must provide either an email or phone number and a type")}catch(t){if(b(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async t=>t))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await r}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 J(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),t!==null&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not val
43id"),await this._removeSession())),!e)return{data:{session:null},error:null};const r=e.expires_at?e.expires_at*1e3-Date.now()<tt:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.userStorage){const o=await J(this.userStorage,this.storageKey+"-user");o!=null&&o.user?e.user=o.user:e.user=st()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const o={value:this.suppressGetSessionWarning};e.user=Zn(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:n},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(-1,async()=>await this._getUser());return t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await E(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:K}):await this._useSession(async t=>{var r,n,i;const{data:o,error:a}=t;if(a)throw a;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new x}:await E(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:K})})}catch(t){if(b(t))return hs(t)&&(await this._removeSession(),await C(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:t});throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{const{data:n,error:i}=r;if(i)throw i;if(!n.session)throw new x;const o=n.session;let a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await se(this.storage,this.storageKey));const{data:c,error:u}=await E(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:K});if(u)throw u;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(r){if(await C(this.storage,`${this.storageKey}-code-verifier`),b(r))return this._returnResult({data:{user:null},error:r});throw r}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new x;const t=Date.now()/1e3;let r=t,n=!0,i=null;const{payload:o}=rt(e.access_token);if(o.exp&&(r=o.exp,n=r<=t),n){const{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};i=a}else{const{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;i={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(t){if(b(t))return this._returnResult({data:{session:null,user:null},error:t});throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){const{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!(e!=null&&e.refresh_token))throw new x;const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(t){if(b(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async _getSessionFromURL(e,t){try{if(!$())throw new we("No browser detected.");
43if(e.error||e.error_description||e.error_code)throw new we(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if(this.flowType==="pkce")throw new vt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new we("Not a valid implicit grant flow url.");break;default:}if(t==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new vt("No code detected.");const{data:m,error:w}=await this._exchangeCodeForSession(e.code);if(w)throw w;const S=new URL(window.location.href);return S.searchParams.delete("code"),window.history.replaceState(window.history.state,"",S.toString()),{data:{session:m.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:n,access_token:i,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!i||!a||!o||!c)throw new we("No session defined in URL");const u=Math.round(Date.now()/1e3),d=parseInt(a);let f=u+d;l&&(f=parseInt(l));const h=f-u;h*1e3<=oe&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${h}s, should have been closer to ${d}s`);const g=f-d;u-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,f,u):u-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,f,u);const{data:_,error:p}=await this._getUser(i);if(p)throw p;const v={provider_token:r,provider_refresh_token:n,access_token:i,expires_in:d,expires_at:f,refresh_token:o,token_type:c,user:_.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:v,redirectType:e.type},error:null})}catch(r){if(b(r))return this._returnResult({data:{session:null,redirectType:null},error:r});throw r}}_isImplicitGrantCallback(e){return!!(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await J(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;const{data:n,error:i}=t;if(i)return this._returnResult({error:i});const o=(r=n.session)===null||r===void 0?void 0:r.access_token;if(o){const{error:a}=await this.admin.signOut(o,e);if(a&&!(us(a)&&(a.status===404||a.status===401||a.status===403)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await C(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const t=Bn(),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(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,n;try{const{data:{session:i},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,t={}){let r=null,n=null;this.flowType==="pkce"&&([r,n]=await se(this.storage,this.storageKey,!0));try{return await E(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:n,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(i){if(await C(this.storage,`${this.storageKey}-code-verifier`),b(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{const{data:t,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(e=t.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(t){if(b(t))return this._returnResult({data:null,error:t});throw t}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:r,error:n}=await this._useSession(async i=>{var o,a,l,c,u;const{data:d,error:f}=i;if(f)throw f;const h=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await E(this.fetch,"GET",h,{headers:this.headers,jwt:(u=(c=d.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(n)throw n;return $()&&!(!((t=e.options)===null||t===void 0)&&t.skipBrowserRedirect)&&window.location.assign(r==null?void 0:r.url),this._returnResult({data:{provider:e.provider,url:r==null?void 0:r.url},error:null})}catch(r){if(b(r))return this._returnResult({data:{provider:e.provider,url:null},error:r});throw r}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var r;try{const{error:n,data:{session:i}}=t;if(n)throw n;const{options:o,provider:a,token:l,access_token:c,nonce:u}=e,d=await E(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i==null?void 0:i.access_token)!==null&&r!==void 0?r:void 0,body:{provider:a,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:D}),{data:f,error:h}=d;return h?this._returnResult({data:{user:null,session:null},error:h}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new z}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:h}))}catch(n){if(await C(this.storage,`${this.storageKey}-code-verifier`),b(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,n;const{data:i,error:o}=t;if(o)throw o;
43return await E(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&n!==void 0?n:void 0})})}catch(t){if(b(t))return this._returnResult({data:null,error:t});throw t}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const r=Date.now();return await Wn(async n=>(n>0&&await Mn(200*Math.pow(2,n-1)),this._debug(t,"refreshing attempt",n),await E(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:D})),(n,i)=>{const o=200*Math.pow(2,n);return i&&xe(i)&&Date.now()+o-r<oe})}catch(r){if(this._debug(t,"error",r),b(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){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),$()&&!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 n=await J(this.storage,this.storageKey);if(n&&this.userStorage){let o=await J(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:n.user},await ae(this.userStorage,this.storageKey+"-user",o)),n.user=(e=o==null?void 0:o.user)!==null&&e!==void 0?e:st()}else if(n&&!n.user&&!n.user){const o=await J(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(n.user=o.user,await C(this.storage,this.storageKey+"-user"),await ae(this.storage,this.storageKey,n)):n.user=st()}if(this._debug(r,"session from storage",n),!this._isValidSession(n)){this._debug(r,"session is not valid"),n!==null&&await this._removeSession();return}const i=((t=n.expires_at)!==null&&t!==void 0?t:1/0)*1e3-Date.now()<tt;if(this._debug(r,`session has${i?"":" not"} expired with margin of ${tt}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:o}=await this._callRefreshToken(n.refresh_token);o&&(console.error(o),xe(o)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:a}=await this._getUser(n.access_token);!a&&(o!=null&&o.user)?(n.user=o.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(r,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(r,"error",n),console.error(n);return}finally{this._debug(r,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new x;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new Qe;const{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new x;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const a={data:i.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(i){if(this._debug(n,"error",i),b(i)){const o={data:null,error:i};return xe(i)||await this._removeSession(),(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,t,r=!0){const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});const i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(l){i.push(l)}});if(await Promise.all(o),i.length>0){for(let a=0;a<i.length;a+=1)console.error(i[a]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await C(this.storage,`${this.storageKey}-code-verifier`);const t=Object.assign({},e),r=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!r&&t.user&&await ae(this.userStorage,this.storageKey+"-user",{user:t.user});const n=Object.assign({},t);delete n.user;const i=Vt(n);await ae(this.storage,this.storageKey,i)}else{const n=Vt(t);await ae(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await C(this.storage,this.storageKey),await C(this.storage,this.storageKey+"-code-verifier"),await C(this.storage,this.storageKey+"-user"),this.userStorage&&await C(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&$()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}
43catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),oe);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((r.expires_at*1e3-e)/oe);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${oe}ms, refresh threshold is ${_t} ticks`),n<=_t&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Pt)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!$()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){const n=[`provider=${encodeURIComponent(t)}`];if(r!=null&&r.redirectTo&&n.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r!=null&&r.scopes&&n.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[i,o]=await se(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});n.push(a.toString())}if(r!=null&&r.queryParams){const i=new URLSearchParams(r.queryParams);n.push(i.toString())}return r!=null&&r.skipBrowserRedirect&&n.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;const{data:n,error:i}=t;return i?this._returnResult({data:null,error:i}):await E(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=n==null?void 0:n.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(b(t))return this._returnResult({data:null,error:t});throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,n;const{data:i,error:o}=t;if(o)return this._returnResult({data:null,error:o});const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await E(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((n=l==null?void 0:l.totp)===null||n===void 0)&&n.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(t){if(b(t))return this._returnResult({data:null,error:t});throw t}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;const{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});const o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?vi(e.webauthn.credential_response):yi(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await E(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(r=n==null?void 0:n.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):(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:l}))})}catch(t){if(b(t))return this._returnResult({data:null,error:t});throw t}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;const{data:n,error:i}=t;if(i)return this._returnResult({data:null,error:i});const o=await E(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(r=n==null?void 0:n.session)===null||r===void 0?void 0:r.access_token});if(o.error)return o;const{data:a}=o;if(a.type!=="webauthn")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:_i(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:wi(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(t){if(b(t))return this._returnResult({data:null,error:t});throw t}})}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 n={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=t==null?void 0:t.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(){var e,t;const{data:{session:r},error:n}
43=await this.getSession();if(n)return this._returnResult({data:null,error:n});if(!r)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:i}=rt(r.access_token);let o=null;i.aal&&(o=i.aal);let a=o;((t=(e=r.user.factors)===null||e===void 0?void 0:e.filter(u=>u.status==="verified"))!==null&&t!==void 0?t:[]).length>0&&(a="aal2");const c=i.amr||[];return{data:{currentLevel:o,nextLevel:a,currentAuthenticationMethods:c},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{const{data:{session:r},error:n}=t;return n?this._returnResult({data:null,error:n}):r?await E(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new x})})}catch(t){if(b(t))return this._returnResult({data:null,error:t});throw t}}async _approveAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new x});const o=await E(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&$()&&!(t!=null&&t.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(r){if(b(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(e,t){try{return await this._useSession(async r=>{const{data:{session:n},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new x});const o=await E(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&$()&&!(t!=null&&t.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(r){if(b(r))return this._returnResult({data:null,error:r});throw r}}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 E(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new x})})}catch(e){if(b(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:n}=t;return n?this._returnResult({data:null,error:n}):r?(await E(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 x})})}catch(t){if(b(t))return this._returnResult({data:null,error:t});throw t}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(a=>a.kid===e);if(r)return r;const n=Date.now();if(r=this.jwks.keys.find(a=>a.kid===e),r&&this.jwks_cached_at+Cn>n)return r;const{data:i,error:o}=await E(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,r=i.keys.find(a=>a.kid===e),!r)?null:r}async getClaims(e,t={}){try{let r=e;if(!r){const{data:h,error:g}
43=await this.getSession();if(g||!h.session)return this._returnResult({data:null,error:g});r=h.session.access_token}const{header:n,payload:i,signature:o,raw:{header:a,payload:l}}=rt(r);t!=null&&t.allowExpired||Yn(i.exp);const c=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,t!=null&&t.keys?{keys:t.keys}:t==null?void 0:t.jwks);if(!c){const{error:h}=await this.getUser(r);if(h)throw h;return{data:{claims:i,header:n,signature:o},error:null}}const u=Qn(n.alg),d=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,o,Dn(`${a}.${l}`)))throw new Me("Invalid JWT signature");return{data:{claims:i,header:n,signature:o},error:null}}catch(r){if(b(r))return this._returnResult({data:null,error:r});throw r}}};jt.nextInstanceID={};const Ri=Rt,Pi=jt,ji=Object.freeze(Object.defineProperty({__proto__:null,AuthAdminApi:Ri,AuthApiError:cs,AuthClient:Pi,AuthError:he,AuthImplicitGrantRedirectError:we,AuthInvalidCredentialsError:_e,AuthInvalidJwtError:Me,AuthInvalidToken
43ResponseError:z,AuthPKCEGrantCodeExchangeError:vt,AuthRetryableFetchError:Fe,AuthSessionMissingError:x,AuthUnknownError:V,AuthWeakPasswordError:yt,CustomAuthError:M,GoTrueAdminApi:Rt,GoTrueClient:jt,NavigatorLockAcquireTimeoutError:_s,SIGN_OUT_SCOPES:Ue,isAuthApiError:us,isAuthError:b,isAuthImplicitGrantRedirectError:ds,isAuthRetryableFetchError:xe,isAuthSessionMissingError:hs,isAuthWeakPasswordError:$n,lockInternals:Q,navigatorLock:ws,processLock:ai},Symbol.toStringTag,{value:"Module"})),bs=be(ji);Object.defineProperty(Ye,"__esModule",{value:!0});Ye.SupabaseAuthClient=void 0;const Ci=bs;class $i extends Ci.AuthClient{constructor(e){super(e)}}Ye.SupabaseAuthClient=$i;Object.defineProperty(Ne,"__esModule",{value:!0});const Ii=Or,xi=I,Ui=Vr,Ni=En,Ce=ns,Di=is,Xt=G,Li=Ye;let Bi=class{constructor(e,t,r){var n,i,o;this.supabaseUrl=e,this.supabaseKey=t;const a=(0,Xt.validateSupabaseUrl)(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",a),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",a),this.storageUrl=new URL("storage/v1",a),this.functionsUrl=new URL("functions/v1",a);const l=`sb-${a.hostname.split(".")[0]}-auth-token`,c={db:Ce.DEFAULT_DB_OPTIONS,realtime:Ce.DEFAULT_REALTIME_OPTIONS,auth:Object.assign(Object.assign({},Ce.DEFAULT_AUTH_OPTIONS),{storageKey:l}),global:Ce.DEFAULT_GLOBAL_OPTIONS},u=(0,Xt.applySettingDefaults)(r??{},c);this.storageKey=(n=u.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=u.global.headers)!==null&&i!==void 0?i:{},u.accessToken?(this.accessToken=u.accessToken,this.auth=new Proxy({},{get:(d,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((o=u.auth)!==null&&o!==void 0?o:{},this.headers,u.global.fetch),this.fetch=(0,Di.fetchWithAuth)(t,this._getAccessToken.bind(this),u.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},u.realtime)),this.accessToken&&this.accessToken().then(d=>this.realtime.setAuth(d)).catch(d=>console.warn("Failed to set initial Realtime auth token:",d)),this.rest=new xi.PostgrestClient(new URL("rest/v1",a).href,{headers:this.headers,schema:u.db.schema,fetch:this.fetch}),this.storage=new Ni.StorageClient(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),u.accessToken||this._listenForAuthEvents()}get functions(){return new Ii.FunctionsClient(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;if(this.accessToken)return await this.accessToken();const{data:r}=await this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:n,userStorage:i,storageKey:o,flowType:a,lock:l,debug:c,throwOnError:u},d,f){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Li.SupabaseAuthClient({url:this.authUrl.href,headers:Object.assign(Object.assign({},h),d),storageKey:o,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:n,userStorage:i,flowType:a,lock:l,debug:c,throwOnError:u,fetch:f,hasCustomAuthorizationHeader:Object.keys(this.headers).some(g=>g.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new Ui.RealtimeClient(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,r)=>{this._handleTokenChanged(t,"CLIENT",r==null?void 0:r.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};Ne.default=Bi;(function(s){var e=te&&te.__createBinding||(Object.create?function(u,d,f,h){h===void 0&&(h=f);var g=Object.getOwnPropertyDescriptor(d,f);(!g||("get"in g?!d.__esModule:g.writable||g.configurable))&&(g={enumerable:!0,get:function(){return d[f]}}),Object.defineProperty(u,h,g)}:function(u,d,f,h){h===void 0&&(h=f),u[h]=d[f]}),t=te&&te.__exportStar||function(u,d){for(var f in u)f!=="default"&&!Object.prototype.hasOwnProperty.call(d,f)&&e(d,u,f)}
43,r=te&&te.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(s,"__esModule",{value:!0}),s.createClient=s.SupabaseClient=s.FunctionRegion=s.FunctionsError=s.FunctionsRelayError=s.FunctionsFetchError=s.FunctionsHttpError=s.PostgrestError=void 0;const n=r(Ne);t(bs,s);var i=I;Object.defineProperty(s,"PostgrestError",{enumerable:!0,get:function(){return i.PostgrestError}});var o=Or;Object.defineProperty(s,"FunctionsHttpError",{enumerable:!0,get:function(){return o.FunctionsHttpError}}),Object.defineProperty(s,"FunctionsFetchError",{enumerable:!0,get:function(){return o.FunctionsFetchError}}),Object.defineProperty(s,"FunctionsRelayError",{enumerable:!0,get:function(){return o.FunctionsRelayError}}),Object.defineProperty(s,"FunctionsError",{enumerable:!0,get:function(){return o.FunctionsError}}),Object.defineProperty(s,"FunctionRegion",{enumerable:!0,get:function(){return o.FunctionRegion}}),t(Vr,s);var a=Ne;Object.defineProperty(s,"SupabaseClient",{enumerable:!0,get:function(){return r(a).default}});const l=(u,d,f)=>new n.default(u,d,f);s.createClient=l;function c(){if(typeof window<"u"||typeof process>"u")return!1;const u=process.version;if(u==null)return!1;const d=u.match(/^v(\d+)\./);return d?parseInt(d[1],10)<=18:!1}c()&&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")})(mt);const ms=Es(mt),qi=Ss({__proto__:null,default:ms},[mt]),{PostgrestError:fo,FunctionsHttpError:go,FunctionsFetchError:po,FunctionsRelayError:_o,FunctionsError:wo,FunctionRegion:vo,SupabaseClient:yo,createClient:bo,GoTrueAdminApi:mo,GoTrueClient:Eo,AuthAdminApi:So,AuthClient:To,navigatorLock:Oo,NavigatorLockAcquireTimeoutError:ko,lockInternals:Ao,processLock:Ro,SIGN_OUT_SCOPES:Po,AuthError:jo,AuthApiError:Co,AuthUnknownError:$o,CustomAuthError:Io,AuthSessionMissingError:xo,AuthInvalidToken
43ResponseError:Uo,AuthInvalidCredentialsError:No,AuthImplicitGrantRedirectError:Do,AuthPKCEGrantCodeExchangeError:Lo,AuthRetryableFetchError:Bo,AuthWeakPasswordError:qo,AuthInvalidJwtError:Fo,isAuthError:Mo,isAuthApiError:Wo,isAuthSessionMissingError:Vo,isAuthImplicitGrantRedirectError:Ko,isAuthRetryableFetchError:Go,isAuthWeakPasswordError:Ho,RealtimePresence:Jo,RealtimeChannel:zo,RealtimeClient:Yo,REALTIME_LISTEN_TYPES:Qo,REALTIME_POSTGRES_CHANGES_LISTEN_EVENT:Xo,REALTIME_PRESENCE_LISTEN_EVENTS:Zo,REALTIME_SUBSCRIBE_STATES:ea,REALTIME_CHANNEL_STATES:ta}=ms||qi;export{De as _,de as a,hr as b,bo as c};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.