@moneybar.online/moneybar 4.2.0 → 4.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- function e(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if("default"!==n&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},t(e,n)};function n(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var r=function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)};function i(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}function s(e,t,n,r){var i,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,n,o):i(t,n))||o);return s>3&&o&&Object.defineProperty(t,n,o),o}function o(e,t){return function(n,r){t(n,r,e)}}function a(e,t,n,r,i,s){function o(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var a,c=r.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!t&&e?r.static?e:e.prototype:null,d=t||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),h=!1,f=n.length-1;f>=0;f--){var p={};for(var m in r)p[m]="access"===m?{}:r[m];for(var m in r.access)p.access[m]=r.access[m];p.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(e||null))};var g=(0,n[f])("accessor"===c?{get:d.get,set:d.set}:d[l],p);if("accessor"===c){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(a=o(g.get))&&(d.get=a),(a=o(g.set))&&(d.set=a),(a=o(g.init))&&i.unshift(a)}else(a=o(g))&&("field"===c?i.unshift(a):d[l]=a)}u&&Object.defineProperty(u,r.name,d),h=!0}function c(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0}function l(e){return"symbol"==typeof e?e:"".concat(e)}function u(e,t,n){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:n?"".concat(n," ",t):t})}function d(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function h(e,t,n,r){return new(n||(n=Promise))(function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((r=r.apply(e,t||[])).next())})}function f(e,t){var n,r,i,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(c){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(s=0)),s;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){s.label=a[1];break}if(6===a[0]&&s.label<i[1]){s.label=i[1],i=a;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(a);break}i[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}var p=Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]};function m(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||p(t,e,n)}function g(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function b(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,s=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)o.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}return o}function w(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(b(arguments[t]));return e}function y(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;var r=Array(e),i=0;for(t=0;t<n;t++)for(var s=arguments[t],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function v(e,t,n){if(n||2===arguments.length)for(var r,i=0,s=t.length;i<s;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}function _(e){return this instanceof _?(this.v=e,this):new _(e)}function k(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,i=n.apply(e,t||[]),s=[];return r=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",function(e){return function(t){return Promise.resolve(t).then(e,l)}}),r[Symbol.asyncIterator]=function(){return this},r;function o(e,t){i[e]&&(r[e]=function(t){return new Promise(function(n,r){s.push([e,t,n,r])>1||a(e,t)})},t&&(r[e]=t(r[e])))}function a(e,t){try{(n=i[e](t)).value instanceof _?Promise.resolve(n.value.v).then(c,l):u(s[0][2],n)}catch(e){u(s[0][3],e)}var n}function c(e){a("next",e)}function l(e){a("throw",e)}function u(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}function S(e){var t,n;return t={},r("next"),r("throw",function(e){throw e}),r("return"),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:_(e[r](t)),done:!1}:i?i(t):t}:i}}function E(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=g(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise(function(r,i){(function(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)})(r,i,(t=e[n](t)).done,t.value)})}}}function T(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}var O=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t},x=function(e){return x=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},x(e)};function j(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=x(e),r=0;r<n.length;r++)"default"!==n[r]&&p(t,e,n[r]);return O(t,e),t}function P(e){return e&&e.__esModule?e:{default:e}}function A(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}function I(e,t,n,r,i){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?i.call(e,n):i?i.value=n:t.set(e,n),n}function C(e,t){if(null===t||"object"!=typeof t&&"function"!=typeof t)throw new TypeError("Cannot use 'in' operator on non-object");return"function"==typeof e?t===e:e.has(t)}function R(e,t,n){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var r,i;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],n&&(i=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t}var $="function"==typeof SuppressedError?SuppressedError:function(e,t,n){var r=new Error(n);return r.name="SuppressedError",r.error=e,r.suppressed=t,r};function U(e){function t(t){e.error=e.hasError?new $(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var n,r=0;return function i(){for(;n=e.stack.pop();)try{if(!n.async&&1===r)return r=0,e.stack.push(n),Promise.resolve().then(i);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return r|=2,Promise.resolve(s).then(i,function(e){return t(e),i()})}else r|=1}catch(e){t(e)}if(1===r)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}function N(e,t){return"string"==typeof e&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,n,r,i,s){return n?t?".jsx":".js":!r||i&&s?r+i+"."+s.toLowerCase()+"js":e}):e}var D={__extends:n,__assign:r,__rest:i,__decorate:s,__param:o,__esDecorate:a,__runInitializers:c,__propKey:l,__setFunctionName:u,__metadata:d,__awaiter:h,__generator:f,__createBinding:p,__exportStar:m,__values:g,__read:b,__spread:w,__spreadArrays:y,__spreadArray:v,__await:_,__asyncGenerator:k,__asyncDelegator:S,__asyncValues:E,__makeTemplateObject:T,__importStar:j,__importDefault:P,__classPrivateFieldGet:A,__classPrivateFieldSet:I,__classPrivateFieldIn:C,__addDisposableResource:R,__disposeResources:U,__rewriteRelativeImportExtension:N},B=Object.freeze({__proto__:null,__extends:n,get __assign(){return r},__rest:i,__decorate:s,__param:o,__esDecorate:a,__runInitializers:c,__propKey:l,__setFunctionName:u,__metadata:d,__awaiter:h,__generator:f,__createBinding:p,__exportStar:m,__values:g,__read:b,__spread:w,__spreadArrays:y,__spreadArray:v,__await:_,__asyncGenerator:k,__asyncDelegator:S,__asyncValues:E,__makeTemplateObject:T,__importStar:j,__importDefault:P,__classPrivateFieldGet:A,__classPrivateFieldSet:I,__classPrivateFieldIn:C,__addDisposableResource:R,__disposeResources:U,__rewriteRelativeImportExtension:N,default:D});class L extends Error{constructor(e,t="FunctionsError",n){super(e),this.name=t,this.context=n}}class q extends L{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class F extends L{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class M extends L{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var K;!function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"}(K||(K={}));class z{constructor(e,{headers:t={},customFetch:n,region:r=K.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return h(this,arguments,void 0,function*(e,t={}){var n;let r,i;try{const{headers:s,method:o,body:a,signal:c,timeout:l}=t;let u={},{region:d}=t;d||(d=this.region);const h=new URL(`${this.url}/${e}`);let f;d&&"any"!==d&&(u["x-region"]=d,h.searchParams.set("forceFunctionRegion",d)),a&&(s&&!Object.prototype.hasOwnProperty.call(s,"Content-Type")||!s)?"undefined"!=typeof Blob&&a instanceof Blob||a instanceof ArrayBuffer?(u["Content-Type"]="application/octet-stream",f=a):"string"==typeof a?(u["Content-Type"]="text/plain",f=a):"undefined"!=typeof FormData&&a instanceof FormData?f=a:(u["Content-Type"]="application/json",f=JSON.stringify(a)):f=a;let p=c;l&&(i=new AbortController,r=setTimeout(()=>i.abort(),l),c?(p=i.signal,c.addEventListener("abort",()=>i.abort())):p=i.signal);const m=yield this.fetch(h.toString(),{method:o||"POST",headers:Object.assign(Object.assign(Object.assign({},u),this.headers),s),body:f,signal:p}).catch(e=>{throw new q(e)}),g=m.headers.get("x-relay-error");if(g&&"true"===g)throw new F(m);if(!m.ok)throw new M(m);let b,w=(null!==(n=m.headers.get("Content-Type"))&&void 0!==n?n:"text/plain").split(";")[0].trim();return b="application/json"===w?yield m.json():"application/octet-stream"===w||"application/pdf"===w?yield m.blob():"text/event-stream"===w?m:"multipart/form-data"===w?yield m.formData():yield m.text(),{data:b,error:null,response:m}}catch(e){return{data:null,error:e,response:e instanceof M||e instanceof F?e.context:void 0}}finally{r&&clearTimeout(r)}})}}function W(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function G(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=!1;try{n=this instanceof e}catch{}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}),n}var V,H,J,Y,Q,X,Z,ee={},te=G(B),ne={},re={},ie={},se={},oe={},ae={};function ce(){if(V)return ae;V=1,Object.defineProperty(ae,"__esModule",{value:!0});class e extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}}return ae.default=e,ae}function le(){if(H)return oe;H=1,Object.defineProperty(oe,"__esModule",{value:!0});const e=te.__importDefault(ce());return oe.default=class{constructor(e){var t,n;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!==(t=e.shouldThrowOnError)&&void 0!==t&&t,this.signal=e.signal,this.isMaybeSingle=null!==(n=e.isMaybeSingle)&&void 0!==n&&n,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(t,n){void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json");let r=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async t=>{var n,r,i,s;let o=null,a=null,c=null,l=t.status,u=t.statusText;if(t.ok){if("HEAD"!==this.method){const e=await t.text();""===e||(a="text/csv"===this.headers.get("Accept")||this.headers.get("Accept")&&(null===(n=this.headers.get("Accept"))||void 0===n?void 0:n.includes("application/vnd.pgrst.plan+text"))?e:JSON.parse(e))}const e=null===(r=this.headers.get("Prefer"))||void 0===r?void 0:r.match(/count=(exact|planned|estimated)/),s=null===(i=t.headers.get("content-range"))||void 0===i?void 0:i.split("/");e&&s&&s.length>1&&(c=parseInt(s[1])),this.isMaybeSingle&&"GET"===this.method&&Array.isArray(a)&&(a.length>1?(o={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,c=null,l=406,u="Not Acceptable"):a=1===a.length?a[0]:null)}else{const n=await t.text();try{o=JSON.parse(n),Array.isArray(o)&&404===t.status&&(a=[],o=null,l=200,u="OK")}catch(e){404===t.status&&""===n?(l=204,u="No Content"):o={message:n}}if(o&&this.isMaybeSingle&&(null===(s=null==o?void 0:o.details)||void 0===s?void 0:s.includes("0 rows"))&&(o=null,l=200,u="OK"),o&&this.shouldThrowOnError)throw new e.default(o)}return{error:o,data:a,count:c,status:l,statusText:u}});return this.shouldThrowOnError||(r=r.catch(e=>{var t,n,r,i,s,o;let a="";const c=null==e?void 0:e.cause;if(c){const s=null!==(t=null==c?void 0:c.message)&&void 0!==t?t:"",o=null!==(n=null==c?void 0:c.code)&&void 0!==n?n:"";a=`${null!==(r=null==e?void 0:e.name)&&void 0!==r?r:"FetchError"}: ${null==e?void 0:e.message}`,a+=`\n\nCaused by: ${null!==(i=null==c?void 0:c.name)&&void 0!==i?i:"Error"}: ${s}`,o&&(a+=` (${o})`),(null==c?void 0:c.stack)&&(a+=`\n${c.stack}`)}else a=null!==(s=null==e?void 0:e.stack)&&void 0!==s?s:"";return{error:{message:`${null!==(o=null==e?void 0:e.name)&&void 0!==o?o:"FetchError"}: ${null==e?void 0:e.message}`,details:a,hint:"",code:""},data:null,count:null,status:0,statusText:""}})),r.then(t,n)}returns(){return this}overrideTypes(){return this}},oe}function ue(){if(J)return se;J=1,Object.defineProperty(se,"__esModule",{value:!0});const e=te.__importDefault(le());class t extends e.default{select(e){let t=!1;const n=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",n),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:n,foreignTable:r,referencedTable:i=r}={}){const s=i?`${i}.order`:"order",o=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${void 0===n?"":n?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:n=t}={}){const r=void 0===n?"limit":`${n}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:n,referencedTable:r=n}={}){const i=void 0===r?"offset":`${r}.offset`,s=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(s,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return"GET"===this.method?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:n=!1,buffers:r=!1,wal:i=!1,format:s="text"}={}){var o;const a=[e?"analyze":null,t?"verbose":null,n?"settings":null,r?"buffers":null,i?"wal":null].filter(Boolean).join("|"),c=null!==(o=this.headers.get("Accept"))&&void 0!==o?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${c}"; options=${a};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}}return se.default=t,se}function de(){if(Y)return ie;Y=1,Object.defineProperty(ie,"__esModule",{value:!0});const e=te.__importDefault(ue()),t=new RegExp("[,()]");class n extends e.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,n){const r=Array.from(new Set(n)).map(e=>"string"==typeof e&&t.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:n,type:r}={}){let i="";"plain"===r?i="pl":"phrase"===r?i="ph":"websearch"===r&&(i="w");const s=void 0===n?"":`(${n})`;return this.url.searchParams.append(e,`${i}fts${s}.${t}`),this}match(e){return Object.entries(e).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,n){return this.url.searchParams.append(e,`not.${t}.${n}`),this}or(e,{foreignTable:t,referencedTable:n=t}={}){const r=n?`${n}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,n){return this.url.searchParams.append(e,`${t}.${n}`),this}}return ie.default=n,ie}function he(){if(Q)return re;Q=1,Object.defineProperty(re,"__esModule",{value:!0});const e=te.__importDefault(de());return re.default=class{constructor(e,{headers:t={},schema:n,fetch:r}){this.url=e,this.headers=new Headers(t),this.schema=n,this.fetch=r}select(t,n){const{head:r=!1,count:i}=null!=n?n:{},s=r?"HEAD":"GET";let o=!1;const a=(null!=t?t:"*").split("").map(e=>/\s/.test(e)&&!o?"":('"'===e&&(o=!o),e)).join("");return this.url.searchParams.set("select",a),i&&this.headers.append("Prefer",`count=${i}`),new e.default({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(t,{count:n,defaultToNull:r=!0}={}){var i;if(n&&this.headers.append("Prefer",`count=${n}`),r||this.headers.append("Prefer","missing=default"),Array.isArray(t)){const e=t.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(e.length>0){const t=[...new Set(e)].map(e=>`"${e}"`);this.url.searchParams.set("columns",t.join(","))}}return new e.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch})}upsert(t,{onConflict:n,ignoreDuplicates:r=!1,count:i,defaultToNull:s=!0}={}){var o;if(this.headers.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==n&&this.url.searchParams.set("on_conflict",n),i&&this.headers.append("Prefer",`count=${i}`),s||this.headers.append("Prefer","missing=default"),Array.isArray(t)){const e=t.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(e.length>0){const t=[...new Set(e)].map(e=>`"${e}"`);this.url.searchParams.set("columns",t.join(","))}}return new e.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:null!==(o=this.fetch)&&void 0!==o?o:fetch})}update(t,{count:n}={}){var r;return n&&this.headers.append("Prefer",`count=${n}`),new e.default({method:"PATCH",url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:null!==(r=this.fetch)&&void 0!==r?r:fetch})}delete({count:t}={}){var n;return t&&this.headers.append("Prefer",`count=${t}`),new e.default({method:"DELETE",url:this.url,headers:this.headers,schema:this.schema,fetch:null!==(n=this.fetch)&&void 0!==n?n:fetch})}},re}var fe=function(){if(Z)return ee;Z=1,Object.defineProperty(ee,"__esModule",{value:!0}),ee.PostgrestError=ee.PostgrestBuilder=ee.PostgrestTransformBuilder=ee.PostgrestFilterBuilder=ee.PostgrestQueryBuilder=ee.PostgrestClient=void 0;const e=te,t=e.__importDefault(function(){if(X)return ne;X=1,Object.defineProperty(ne,"__esModule",{value:!0});const e=te,t=e.__importDefault(he()),n=e.__importDefault(de());class r{constructor(e,{headers:t={},schema:n,fetch:r}={}){this.url=e,this.headers=new Headers(t),this.schemaName=n,this.fetch=r}from(e){if(!e||"string"!=typeof e||""===e.trim())throw new Error("Invalid relation name: relation must be a non-empty string.");const n=new URL(`${this.url}/${e}`);return new t.default(n,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:i=!1,count:s}={}){var o;let a;const c=new URL(`${this.url}/rpc/${e}`);let l;r||i?(a=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{c.searchParams.append(e,t)})):(a="POST",l=t);const u=new Headers(this.headers);return s&&u.set("Prefer",`count=${s}`),new n.default({method:a,url:c,headers:u,schema:this.schemaName,body:l,fetch:null!==(o=this.fetch)&&void 0!==o?o:fetch})}}return ne.default=r,ne}());ee.PostgrestClient=t.default;const n=e.__importDefault(he());ee.PostgrestQueryBuilder=n.default;const r=e.__importDefault(de());ee.PostgrestFilterBuilder=r.default;const i=e.__importDefault(ue());ee.PostgrestTransformBuilder=i.default;const s=e.__importDefault(le());ee.PostgrestBuilder=s.default;const o=e.__importDefault(ce());return ee.PostgrestError=o.default,ee.default={PostgrestClient:t.default,PostgrestQueryBuilder:n.default,PostgrestFilterBuilder:r.default,PostgrestTransformBuilder:i.default,PostgrestBuilder:s.default,PostgrestError:o.default},ee}(),pe=W(fe),me=e({__proto__:null,default:pe},[fe]);const{PostgrestClient:ge,PostgrestQueryBuilder:be,PostgrestFilterBuilder:we,PostgrestTransformBuilder:ye,PostgrestBuilder:ve,PostgrestError:_e}=pe||me;class ke{constructor(){}static detectEnvironment(){var e;if("undefined"!=typeof WebSocket)return{type:"native",constructor:WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocket)return{type:"native",constructor:globalThis.WebSocket};if("undefined"!=typeof global&&void 0!==global.WebSocket)return{type:"native",constructor:global.WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("undefined"!=typeof globalThis&&globalThis.EdgeRuntime||"undefined"!=typeof navigator&&(null===(e=navigator.userAgent)||void 0===e?void 0:e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};if("undefined"!=typeof process){const e=process.versions;if(e&&e.node){const t=e.node,n=parseInt(t.replace(/^v/,"").split(".")[0]);return n>=22?void 0!==globalThis.WebSocket?{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:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}}const Se="1.0.0",Ee=Se,Te=1e4;var Oe,xe,je,Pe,Ae,Ie;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(Oe||(Oe={})),function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"}(xe||(xe={})),function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"}(je||(je={})),function(e){e.websocket="websocket"}(Pe||(Pe={})),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(Ae||(Ae={}));class Ce{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=null!=e?e:[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&"string"==typeof e.payload.event)return t(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer(null===(t=e.payload)||void 0===t?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,n;const r=null!==(n=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==n?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,r)}_encodeJsonUserBroadcastPush(e){var t,n;const r=null!==(n=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==n?n:{},i=(new TextEncoder).encode(JSON.stringify(r)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(e,t,n){var r,i;const s=e.topic,o=null!==(r=e.ref)&&void 0!==r?r:"",a=null!==(i=e.join_ref)&&void 0!==i?i:"",c=e.payload.event,l=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},u=0===Object.keys(l).length?"":JSON.stringify(l);if(a.length>255)throw new Error(`joinRef length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`ref length ${o.length} exceeds maximum of 255`);if(s.length>255)throw new Error(`topic length ${s.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`metadata length ${u.length} exceeds maximum of 255`);const d=this.USER_BROADCAST_PUSH_META_LENGTH+a.length+o.length+s.length+c.length+u.length,h=new ArrayBuffer(this.HEADER_LENGTH+d);let f=new DataView(h),p=0;f.setUint8(p++,this.KINDS.userBroadcastPush),f.setUint8(p++,a.length),f.setUint8(p++,o.length),f.setUint8(p++,s.length),f.setUint8(p++,c.length),f.setUint8(p++,u.length),f.setUint8(p++,t),Array.from(a,e=>f.setUint8(p++,e.charCodeAt(0))),Array.from(o,e=>f.setUint8(p++,e.charCodeAt(0))),Array.from(s,e=>f.setUint8(p++,e.charCodeAt(0))),Array.from(c,e=>f.setUint8(p++,e.charCodeAt(0))),Array.from(u,e=>f.setUint8(p++,e.charCodeAt(0)));var m=new Uint8Array(h.byteLength+n.byteLength);return m.set(new Uint8Array(h),0),m.set(new Uint8Array(n),h.byteLength),m.buffer}decode(e,t){if(this._isArrayBuffer(e)){return t(this._binaryDecode(e))}if("string"==typeof e){const n=JSON.parse(e),[r,i,s,o,a]=n;return t({join_ref:r,ref:i,topic:s,event:o,payload:a})}return t({})}_binaryDecode(e){const t=new DataView(e),n=t.getUint8(0),r=new TextDecoder;if(n===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,r)}_decodeUserBroadcast(e,t,n){const r=t.getUint8(1),i=t.getUint8(2),s=t.getUint8(3),o=t.getUint8(4);let a=this.HEADER_LENGTH+4;const c=n.decode(e.slice(a,a+r));a+=r;const l=n.decode(e.slice(a,a+i));a+=i;const u=n.decode(e.slice(a,a+s));a+=s;const d=e.slice(a,e.byteLength),h=o===this.JSON_ENCODING?JSON.parse(n.decode(d)):d,f={type:this.BROADCAST_EVENT,event:l,payload:h};return s>0&&(f.meta=JSON.parse(u)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:f}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||"ArrayBuffer"===(null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e))):{}}}class Re{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}!function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"}(Ie||(Ie={}));const $e=(e,t,n={})=>{var r;const i=null!==(r=n.skipTypes)&&void 0!==r?r:[];return t?Object.keys(t).reduce((n,r)=>(n[r]=Ue(r,e,t,i),n),{}):{}},Ue=(e,t,n,r)=>{const i=t.find(t=>t.name===e),s=null==i?void 0:i.type,o=n[e];return s&&!r.includes(s)?Ne(s,o):De(o)},Ne=(e,t)=>{if("_"===e.charAt(0)){const n=e.slice(1,e.length);return Fe(t,n)}switch(e){case Ie.bool:return Be(t);case Ie.float4:case Ie.float8:case Ie.int2:case Ie.int4:case Ie.int8:case Ie.numeric:case Ie.oid:return Le(t);case Ie.json:case Ie.jsonb:return qe(t);case Ie.timestamp:return Me(t);case Ie.abstime:case Ie.date:case Ie.daterange:case Ie.int4range:case Ie.int8range:case Ie.money:case Ie.reltime:case Ie.text:case Ie.time:case Ie.timestamptz:case Ie.timetz:case Ie.tsrange:case Ie.tstzrange:default:return De(t)}},De=e=>e,Be=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},Le=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},qe=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return console.log(`JSON parse error: ${t}`),e}return e},Fe=(e,t)=>{if("string"!=typeof e)return e;const n=e.length-1,r=e[n];if("{"===e[0]&&"}"===r){let r;const i=e.slice(1,n);try{r=JSON.parse("["+i+"]")}catch(e){r=i?i.split(","):[]}return r.map(e=>Ne(t,e))}return e},Me=e=>"string"==typeof e?e.replace(" ","T"):e,Ke=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};class ze{constructor(e,t,n={},r=1e4){this.channel=e,this.event=t,this.payload=n,this.timeout=r,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var n;return this._hasReceived(e)&&t(null===(n=this.receivedResp)||void 0===n?void 0:n.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);this.channel._on(this.refEvent,{},e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var We,Ge,Ve,He;!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(We||(We={}));class Je{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const n=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(n.state,{},e=>{const{onJoin:t,onLeave:n,onSync:r}=this.caller;this.joinRef=this.channel._joinRef(),this.state=Je.syncState(this.state,e,t,n),this.pendingDiffs.forEach(e=>{this.state=Je.syncDiff(this.state,e,t,n)}),this.pendingDiffs=[],r()}),this.channel._on(n.diff,{},e=>{const{onJoin:t,onLeave:n,onSync:r}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=Je.syncDiff(this.state,e,t,n),r())}),this.onJoin((e,t,n)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:n})}),this.onLeave((e,t,n)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:n})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,n,r){const i=this.cloneDeep(e),s=this.transformState(t),o={},a={};return this.map(i,(e,t)=>{s[e]||(a[e]=t)}),this.map(s,(e,t)=>{const n=i[e];if(n){const r=t.map(e=>e.presence_ref),i=n.map(e=>e.presence_ref),s=t.filter(e=>i.indexOf(e.presence_ref)<0),c=n.filter(e=>r.indexOf(e.presence_ref)<0);s.length>0&&(o[e]=s),c.length>0&&(a[e]=c)}else o[e]=t}),this.syncDiff(i,{joins:o,leaves:a},n,r)}static syncDiff(e,t,n,r){const{joins:i,leaves:s}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return n||(n=()=>{}),r||(r=()=>{}),this.map(i,(t,r)=>{var i;const s=null!==(i=e[t])&&void 0!==i?i:[];if(e[t]=this.cloneDeep(r),s.length>0){const n=e[t].map(e=>e.presence_ref),r=s.filter(e=>n.indexOf(e.presence_ref)<0);e[t].unshift(...r)}n(t,s,r)}),this.map(s,(t,n)=>{let i=e[t];if(!i)return;const s=n.map(e=>e.presence_ref);i=i.filter(e=>s.indexOf(e.presence_ref)<0),e[t]=i,r(t,i,n),0===i.length&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(n=>t(n,e[n]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,n)=>{const r=e[n];return t[n]="metas"in r?r.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):r,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}!function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(Ge||(Ge={})),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"}(Ve||(Ve={})),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(He||(He={}));class Ye{constructor(e,t={config:{}},n){var r,i;if(this.topic=e,this.params=t,this.socket=n,this.bindings={},this.state=xe.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 ze(this,je.join,this.params,this.timeout),this.rejoinTimer=new Re(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=xe.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=xe.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=xe.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=xe.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=xe.errored,this.rejoinTimer.scheduleTimeout())}),this._on(je.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new Je(this),this.broadcastEndpointURL=Ke(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(null===(i=null===(r=this.params.config)||void 0===r?void 0:r.broadcast)||void 0===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 n,r,i;if(this.socket.isConnected()||this.socket.connect(),this.state==xe.closed){const{config:{broadcast:s,presence:o,private:a}}=this.params,c=null!==(r=null===(n=this.bindings.postgres_changes)||void 0===n?void 0:n.map(e=>e.filter))&&void 0!==r?r:[],l=!!this.bindings[Ve.PRESENCE]&&this.bindings[Ve.PRESENCE].length>0||!0===(null===(i=this.params.config.presence)||void 0===i?void 0:i.enabled),u={},d={broadcast:s,presence:Object.assign(Object.assign({},o),{enabled:l}),postgres_changes:c,private:a};this.socket.accessTokenValue&&(u.access_token=this.socket.accessTokenValue),this._onError(t=>null==e?void 0:e(He.CHANNEL_ERROR,t)),this._onClose(()=>null==e?void 0:e(He.CLOSED)),this.updateJoinPayload(Object.assign({config:d},u)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:t})=>{var n;if(this.socket.setAuth(),void 0!==t){const r=this.bindings.postgres_changes,i=null!==(n=null==r?void 0:r.length)&&void 0!==n?n:0,s=[];for(let n=0;n<i;n++){const i=r[n],{filter:{event:o,schema:a,table:c,filter:l}}=i,u=t&&t[n];if(!u||u.event!==o||u.schema!==a||u.table!==c||u.filter!==l)return this.unsubscribe(),this.state=xe.errored,void(null==e||e(He.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes")));s.push(Object.assign(Object.assign({},i),{id:u.id}))}return this.bindings.postgres_changes=s,void(e&&e(He.SUBSCRIBED))}null==e||e(He.SUBSCRIBED)}).receive("error",t=>{this.state=xe.errored,null==e||e(He.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(He.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,n){return this.state===xe.joined&&e===Ve.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(()=>this.subscribe())),this._on(e,t,n)}async httpSend(e,t,n={}){var r;const i=this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"";if(null==t)return Promise.reject("Payload is required for httpSend()");const s={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}]})},o=await this._fetchWithTimeout(this.broadcastEndpointURL,s,null!==(r=n.timeout)&&void 0!==r?r:this.timeout);if(202===o.status)return{success:!0};let a=o.statusText;try{const e=await o.json();a=e.error||e.message||a}catch(e){}return Promise.reject(new Error(a))}async send(e,t={}){var n,r;if(this._canPush()||"broadcast"!==e.type)return new Promise(n=>{var r,i,s;const o=this._push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null===(s=null===(i=null===(r=this.params)||void 0===r?void 0:r.config)||void 0===i?void 0:i.broadcast)||void 0===s?void 0:s.ack)||n("ok"),o.receive("ok",()=>n("ok")),o.receive("error",()=>n("error")),o.receive("timeout",()=>n("timed out"))});{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:i,payload:s}=e,o={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:s,private:this.private}]})};try{const e=await this._fetchWithTimeout(this.broadcastEndpointURL,o,null!==(n=t.timeout)&&void 0!==n?n:this.timeout);return await(null===(r=e.body)||void 0===r?void 0:r.cancel()),e.ok?"ok":"error"}catch(e){return"AbortError"===e.name?"timed out":"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=xe.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(je.close,"leave",this._joinRef())};this.joinPush.destroy();let n=null;return new Promise(r=>{n=new ze(this,je.leave,{},e),n.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),n.send(),this._canPush()||n.trigger("ok",{})}).finally(()=>{null==n||n.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=xe.closed,this.bindings={}}async _fetchWithTimeout(e,t,n){const r=new AbortController,i=setTimeout(()=>r.abort(),n),s=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(i),s}_push(e,t,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new ze(this,e,t,n);return this._canPush()?r.send():this._addToPushBuffer(r),r}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>100){const e=this.pushBuffer.shift();e&&(e.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload))}}_onMessage(e,t,n){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,n){var r,i;const s=e.toLocaleLowerCase(),{close:o,error:a,leave:c,join:l}=je;if(n&&[o,a,c,l].indexOf(s)>=0&&n!==this._joinRef())return;let u=this._onMessage(s,t,n);if(t&&!u)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(s)?null===(r=this.bindings.postgres_changes)||void 0===r||r.filter(e=>{var t,n,r;return"*"===(null===(t=e.filter)||void 0===t?void 0:t.event)||(null===(r=null===(n=e.filter)||void 0===n?void 0:n.event)||void 0===r?void 0:r.toLocaleLowerCase())===s}).map(e=>e.callback(u,n)):null===(i=this.bindings[s])||void 0===i||i.filter(e=>{var n,r,i,o,a,c;if(["broadcast","presence","postgres_changes"].includes(s)){if("id"in e){const s=e.id,o=null===(n=e.filter)||void 0===n?void 0:n.event;return s&&(null===(r=t.ids)||void 0===r?void 0:r.includes(s))&&("*"===o||(null==o?void 0:o.toLocaleLowerCase())===(null===(i=t.data)||void 0===i?void 0:i.type.toLocaleLowerCase()))}{const n=null===(a=null===(o=null==e?void 0:e.filter)||void 0===o?void 0:o.event)||void 0===a?void 0:a.toLocaleLowerCase();return"*"===n||n===(null===(c=null==t?void 0:t.event)||void 0===c?void 0:c.toLocaleLowerCase())}}return e.type.toLocaleLowerCase()===s}).map(e=>{if("object"==typeof u&&"ids"in u){const e=u.data,{schema:t,table:n,commit_timestamp:r,type:i,errors:s}=e,o={schema:t,table:n,commit_timestamp:r,eventType:i,new:{},old:{},errors:s};u=Object.assign(Object.assign({},o),this._getPayloadRecords(e))}e.callback(u,n)})}_isClosed(){return this.state===xe.closed}_isJoined(){return this.state===xe.joined}_isJoining(){return this.state===xe.joining}_isLeaving(){return this.state===xe.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,n){const r=e.toLocaleLowerCase(),i={type:r,filter:t,callback:n};return this.bindings[r]?this.bindings[r].push(i):this.bindings[r]=[i],this}_off(e,t){const n=e.toLocaleLowerCase();return this.bindings[n]&&(this.bindings[n]=this.bindings[n].filter(e=>{var r;return!((null===(r=e.type)||void 0===r?void 0:r.toLocaleLowerCase())===n&&Ye.isEqual(e.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(je.close,{},e)}_onError(e){this._on(je.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=xe.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=$e(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=$e(e.columns,e.old_record)),t}}const Qe=()=>{},Xe=25e3,Ze=10,et=100,tt=[1e3,2e3,5e3,1e4];class nt{constructor(e,t){var n;if(this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=Te,this.transport=null,this.heartbeatIntervalMs=Xe,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Qe,this.ref=0,this.reconnectTimer=null,this.vsn=Ee,this.logger=Qe,this.conn=null,this.sendBuffer=[],this.serializer=new Ce,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!(null===(n=null==t?void 0:t.params)||void 0===n?void 0:n.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${Pe.websocket}`,this.httpEndpoint=Ke(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||null!==this.conn&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=ke.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;if(t.includes("Node.js"))throw new Error(`${t}\n\nTo use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n npm install ws\n\n import ws from "ws"\n const client = new RealtimeClient(url, {\n ...options,\n transport: ws\n })`);throw new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const n=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(n),this._setConnectionState("disconnected")},"function"==typeof this.conn.close&&(e?this.conn.close(e,null!=t?t:""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,n){this.logger(e,t,n)}connectionState(){switch(this.conn&&this.conn.readyState){case Oe.connecting:return Ae.Connecting;case Oe.open:return Ae.Open;case Oe.closing:return Ae.Closing;default:return Ae.Closed}}isConnected(){return this.connectionState()===Ae.Open}isConnecting(){return"connecting"===this._connectionState}isDisconnecting(){return"disconnecting"===this._connectionState}channel(e,t={config:{}}){const n=`realtime:${e}`,r=this.getChannels().find(e=>e.topic===n);if(r)return r;{const n=new Ye(`realtime:${e}`,t,this);return this.channels.push(n),n}}push(e){const{topic:t,event:n,payload:r,ref:i}=e,s=()=>{this.encode(e,e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)})};this.log("push",`${t} ${n} (${i})`,r),this.isConnected()?s():this.sendBuffer.push(s)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}return this._wasManualDisconnect=!1,null===(e=this.conn)||void 0===e||e.close(1e3,"heartbeat timeout"),void setTimeout(()=>{var e;this.isConnected()||null===(e=this.reconnectTimer)||void 0===e||e.scheduleTimeout()},et)}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this._setAuthSafely("heartbeat")}else try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,e=>{if("phoenix"===e.topic&&"phx_reply"===e.event)try{this.heartbeatCallback("ok"===e.payload.status?"ok":"error")}catch(e){this.log("error","error in heartbeat callback",e)}e.ref&&e.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:t,event:n,payload:r,ref:i}=e,s=i?`(${i})`:"",o=r.status||"";this.log("receive",`${o} ${t} ${n} ${s}`.trim(),r),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(n,r,i)),this._triggerStateCallbacks("message",e)})}_clearTimer(e){var t;"heartbeat"===e&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):"reconnect"===e&&(null===(t=this.reconnectTimer)||void 0===t||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_teardownConnection(){if(this.conn){if(this.conn.readyState===Oe.open||this.conn.readyState===Oe.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(e=>{this.log("error","error waiting for auth on connect",e),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this.workerRef.terminate()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&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||null===(t=this.reconnectTimer)||void 0===t||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(je.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const n=e.match(/\?/)?"&":"?";return`${e}${n}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{const e=new Blob(['\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_setConnectionState(e,t=!1){this._connectionState=e,"connecting"===e?this._wasManualDisconnect=!1:"disconnecting"===e&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t;t=e||(this.accessToken?await this.accessToken():this.accessTokenValue),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{const n={access_token:t,version:"realtime-js/2.86.0"};t&&e.updateJoinPayload(n),e.joinedOnce&&e._isJoined()&&e._push(je.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this.setAuth().catch(t=>{this.log("error",`error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(n=>{try{n(t)}catch(t){this.log("error",`error in ${e} callback`,t)}})}catch(t){this.log("error",`error triggering ${e} callbacks`,t)}}_setupReconnectionTimer(){this.reconnectTimer=new Re(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Ze)},this.reconnectAfterMs)}_initializeOptions(e){var t,n,r,i,s,o,a,c,l,u,d,h;switch(this.transport=null!==(t=null==e?void 0:e.transport)&&void 0!==t?t:null,this.timeout=null!==(n=null==e?void 0:e.timeout)&&void 0!==n?n:Te,this.heartbeatIntervalMs=null!==(r=null==e?void 0:e.heartbeatIntervalMs)&&void 0!==r?r:Xe,this.worker=null!==(i=null==e?void 0:e.worker)&&void 0!==i&&i,this.accessToken=null!==(s=null==e?void 0:e.accessToken)&&void 0!==s?s:null,this.heartbeatCallback=null!==(o=null==e?void 0:e.heartbeatCallback)&&void 0!==o?o:Qe,this.vsn=null!==(a=null==e?void 0:e.vsn)&&void 0!==a?a:Ee,(null==e?void 0:e.params)&&(this.params=e.params),(null==e?void 0:e.logger)&&(this.logger=e.logger),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=null!==(c=null==e?void 0:e.reconnectAfterMs)&&void 0!==c?c:e=>tt[e-1]||1e4,this.vsn){case Se:this.encode=null!==(l=null==e?void 0:e.encode)&&void 0!==l?l:(e,t)=>t(JSON.stringify(e)),this.decode=null!==(u=null==e?void 0:e.decode)&&void 0!==u?u:(e,t)=>t(JSON.parse(e));break;case"2.0.0":this.encode=null!==(d=null==e?void 0:e.encode)&&void 0!==d?d:this.serializer.encode.bind(this.serializer),this.decode=null!==(h=null==e?void 0:e.decode)&&void 0!==h?h:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if("undefined"!=typeof window&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl}}}class rt extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function it(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}class st extends rt{constructor(e,t,n){super(e),this.name="StorageApiError",this.status=t,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class ot extends rt{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}const at=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),ct=e=>{if(Array.isArray(e))return e.map(e=>ct(e));if("function"==typeof e||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([e,n])=>{const r=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""));t[r]=ct(n)}),t},lt=e=>{var t;return e.msg||e.message||e.error_description||("string"==typeof e.error?e.error:null===(t=e.error)||void 0===t?void 0:t.message)||JSON.stringify(e)},ut=(e,t,n)=>h(void 0,void 0,void 0,function*(){const r=yield Response;e instanceof r&&!(null==n?void 0:n.noResolveJson)?e.json().then(n=>{const r=e.status||500,i=(null==n?void 0:n.statusCode)||r+"";t(new st(lt(n),r,i))}).catch(e=>{t(new ot(lt(e),e))}):t(new ot(lt(e),e))}),dt=(e,t,n,r)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&r?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(r)?(i.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),i.body=JSON.stringify(r)):i.body=r,(null==t?void 0:t.duplex)&&(i.duplex=t.duplex),Object.assign(Object.assign({},i),n)):i};function ht(e,t,n,r,i,s){return h(this,void 0,void 0,function*(){return new Promise((o,a)=>{e(n,dt(t,r,i,s)).then(e=>{if(!e.ok)throw e;return(null==r?void 0:r.noResolveJson)?e:e.json()}).then(e=>o(e)).catch(e=>ut(e,a,r))})})}function ft(e,t,n,r){return h(this,void 0,void 0,function*(){return ht(e,"GET",t,n,r)})}function pt(e,t,n,r,i){return h(this,void 0,void 0,function*(){return ht(e,"POST",t,r,i,n)})}function mt(e,t,n,r,i){return h(this,void 0,void 0,function*(){return ht(e,"PUT",t,r,i,n)})}function gt(e,t,n,r,i){return h(this,void 0,void 0,function*(){return ht(e,"DELETE",t,r,i,n)})}class bt{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}execute(){return h(this,void 0,void 0,function*(){try{return{data:(yield this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}}var wt;wt=Symbol.toStringTag;var yt=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[wt]="BlobDownloadBuilder",this.promise=null}asStream(){return new bt(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 h(this,void 0,void 0,function*(){try{const e=yield this.downloadFn();return{data:yield e.blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}};const vt={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},_t={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class kt{constructor(e,t={},n,r){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=n,this.fetch=at(r)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,t,n,r){return h(this,void 0,void 0,function*(){try{let i;const s=Object.assign(Object.assign({},_t),r);let o=Object.assign(Object.assign({},this.headers),"POST"===e&&{"x-upsert":String(s.upsert)});const a=s.metadata;if("undefined"!=typeof Blob&&n instanceof Blob)i=new FormData,i.append("cacheControl",s.cacheControl),a&&i.append("metadata",this.encodeMetadata(a)),i.append("",n);else if("undefined"!=typeof FormData&&n instanceof FormData)i=n,i.has("cacheControl")||i.append("cacheControl",s.cacheControl),a&&!i.has("metadata")&&i.append("metadata",this.encodeMetadata(a));else{i=n,o["cache-control"]=`max-age=${s.cacheControl}`,o["content-type"]=s.contentType,a&&(o["x-metadata"]=this.toBase64(this.encodeMetadata(a)));("undefined"!=typeof ReadableStream&&i instanceof ReadableStream||i&&"object"==typeof i&&"pipe"in i&&"function"==typeof i.pipe)&&!s.duplex&&(s.duplex="half")}(null==r?void 0:r.headers)&&(o=Object.assign(Object.assign({},o),r.headers));const c=this._removeEmptyFolders(t),l=this._getFinalPath(c),u=yield("PUT"==e?mt:pt)(this.fetch,`${this.url}/object/${l}`,i,Object.assign({headers:o},(null==s?void 0:s.duplex)?{duplex:s.duplex}:{}));return{data:{path:c,id:u.Id,fullPath:u.Key},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}upload(e,t,n){return h(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,n)})}uploadToSignedUrl(e,t,n,r){return h(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(e),s=this._getFinalPath(i),o=new URL(this.url+`/object/upload/sign/${s}`);o.searchParams.set("token",t);try{let e;const t=Object.assign({upsert:_t.upsert},r),s=Object.assign(Object.assign({},this.headers),{"x-upsert":String(t.upsert)});"undefined"!=typeof Blob&&n instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),e.append("",n)):"undefined"!=typeof FormData&&n instanceof FormData?(e=n,e.append("cacheControl",t.cacheControl)):(e=n,s["cache-control"]=`max-age=${t.cacheControl}`,s["content-type"]=t.contentType);return{data:{path:i,fullPath:(yield mt(this.fetch,o.toString(),e,{headers:s})).Key},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}createSignedUploadUrl(e,t){return h(this,void 0,void 0,function*(){try{let n=this._getFinalPath(e);const r=Object.assign({},this.headers);(null==t?void 0:t.upsert)&&(r["x-upsert"]="true");const i=yield pt(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:r}),s=new URL(this.url+i.url),o=s.searchParams.get("token");if(!o)throw new rt("No token returned by API");return{data:{signedUrl:s.toString(),path:e,token:o},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}update(e,t,n){return h(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,n)})}move(e,t,n){return h(this,void 0,void 0,function*(){try{return{data:yield pt(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==n?void 0:n.destinationBucket},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}copy(e,t,n){return h(this,void 0,void 0,function*(){try{return{data:{path:(yield pt(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==n?void 0:n.destinationBucket},{headers:this.headers})).Key},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}createSignedUrl(e,t,n){return h(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=yield pt(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},(null==n?void 0:n.transform)?{transform:n.transform}:{}),{headers:this.headers});const s=(null==n?void 0:n.download)?`&download=${!0===n.download?"":n.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${s}`)},{data:i,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}createSignedUrls(e,t,n){return h(this,void 0,void 0,function*(){try{const r=yield pt(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=(null==n?void 0:n.download)?`&download=${!0===n.download?"":n.download}`:"";return{data:r.map(e=>Object.assign(Object.assign({},e),{signedUrl:e.signedURL?encodeURI(`${this.url}${e.signedURL}${i}`):null})),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}download(e,t){const n=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",r=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),i=r?`?${r}`:"",s=this._getFinalPath(e);return new yt(()=>ft(this.fetch,`${this.url}/${n}/${s}${i}`,{headers:this.headers,noResolveJson:!0}),this.shouldThrowOnError)}info(e){return h(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const e=yield ft(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:ct(e),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}exists(e){return h(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield function(e,t,n,r){return h(this,void 0,void 0,function*(){return ht(e,"HEAD",t,Object.assign(Object.assign({},n),{noResolveJson:!0}),r)})}(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e)&&e instanceof ot){const t=e.originalError;if([400,404].includes(null==t?void 0:t.status))return{data:!1,error:e}}throw e}})}getPublicUrl(e,t){const n=this._getFinalPath(e),r=[],i=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==i&&r.push(i);const s=void 0!==(null==t?void 0:t.transform)?"render/image":"object",o=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==o&&r.push(o);let a=r.join("&");return""!==a&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${n}${a}`)}}}remove(e){return h(this,void 0,void 0,function*(){try{return{data:yield gt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}list(e,t,n){return h(this,void 0,void 0,function*(){try{const r=Object.assign(Object.assign(Object.assign({},vt),t),{prefix:e||""});return{data:yield pt(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},n),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}listV2(e,t){return h(this,void 0,void 0,function*(){try{const n=Object.assign({},e);return{data:yield pt(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,n,{headers:this.headers},t),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}const St="2.86.0",Et={"X-Client-Info":`storage-js/${St}`};class Tt{constructor(e,t={},n,r){this.shouldThrowOnError=!1;const i=new URL(e);if(null==r?void 0:r.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({},Et),t),this.fetch=at(n)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(e){return h(this,void 0,void 0,function*(){try{const t=this.listBucketOptionsToQueryString(e);return{data:yield ft(this.fetch,`${this.url}/bucket${t}`,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}getBucket(e){return h(this,void 0,void 0,function*(){try{return{data:yield ft(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}createBucket(e){return h(this,arguments,void 0,function*(e,t={public:!1}){try{return{data:yield pt(this.fetch,`${this.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}updateBucket(e,t){return h(this,void 0,void 0,function*(){try{return{data:yield mt(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(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}emptyBucket(e){return h(this,void 0,void 0,function*(){try{return{data:yield pt(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}deleteBucket(e){return h(this,void 0,void 0,function*(){try{return{data:yield gt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}}var Ot=class extends Error{constructor(e,t){super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown="CommitStateUnknownException"===t.icebergType||[500,502,504].includes(t.status)&&!0===t.icebergType?.includes("CommitState")}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};function xt(e){const t=e.fetchImpl??globalThis.fetch;return{async request({method:n,path:r,query:i,body:s,headers:o}){const a=function(e,t,n){const r=new URL(t,e);if(n)for(const[e,t]of Object.entries(n))void 0!==t&&r.searchParams.set(e,t);return r.toString()}(e.baseUrl,r,i),c=await async function(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:`Bearer ${e.token}`}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}(e.auth),l=await t(a,{method:n,headers:{...s?{"Content-Type":"application/json"}:{},...c,...o},body:s?JSON.stringify(s):void 0}),u=await l.text(),d=(l.headers.get("content-type")||"").includes("application/json"),h=d&&u?JSON.parse(u):u;if(!l.ok){const e=d?h:void 0,t=e?.error;throw new Ot(t?.message??`Request failed with status ${l.status}`,{status:l.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:l.status,headers:l.headers,data:h}}}}function jt(e){return e.join("")}var Pt=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){const t=e?{parent:jt(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){const n={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:n})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${jt(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${jt(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${jt(e.namespace)}`}),!0}catch(e){if(e instanceof Ot&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof Ot&&409===e.status)return;throw e}}};function At(e){return e.join("")}var It=class{constructor(e,t="",n){this.client=e,this.prefix=t,this.accessDelegation=n}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${At(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){const n={};this.accessDelegation&&(n["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${At(e.namespace)}/tables`,body:t,headers:n})).data.metadata}async updateTable(e,t){const n=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${At(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":n.data["metadata-location"],metadata:n.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${At(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${At(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${At(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof Ot&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(n){if(n instanceof Ot&&409===n.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw n}}},Ct=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const n=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=xt({baseUrl:n,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new Pt(this.client,t),this.tableOps=new It(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}};class Rt{constructor(e,t={},n){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Et),t),this.fetch=at(n)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return h(this,void 0,void 0,function*(){try{return{data:yield pt(this.fetch,`${this.url}/bucket`,{name:e},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}listBuckets(e){return h(this,void 0,void 0,function*(){try{const t=new URLSearchParams;void 0!==(null==e?void 0:e.limit)&&t.set("limit",e.limit.toString()),void 0!==(null==e?void 0:e.offset)&&t.set("offset",e.offset.toString()),(null==e?void 0:e.sortColumn)&&t.set("sortColumn",e.sortColumn),(null==e?void 0:e.sortOrder)&&t.set("sortOrder",e.sortOrder),(null==e?void 0:e.search)&&t.set("search",e.search);const n=t.toString(),r=n?`${this.url}/bucket?${n}`:`${this.url}/bucket`;return{data:yield ft(this.fetch,r,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}deleteBucket(e){return h(this,void 0,void 0,function*(){try{return{data:yield gt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}from(e){if(!(e=>!(!e||"string"!=typeof e)&&(!(0===e.length||e.length>100)&&(e.trim()===e&&(!e.includes("/")&&!e.includes("\\")&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e)))))(e))throw new rt("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");return new Ct({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:()=>h(this,void 0,void 0,function*(){return this.headers})},fetch:this.fetch})}}const $t={"X-Client-Info":`storage-js/${St}`,"Content-Type":"application/json"};class Ut extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}}function Nt(e){return"object"==typeof e&&null!==e&&"__isStorageVectorsError"in e}class Dt extends Ut{constructor(e,t,n){super(e),this.name="StorageVectorsApiError",this.status=t,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class Bt extends Ut{constructor(e,t){super(e),this.name="StorageVectorsUnknownError",this.originalError=t}}var Lt;!function(e){e.InternalError="InternalError",e.S3VectorConflictException="S3VectorConflictException",e.S3VectorNotFoundException="S3VectorNotFoundException",e.S3VectorBucketNotEmpty="S3VectorBucketNotEmpty",e.S3VectorMaxBucketsExceeded="S3VectorMaxBucketsExceeded",e.S3VectorMaxIndexesExceeded="S3VectorMaxIndexesExceeded"}(Lt||(Lt={}));const qt=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Ft=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Mt=(e,t,n,r)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&r?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(r)?(i.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),i.body=JSON.stringify(r)):i.body=r,Object.assign(Object.assign({},i),n)):i};function Kt(e,t,n,r,i,s){return h(this,void 0,void 0,function*(){return new Promise((o,a)=>{e(n,Mt(t,r,i,s)).then(e=>{if(!e.ok)throw e;if(null==r?void 0:r.noResolveJson)return e;const t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():{}}).then(e=>o(e)).catch(e=>((e,t,n)=>h(void 0,void 0,void 0,function*(){if(e&&"object"==typeof e&&"status"in e&&"ok"in e&&"number"==typeof e.status&&!(null==n?void 0:n.noResolveJson)){const n=e.status||500,r=e;if("function"==typeof r.json)r.json().then(e=>{const r=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||n+"";t(new Dt(Ft(e),n,r))}).catch(()=>{const e=n+"",i=r.statusText||`HTTP ${n} error`;t(new Dt(i,n,e))});else{const e=n+"",i=r.statusText||`HTTP ${n} error`;t(new Dt(i,n,e))}}else t(new Bt(Ft(e),e))}))(e,a,r))})})}function zt(e,t,n,r,i){return h(this,void 0,void 0,function*(){return Kt(e,"POST",t,r,i,n)})}class Wt{constructor(e,t={},n){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},$t),t),this.fetch=qt(n)}throwOnError(){return this.shouldThrowOnError=!0,this}createIndex(e){return h(this,void 0,void 0,function*(){try{return{data:(yield zt(this.fetch,`${this.url}/CreateIndex`,e,{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}getIndex(e,t){return h(this,void 0,void 0,function*(){try{return{data:yield zt(this.fetch,`${this.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}listIndexes(e){return h(this,void 0,void 0,function*(){try{return{data:yield zt(this.fetch,`${this.url}/ListIndexes`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}deleteIndex(e,t){return h(this,void 0,void 0,function*(){try{return{data:(yield zt(this.fetch,`${this.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}}class Gt{constructor(e,t={},n){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},$t),t),this.fetch=qt(n)}throwOnError(){return this.shouldThrowOnError=!0,this}putVectors(e){return h(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 zt(this.fetch,`${this.url}/PutVectors`,e,{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}getVectors(e){return h(this,void 0,void 0,function*(){try{return{data:yield zt(this.fetch,`${this.url}/GetVectors`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}listVectors(e){return h(this,void 0,void 0,function*(){try{if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error("segmentIndex must be between 0 and "+(e.segmentCount-1))}return{data:yield zt(this.fetch,`${this.url}/ListVectors`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}queryVectors(e){return h(this,void 0,void 0,function*(){try{return{data:yield zt(this.fetch,`${this.url}/QueryVectors`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}deleteVectors(e){return h(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 zt(this.fetch,`${this.url}/DeleteVectors`,e,{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}}class Vt{constructor(e,t={},n){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},$t),t),this.fetch=qt(n)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return h(this,void 0,void 0,function*(){try{return{data:(yield zt(this.fetch,`${this.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}getBucket(e){return h(this,void 0,void 0,function*(){try{return{data:yield zt(this.fetch,`${this.url}/GetVectorBucket`,{vectorBucketName:e},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}listBuckets(){return h(this,arguments,void 0,function*(e={}){try{return{data:yield zt(this.fetch,`${this.url}/ListVectorBuckets`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}deleteBucket(e){return h(this,void 0,void 0,function*(){try{return{data:(yield zt(this.fetch,`${this.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}}class Ht extends Vt{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new Jt(this.url,this.headers,e,this.fetch)}createBucket(e){const t=Object.create(null,{createBucket:{get:()=>super.createBucket}});return h(this,void 0,void 0,function*(){return t.createBucket.call(this,e)})}getBucket(e){const t=Object.create(null,{getBucket:{get:()=>super.getBucket}});return h(this,void 0,void 0,function*(){return t.getBucket.call(this,e)})}listBuckets(){const e=Object.create(null,{listBuckets:{get:()=>super.listBuckets}});return h(this,arguments,void 0,function*(t={}){return e.listBuckets.call(this,t)})}deleteBucket(e){const t=Object.create(null,{deleteBucket:{get:()=>super.deleteBucket}});return h(this,void 0,void 0,function*(){return t.deleteBucket.call(this,e)})}}class Jt extends Wt{constructor(e,t,n,r){super(e,t,r),this.vectorBucketName=n}createIndex(e){const t=Object.create(null,{createIndex:{get:()=>super.createIndex}});return h(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 h(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 h(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 h(this,void 0,void 0,function*(){return t.deleteIndex.call(this,this.vectorBucketName,e)})}index(e){return new Yt(this.url,this.headers,this.vectorBucketName,e,this.fetch)}}class Yt extends Gt{constructor(e,t,n,r,i){super(e,t,i),this.vectorBucketName=n,this.indexName=r}putVectors(e){const t=Object.create(null,{putVectors:{get:()=>super.putVectors}});return h(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 h(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 h(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 h(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 h(this,void 0,void 0,function*(){return t.deleteVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}}class Qt extends Tt{constructor(e,t={},n,r){super(e,t,n,r)}from(e){return new kt(this.url,this.headers,e,this.fetch)}get vectors(){return new Ht(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Rt(this.url+"/iceberg",this.headers,this.fetch)}}let Xt="";Xt="undefined"!=typeof Deno?"deno":"undefined"!=typeof document?"web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";const Zt={headers:{"X-Client-Info":`supabase-js-${Xt}/2.86.0`}},en={schema:"public"},tn={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},nn={},rn=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),sn=(e,t,n)=>{const r=rn(n),i=Headers;return async(n,s)=>{var o;const a=null!==(o=await t())&&void 0!==o?o:e;let c=new i(null==s?void 0:s.headers);return c.has("apikey")||c.set("apikey",e),c.has("Authorization")||c.set("Authorization",`Bearer ${a}`),r(n,Object.assign(Object.assign({},s),{headers:c}))}};const on="2.86.0",an=3e4,cn=9e4,ln={"X-Client-Info":`gotrue-js/${on}`},un="X-Supabase-Api-Version",dn={timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"},hn=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class fn extends Error{constructor(e,t,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=n}}function pn(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class mn extends fn{constructor(e,t,n){super(e,t,n),this.name="AuthApiError",this.status=t,this.code=n}}class gn extends fn{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class bn extends fn{constructor(e,t,n,r){super(e,n,r),this.name=t,this.status=n}}class wn extends bn{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class yn extends bn{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class vn extends bn{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class _n extends bn{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class kn extends bn{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Sn extends bn{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function En(e){return pn(e)&&"AuthRetryableFetchError"===e.name}class Tn extends bn{constructor(e,t,n){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=n}}class On extends bn{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const xn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),jn=" \t\n\r=".split(""),Pn=(()=>{const e=new Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<jn.length;t+=1)e[jn[t].charCodeAt(0)]=-2;for(let t=0;t<xn.length;t+=1)e[xn[t].charCodeAt(0)]=t;return e})();function An(e,t,n){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;n(xn[e]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;n(xn[e]),t.queuedBits-=6}}function In(e,t,n){const r=Pn[e];if(!(r>-1)){if(-2===r)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)n(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}function Cn(e){const t=[],n=e=>{t.push(String.fromCodePoint(e))},r={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},s=e=>{!function(e,t,n){if(0===t.utf8seq){if(e<=127)return void n(e);for(let n=1;n<6;n+=1)if(!(e>>7-n&1)){t.utf8seq=n;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else{if(4!==t.utf8seq)throw new Error("Invalid UTF-8 sequence");t.codepoint=7&e}t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&n(t.codepoint)}}(e,r,n)};for(let t=0;t<e.length;t+=1)In(e.charCodeAt(t),i,s);return t.join("")}function Rn(e,t){if(!(e<=127)){if(e<=2047)return t(192|e>>6),void t(128|63&e);if(e<=65535)return t(224|e>>12),t(128|e>>6&63),void t(128|63&e);if(e<=1114111)return t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),void t(128|63&e);throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}t(e)}function $n(e){const t=[],n={queue:0,queuedBits:0},r=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)In(e.charCodeAt(t),n,r);return new Uint8Array(t)}function Un(e){const t=[];return function(e,t){for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);if(r>55295&&r<=56319){const t=1024*(r-55296)&65535;r=65536+(e.charCodeAt(n+1)-56320&65535|t),n+=1}Rn(r,t)}}(e,e=>t.push(e)),new Uint8Array(t)}function Nn(e){const t=[],n={queue:0,queuedBits:0},r=e=>{t.push(e)};return e.forEach(e=>An(e,n,r)),An(null,n,r),t.join("")}const Dn=()=>"undefined"!=typeof window&&"undefined"!=typeof document,Bn={tested:!1,writable:!1},Ln=()=>{if(!Dn())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(Bn.tested)return Bn.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Bn.tested=!0,Bn.writable=!0}catch(e){Bn.tested=!0,Bn.writable=!1}return Bn.writable};const qn=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Fn=async(e,t,n)=>{await e.setItem(t,JSON.stringify(n))},Mn=async(e,t)=>{const n=await e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch(e){return n}},Kn=async(e,t)=>{await e.removeItem(t)};class zn{constructor(){this.promise=new zn.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function Wn(e){const t=e.split(".");if(3!==t.length)throw new On("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!hn.test(t[e]))throw new On("JWT not in base64url format");return{header:JSON.parse(Cn(t[0])),payload:JSON.parse(Cn(t[1])),signature:$n(t[2]),raw:{header:t[0],payload:t[1]}}}function Gn(e){return("0"+e.toString(16)).substr(-2)}async function Vn(e){if(!("undefined"!=typeof crypto&&void 0!==crypto.subtle&&"undefined"!=typeof TextEncoder))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;const t=await async function(e){const t=(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(n);return Array.from(r).map(e=>String.fromCharCode(e)).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Hn(e,t,n=!1){const r=function(){const e=new Uint32Array(56);if("undefined"==typeof crypto){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length;let n="";for(let r=0;r<56;r++)n+=e.charAt(Math.floor(Math.random()*t));return n}return crypto.getRandomValues(e),Array.from(e,Gn).join("")}();let i=r;n&&(i+="/PASSWORD_RECOVERY"),await Fn(e,`${t}-code-verifier`,i);const s=await Vn(r);return[s,r===s?"plain":"s256"]}zn.promiseConstructor=Promise;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;const Yn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Qn(e){if(!Yn.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Xn(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){const e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Zn(e){return JSON.parse(JSON.stringify(e))}const er=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),tr=[502,503,504];async function nr(e){var t,n;if(!("object"==typeof(n=e)&&null!==n&&"status"in n&&"ok"in n&&"json"in n&&"function"==typeof n.json))throw new Sn(er(e),0);if(tr.includes(e.status))throw new Sn(er(e),e.status);let r,i;try{r=await e.json()}catch(e){throw new gn(er(e),e)}const s=function(e){const t=e.headers.get(un);if(!t)return null;if(!t.match(Jn))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(e){return null}}(e);if(s&&s.getTime()>=dn.timestamp&&"object"==typeof r&&r&&"string"==typeof r.code?i=r.code:"object"==typeof r&&r&&"string"==typeof r.error_code&&(i=r.error_code),i){if("weak_password"===i)throw new Tn(er(r),e.status,(null===(t=r.weak_password)||void 0===t?void 0:t.reasons)||[]);if("session_not_found"===i)throw new wn}else if("object"==typeof r&&r&&"object"==typeof r.weak_password&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new Tn(er(r),e.status,r.weak_password.reasons);throw new mn(er(r),e.status||500,i)}async function rr(e,t,n,r){var i;const s=Object.assign({},null==r?void 0:r.headers);s[un]||(s[un]=dn.name),(null==r?void 0:r.jwt)&&(s.Authorization=`Bearer ${r.jwt}`);const o=null!==(i=null==r?void 0:r.query)&&void 0!==i?i:{};(null==r?void 0:r.redirectTo)&&(o.redirect_to=r.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await async function(e,t,n,r,i,s){const o=((e,t,n,r)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),n))})(t,r,i,s);let a;try{a=await e(n,Object.assign({},o))}catch(e){throw console.error(e),new Sn(er(e),0)}a.ok||await nr(a);if(null==r?void 0:r.noResolveJson)return a;try{return await a.json()}catch(e){await nr(e)}}(e,t,n+a,{headers:s,noResolveJson:null==r?void 0:r.noResolveJson},{},null==r?void 0:r.body);return(null==r?void 0:r.xform)?null==r?void 0:r.xform(c):{data:Object.assign({},c),error:null}}function ir(e){var t;let n=null;var r;(function(e){return e.access_token&&e.refresh_token&&e.expires_in})(e)&&(n=Object.assign({},e),e.expires_at||(n.expires_at=(r=e.expires_in,Math.round(Date.now()/1e3)+r)));return{data:{session:n,user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function sr(e){const t=ir(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function or(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function ar(e){return{data:e,error:null}}function cr(e){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:s,verification_type:o}=e,a=i(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]);return{data:{properties:{action_link:t,email_otp:n,hashed_token:r,redirect_to:s,verification_type:o},user:Object.assign({},a)},error:null}}function lr(e){return e}const ur=["global","local","others"];class dr{constructor({url:e="",headers:t={},fetch:n}){this.url=e,this.headers=t,this.fetch=qn(n),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=ur[0]){if(ur.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ur.join(", ")}`);try{return await rr(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(pn(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await rr(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:or})}catch(e){if(pn(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{const{options:t}=e,n=i(e,["options"]),r=Object.assign(Object.assign({},n),t);return"newEmail"in n&&(r.new_email=null==n?void 0:n.newEmail,delete r.newEmail),await rr(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:cr,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(pn(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await rr(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:or})}catch(e){if(pn(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,n,r,i,s,o,a;try{const c={nextPage:null,lastPage:0,total:0},l=await rr(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(n=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==n?n:"",per_page:null!==(i=null===(r=null==e?void 0:e.perPage)||void 0===r?void 0:r.toString())&&void 0!==i?i:""},xform:lr});if(l.error)throw l.error;const u=await l.json(),d=null!==(s=l.headers.get("x-total-count"))&&void 0!==s?s:0,h=null!==(a=null===(o=l.headers.get("link"))||void 0===o?void 0:o.split(","))&&void 0!==a?a:[];return h.length>0&&(h.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),n=JSON.parse(e.split(";")[1].split("=")[1]);c[`${n}Page`]=t}),c.total=parseInt(d)),{data:Object.assign(Object.assign({},u),c),error:null}}catch(e){if(pn(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){Qn(e);try{return await rr(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:or})}catch(e){if(pn(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){Qn(e);try{return await rr(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:or})}catch(e){if(pn(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){Qn(e);try{return await rr(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:or})}catch(e){if(pn(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){Qn(e.userId);try{const{data:t,error:n}=await rr(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:n}}catch(e){if(pn(e))return{data:null,error:e};throw e}}async _deleteFactor(e){Qn(e.userId),Qn(e.id);try{return{data:await rr(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(pn(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){var t,n,r,i,s,o,a;try{const c={nextPage:null,lastPage:0,total:0},l=await rr(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(n=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==n?n:"",per_page:null!==(i=null===(r=null==e?void 0:e.perPage)||void 0===r?void 0:r.toString())&&void 0!==i?i:""},xform:lr});if(l.error)throw l.error;const u=await l.json(),d=null!==(s=l.headers.get("x-total-count"))&&void 0!==s?s:0,h=null!==(a=null===(o=l.headers.get("link"))||void 0===o?void 0:o.split(","))&&void 0!==a?a:[];return h.length>0&&(h.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),n=JSON.parse(e.split(";")[1].split("=")[1]);c[`${n}Page`]=t}),c.total=parseInt(d)),{data:Object.assign(Object.assign({},u),c),error:null}}catch(e){if(pn(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await rr(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(pn(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await rr(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(pn(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await rr(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(pn(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await rr(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(pn(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await rr(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(pn(e))return{data:null,error:e};throw e}}}function hr(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}const fr=!!(globalThis&&Ln()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"));class pr extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class mr extends pr{}async function gr(e,t,n){fr&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),fr&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async r=>{if(!r){if(0===t)throw fr&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new mr(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(fr)try{const e=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(e,null," "))}catch(e){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",e)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await n()}fr&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,r.name);try{return await n()}finally{fr&&console.log("@supabase/gotrue-js: navigatorLock: released",e,r.name)}}))}function br(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function wr(e){const t=(new TextEncoder).encode(e);return"0x"+Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}class yr extends Error{constructor({message:e,code:t,cause:n,name:r}){var i;super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=null!==(i=null!=r?r:n instanceof Error?n.name:void 0)&&void 0!==i?i:"Unknown Error",this.code=t}}class vr extends yr{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function _r({error:e,options:t}){var n,r,i;const{publicKey:s}=t;if(!s)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new yr({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===(null===(n=s.authenticatorSelection)||void 0===n?void 0:n.requireResidentKey))return new yr({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===(null===(r=s.authenticatorSelection)||void 0===r?void 0:r.userVerification))return new yr({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===(null===(i=s.authenticatorSelection)||void 0===i?void 0:i.userVerification))return new yr({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new yr({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new yr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name){return 0===s.pubKeyCredParams.filter(e=>"public-key"===e.type).length?new yr({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new yr({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e})}if("SecurityError"===e.name){const t=window.location.hostname;if(!jr(t))return new yr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(s.rp.id!==t)return new yr({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new yr({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new yr({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new yr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function kr({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new yr({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new yr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!jr(t))return new yr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rpId!==t)return new yr({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new yr({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new yr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}const Sr=new class{createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function Er(e){if(!e)throw new Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:t,user:n,excludeCredentials:r}=e,s=i(e,["challenge","user","excludeCredentials"]),o=$n(t).buffer,a=Object.assign(Object.assign({},n),{id:$n(n.id).buffer}),c=Object.assign(Object.assign({},s),{challenge:o,user:a});if(r&&r.length>0){c.excludeCredentials=new Array(r.length);for(let e=0;e<r.length;e++){const t=r[e];c.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:$n(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return c}function Tr(e){if(!e)throw new Error("Credential request options are required");if("undefined"!=typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);const{challenge:t,allowCredentials:n}=e,r=i(e,["challenge","allowCredentials"]),s=$n(t).buffer,o=Object.assign(Object.assign({},r),{challenge:s});if(n&&n.length>0){o.allowCredentials=new Array(n.length);for(let e=0;e<n.length;e++){const t=n[e];o.allowCredentials[e]=Object.assign(Object.assign({},t),{id:$n(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return o}function Or(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const n=e;return{id:e.id,rawId:e.id,response:{attestationObject:Nn(new Uint8Array(e.response.attestationObject)),clientDataJSON:Nn(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:null!==(t=n.authenticatorAttachment)&&void 0!==t?t:void 0}}function xr(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const n=e,r=e.getClientExtensionResults(),i=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:Nn(new Uint8Array(i.authenticatorData)),clientDataJSON:Nn(new Uint8Array(i.clientDataJSON)),signature:Nn(new Uint8Array(i.signature)),userHandle:i.userHandle?Nn(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:null!==(t=n.authenticatorAttachment)&&void 0!==t?t:void 0}}function jr(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function Pr(){var e,t;return!!(Dn()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null===(e=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===e?void 0:e.create)&&"function"==typeof(null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.get))}const Ar={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Ir={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Cr(...e){const t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),n=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),r={};for(const i of e)if(i)for(const e in i){const s=i[e];if(void 0!==s)if(Array.isArray(s))r[e]=s;else if(n(s))r[e]=s;else if(t(s)){const n=r[e];t(n)?r[e]=Cr(n,s):r[e]=Cr(s)}else r[e]=s}return r}class Rr{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:n,signal:r},i){try{const{data:s,error:o}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!s)return{data:null,error:o};const a=null!=r?r:Sr.createNewAbortSignal();if("create"===s.webauthn.type){const{user:e}=s.webauthn.credential_options.publicKey;e.name||(e.name=`${e.id}:${n}`),e.displayName||(e.displayName=e.name)}switch(s.webauthn.type){case"create":{const t=function(e,t){return Cr(Ar,e,t||{})}(s.webauthn.credential_options.publicKey,null==i?void 0:i.create),{data:n,error:r}=await async function(e){try{const t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new vr("Browser returned unexpected credential type",t)}:{data:null,error:new vr("Empty credential response",t)}}catch(t){return{data:null,error:_r({error:t,options:e})}}}({publicKey:t,signal:a});return n?{data:{factorId:e,challengeId:s.id,webauthn:{type:s.webauthn.type,credential_response:n}},error:null}:{data:null,error:r}}case"request":{const t=function(e,t){return Cr(Ir,e,t||{})}(s.webauthn.credential_options.publicKey,null==i?void 0:i.request),{data:n,error:r}=await async function(e){try{const t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new vr("Browser returned unexpected credential type",t)}:{data:null,error:new vr("Empty credential response",t)}}catch(t){return{data:null,error:kr({error:t,options:e})}}}(Object.assign(Object.assign({},s.webauthn.credential_options),{publicKey:t,signal:a}));return n?{data:{factorId:e,challengeId:s.id,webauthn:{type:s.webauthn.type,credential_response:n}},error:null}:{data:null,error:r}}}}catch(e){return pn(e)?{data:null,error:e}:{data:null,error:new gn("Unexpected error in challenge",e)}}}async _verify({challengeId:e,factorId:t,webauthn:n}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:n=("undefined"!=typeof window?[window.location.origin]:void 0),signal:r}={}},i){if(!t)return{data:null,error:new fn("rpId is required for WebAuthn authentication")};try{if(!Pr())return{data:null,error:new gn("Browser does not support WebAuthn",null)};const{data:s,error:o}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:n},signal:r},{request:i});if(!s)return{data:null,error:o};const{webauthn:a}=s;return this._verify({factorId:e,challengeId:s.challengeId,webauthn:{type:a.type,rpId:t,rpOrigins:n,credential_response:a.credential_response}})}catch(e){return pn(e)?{data:null,error:e}:{data:null,error:new gn("Unexpected error in authenticate",e)}}}async _register({friendlyName:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:n=("undefined"!=typeof window?[window.location.origin]:void 0),signal:r}={}},i){if(!t)return{data:null,error:new fn("rpId is required for WebAuthn registration")};try{if(!Pr())return{data:null,error:new gn("Browser does not support WebAuthn",null)};const{data:s,error:o}=await this._enroll({friendlyName:e});if(!s)return await this.client.mfa.listFactors().then(t=>{var n;return null===(n=t.data)||void 0===n?void 0:n.all.find(t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:o};const{data:a,error:c}=await this._challenge({factorId:s.id,friendlyName:s.friendly_name,webauthn:{rpId:t,rpOrigins:n},signal:r},{create:i});return a?this._verify({factorId:s.id,challengeId:a.challengeId,webauthn:{rpId:t,rpOrigins:n,type:a.webauthn.type,credential_response:a.webauthn.credential_response}}):{data:null,error:c}}catch(e){return pn(e)?{data:null,error:e}:{data:null,error:new gn("Unexpected error in register",e)}}}}!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();const $r={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:ln,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1};async function Ur(e,t,n){return await n()}const Nr={};class Dr{get jwks(){var e,t;return null!==(t=null===(e=Nr[this.storageKey])||void 0===e?void 0:e.jwks)&&void 0!==t?t:{keys:[]}}set jwks(e){Nr[this.storageKey]=Object.assign(Object.assign({},Nr[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!==(t=null===(e=Nr[this.storageKey])||void 0===e?void 0:e.cachedAt)&&void 0!==t?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Nr[this.storageKey]=Object.assign(Object.assign({},Nr[this.storageKey]),{cachedAt:e})}constructor(e){var t,n,r;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({},$r),e);if(this.storageKey=i.storageKey,this.instanceID=null!==(t=Dr.nextInstanceID[this.storageKey])&&void 0!==t?t:0,Dr.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,"function"==typeof i.debug&&(this.logger=i.debug),this.instanceID>0&&Dn()){const e=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new dr({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=qn(i.fetch),this.lock=i.lock||Ur,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,i.lock?this.lock=i.lock:Dn()&&(null===(n=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===n?void 0:n.locks)?this.lock=gr:this.lock=Ur,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 Rr(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:Ln()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=hr(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=hr(this.memoryStorage)),Dn()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null===(r=this.broadcastChannel)||void 0===r||r.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)})}this.initialize()}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${on}) ${(new Date).toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{let t={},n="none";if(Dn()&&(t=function(e){const t={},n=new URL(e);if(n.hash&&"#"===n.hash[0])try{new URLSearchParams(n.hash.substring(1)).forEach((e,n)=>{t[n]=e})}catch(e){}return n.searchParams.forEach((e,n)=>{t[n]=e}),t}(window.location.href),this._isImplicitGrantCallback(t)?n="implicit":await this._isPKCECallback(t)&&(n="pkce")),Dn()&&this.detectSessionInUrl&&"none"!==n){const{data:r,error:i}=await this._getSessionFromURL(t,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),function(e){return pn(e)&&"AuthImplicitGrantRedirectError"===e.name}(i)){const t=null===(e=i.details)||void 0===e?void 0:e.code;if("identity_already_exists"===t||"identity_not_found"===t||"single_identity_not_deletable"===t)return{error:i}}return await this._removeSession(),{error:i}}const{session:s,redirectType:o}=r;return this._debug("#_initialize()","detected session in URL",s,"redirect type",o),await this._saveSession(s),setTimeout(async()=>{"recovery"===o?await this._notifyAllSubscribers("PASSWORD_RECOVERY",s):await this._notifyAllSubscribers("SIGNED_IN",s)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return pn(e)?this._returnResult({error:e}):this._returnResult({error:new gn("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,n,r;try{const i=await rr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(n=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==n?n:{},gotrue_meta_security:{captcha_token:null===(r=null==e?void 0:e.options)||void 0===r?void 0:r.captchaToken}},xform:ir}),{data:s,error:o}=i;if(o||!s)return this._returnResult({data:{user:null,session:null},error:o});const a=s.session,c=s.user;return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:c,session:a},error:null})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){var t,n,r;try{let i;if("email"in e){const{email:n,password:r,options:s}=e;let o=null,a=null;"pkce"===this.flowType&&([o,a]=await Hn(this.storage,this.storageKey)),i=await rr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==s?void 0:s.emailRedirectTo,body:{email:n,password:r,data:null!==(t=null==s?void 0:s.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken},code_challenge:o,code_challenge_method:a},xform:ir})}else{if(!("phone"in e))throw new vn("You must provide either an email or phone number and a password");{const{phone:t,password:s,options:o}=e;i=await rr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:s,data:null!==(n=null==o?void 0:o.data)&&void 0!==n?n:{},channel:null!==(r=null==o?void 0:o.channel)&&void 0!==r?r:"sms",gotrue_meta_security:{captcha_token:null==o?void 0:o.captchaToken}},xform:ir})}}const{data:s,error:o}=i;if(o||!s)return this._returnResult({data:{user:null,session:null},error:o});const a=s.session,c=s.user;return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",a)),this._returnResult({data:{user:c,session:a},error:null})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if("email"in e){const{email:n,password:r,options:i}=e;t=await rr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:sr})}else{if(!("phone"in e))throw new vn("You must provide either an email or phone number and a password");{const{phone:n,password:r,options:i}=e;t=await rr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:sr})}}const{data:n,error:r}=t;if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!n||!n.session||!n.user){const e=new yn;return this._returnResult({data:{user:null,session:null},error:e})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:r})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){var t,n,r,i;return await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(n=e.options)||void 0===n?void 0:n.scopes,queryParams:null===(r=e.options)||void 0===r?void 0:r.queryParams,skipBrowserRedirect:null===(i=e.options)||void 0===i?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,n,r,i,s,o,a,c,l,u,d;let h,f;if("message"in e)h=e.message,f=e.signature;else{const{chain:u,wallet:d,statement:p,options:m}=e;let g;if(Dn())if("object"==typeof d)g=d;else{const e=window;if(!("ethereum"in e)||"object"!=typeof e.ethereum||!("request"in e.ethereum)||"function"!=typeof e.ethereum.request)throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.");g=e.ethereum}else{if("object"!=typeof d||!(null==m?void 0:m.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");g=d}const b=new URL(null!==(t=null==m?void 0:m.url)&&void 0!==t?t:window.location.href),w=await g.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!w||0===w.length)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const y=br(w[0]);let v=null===(n=null==m?void 0:m.signInWithEthereum)||void 0===n?void 0:n.chainId;if(!v){const e=await g.request({method:"eth_chainId"});v=parseInt(e,16)}h=function(e){var t;const{chainId:n,domain:r,expirationTime:i,issuedAt:s=new Date,nonce:o,notBefore:a,requestId:c,resources:l,scheme:u,uri:d,version:h}=e;if(!Number.isInteger(n))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${n}`);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("1"!==h)throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${h}`);if(null===(t=e.statement)||void 0===t?void 0:t.includes("\n"))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);const f=`${u?`${u}://${r}`:r} wants you to sign in with your Ethereum account:\n${br(e.address)}\n\n${e.statement?`${e.statement}\n`:""}`;let p=`URI: ${d}\nVersion: ${h}\nChain ID: ${n}${o?`\nNonce: ${o}`:""}\nIssued At: ${s.toISOString()}`;if(i&&(p+=`\nExpiration Time: ${i.toISOString()}`),a&&(p+=`\nNot Before: ${a.toISOString()}`),c&&(p+=`\nRequest ID: ${c}`),l){let e="\nResources:";for(const t of l){if(!t||"string"!=typeof t)throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}p+=e}return`${f}\n${p}`}({domain:b.host,address:y,statement:p,uri:b.href,version:"1",chainId:v,nonce:null===(r=null==m?void 0:m.signInWithEthereum)||void 0===r?void 0:r.nonce,issuedAt:null!==(s=null===(i=null==m?void 0:m.signInWithEthereum)||void 0===i?void 0:i.issuedAt)&&void 0!==s?s:new Date,expirationTime:null===(o=null==m?void 0:m.signInWithEthereum)||void 0===o?void 0:o.expirationTime,notBefore:null===(a=null==m?void 0:m.signInWithEthereum)||void 0===a?void 0:a.notBefore,requestId:null===(c=null==m?void 0:m.signInWithEthereum)||void 0===c?void 0:c.requestId,resources:null===(l=null==m?void 0:m.signInWithEthereum)||void 0===l?void 0:l.resources}),f=await g.request({method:"personal_sign",params:[wr(h),y]})}try{const{data:t,error:n}=await rr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:h,signature:f},(null===(u=e.options)||void 0===u?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null===(d=e.options)||void 0===d?void 0:d.captchaToken}}:null),xform:ir});if(n)throw n;if(!t||!t.session||!t.user){const e=new yn;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:n})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){var t,n,r,i,s,o,a,c,l,u,d,h;let f,p;if("message"in e)f=e.message,p=e.signature;else{const{chain:d,wallet:h,statement:m,options:g}=e;let b;if(Dn())if("object"==typeof h)b=h;else{const e=window;if(!("solana"in e)||"object"!=typeof e.solana||!("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.");b=e.solana}else{if("object"!=typeof h||!(null==g?void 0:g.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");b=h}const w=new URL(null!==(t=null==g?void 0:g.url)&&void 0!==t?t:window.location.href);if("signIn"in b&&b.signIn){const e=await b.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},null==g?void 0:g.signInWithSolana),{version:"1",domain:w.host,uri:w.href}),m?{statement:m}:null));let t;if(Array.isArray(e)&&e[0]&&"object"==typeof e[0])t=e[0];else{if(!(e&&"object"==typeof e&&"signedMessage"in e&&"signature"in e))throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");t=e}if(!("signedMessage"in t&&"signature"in t&&("string"==typeof t.signedMessage||t.signedMessage instanceof Uint8Array)&&t.signature instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");f="string"==typeof t.signedMessage?t.signedMessage:(new TextDecoder).decode(t.signedMessage),p=t.signature}else{if(!("signMessage"in b&&"function"==typeof b.signMessage&&"publicKey"in b&&"object"==typeof b&&b.publicKey&&"toBase58"in b.publicKey&&"function"==typeof b.publicKey.toBase58))throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");f=[`${w.host} wants you to sign in with your Solana account:`,b.publicKey.toBase58(),...m?["",m,""]:[""],"Version: 1",`URI: ${w.href}`,`Issued At: ${null!==(r=null===(n=null==g?void 0:g.signInWithSolana)||void 0===n?void 0:n.issuedAt)&&void 0!==r?r:(new Date).toISOString()}`,...(null===(i=null==g?void 0:g.signInWithSolana)||void 0===i?void 0:i.notBefore)?[`Not Before: ${g.signInWithSolana.notBefore}`]:[],...(null===(s=null==g?void 0:g.signInWithSolana)||void 0===s?void 0:s.expirationTime)?[`Expiration Time: ${g.signInWithSolana.expirationTime}`]:[],...(null===(o=null==g?void 0:g.signInWithSolana)||void 0===o?void 0:o.chainId)?[`Chain ID: ${g.signInWithSolana.chainId}`]:[],...(null===(a=null==g?void 0:g.signInWithSolana)||void 0===a?void 0:a.nonce)?[`Nonce: ${g.signInWithSolana.nonce}`]:[],...(null===(c=null==g?void 0:g.signInWithSolana)||void 0===c?void 0:c.requestId)?[`Request ID: ${g.signInWithSolana.requestId}`]:[],...(null===(u=null===(l=null==g?void 0:g.signInWithSolana)||void 0===l?void 0:l.resources)||void 0===u?void 0:u.length)?["Resources",...g.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");const e=await b.signMessage((new TextEncoder).encode(f),"utf8");if(!(e&&e instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");p=e}}try{const{data:t,error:n}=await rr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:f,signature:Nn(p)},(null===(d=e.options)||void 0===d?void 0:d.captchaToken)?{gotrue_meta_security:{captcha_token:null===(h=e.options)||void 0===h?void 0:h.captchaToken}}:null),xform:ir});if(n)throw n;if(!t||!t.session||!t.user){const e=new yn;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:n})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){const t=await Mn(this.storage,`${this.storageKey}-code-verifier`),[n,r]=(null!=t?t:"").split("/");try{const{data:t,error:i}=await rr(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:ir});if(await Kn(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!t||!t.session||!t.user){const e=new yn;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:null!=r?r:null}),error:i})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{const{options:t,provider:n,token:r,access_token:i,nonce:s}=e,o=await rr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:r,access_token:i,nonce:s,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:ir}),{data:a,error:c}=o;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!a||!a.session||!a.user){const e=new yn;return this._returnResult({data:{user:null,session:null},error:e})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",a.session)),this._returnResult({data:a,error:c})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){var t,n,r,i,s;try{if("email"in e){const{email:r,options:i}=e;let s=null,o=null;"pkce"===this.flowType&&([s,o]=await Hn(this.storage,this.storageKey));const{error:a}=await rr(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:r,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},create_user:null===(n=null==i?void 0:i.shouldCreateUser)||void 0===n||n,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:s,code_challenge_method:o},redirectTo:null==i?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}if("phone"in e){const{phone:t,options:n}=e,{data:o,error:a}=await rr(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(r=null==n?void 0:n.data)&&void 0!==r?r:{},create_user:null===(i=null==n?void 0:n.shouldCreateUser)||void 0===i||i,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},channel:null!==(s=null==n?void 0:n.channel)&&void 0!==s?s:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==o?void 0:o.message_id},error:a})}throw new vn("You must provide either an email or phone number.")}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){var t,n;try{let r,i;"options"in e&&(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo,i=null===(n=e.options)||void 0===n?void 0:n.captchaToken);const{data:s,error:o}=await rr(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:r,xform:ir});if(o)throw o;if(!s){throw new Error("An error occurred on token verification.")}const a=s.session,c=s.user;return(null==a?void 0:a.access_token)&&(await this._saveSession(a),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",a)),this._returnResult({data:{user:c,session:a},error:null})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){var t,n,r,i,s;try{let o=null,a=null;"pkce"===this.flowType&&([o,a]=await Hn(this.storage,this.storageKey));const c=await rr(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:null!==(n=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==n?n:void 0}),(null===(r=null==e?void 0:e.options)||void 0===r?void 0:r.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:o,code_challenge_method:a}),headers:this.headers,xform:ar});return(null===(i=c.data)||void 0===i?void 0:i.url)&&Dn()&&!(null===(s=e.options)||void 0===s?void 0:s.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}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:n}=e;if(n)throw n;if(!t)throw new wn;const{error:r}=await rr(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:r})})}catch(e){if(pn(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:n,type:r,options:i}=e,{error:s}=await rr(this.fetch,"POST",t,{headers:this.headers,body:{email:n,type:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},redirectTo:null==i?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:s})}if("phone"in e){const{phone:n,type:r,options:i}=e,{data:s,error:o}=await rr(this.fetch,"POST",t,{headers:this.headers,body:{phone:n,type:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==s?void 0:s.message_id},error:o})}throw new vn("You must provide either an email or phone number and a type")}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){await this.initializePromise;return await this._acquireLock(-1,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await n}catch(e){}})()),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 e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){const e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",(new Error).stack);try{let e=null;const t=await Mn(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const n=!!e.expires_at&&1e3*e.expires_at-Date.now()<cn;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){const t=await Mn(this.userStorage,this.storageKey+"-user");(null==t?void 0:t.user)?e.user=t.user:e.user=Xn()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const t={value:this.suppressGetSessionWarning};e.user=function(e,t){return new Proxy(e,{get:(e,n,r)=>{if("__isInsecureUserWarningProxy"===n)return!0;if("symbol"==typeof n){const t=n.toString();if("Symbol(Symbol.toPrimitive)"===t||"Symbol(Symbol.toStringTag)"===t||"Symbol(util.inspect.custom)"===t||"Symbol(nodejs.util.inspect.custom)"===t)return Reflect.get(e,n,r)}return t.value||"string"!=typeof n||(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),t.value=!0),Reflect.get(e,n,r)}})}(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:r},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;return await this._acquireLock(-1,async()=>await this._getUser())}async _getUser(e){try{return e?await rr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:or}):await this._useSession(async e=>{var t,n,r;const{data:i,error:s}=e;if(s)throw s;return(null===(t=i.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await rr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(r=null===(n=i.session)||void 0===n?void 0:n.access_token)&&void 0!==r?r:void 0,xform:or}):{data:{user:null},error:new wn}})}catch(e){if(pn(e))return function(e){return pn(e)&&"AuthSessionMissingError"===e.name}(e)&&(await this._removeSession(),await Kn(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async n=>{const{data:r,error:i}=n;if(i)throw i;if(!r.session)throw new wn;const s=r.session;let o=null,a=null;"pkce"===this.flowType&&null!=e.email&&([o,a]=await Hn(this.storage,this.storageKey));const{data:c,error:l}=await rr(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:o,code_challenge_method:a}),jwt:s.access_token,xform:or});if(l)throw l;return s.user=c.user,await this._saveSession(s),await this._notifyAllSubscribers("USER_UPDATED",s),this._returnResult({data:{user:s.user},error:null})})}catch(e){if(pn(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new wn;const t=Date.now()/1e3;let n=t,r=!0,i=null;const{payload:s}=Wn(e.access_token);if(s.exp&&(n=s.exp,r=n<=t),r){const{data:t,error:n}=await this._callRefreshToken(e.refresh_token);if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!t)return{data:{user:null,session:null},error:null};i=t}else{const{data:r,error:s}=await this._getUser(e.access_token);if(s)throw s;i={access_token:e.access_token,refresh_token:e.refresh_token,user:r.user,token_type:"bearer",expires_in:n-t,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(e){if(pn(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var n;if(!e){const{data:r,error:i}=t;if(i)throw i;e=null!==(n=r.session)&&void 0!==n?n:void 0}if(!(null==e?void 0:e.refresh_token))throw new wn;const{data:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):r?this._returnResult({data:{user:r.user,session:r},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!Dn())throw new _n("No browser detected.");if(e.error||e.error_description||e.error_code)throw new _n(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if("pkce"===this.flowType)throw new kn("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new _n("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new kn("No code detected.");const{data:t,error:n}=await this._exchangeCodeForSession(e.code);if(n)throw n;const r=new URL(window.location.href);return r.searchParams.delete("code"),window.history.replaceState(window.history.state,"",r.toString()),{data:{session:t.session,redirectType:null},error:null}}const{provider_token:n,provider_refresh_token:r,access_token:i,refresh_token:s,expires_in:o,expires_at:a,token_type:c}=e;if(!(i&&o&&s&&c))throw new _n("No session defined in URL");const l=Math.round(Date.now()/1e3),u=parseInt(o);let d=l+u;a&&(d=parseInt(a));const h=d-l;1e3*h<=an&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${h}s, should have been closer to ${u}s`);const f=d-u;l-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,d,l):l-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",f,d,l);const{data:p,error:m}=await this._getUser(i);if(m)throw m;const g={provider_token:n,provider_refresh_token:r,access_token:i,expires_in:u,expires_at:d,refresh_token:s,token_type:c,user:p.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:g,redirectType:e.type},error:null})}catch(e){if(pn(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await Mn(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var n;const{data:r,error:i}=t;if(i)return this._returnResult({error:i});const s=null===(n=r.session)||void 0===n?void 0:n.access_token;if(s){const{error:t}=await this.admin.signOut(s,e);if(t&&(!function(e){return pn(e)&&"AuthApiError"===e.name}(t)||404!==t.status&&401!==t.status&&403!==t.status))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await Kn(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const t=Symbol("auth-callback"),n={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,n),(async()=>{await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async t=>{var n,r;try{const{data:{session:r},error:i}=t;if(i)throw i;await(null===(n=this.stateChangeEmitters.get(e))||void 0===n?void 0:n.callback("INITIAL_SESSION",r)),this._debug("INITIAL_SESSION","callback id",e,"session",r)}catch(t){await(null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let n=null,r=null;"pkce"===this.flowType&&([n,r]=await Hn(this.storage,this.storageKey,!0));try{return await rr(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){var e;try{const{data:t,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:n,error:r}=await this._useSession(async t=>{var n,r,i,s,o;const{data:a,error:c}=t;if(c)throw c;const l=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(n=e.options)||void 0===n?void 0:n.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(i=e.options)||void 0===i?void 0:i.queryParams,skipBrowserRedirect:!0});return await rr(this.fetch,"GET",l,{headers:this.headers,jwt:null!==(o=null===(s=a.session)||void 0===s?void 0:s.access_token)&&void 0!==o?o:void 0})});if(r)throw r;return Dn()&&!(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)&&window.location.assign(null==n?void 0:n.url),this._returnResult({data:{provider:e.provider,url:null==n?void 0:n.url},error:null})}catch(t){if(pn(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var n;try{const{error:r,data:{session:i}}=t;if(r)throw r;const{options:s,provider:o,token:a,access_token:c,nonce:l}=e,u=await rr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!==(n=null==i?void 0:i.access_token)&&void 0!==n?n:void 0,body:{provider:o,id_token:a,access_token:c,nonce:l,link_identity:!0,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken}},xform:ir}),{data:d,error:h}=u;return h?this._returnResult({data:{user:null,session:null},error:h}):d&&d.session&&d.user?(d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("USER_UPDATED",d.session)),this._returnResult({data:d,error:h})):this._returnResult({data:{user:null,session:null},error:new yn})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var n,r;const{data:i,error:s}=t;if(s)throw s;return await rr(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(r=null===(n=i.session)||void 0===n?void 0:n.access_token)&&void 0!==r?r:void 0})})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const i=Date.now();return await(n=async n=>(n>0&&await async function(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}(200*Math.pow(2,n-1)),this._debug(t,"refreshing attempt",n),await rr(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ir})),r=(e,t)=>{const n=200*Math.pow(2,e);return t&&En(t)&&Date.now()+n-i<an},new Promise((e,t)=>{(async()=>{for(let i=0;i<1/0;i++)try{const t=await n(i);if(!r(i,null,t))return void e(t)}catch(e){if(!r(i,e))return void t(e)}})()}))}catch(e){if(this._debug(t,"error",e),pn(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,"end")}var n,r}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",n),Dn()&&!t.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,t;const n="#_recoverAndRefresh()";this._debug(n,"begin");try{const r=await Mn(this.storage,this.storageKey);if(r&&this.userStorage){let t=await Mn(this.userStorage,this.storageKey+"-user");this.storage.isServer||!Object.is(this.storage,this.userStorage)||t||(t={user:r.user},await Fn(this.userStorage,this.storageKey+"-user",t)),r.user=null!==(e=null==t?void 0:t.user)&&void 0!==e?e:Xn()}else if(r&&!r.user&&!r.user){const e=await Mn(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(r.user=e.user,await Kn(this.storage,this.storageKey+"-user"),await Fn(this.storage,this.storageKey,r)):r.user=Xn()}if(this._debug(n,"session from storage",r),!this._isValidSession(r))return this._debug(n,"session is not valid"),void(null!==r&&await this._removeSession());const i=1e3*(null!==(t=r.expires_at)&&void 0!==t?t:1/0)-Date.now()<cn;if(this._debug(n,`session has${i?"":" not"} expired with margin of 90000s`),i){if(this.autoRefreshToken&&r.refresh_token){const{error:e}=await this._callRefreshToken(r.refresh_token);e&&(console.error(e),En(e)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else if(r.user&&!0===r.user.__isUserNotAvailableProxy)try{const{data:e,error:t}=await this._getUser(r.access_token);!t&&(null==e?void 0:e.user)?(r.user=e.user,await this._saveSession(r),await this._notifyAllSubscribers("SIGNED_IN",r)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(e){console.error("Error getting user data:",e),this._debug(n,"error getting user data, skipping SIGNED_IN notification",e)}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(e){return this._debug(n,"error",e),void console.error(e)}finally{this._debug(n,"end")}}async _callRefreshToken(e){var t,n;if(!e)throw new wn;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new zn;const{data:t,error:n}=await this._refreshAccessToken(e);if(n)throw n;if(!t.session)throw new wn;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);const r={data:t.session,error:null};return this.refreshingDeferred.resolve(r),r}catch(e){if(this._debug(r,"error",e),pn(e)){const n={data:null,error:e};return En(e)||await this._removeSession(),null===(t=this.refreshingDeferred)||void 0===t||t.resolve(n),n}throw null===(n=this.refreshingDeferred)||void 0===n||n.reject(e),e}finally{this.refreshingDeferred=null,this._debug(r,"end")}}async _notifyAllSubscribers(e,t,n=!0){const r=`#_notifyAllSubscribers(${e})`;this._debug(r,"begin",t,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:t});const r=[],i=Array.from(this.stateChangeEmitters.values()).map(async n=>{try{await n.callback(e,t)}catch(e){r.push(e)}});if(await Promise.all(i),r.length>0){for(let e=0;e<r.length;e+=1)console.error(r[e]);throw r[0]}}finally{this._debug(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;const t=Object.assign({},e),n=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!n&&t.user&&await Fn(this.userStorage,this.storageKey+"-user",{user:t.user});const e=Object.assign({},t);delete e.user;const r=Zn(e);await Fn(this.storage,this.storageKey,r)}else{const e=Zn(t);await Fn(this.storage,this.storageKey,e)}}async _removeSession(){this._debug("#_removeSession()"),await Kn(this.storage,this.storageKey),await Kn(this.storage,this.storageKey+"-code-verifier"),await Kn(this.storage,this.storageKey+"-user"),this.userStorage&&await Kn(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Dn()&&(null===window||void 0===window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),an);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&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:n}}=t;if(!n||!n.refresh_token||!n.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");const r=Math.floor((1e3*n.expires_at-e)/an);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),r<=3&&await this._callRefreshToken(n.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(!(e.isAcquireTimeout||e instanceof pr))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Dn()||!(null===window||void 0===window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null===window||void 0===window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{"visible"===document.visibilityState?await this._recoverAndRefresh():this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting")}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,n){const r=[`provider=${encodeURIComponent(t)}`];if((null==n?void 0:n.redirectTo)&&r.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),(null==n?void 0:n.scopes)&&r.push(`scopes=${encodeURIComponent(n.scopes)}`),"pkce"===this.flowType){const[e,t]=await Hn(this.storage,this.storageKey),n=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});r.push(n.toString())}if(null==n?void 0:n.queryParams){const e=new URLSearchParams(n.queryParams);r.push(e.toString())}return(null==n?void 0:n.skipBrowserRedirect)&&r.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var n;const{data:r,error:i}=t;return i?this._returnResult({data:null,error:i}):await rr(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(n=null==r?void 0:r.session)||void 0===n?void 0:n.access_token})})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{var n,r;const{data:i,error:s}=t;if(s)return this._returnResult({data:null,error:s});const o=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:a,error:c}=await rr(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:null===(n=null==i?void 0:i.session)||void 0===n?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):("totp"===e.factorType&&"totp"===a.type&&(null===(r=null==a?void 0:a.totp)||void 0===r?void 0:r.qr_code)&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),this._returnResult({data:a,error:null}))})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var n;const{data:r,error:i}=t;if(i)return this._returnResult({data:null,error:i});const s=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?Or(e.webauthn.credential_response):xr(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:a}=await rr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:s,headers:this.headers,jwt:null===(n=null==r?void 0:r.session)||void 0===n?void 0:n.access_token});return a?this._returnResult({data:null,error:a}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),this._returnResult({data:o,error:a}))})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var n;const{data:r,error:i}=t;if(i)return this._returnResult({data:null,error:i});const s=await rr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null===(n=null==r?void 0:r.session)||void 0===n?void 0:n.access_token});if(s.error)return s;const{data:o}=s;if("webauthn"!==o.type)return{data:o,error:null};switch(o.webauthn.type){case"create":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Er(o.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:Tr(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}})}async _challengeAndVerify(e){const{data:t,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;const{data:{user:t},error:n}=await this.getUser();if(n)return{data:null,error:n};const r={all:[],phone:[],totp:[],webauthn:[]};for(const n of null!==(e=null==t?void 0:t.factors)&&void 0!==e?e:[])r.all.push(n),"verified"===n.status&&r[n.factor_type].push(n);return{data:r,error:null}}async _getAuthenticatorAssuranceLevel(){var e,t;const{data:{session:n},error:r}=await this.getSession();if(r)return this._returnResult({data:null,error:r});if(!n)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:i}=Wn(n.access_token);let s=null;i.aal&&(s=i.aal);let o=s;(null!==(t=null===(e=n.user.factors)||void 0===e?void 0:e.filter(e=>"verified"===e.status))&&void 0!==t?t:[]).length>0&&(o="aal2");return{data:{currentLevel:s,nextLevel:o,currentAuthenticationMethods:i.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;return r?this._returnResult({data:null,error:r}):n?await rr(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new wn})})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async n=>{const{data:{session:r},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!r)return this._returnResult({data:null,error:new wn});const s=await rr(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:r.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return s.data&&s.data.redirect_url&&Dn()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(s.data.redirect_url),s})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async n=>{const{data:{session:r},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!r)return this._returnResult({data:null,error:new wn});const s=await rr(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:r.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return s.data&&s.data.redirect_url&&Dn()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(s.data.redirect_url),s})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:t},error:n}=e;return n?this._returnResult({data:null,error:n}):t?await rr(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new wn})})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;return r?this._returnResult({data:null,error:r}):n?(await rr(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new wn})})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let n=t.keys.find(t=>t.kid===e);if(n)return n;const r=Date.now();if(n=this.jwks.keys.find(t=>t.kid===e),n&&this.jwks_cached_at+6e5>r)return n;const{data:i,error:s}=await rr(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(s)throw s;return i.keys&&0!==i.keys.length?(this.jwks=i,this.jwks_cached_at=r,n=i.keys.find(t=>t.kid===e),n||null):null}async getClaims(e,t={}){try{let n=e;if(!n){const{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});n=e.session.access_token}const{header:r,payload:i,signature:s,raw:{header:o,payload:a}}=Wn(n);(null==t?void 0:t.allowExpired)||function(e){if(!e)throw new Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw new Error("JWT has expired")}(i.exp);const c=r.alg&&!r.alg.startsWith("HS")&&r.kid&&"crypto"in globalThis&&"subtle"in globalThis.crypto?await this.fetchJwk(r.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks):null;if(!c){const{error:e}=await this.getUser(n);if(e)throw e;return{data:{claims:i,header:r,signature:s},error:null}}const l=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}(r.alg),u=await crypto.subtle.importKey("jwk",c,l,!0,["verify"]);if(!await crypto.subtle.verify(l,u,s,Un(`${o}.${a}`)))throw new On("Invalid JWT signature");return{data:{claims:i,header:r,signature:s},error:null}}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}}Dr.nextInstanceID={};const Br=Dr;class Lr extends Br{constructor(e){super(e)}}class qr{constructor(e,t,n){var r,i,s;this.supabaseUrl=e,this.supabaseKey=t;const o=function(e){const t=null==e?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL((n=t).endsWith("/")?n:n+"/")}catch(e){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}var n}(e);if(!t)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",o),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",o),this.storageUrl=new URL("storage/v1",o),this.functionsUrl=new URL("functions/v1",o);const a=`sb-${o.hostname.split(".")[0]}-auth-token`,c=function(e,t){var n,r;const{db:i,auth:s,realtime:o,global:a}=e,{db:c,auth:l,realtime:u,global:d}=t,h={db:Object.assign(Object.assign({},c),i),auth:Object.assign(Object.assign({},l),s),realtime:Object.assign(Object.assign({},u),o),storage:{},global:Object.assign(Object.assign(Object.assign({},d),a),{headers:Object.assign(Object.assign({},null!==(n=null==d?void 0:d.headers)&&void 0!==n?n:{}),null!==(r=null==a?void 0:a.headers)&&void 0!==r?r:{})}),accessToken:async()=>""};return e.accessToken?h.accessToken=e.accessToken:delete h.accessToken,h}(null!=n?n:{},{db:en,realtime:nn,auth:Object.assign(Object.assign({},tn),{storageKey:a}),global:Zt});this.storageKey=null!==(r=c.auth.storageKey)&&void 0!==r?r:"",this.headers=null!==(i=c.global.headers)&&void 0!==i?i:{},c.accessToken?(this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!==(s=c.auth)&&void 0!==s?s:{},this.headers,c.global.fetch),this.fetch=sn(t,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},c.realtime)),this.accessToken&&this.accessToken().then(e=>this.realtime.setAuth(e)).catch(e=>console.warn("Failed to set initial Realtime auth token:",e)),this.rest=new ge(new URL("rest/v1",o).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this.storage=new Qt(this.storageUrl.href,this.headers,this.fetch,null==n?void 0:n.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new z(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={},n={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,n)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t;if(this.accessToken)return await this.accessToken();const{data:n}=await this.auth.getSession();return null!==(t=null===(e=n.session)||void 0===e?void 0:e.access_token)&&void 0!==t?t:this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:i,storageKey:s,flowType:o,lock:a,debug:c,throwOnError:l},u,d){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Lr({url:this.authUrl.href,headers:Object.assign(Object.assign({},h),u),storageKey:s,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:i,flowType:o,lock:a,debug:c,throwOnError:l,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new nt(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,n){"TOKEN_REFRESHED"!==e&&"SIGNED_IN"!==e||this.changedAccessToken===n?"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.changedAccessToken=n,this.realtime.setAuth(n))}}(function(){if("undefined"!=typeof window)return!1;if("undefined"==typeof process)return!1;const e=process.version;if(null==e)return!1;const t=e.match(/^v(\d+)\./);return!!t&&parseInt(t[1],10)<=18})()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");class Fr{mergeConfigs(e){const t="undefined"!=typeof window?window.APP_CONFIG:null;if(!e&&!t)throw new Error("MoneyBar: No configuration provided. Either pass config to constructor or set window.APP_CONFIG");return e?t?{...t,...e}:e:t}constructor(e){this.currentUser=null,this.userFingerprint=null,this.eventListeners=new Map,this.supabaseConnectionFailed=!1,this.paymentConnectionFailed=!1,this.securityKeyFailed=!1,this.cachedStatus=null,this.statusCacheTime=0,this.STATUS_CACHE_DURATION=5e3,this.initializationPromise=null,this.cachedPremiumStatus=null,this.premiumStatusCacheTime=0,this.config=this.mergeConfigs(e),this.config.options,this.validateConfig(),this.initializeSupabase(),this.initializePayment(),this.initializeFingerprint(),this.setupAuthListener(),this.checkPaymentStatus()}async handleDownload(){try{if(this.securityKeyFailed)return void this.showError("Invalid Security Key","Your security key is invalid, expired, or not found. Please check your MoneyBar configuration and ensure you have a valid security_key.");if(this.supabaseConnectionFailed)return void this.config.callbacks?.onError?.(new Error("Server connection required for download verification. Please check your configuration."));if(this.config.payment&&this.paymentConnectionFailed)return void this.config.callbacks?.onError?.(new Error("Payment configuration error. Please contact support."));if(this.currentUser){if(await this.checkPremiumStatus(this.currentUser.email))return void this.config.callbacks?.onPremiumDownload()}const e=await this.getDownloadStatus();if(e.currentCount>=e.limit)return void this.config.callbacks?.onLimitReached(e.currentCount,e.limit);await this.incrementDownloadCount(),this.config.callbacks?.onDownloadAllowed(),this.cachedStatus=null;const t=await this.getDownloadStatus();this.emit("countChanged",{count:t.currentCount,limit:t.limit}),t.currentCount>=t.limit&&setTimeout(()=>{this.config.callbacks?.onLimitReached(t.currentCount,t.limit)},100)}catch(e){this.handleError(e)}}async getDownloadStatus(e=!1){console.log(`🔍 [INIT] getDownloadStatus called (forceRefresh: ${e}) at ${(new Date).toISOString()}`);const t=this.cachedStatus?Date.now()-this.statusCacheTime:-1;if(!e&&this.cachedStatus&&t<this.STATUS_CACHE_DURATION)return console.log(`🔍 [INIT] Using cached status (age: ${t}ms)`),this.cachedStatus;if(!e&&this.initializationPromise)return console.log("🔍 [INIT] Waiting for existing initialization promise"),await this.initializationPromise;console.log(`🔍 [INIT] Starting new status fetch (cache age: ${t}ms)`),this.initializationPromise=this.fetchFreshStatus(e);try{const e=await this.initializationPromise;return console.log("🔍 [INIT] Status fetch completed successfully"),e}finally{this.initializationPromise=null}}async fetchFreshStatus(e){try{let t=0,n=!1;if(e||!this.cachedStatus){if(t=await this.getDownloadCount(),this.securityKeyFailed)return{currentCount:0,limit:this.config.freeAttemptLimit,isPremium:!1,isAuthenticated:!1,remaining:0}}else t=this.cachedStatus.currentCount;if(this.currentUser){const t=null!==this.cachedPremiumStatus&&Date.now()-this.premiumStatusCacheTime<this.STATUS_CACHE_DURATION;e||!t?(console.log(`🔥 [SUPABASE API] About to call checkPremiumStatus from getDownloadStatus (forceRefresh: ${e}, cacheValid: ${t})`),n=await this.checkPremiumStatus(this.currentUser.email),this.cachedPremiumStatus=n,this.premiumStatusCacheTime=Date.now()):(n=this.cachedPremiumStatus,console.log(`🔍 [CACHE] Using cached premium status from getDownloadStatus: ${n}`))}else n=!1;const r={currentCount:t,limit:this.config.freeAttemptLimit,isPremium:n,isAuthenticated:!!this.currentUser,remaining:Math.max(0,this.config.freeAttemptLimit-t)};return this.cachedStatus=r,this.statusCacheTime=Date.now(),r}catch(e){this.handleError(e);const t={currentCount:0,limit:this.config.freeAttemptLimit,isPremium:!1,isAuthenticated:!1,remaining:this.config.freeAttemptLimit};return this.cachedStatus=t,this.statusCacheTime=Date.now(),t}}async getUserContext(){const e=await this.getDownloadStatus();return{isPremium:e.isPremium,isAuthenticated:e.isAuthenticated,email:this.currentUser?.email,name:this.currentUser?.user_metadata?.full_name||this.currentUser?.user_metadata?.name,currentCount:e.currentCount,remaining:e.remaining,limit:e.limit,user:this.currentUser}}async signIn(){try{const{error:e}=await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}${window.location.pathname}`}});if(e)throw e}catch(e){this.handleError(e)}}async signOut(){try{await this.supabase.auth.signOut(),this.currentUser=null,this.emit("authChanged",{user:null,isPremium:!1})}catch(e){this.handleError(e)}}async createPayment(){if(!this.currentUser)throw new Error("User must be signed in to create payment");if(!this.config.payment)throw new Error("Payment configuration not provided");const e=this.config.payment?.find(e=>"dodo"===e.provider);if(!e)throw new Error("No dodo payment provider configured");const t={email:this.currentUser.email,product_id:e.productId,mode:e.mode||"test",app_id:this.config.appId,return_url:`${window.location.origin}${window.location.pathname}?payment=success`};console.log(`🔥 [PAYMENT API] createPayment called for provider: ${e.provider}, email: ${this.currentUser.email} | Time: ${(new Date).toISOString()}`);try{let n;if("dodo"!==e.provider)throw new Error(`Payment provider '${e.provider}' is not yet supported`);if(n=await fetch(`${this.config.supabase.url}/functions/v1/create-payment`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.supabase.anonKey}`},body:JSON.stringify(t)}),console.log(`🔥 [PAYMENT API] createPayment response for ${e.provider}: ${n.status}`),this.config.options,!n.ok){const e=await n.text();let t;this.config.options?.debug&&console.error("🔍 DEBUG: createPayment error response:",e);try{t=JSON.parse(e)}catch{t={error:e}}throw(e.includes("404")||e.includes("could not be found"))&&(this.paymentConnectionFailed=!0,this.config.options?.debug&&console.warn("Invalid payment product ID detected, disabling downloads"),this.updateStatusDisplays()),new Error(t.error||"Payment creation failed")}const r=await n.json();return this.config.options,r}catch(e){return this.handleError(e),null}}attachToButton(e,t){const n=document.querySelector(e);if(!n)throw new Error(`Button not found: ${e}`);this.injectBaseStyles(),this.createTitleBar(),this.createPaywallModal(),this.createSuccessModal(),this.createAuthUI(),this.createStatusDisplay(),n.setAttribute("data-leadfast-attached","true"),n.onclick=async e=>{e.preventDefault(),await this.handleButtonClick(t)},this.setupUIUpdates()}attachToButtons(e){this.injectBaseStyles(),this.createTitleBar(),this.createPaywallModal(),this.createSuccessModal(),this.createAuthUI(),e.buttons.forEach(e=>{const t=document.querySelector(e.selector);t?(t.setAttribute("data-leadfast-attached","true"),t.onclick=async t=>{t.preventDefault(),await this.handleButtonClick(e.downloadCallback)},this.setupUIUpdates()):console.warn(`Button not found: ${e.selector}`)}),this.createGlobalStatusDisplay()}async handleButtonClick(e){const t=document.querySelector('[data-leadfast-attached="true"]');if(t&&t.disabled)console.log("⚠️ Button click ignored - operation already in progress");else{t&&(t.disabled=!0,t.style.opacity="0.6");try{await this.handleButtonClickInternal(e)}finally{t&&(t.disabled=!1,t.style.opacity="1")}}}async handleButtonClickInternal(e){if(this.supabaseConnectionFailed)return void this.showConnectionError();if(this.config.payment&&this.paymentConnectionFailed)return void this.showPaymentConfigError();const t=this.cachedStatus&&Date.now()-this.statusCacheTime<this.STATUS_CACHE_DURATION?this.cachedStatus:await this.getDownloadStatus();if(t.isPremium){const t=await this.getUserContext();return void(e.length>0?e(t):e())}if(t.currentCount>=t.limit)this.showPaywallInstant(t);else{try{if(e.length>0){const t=await this.getUserContext();t.isPremium||(t.currentCount+=1,t.remaining=Math.max(0,t.limit-t.currentCount)),e(t)}else e();const t=await this.getDownloadStatus(!0);if(t.currentCount>=t.limit)return console.warn(`⚠️ Limit reached during execution (${t.currentCount}/${t.limit}) - canceling increment`),void alert("⚠️ You reached the limit while this action was processing. No attempt was counted.");const n=await this.incrementDownloadCount();if(n>this.config.freeAttemptLimit)return void console.error(`⚠️ Server returned count (${n}) exceeding limit (${this.config.freeAttemptLimit})`);if(!0===this.config.successMessage?.enabled){const e=this.config.successMessage?.title||"Action Completed!",t=this.config.successMessage?.message||"Your action completed successfully!";this.showSuccess(e,t)}}catch(e){return console.error("User function failed:",e),void alert("Action failed. Please check the console for details. No attempt was counted.")}this.cachedStatus=null,this.updateStatusDisplays()}}injectBaseStyles(){if(document.getElementById("lead-fast-styles"))return;this.config.theme?.name&&this.injectDaisyUI();const e=document.createElement("style");e.id="lead-fast-styles";const t=this.config.theme?.primaryColor||"#3182ce";e.textContent=`\n /* User Profile Card - Top Right */\n .lead-fast-profile {\n position: fixed;\n top: 20px;\n left: 50%;\n transform: translateX(-50%);\n z-index: 1000;\n font-family: system-ui, -apple-system, sans-serif;\n width: 90%;\n max-width: 1200px;\n }\n\n .lead-fast-title-bar {\n background: rgba(250, 247, 245, 0.9) !important;\n border: 1px solid rgba(231, 226, 223, 0.6) !important;\n color: #291334 !important;\n border-radius: 16px;\n padding: 12px 24px;\n box-shadow: 0 8px 32px rgb(0 0 0 / 0.1), 0 2px 8px rgb(0 0 0 / 0.05);\n backdrop-filter: blur(20px);\n display: flex;\n align-items: center;\n justify-content: space-between;\n min-height: 60px;\n font-family: system-ui, -apple-system, sans-serif;\n }\n\n /* Theme variations for floating title bar */\n [data-theme="bumblebee"] .lead-fast-title-bar {\n background: rgba(255, 248, 220, 0.9) !important;\n border-color: rgba(254, 215, 170, 0.6) !important;\n color: #1c1917 !important;\n }\n\n [data-theme="garden"] .lead-fast-title-bar {\n background: rgba(240, 253, 244, 0.9) !important;\n border-color: rgba(134, 239, 172, 0.6) !important;\n color: #14532d !important;\n }\n\n [data-theme="emerald"] .lead-fast-title-bar {\n background: rgba(236, 253, 245, 0.9) !important;\n border-color: rgba(167, 243, 208, 0.6) !important;\n color: #065f46 !important;\n }\n\n [data-theme="corporate"] .lead-fast-title-bar {\n background: rgba(248, 250, 252, 0.9) !important;\n border-color: rgba(226, 232, 240, 0.6) !important;\n color: #1e293b !important;\n }\n\n [data-theme="dark"] .lead-fast-title-bar {\n background: rgba(31, 41, 55, 0.9) !important;\n border-color: rgba(55, 65, 81, 0.6) !important;\n color: #f9fafb !important;\n }\n\n [data-theme="cyberpunk"] .lead-fast-title-bar {\n background: rgba(0, 20, 36, 0.9) !important;\n border-color: rgba(7, 89, 133, 0.6) !important;\n color: #0ea5e9 !important;\n box-shadow: 0 8px 32px rgba(14, 165, 233, 0.2), 0 2px 8px rgba(14, 165, 233, 0.1);\n }\n\n [data-theme="valentine"] .lead-fast-title-bar {\n background: rgba(233, 30, 122, 0.15) !important;\n border-color: rgba(233, 30, 122, 0.6) !important;\n color: #831843 !important;\n }\n\n [data-theme="synthwave"] .lead-fast-title-bar {\n background: rgba(32, 20, 64, 0.9) !important;\n border-color: rgba(186, 85, 211, 0.6) !important;\n color: #ff00ff !important;\n box-shadow: 0 8px 32px rgba(255, 0, 255, 0.2), 0 2px 8px rgba(255, 0, 255, 0.1);\n }\n\n [data-theme="dracula"] .lead-fast-title-bar {\n background: rgba(40, 42, 54, 0.9) !important;\n border-color: rgba(98, 114, 164, 0.6) !important;\n color: #f8f8f2 !important;\n }\n\n [data-theme="halloween"] .lead-fast-title-bar {\n background: rgba(26, 26, 26, 0.9) !important;\n border-color: rgba(255, 165, 0, 0.6) !important;\n color: #ff6600 !important;\n }\n\n [data-theme="forest"] .lead-fast-title-bar {\n background: rgba(23, 46, 23, 0.9) !important;\n border-color: rgba(34, 197, 94, 0.6) !important;\n color: #22c55e !important;\n }\n\n [data-theme="luxury"] .lead-fast-title-bar {\n background: rgba(9, 9, 11, 0.9) !important;\n border-color: rgba(212, 175, 55, 0.6) !important;\n color: #d4af37 !important;\n }\n\n [data-theme="night"] .lead-fast-title-bar {\n background: rgba(15, 23, 42, 0.9) !important;\n border-color: rgba(30, 58, 138, 0.6) !important;\n color: #60a5fa !important;\n }\n\n [data-theme="light"] .lead-fast-title-bar {\n background: rgba(255, 255, 255, 0.9) !important;\n border-color: rgba(229, 231, 235, 0.6) !important;\n color: #1f2937 !important;\n }\n\n [data-theme="cupcake"] .lead-fast-title-bar {\n background: rgba(250, 235, 215, 0.9) !important;\n border-color: rgba(219, 185, 156, 0.6) !important;\n color: #8b4513 !important;\n }\n\n [data-theme="retro"] .lead-fast-title-bar {\n background: rgba(212, 165, 116, 0.9) !important;\n border-color: rgba(185, 144, 102, 0.6) !important;\n color: #5d4037 !important;\n }\n\n [data-theme="aqua"] .lead-fast-title-bar {\n background: rgba(240, 253, 250, 0.9) !important;\n border-color: rgba(125, 211, 252, 0.6) !important;\n color: #155e75 !important;\n }\n\n [data-theme="lofi"] .lead-fast-title-bar {\n background: rgba(248, 248, 248, 0.9) !important;\n border-color: rgba(68, 68, 68, 0.6) !important;\n color: #1a1a1a !important;\n }\n\n [data-theme="pastel"] .lead-fast-title-bar {\n background: rgba(254, 251, 255, 0.9) !important;\n border-color: rgba(209, 196, 233, 0.6) !important;\n color: #7c3aed !important;\n }\n\n [data-theme="fantasy"] .lead-fast-title-bar {\n background: rgba(255, 247, 237, 0.9) !important;\n border-color: rgba(249, 168, 212, 0.6) !important;\n color: #be185d !important;\n }\n\n [data-theme="wireframe"] .lead-fast-title-bar {\n background: rgba(223, 223, 223, 0.9) !important;\n border-color: rgba(0, 0, 0, 0.3) !important;\n color: #000000 !important;\n }\n\n [data-theme="black"] .lead-fast-title-bar {\n background: rgba(0, 0, 0, 0.9) !important;\n border-color: rgba(55, 55, 55, 0.6) !important;\n color: #ffffff !important;\n }\n\n [data-theme="cmyk"] .lead-fast-title-bar {\n background: rgba(0, 255, 255, 0.9) !important;\n border-color: rgba(255, 0, 255, 0.6) !important;\n color: #000000 !important;\n }\n\n [data-theme="autumn"] .lead-fast-title-bar {\n background: rgba(139, 69, 19, 0.9) !important;\n border-color: rgba(255, 140, 0, 0.6) !important;\n color: #ff8c00 !important;\n }\n\n [data-theme="business"] .lead-fast-title-bar {\n background: rgba(29, 78, 216, 0.9) !important;\n border-color: rgba(59, 130, 246, 0.6) !important;\n color: #3b82f6 !important;\n }\n\n [data-theme="acid"] .lead-fast-title-bar {\n background: rgba(255, 255, 0, 0.9) !important;\n border-color: rgba(255, 0, 255, 0.6) !important;\n color: #000000 !important;\n }\n\n [data-theme="lemonade"] .lead-fast-title-bar {\n background: rgba(255, 255, 224, 0.9) !important;\n border-color: rgba(34, 197, 94, 0.6) !important;\n color: #15803d !important;\n }\n\n [data-theme="coffee"] .lead-fast-title-bar {\n background: rgba(101, 67, 33, 0.9) !important;\n border-color: rgba(160, 82, 45, 0.6) !important;\n color: #d2b48c !important;\n }\n\n [data-theme="winter"] .lead-fast-title-bar {\n background: rgba(248, 250, 252, 0.9) !important;\n border-color: rgba(59, 130, 246, 0.6) !important;\n color: #1e40af !important;\n }\n\n .lead-fast-title-section {\n display: flex;\n align-items: center;\n gap: 16px;\n }\n\n .lead-fast-logo {\n font-size: 20px;\n font-weight: 700;\n display: flex;\n align-items: center;\n gap: 8px;\n color: inherit;\n text-decoration: none;\n }\n\n .lead-fast-logo img {\n width: 32px;\n height: 32px;\n border-radius: 6px;\n }\n\n .lead-fast-nav {\n display: flex;\n align-items: center;\n gap: 32px;\n margin-left: 24px;\n }\n\n .lead-fast-nav-link {\n color: inherit;\n text-decoration: none;\n font-weight: 500;\n font-size: 14px;\n opacity: 0.8;\n transition: all 0.2s;\n }\n\n .lead-fast-nav-link:hover {\n opacity: 1;\n text-decoration: none;\n }\n\n .lead-fast-user-section {\n display: flex;\n align-items: center;\n gap: 12px;\n }\n\n .lead-fast-avatar {\n width: 36px;\n height: 36px;\n border-radius: 50%;\n background: linear-gradient(135deg, ${t}, #4f46e5);\n display: flex;\n align-items: center;\n justify-content: center;\n color: white;\n font-weight: 600;\n font-size: 14px;\n }\n\n .lead-fast-user-info {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n gap: 2px;\n }\n\n .lead-fast-user-email {\n color: inherit !important;\n font-size: 13px;\n font-weight: 500;\n line-height: 1;\n }\n\n .lead-fast-user-status {\n display: flex;\n align-items: center;\n gap: 6px;\n }\n\n .lead-fast-badge {\n padding: 2px 6px;\n border-radius: 12px;\n font-size: 10px;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.025em;\n line-height: 1;\n }\n\n .lead-fast-badge.premium {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n .lead-fast-badge.free {\n background: #65c3c8 !important;\n color: #291334 !important;\n }\n\n [data-theme="dark"] .lead-fast-badge.premium {\n background: #059669 !important;\n color: #ffffff !important;\n }\n\n [data-theme="dark"] .lead-fast-badge.free {\n background: #374151 !important;\n color: #f9fafb !important;\n }\n\n .lead-fast-count {\n font-size: 10px;\n color: inherit !important;\n opacity: 0.7;\n line-height: 1;\n }\n\n .lead-fast-signout {\n background: rgba(0, 0, 0, 0.1) !important;\n border: none;\n color: inherit !important;\n cursor: pointer;\n padding: 6px 12px;\n border-radius: 8px;\n transition: all 0.2s;\n font-size: 11px;\n font-weight: 500;\n margin-left: 8px;\n }\n\n [data-theme="dark"] .lead-fast-signout {\n background: rgba(255, 255, 255, 0.1) !important;\n }\n\n [data-theme="cyberpunk"] .lead-fast-signout {\n background: rgba(14, 165, 233, 0.2) !important;\n }\n\n .lead-fast-signout:hover {\n background: rgba(0, 0, 0, 0.2) !important;\n transform: translateY(-1px);\n }\n\n [data-theme="dark"] .lead-fast-signout:hover {\n background: rgba(255, 255, 255, 0.2) !important;\n }\n\n [data-theme="cyberpunk"] .lead-fast-signout:hover {\n background: rgba(14, 165, 233, 0.3) !important;\n }\n\n .lead-fast-branding {\n position: absolute;\n bottom: -20px;\n left: 24px;\n font-size: 9px;\n color: inherit !important;\n opacity: 0.4;\n font-weight: 500;\n letter-spacing: 0.05em;\n text-transform: lowercase;\n background: rgba(255, 255, 255, 0.8);\n padding: 2px 6px;\n border-radius: 4px;\n backdrop-filter: blur(8px);\n }\n\n [data-theme="dark"] .lead-fast-branding {\n background: rgba(0, 0, 0, 0.6);\n }\n\n [data-theme="cyberpunk"] .lead-fast-branding {\n background: rgba(0, 20, 36, 0.8);\n }\n\n /* Modal Theming */\n .download-limiter-modal {\n display: none;\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0,0,0,0.5);\n z-index: 9999;\n align-items: center;\n justify-content: center;\n }\n .download-limiter-modal.show { display: flex; }\n\n .download-limiter-content {\n background: #faf7f5 !important;\n color: #291334 !important;\n padding: 2rem;\n border-radius: 12px;\n max-width: 400px;\n text-align: center;\n box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);\n border: 1px solid #e7e2df !important;\n font-family: system-ui, -apple-system, sans-serif;\n }\n\n [data-theme="dark"] .download-limiter-content {\n background: #1f2937 !important;\n color: #f9fafb !important;\n border-color: #374151 !important;\n }\n\n [data-theme="cyberpunk"] .download-limiter-content {\n background: #001424 !important;\n color: #0ea5e9 !important;\n border-color: #075985 !important;\n }\n\n [data-theme="valentine"] .download-limiter-content {\n background: rgba(233, 30, 122, 0.05) !important;\n color: #831843 !important;\n border-color: #e91e7a !important;\n }\n\n [data-theme="bumblebee"] .download-limiter-content {\n background: rgba(255, 248, 220, 0.95) !important;\n color: #1c1917 !important;\n border-color: rgba(254, 215, 170, 0.8) !important;\n }\n\n [data-theme="garden"] .download-limiter-content {\n background: rgba(240, 253, 244, 0.95) !important;\n color: #14532d !important;\n border-color: rgba(134, 239, 172, 0.8) !important;\n }\n\n [data-theme="emerald"] .download-limiter-content {\n background: rgba(236, 253, 245, 0.95) !important;\n color: #065f46 !important;\n border-color: rgba(167, 243, 208, 0.8) !important;\n }\n\n [data-theme="corporate"] .download-limiter-content {\n background: rgba(248, 250, 252, 0.95) !important;\n color: #1e293b !important;\n border-color: rgba(226, 232, 240, 0.8) !important;\n }\n\n [data-theme="forest"] .download-limiter-content {\n background: rgba(23, 46, 23, 0.95) !important;\n color: #22c55e !important;\n border-color: rgba(34, 197, 94, 0.8) !important;\n }\n\n [data-theme="halloween"] .download-limiter-content {\n background: rgba(26, 26, 26, 0.95) !important;\n color: #ff6500 !important;\n border-color: rgba(255, 165, 0, 0.3) !important;\n }\n\n [data-theme="synthwave"] .download-limiter-content {\n background: rgba(32, 20, 64, 0.95) !important;\n color: #ba55d3 !important;\n border-color: rgba(186, 85, 211, 0.3) !important;\n }\n\n [data-theme="dracula"] .download-limiter-content {\n background: rgba(40, 42, 54, 0.95) !important;\n color: #f8f8f2 !important;\n border-color: rgba(98, 114, 164, 0.3) !important;\n }\n\n [data-theme="luxury"] .download-limiter-content {\n background: rgba(9, 9, 11, 0.95) !important;\n color: #d4af37 !important;\n border-color: rgba(212, 175, 55, 0.3) !important;\n }\n\n [data-theme="night"] .download-limiter-content {\n background: rgba(15, 23, 42, 0.95) !important;\n color: #1e40af !important;\n border-color: rgba(30, 58, 138, 0.3) !important;\n }\n\n [data-theme="light"] .download-limiter-content {\n background: rgba(255, 255, 255, 0.95) !important;\n color: #1f2937 !important;\n border-color: rgba(229, 231, 235, 0.8) !important;\n }\n\n [data-theme="cupcake"] .download-limiter-content {\n background: rgba(250, 235, 215, 0.95) !important;\n color: #8b4513 !important;\n border-color: rgba(219, 185, 156, 0.8) !important;\n }\n\n [data-theme="retro"] .download-limiter-content {\n background: rgba(212, 165, 116, 0.95) !important;\n color: #5d4037 !important;\n border-color: rgba(185, 144, 102, 0.8) !important;\n }\n\n [data-theme="aqua"] .download-limiter-content {\n background: rgba(240, 253, 250, 0.95) !important;\n color: #155e75 !important;\n border-color: rgba(125, 211, 252, 0.8) !important;\n }\n\n [data-theme="lofi"] .download-limiter-content {\n background: rgba(248, 248, 248, 0.95) !important;\n color: #1a1a1a !important;\n border-color: rgba(68, 68, 68, 0.8) !important;\n }\n\n [data-theme="pastel"] .download-limiter-content {\n background: rgba(254, 251, 255, 0.95) !important;\n color: #7c3aed !important;\n border-color: rgba(209, 196, 233, 0.8) !important;\n }\n\n [data-theme="fantasy"] .download-limiter-content {\n background: rgba(255, 247, 237, 0.95) !important;\n color: #be185d !important;\n border-color: rgba(249, 168, 212, 0.8) !important;\n }\n\n [data-theme="wireframe"] .download-limiter-content {\n background: rgba(255, 255, 255, 0.95) !important;\n color: #000000 !important;\n border-color: rgba(0, 0, 0, 0.3) !important;\n }\n\n [data-theme="black"] .download-limiter-content {\n background: rgba(0, 0, 0, 0.95) !important;\n color: #ffffff !important;\n border-color: rgba(55, 55, 55, 0.8) !important;\n }\n\n [data-theme="cmyk"] .download-limiter-content {\n background: rgba(0, 255, 255, 0.95) !important;\n color: #000000 !important;\n border-color: rgba(255, 0, 255, 0.8) !important;\n }\n\n [data-theme="autumn"] .download-limiter-content {\n background: rgba(139, 69, 19, 0.95) !important;\n color: #ff8c00 !important;\n border-color: rgba(255, 140, 0, 0.8) !important;\n }\n\n [data-theme="business"] .download-limiter-content {\n background: rgba(29, 78, 216, 0.95) !important;\n color: #3b82f6 !important;\n border-color: rgba(59, 130, 246, 0.8) !important;\n }\n\n [data-theme="acid"] .download-limiter-content {\n background: rgba(255, 255, 0, 0.95) !important;\n color: #000000 !important;\n border-color: rgba(255, 0, 255, 0.8) !important;\n }\n\n [data-theme="lemonade"] .download-limiter-content {\n background: rgba(255, 255, 224, 0.95) !important;\n color: #15803d !important;\n border-color: rgba(34, 197, 94, 0.8) !important;\n }\n\n [data-theme="coffee"] .download-limiter-content {\n background: rgba(101, 67, 33, 0.95) !important;\n color: #d2b48c !important;\n border-color: rgba(160, 82, 45, 0.8) !important;\n }\n\n [data-theme="winter"] .download-limiter-content {\n background: rgba(248, 250, 252, 0.95) !important;\n color: #1e40af !important;\n border-color: rgba(59, 130, 246, 0.8) !important;\n }\n\n .download-limiter-content h2 {\n color: inherit !important;\n margin: 0 0 1rem 0;\n font-size: 1.5rem;\n font-weight: 600;\n }\n .download-limiter-content p {\n color: inherit !important;\n margin: 0 0 1.5rem 0;\n line-height: 1.6;\n }\n .download-limiter-signin-btn {\n display: inline-flex;\n align-items: center;\n gap: 8px;\n background: #65c3c8 !important;\n color: #291334 !important;\n border: none;\n padding: 12px 20px;\n border-radius: 8px;\n font-size: 14px;\n font-weight: 500;\n cursor: pointer;\n text-decoration: none;\n transition: all 0.2s;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n }\n\n [data-theme="dark"] .download-limiter-signin-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cyberpunk"] .download-limiter-signin-btn {\n background: #f59e0b !important;\n color: #000000 !important;\n }\n\n [data-theme="valentine"] .download-limiter-signin-btn {\n background: #e91e7a !important;\n color: #ffffff !important;\n }\n\n [data-theme="bumblebee"] .download-limiter-signin-btn {\n background: #fbbf24 !important;\n color: #1c1917 !important;\n }\n\n [data-theme="garden"] .download-limiter-signin-btn {\n background: #22c55e !important;\n color: #ffffff !important;\n }\n\n [data-theme="emerald"] .download-limiter-signin-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="corporate"] .download-limiter-signin-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="forest"] .download-limiter-signin-btn {\n background: #22c55e !important;\n color: #1a1a1a !important;\n }\n\n [data-theme="halloween"] .download-limiter-signin-btn {\n background: #ff6500 !important;\n color: #1a1a1a !important;\n }\n\n [data-theme="synthwave"] .download-limiter-signin-btn {\n background: #ba55d3 !important;\n color: #201040 !important;\n }\n\n [data-theme="dracula"] .download-limiter-signin-btn {\n background: #8be9fd !important;\n color: #282a36 !important;\n }\n\n [data-theme="luxury"] .download-limiter-signin-btn {\n background: #d4af37 !important;\n color: #09090b !important;\n }\n\n [data-theme="night"] .download-limiter-signin-btn {\n background: #1e40af !important;\n color: #ffffff !important;\n }\n\n [data-theme="light"] .download-limiter-signin-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cupcake"] .download-limiter-signin-btn {\n background: #8b4513 !important;\n color: #ffffff !important;\n }\n\n [data-theme="retro"] .download-limiter-signin-btn {\n background: #d4a574 !important;\n color: #ffffff !important;\n }\n\n [data-theme="aqua"] .download-limiter-signin-btn {\n background: #0891b2 !important;\n color: #ffffff !important;\n }\n\n [data-theme="lofi"] .download-limiter-signin-btn {\n background: #1a1a1a !important;\n color: #ffffff !important;\n }\n\n [data-theme="pastel"] .download-limiter-signin-btn {\n background: #7c3aed !important;\n color: #ffffff !important;\n }\n\n [data-theme="fantasy"] .download-limiter-signin-btn {\n background: #be185d !important;\n color: #ffffff !important;\n }\n\n [data-theme="wireframe"] .download-limiter-signin-btn {\n background: #dfdfdf !important;\n color: #000000 !important;\n border: 1px solid #000000 !important;\n }\n\n [data-theme="black"] .download-limiter-signin-btn {\n background: #ffffff !important;\n color: #000000 !important;\n }\n\n [data-theme="cmyk"] .download-limiter-signin-btn {\n background: #ff00ff !important;\n color: #000000 !important;\n }\n\n [data-theme="autumn"] .download-limiter-signin-btn {\n background: #ff8c00 !important;\n color: #ffffff !important;\n }\n\n [data-theme="business"] .download-limiter-signin-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="acid"] .download-limiter-signin-btn {\n background: #ff00ff !important;\n color: #000000 !important;\n }\n\n [data-theme="lemonade"] .download-limiter-signin-btn {\n background: #22c55e !important;\n color: #ffffff !important;\n }\n\n [data-theme="coffee"] .download-limiter-signin-btn {\n background: #a0522d !important;\n color: #ffffff !important;\n }\n\n [data-theme="winter"] .download-limiter-signin-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n .download-limiter-signin-btn:hover {\n opacity: 0.9;\n transform: translateY(-1px);\n box-shadow: 0 4px 8px rgba(0,0,0,0.15);\n }\n\n /* Upgrade Button Styles for All Themes */\n [data-theme="dark"] .upgrade-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cyberpunk"] .upgrade-btn {\n background: #ff073a !important;\n color: #ffffff !important;\n }\n\n [data-theme="valentine"] .upgrade-btn {\n background: #e91e7a !important;\n color: #ffffff !important;\n }\n\n [data-theme="bumblebee"] .upgrade-btn {\n background: #f59e0b !important;\n color: #ffffff !important;\n }\n\n [data-theme="garden"] .upgrade-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="emerald"] .upgrade-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="corporate"] .upgrade-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="forest"] .upgrade-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="halloween"] .upgrade-btn {\n background: #ff7b00 !important;\n color: #000000 !important;\n }\n\n [data-theme="synthwave"] .upgrade-btn {\n background: #e879f9 !important;\n color: #ffffff !important;\n }\n\n [data-theme="dracula"] .upgrade-btn {\n background: #bd93f9 !important;\n color: #ffffff !important;\n }\n\n [data-theme="luxury"] .upgrade-btn {\n background: #d4af37 !important;\n color: #000000 !important;\n }\n\n [data-theme="night"] .upgrade-btn {\n background: #38bdf8 !important;\n color: #ffffff !important;\n }\n\n [data-theme="light"] .upgrade-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cupcake"] .upgrade-btn {\n background: #f472b6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="retro"] .upgrade-btn {\n background: #d4a574 !important;\n color: #ffffff !important;\n }\n\n [data-theme="aqua"] .upgrade-btn {\n background: #06b6d4 !important;\n color: #ffffff !important;\n }\n\n [data-theme="lofi"] .upgrade-btn {\n background: #a3a3a3 !important;\n color: #000000 !important;\n }\n\n [data-theme="pastel"] .upgrade-btn {\n background: #a78bfa !important;\n color: #ffffff !important;\n }\n\n [data-theme="fantasy"] .upgrade-btn {\n background: #f472b6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="wireframe"] .upgrade-btn {\n background: #dfdfdf !important;\n color: #000000 !important;\n border: 1px solid #000000 !important;\n }\n\n [data-theme="black"] .upgrade-btn {\n background: #ffffff !important;\n color: #000000 !important;\n }\n\n [data-theme="cmyk"] .upgrade-btn {\n background: #0891b2 !important;\n color: #ffffff !important;\n }\n\n [data-theme="autumn"] .upgrade-btn {\n background: #d97706 !important;\n color: #ffffff !important;\n }\n\n [data-theme="business"] .upgrade-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="acid"] .upgrade-btn {\n background: #84cc16 !important;\n color: #000000 !important;\n }\n\n [data-theme="lemonade"] .upgrade-btn {\n background: #22c55e !important;\n color: #ffffff !important;\n }\n\n [data-theme="coffee"] .upgrade-btn {\n background: #a0522d !important;\n color: #ffffff !important;\n }\n\n [data-theme="winter"] .upgrade-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n /* Cancel Button Styles for All Themes */\n [data-theme="dark"] .cancel-btn {\n background: #4b5563 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cyberpunk"] .cancel-btn {\n background: #7e22ce !important;\n color: #ffffff !important;\n }\n\n [data-theme="valentine"] .cancel-btn {\n background: #c11560 !important;\n color: #ffffff !important;\n }\n\n [data-theme="bumblebee"] .cancel-btn {\n background: #d97706 !important;\n color: #ffffff !important;\n }\n\n [data-theme="garden"] .cancel-btn {\n background: #059669 !important;\n color: #ffffff !important;\n }\n\n [data-theme="emerald"] .cancel-btn {\n background: #059669 !important;\n color: #ffffff !important;\n }\n\n [data-theme="corporate"] .cancel-btn {\n background: #6b7280 !important;\n color: #ffffff !important;\n }\n\n [data-theme="forest"] .cancel-btn {\n background: #059669 !important;\n color: #ffffff !important;\n }\n\n [data-theme="halloween"] .cancel-btn {\n background: #7c3aed !important;\n color: #ffffff !important;\n }\n\n [data-theme="synthwave"] .cancel-btn {\n background: #7e22ce !important;\n color: #ffffff !important;\n }\n\n [data-theme="dracula"] .cancel-btn {\n background: #6272a4 !important;\n color: #ffffff !important;\n }\n\n [data-theme="luxury"] .cancel-btn {\n background: #8b5cf6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="night"] .cancel-btn {\n background: #0284c7 !important;\n color: #ffffff !important;\n }\n\n [data-theme="light"] .cancel-btn {\n background: #6b7280 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cupcake"] .cancel-btn {\n background: #ec4899 !important;\n color: #ffffff !important;\n }\n\n [data-theme="retro"] .cancel-btn {\n background: #b8925c !important;\n color: #ffffff !important;\n }\n\n [data-theme="aqua"] .cancel-btn {\n background: #0891b2 !important;\n color: #ffffff !important;\n }\n\n [data-theme="lofi"] .cancel-btn {\n background: #6b7280 !important;\n color: #ffffff !important;\n }\n\n [data-theme="pastel"] .cancel-btn {\n background: #8b5cf6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="fantasy"] .cancel-btn {\n background: #ec4899 !important;\n color: #ffffff !important;\n }\n\n [data-theme="wireframe"] .cancel-btn {\n background: #f5f5f5 !important;\n color: #000000 !important;\n border: 1px solid #000000 !important;\n }\n\n [data-theme="black"] .cancel-btn {\n background: #6b7280 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cmyk"] .cancel-btn {\n background: #0369a1 !important;\n color: #ffffff !important;\n }\n\n [data-theme="autumn"] .cancel-btn {\n background: #c2410c !important;\n color: #ffffff !important;\n }\n\n [data-theme="business"] .cancel-btn {\n background: #6b7280 !important;\n color: #ffffff !important;\n }\n\n [data-theme="acid"] .cancel-btn {\n background: #65a30d !important;\n color: #ffffff !important;\n }\n\n [data-theme="lemonade"] .cancel-btn {\n background: #16a34a !important;\n color: #ffffff !important;\n }\n\n [data-theme="coffee"] .cancel-btn {\n background: #8b4513 !important;\n color: #ffffff !important;\n }\n\n [data-theme="winter"] .cancel-btn {\n background: #1e40af !important;\n color: #ffffff !important;\n }\n\n /* Success Button Styles for All Themes */\n [data-theme="dark"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cyberpunk"] .success-btn {\n background: #00ff41 !important;\n color: #000000 !important;\n }\n\n [data-theme="valentine"] .success-btn {\n background: #e91e7a !important;\n color: #ffffff !important;\n }\n\n [data-theme="bumblebee"] .success-btn {\n background: #f59e0b !important;\n color: #ffffff !important;\n }\n\n [data-theme="garden"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="emerald"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="corporate"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="forest"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="halloween"] .success-btn {\n background: #ff7b00 !important;\n color: #000000 !important;\n }\n\n [data-theme="synthwave"] .success-btn {\n background: #00ff41 !important;\n color: #000000 !important;\n }\n\n [data-theme="dracula"] .success-btn {\n background: #50fa7b !important;\n color: #000000 !important;\n }\n\n [data-theme="luxury"] .success-btn {\n background: #d4af37 !important;\n color: #000000 !important;\n }\n\n [data-theme="night"] .success-btn {\n background: #22d3ee !important;\n color: #ffffff !important;\n }\n\n [data-theme="light"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cupcake"] .success-btn {\n background: #f472b6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="retro"] .success-btn {\n background: #d4a574 !important;\n color: #ffffff !important;\n }\n\n [data-theme="aqua"] .success-btn {\n background: #06b6d4 !important;\n color: #ffffff !important;\n }\n\n [data-theme="lofi"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="pastel"] .success-btn {\n background: #34d399 !important;\n color: #ffffff !important;\n }\n\n [data-theme="fantasy"] .success-btn {\n background: #f472b6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="wireframe"] .success-btn {\n background: #dfdfdf !important;\n color: #000000 !important;\n border: 1px solid #000000 !important;\n }\n\n [data-theme="black"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cmyk"] .success-btn {\n background: #06b6d4 !important;\n color: #ffffff !important;\n }\n\n [data-theme="autumn"] .success-btn {\n background: #d97706 !important;\n color: #ffffff !important;\n }\n\n [data-theme="business"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="acid"] .success-btn {\n background: #84cc16 !important;\n color: #000000 !important;\n }\n\n [data-theme="lemonade"] .success-btn {\n background: #22c55e !important;\n color: #ffffff !important;\n }\n\n [data-theme="coffee"] .success-btn {\n background: #a0522d !important;\n color: #ffffff !important;\n }\n\n [data-theme="winter"] .success-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n .download-limiter-signout-btn {\n background: #dc3545;\n color: white;\n border: none;\n padding: 6px 12px;\n border-radius: 4px;\n font-size: 12px;\n cursor: pointer;\n margin-left: 8px;\n }\n .download-limiter-premium-badge {\n background: linear-gradient(45deg, #f39c12, #e74c3c);\n color: white;\n padding: 2px 6px;\n border-radius: 3px;\n font-size: 10px;\n margin-left: 8px;\n font-weight: bold;\n }\n .download-limiter-btn-premium {\n opacity: 0.7;\n }\n .download-limiter-success-modal {\n display: none;\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0,0,0,0.5);\n z-index: 10000;\n align-items: center;\n justify-content: center;\n }\n .download-limiter-success-modal.show { display: flex; }\n .download-limiter-success-content {\n background: white;\n padding: 2rem;\n border-radius: 8px;\n max-width: 400px;\n text-align: center;\n box-shadow: 0 4px 20px rgba(0,0,0,0.15);\n border-left: 4px solid #38a169;\n }\n\n /* Single upgrade flow styles */\n .single-upgrade-container {\n margin: 20px 0;\n text-align: center;\n }\n\n .single-upgrade-content .upgrade-btn {\n background: linear-gradient(135deg, #059669, #0d9488) !important;\n color: white !important;\n border: none !important;\n padding: 16px 32px !important;\n border-radius: 12px !important;\n font-size: 18px !important;\n font-weight: 600 !important;\n cursor: pointer !important;\n transition: all 0.3s ease !important;\n box-shadow: 0 4px 12px rgba(5, 150, 105, 0.3) !important;\n margin-bottom: 16px !important;\n min-width: 200px !important;\n }\n\n .single-upgrade-content .upgrade-btn:hover {\n background: linear-gradient(135deg, #047857, #0f766e) !important;\n transform: translateY(-2px) !important;\n box-shadow: 0 6px 20px rgba(5, 150, 105, 0.4) !important;\n }\n\n .single-upgrade-content .upgrade-description {\n font-size: 14px !important;\n color: #6b7280 !important;\n margin: 12px 0 0 0 !important;\n line-height: 1.5 !important;\n max-width: 300px !important;\n margin-left: auto !important;\n margin-right: auto !important;\n }\n\n /* Anonymous user usage count styles */\n .lead-fast-anonymous-status {\n display: flex;\n align-items: center;\n gap: 12px;\n }\n\n .lead-fast-anonymous-status .lead-fast-count {\n background: rgba(59, 130, 246, 0.1);\n color: #1d4ed8;\n padding: 6px 12px;\n border-radius: 8px;\n font-size: 14px;\n font-weight: 500;\n border: 1px solid rgba(59, 130, 246, 0.2);\n }\n\n /* Success button theming */\n .download-limiter-btn.success-btn {\n background: #059669 !important;\n color: white !important;\n border: none !important;\n padding: 12px 24px !important;\n border-radius: 8px !important;\n cursor: pointer !important;\n margin-top: 20px !important;\n font-size: 16px !important;\n font-weight: 500 !important;\n transition: all 0.2s ease !important;\n }\n\n .download-limiter-btn.success-btn:hover {\n background: #047857 !important;\n transform: translateY(-1px) !important;\n }\n\n /* Theme-specific success button colors */\n [data-theme="cyberpunk"] .download-limiter-btn.success-btn {\n background: #0ea5e9 !important;\n box-shadow: 0 4px 12px rgba(14, 165, 233, 0.3) !important;\n }\n\n [data-theme="cyberpunk"] .download-limiter-btn.success-btn:hover {\n background: #0284c7 !important;\n }\n\n [data-theme="valentine"] .download-limiter-btn.success-btn {\n background: #be185d !important;\n }\n\n [data-theme="valentine"] .download-limiter-btn.success-btn:hover {\n background: #9d174d !important;\n }\n\n [data-theme="bumblebee"] .download-limiter-btn.success-btn {\n background: #f59e0b !important;\n }\n\n [data-theme="bumblebee"] .download-limiter-btn.success-btn:hover {\n background: #d97706 !important;\n }\n\n [data-theme="garden"] .download-limiter-btn.success-btn {\n background: #16a34a !important;\n }\n\n [data-theme="garden"] .download-limiter-btn.success-btn:hover {\n background: #15803d !important;\n }\n\n /* Google Sign-in button theming */\n .download-limiter-btn.google-signin-btn {\n background: #4285f4 !important;\n color: white !important;\n border: none !important;\n padding: 12px 24px !important;\n border-radius: 8px !important;\n cursor: pointer !important;\n margin-right: 10px !important;\n display: inline-flex !important;\n align-items: center !important;\n gap: 8px !important;\n font-size: 14px !important;\n font-weight: 500 !important;\n transition: all 0.2s ease !important;\n }\n\n .download-limiter-btn.google-signin-btn:hover {\n background: #3367d6 !important;\n transform: translateY(-1px) !important;\n }\n\n /* Upgrade button theming */\n .download-limiter-btn.upgrade-btn {\n background: #059669 !important;\n color: white !important;\n border: none !important;\n padding: 12px 24px !important;\n border-radius: 8px !important;\n cursor: pointer !important;\n margin-right: 10px !important;\n font-size: 16px !important;\n font-weight: 500 !important;\n transition: all 0.2s ease !important;\n }\n\n .download-limiter-btn.upgrade-btn:hover {\n background: #047857 !important;\n transform: translateY(-1px) !important;\n }\n\n /* Theme-specific button colors */\n [data-theme="cyberpunk"] .download-limiter-btn.upgrade-btn {\n background: #0ea5e9 !important;\n box-shadow: 0 4px 12px rgba(14, 165, 233, 0.3) !important;\n }\n\n [data-theme="valentine"] .download-limiter-btn.upgrade-btn {\n background: #be185d !important;\n }\n\n [data-theme="bumblebee"] .download-limiter-btn.upgrade-btn {\n background: #f59e0b !important;\n }\n\n [data-theme="garden"] .download-limiter-btn.upgrade-btn {\n background: #16a34a !important;\n }\n\n /* Cancel button container and styling - positioned at very bottom */\n .download-limiter-cancel-container {\n margin-top: 30px !important;\n padding-top: 20px !important;\n border-top: 1px solid rgba(0, 0, 0, 0.1) !important;\n text-align: center !important;\n position: relative !important;\n bottom: 0 !important;\n }\n\n .download-limiter-btn.cancel-btn {\n background: transparent !important;\n color: #6b7280 !important;\n border: none !important;\n padding: 8px 16px !important;\n border-radius: 6px !important;\n cursor: pointer !important;\n font-size: 13px !important;\n font-weight: 400 !important;\n transition: all 0.2s ease !important;\n text-decoration: underline !important;\n margin: 0 auto !important;\n display: block !important;\n }\n\n .download-limiter-btn.cancel-btn:hover {\n color: #374151 !important;\n background: rgba(107, 114, 128, 0.1) !important;\n text-decoration: none !important;\n }\n\n /* Theme-specific cancel button border */\n [data-theme="dark"] .download-limiter-cancel-container {\n border-top-color: rgba(255, 255, 255, 0.1) !important;\n }\n\n [data-theme="dark"] .download-limiter-btn.cancel-btn {\n color: #9ca3af !important;\n }\n\n [data-theme="dark"] .download-limiter-btn.cancel-btn:hover {\n color: #d1d5db !important;\n background: rgba(156, 163, 175, 0.1) !important;\n }\n\n [data-theme="cyberpunk"] .download-limiter-cancel-container {\n border-top-color: rgba(14, 165, 233, 0.2) !important;\n }\n\n [data-theme="cyberpunk"] .download-limiter-btn.cancel-btn {\n color: #0ea5e9 !important;\n }\n\n [data-theme="cyberpunk"] .download-limiter-btn.cancel-btn:hover {\n color: #38bdf8 !important;\n background: rgba(14, 165, 233, 0.1) !important;\n }\n `,document.head.appendChild(e)}injectDaisyUI(){if(document.querySelector('link[href*="daisyui"]')){if(this.config.theme?.name){const e=this.config.theme.name.toLowerCase();document.documentElement.setAttribute("data-theme",e)}}else if(this.config.theme?.name){const e=this.config.theme.name.toLowerCase();document.documentElement.setAttribute("data-theme",e),this.updateStatusDisplays()}}createPaywallModal(){if(document.getElementById("download-limiter-paywall"))return;const e=document.createElement("div");e.id="download-limiter-paywall",e.className="download-limiter-modal",e.innerHTML='\n <div class="download-limiter-content">\n <h3 id="download-limiter-paywall-title">Usage Limit Reached</h3>\n <p id="download-limiter-paywall-subtitle">You\'ve used all your free attempts. Upgrade to premium for unlimited usage!</p>\n\n \x3c!-- Auth Section (shows when not signed in) --\x3e\n <div id="download-limiter-auth-section" style="margin: 20px 0;">\n <p>Sign in to continue or upgrade to premium</p>\n <button id="download-limiter-signin-btn" class="download-limiter-btn google-signin-btn">\n <svg width="18" height="18" viewBox="0 0 18 18" fill="none">\n <path d="M16.51 8H8.98v3h4.3c-.18 1-.74 1.48-1.6 2.04v2.01h2.6a8.8 8.8 0 0 0 2.38-5.88c0-.57-.05-.66-.15-1.18z" fill="white"/>\n <path d="M8.98 17c2.16 0 3.97-.72 5.3-1.94l-2.6-2.04a4.8 4.8 0 0 1-2.7.75 4.8 4.8 0 0 1-4.52-3.4H1.83v2.07A8 8 0 0 0 8.98 17z" fill="white"/>\n <path d="M4.46 10.37a4.8 4.8 0 0 1-.25-1.37c0-.48.09-.94.25-1.37V5.56H1.83a8 8 0 0 0 0 6.88l2.63-2.07z" fill="white"/>\n <path d="M8.98 3.77c1.32 0 2.5.45 3.44 1.35l2.58-2.58C13.94.64 11.66 0 8.98 0A8 8 0 0 0 1.83 5.56l2.63 2.07c.61-1.8 2.26-3.86 4.52-3.86z" fill="white"/>\n </svg>\n Sign in with Google\n </button>\n </div>\n\n \x3c!-- Payment Section (shows when signed in) --\x3e\n <div id="download-limiter-payment-section" style="margin: 20px 0; display: none;">\n <button id="download-limiter-upgrade-btn" class="download-limiter-btn upgrade-btn">\n Upgrade to Premium\n </button>\n </div>\n\n <div class="download-limiter-cancel-container">\n <button id="download-limiter-close-btn" class="download-limiter-btn cancel-btn">\n Cancel\n </button>\n </div>\n </div>\n ',document.body.appendChild(e),e.querySelector("#download-limiter-signin-btn").addEventListener("click",async()=>{await this.signIn()}),e.querySelector("#download-limiter-upgrade-btn").addEventListener("click",async()=>{const e=await this.createPayment();e?.checkout_url&&(window.location.href=e.checkout_url)}),e.querySelector("#download-limiter-close-btn").addEventListener("click",()=>{this.config.options?.debug&&(console.log("🔍 DEBUG: Cancel button clicked"),console.log("🔍 DEBUG: this.config.feedback:",this.config.feedback),console.log("🔍 DEBUG: this.config.email:",this.config.email),console.log("🔍 DEBUG: Feedback config exists:",!(!this.config.feedback&&!this.config.email))),this.config.feedback||this.config.email?(this.config.options?.debug&&console.log("🔍 DEBUG: Showing feedback form"),this.showFeedbackForm()):(this.config.options?.debug&&console.log("🔍 DEBUG: No email config, just closing modal"),e.classList.remove("show"))})}createSuccessModal(){if(document.getElementById("download-limiter-success"))return;const e=document.createElement("div");e.id="download-limiter-success",e.className="download-limiter-modal",e.innerHTML='\n <div class="download-limiter-content"> \x3c!-- Use same content class as paywall for theming --\x3e\n <h3 id="download-limiter-success-title">Action Started!</h3>\n <p id="download-limiter-success-message">Your action completed successfully!</p>\n <button id="download-limiter-success-close" class="download-limiter-btn success-btn">\n OK\n </button>\n </div>\n ',document.body.appendChild(e),e.querySelector("#download-limiter-success-close").addEventListener("click",()=>{e.classList.remove("show")}),e.addEventListener("click",t=>{t.target===e&&e.classList.remove("show")})}showFeedbackForm(){const e=document.getElementById("download-limiter-paywall");e&&e.classList.remove("show"),this.createFeedbackModal();const t=document.getElementById("download-limiter-feedback");t&&t.classList.add("show")}createFeedbackModal(){if(document.getElementById("download-limiter-feedback"))return void(this.config.options?.debug&&console.log("🔍 DEBUG: Feedback modal already exists"));const e=this.config.feedback||(this.config.email?{form:{title:"Quick Feedback",description:"Why didn't you upgrade?",option1:"Not useful for my needs",option2:"Didn't find what I was looking for",option3:"Just trying it out"},email:this.config.email}:null);if(this.config.options?.debug&&(console.log("🔍 DEBUG: Feedback config:",e),console.log("🔍 DEBUG: this.config.feedback:",this.config.feedback),console.log("🔍 DEBUG: this.config.email:",this.config.email)),!e)return void(this.config.options?.debug&&console.log("🔍 DEBUG: No feedback config found, not creating modal"));const t=document.createElement("div");t.id="download-limiter-feedback",t.className="download-limiter-modal",t.innerHTML=`\n <div class="download-limiter-content">\n <h3>${e.form.title}</h3>\n <p style="margin-bottom: 20px;">${e.form.description}</p>\n\n <form id="feedback-form" style="text-align: left;">\n <div style="margin-bottom: 15px;">\n <label style="display: block; margin-bottom: 8px;">\n <input type="radio" name="reason" value="option1" style="margin-right: 8px;">\n ${e.form.option1}\n </label>\n <label style="display: block; margin-bottom: 8px;">\n <input type="radio" name="reason" value="option2" style="margin-right: 8px;">\n ${e.form.option2}\n </label>\n <label style="display: block; margin-bottom: 8px;">\n <input type="radio" name="reason" value="option3" style="margin-right: 8px;">\n ${e.form.option3}\n </label>\n </div>\n\n <div style="margin-bottom: 15px;">\n <label for="feedback-details" style="display: block; margin-bottom: 5px;">Tell us more:</label>\n <textarea\n id="feedback-details"\n name="details"\n rows="3"\n style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;"\n placeholder="Your feedback helps us improve..." maxlength="200"></textarea>\n </div>\n\n <div style="margin-bottom: 20px;">\n <label for="feedback-email" style="display: block; margin-bottom: 5px;">\n Email (optional):\n </label>\n <input\n type="email"\n id="feedback-email"\n name="email"\n style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;"\n placeholder="your@email.com">\n <small style="color: #666; display: block; margin-top: 4px;">\n Only if you want us to reach out about what you mentioned above. We don't follow up unless you want us to\n </small>\n </div>\n\n \n <div style="text-align: center;">\n <button type="submit" class="download-limiter-btn success-btn" style="margin-right: 10px;">\n Submit Feedback\n </button>\n <button type="button" id="feedback-skip-btn" class="download-limiter-btn cancel-btn">\n Skip\n </button>\n </div>\n </form>\n </div>\n `,document.body.appendChild(t),this.config.options?.debug&&console.log("🔍 DEBUG: Feedback modal created and added to DOM");const n=t.querySelector("#feedback-form");n.addEventListener("submit",e=>{e.preventDefault(),this.submitFeedback(n)}),t.querySelector("#feedback-skip-btn").addEventListener("click",()=>{t.classList.remove("show")}),t.addEventListener("click",e=>{e.target===t&&t.classList.remove("show")})}async submitFeedback(e){const t=new FormData(e),n=t.get("reason"),r=t.get("details"),i=t.get("email");if(!n)return void alert("Please select a reason");const s={reason:n,details:r,email:i||void 0,timestamp:(new Date).toISOString(),userAgent:navigator.userAgent,appId:this.config.appId};try{await this.sendFeedbackEmail(s);const e=document.getElementById("download-limiter-feedback");e&&e.classList.remove("show"),alert("Thank you for your feedback!")}catch(e){console.error("Failed to send feedback:",e),alert("Failed to send feedback. Please try again.")}}async sendFeedbackEmail(e){let t;if(this.config.feedback?.email?t=Array.isArray(this.config.feedback.email)?this.config.feedback.email[0]:this.config.feedback.email:this.config.email&&(t={provider:"resend",apiKey:this.config.email.resendApiKey,fromEmail:this.config.email.fromEmail}),!t)throw new Error("Email configuration not available");const n=`\nNew Feedback from ${this.config.appId}\n\nReason: ${e.reason}\nDetails: ${e.details}\nUser Email: ${e.email||"Not provided"}\nTimestamp: ${e.timestamp}\nUser Agent: ${e.userAgent}\n `.trim();let r;if("resend"!==t.provider&&t.provider)throw new Error(`Unsupported email provider: ${t.provider}`);if(r=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.apiKey||t.resendApiKey}`},body:JSON.stringify({from:t.fromEmail,to:[t.fromEmail],subject:`Feedback from ${this.config.appId}`,text:n})}),!r.ok)throw new Error(`Email API error: ${r.status}`)}createAuthUI(){if(document.getElementById("lead-fast-profile"))return;const e=document.createElement("div");e.id="lead-fast-profile",e.className="lead-fast-profile",document.body.appendChild(e)}createStatusDisplay(){if(document.getElementById("download-limiter-status"))return;const e=document.createElement("div");e.id="download-limiter-status",e.className="download-limiter-status",document.body.appendChild(e)}createGlobalStatusDisplay(){this.createStatusDisplay()}showPaywallInstant(e){this.createPaywallModal();const t=document.getElementById("download-limiter-paywall");if(t){const n=t.querySelector("#download-limiter-paywall-title");n&&(n.textContent=`You've used ${e.limit} free attempts`);const r=t.querySelector("#download-limiter-auth-section"),i=t.querySelector("#download-limiter-payment-section");if(this.currentUser)r.style.display="none",i.style.display="block";else{const e=t.querySelector("#download-limiter-paywall-subtitle");e&&(e.textContent="Sign in to continue. If you're already premium, you'll get unlimited access. New users can upgrade after signing in."),r.style.display="none",i.style.display="none",this.showSingleUpgradeFlow(t)}t.classList.add("show")}}async showPaywall(){const e=await this.getDownloadStatus();this.showPaywallInstant(e)}showSingleUpgradeFlow(e){let t=e.querySelector(".single-upgrade-container");if(!t){t=document.createElement("div"),t.className="single-upgrade-container",t.innerHTML='\n <div class="single-upgrade-content">\n <button class="download-limiter-btn upgrade-btn" id="single-upgrade-btn">\n Continue with Google\n </button>\n \x3c!--<p class="upgrade-description">\n Sign in to restore access. Premium members get unlimited usage immediately.\n </p>--\x3e\n </div>\n ';const n=e.querySelector(".download-limiter-cancel-container");n?e.querySelector(".download-limiter-content")?.insertBefore(t,n):e.querySelector(".download-limiter-content")?.appendChild(t)}t.style.display="block";const n=e.querySelector("#single-upgrade-btn");if(n){n.replaceWith(n.cloneNode(!0));const t=e.querySelector("#single-upgrade-btn");t?.addEventListener("click",async()=>{try{const{error:e}=await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}${window.location.pathname}?upgrade=true`}});e&&(console.error("Sign in error:",e),this.showError("Sign In Failed","Failed to sign in with Google. Please try again."))}catch(e){console.error("Upgrade flow error:",e),this.showError("Upgrade Failed","Failed to start upgrade process. Please try again.")}})}}showSuccess(e,t){const n=document.getElementById("download-limiter-success");if(n){const r=n.querySelector("#download-limiter-success-title"),i=n.querySelector("#download-limiter-success-message");r&&(r.textContent=e),i&&(i.textContent=t),n.classList.add("show")}}showError(e,t){const n=document.createElement("div");n.style.cssText="\n position: fixed;\n top: 20px;\n right: 20px;\n background: #fee2e2;\n border: 1px solid #fecaca;\n color: #dc2626;\n padding: 12px 16px;\n border-radius: 8px;\n font-size: 14px;\n font-weight: 500;\n line-height: 1.4;\n max-width: 300px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);\n z-index: 10000;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n ",n.innerHTML=`\n <div style="font-weight: 600; margin-bottom: 4px;">${e}</div>\n <div style="font-size: 13px; opacity: 0.9;">${t}</div>\n `,document.body.appendChild(n),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},5e3),n.addEventListener("click",()=>{n.parentNode&&n.parentNode.removeChild(n)})}showConnectionError(){this.showError("Connection Error","Server connection required for download verification. Please check your configuration and try again.")}showPaymentConfigError(){this.showError("Payment Configuration Error","Payment system is not properly configured. Please contact support.")}disableDownloadButtons(e){const t=document.querySelectorAll("[data-leadfast-attached]"),n={connection:"Download disabled: Server connection required",payment:"Download disabled: Payment configuration error",security_key:"Download disabled: Invalid or missing security key"},r={connection:"⚠️ Connection Error - Downloads Disabled",payment:"⚠️ Payment Config Error - Downloads Disabled",security_key:"🔐 Invalid Security Key - Please Update Configuration"};t.forEach(t=>{const r=t;r.disabled=!0,r.style.opacity="0.5",r.style.cursor="not-allowed",r.title=n[e]});const i=document.querySelector(".lead-fast-user-section");i&&(i.innerHTML=`\n <div style="\n color: #ef4444;\n padding: 6px 8px;\n font-size: 12px;\n font-weight: 500;\n line-height: 1.2;\n border-radius: 4px;\n background: rgba(239, 68, 68, 0.05);\n border: 1px solid rgba(239, 68, 68, 0.2);\n max-width: 200px;\n text-align: center;\n ">\n ${r[e]}\n </div>\n `)}async updateStatusDisplays(){if(this.securityKeyFailed)return void this.disableDownloadButtons("security_key");if(this.supabaseConnectionFailed)return void this.disableDownloadButtons("connection");if(this.config.payment&&this.paymentConnectionFailed)return void this.disableDownloadButtons("payment");const e=await this.getDownloadStatus();this.updateUserSection(e)}createTitleBar(){let e=document.getElementById("lead-fast-profile");e||(e=document.createElement("div"),e.id="lead-fast-profile",e.className="lead-fast-profile",document.body.appendChild(e));const t=this.config.titleBar||{},n=t.title||"My App",r=t.titleImage,i=t.links||[];e.innerHTML=`\n <div class="lead-fast-title-bar">\n <div class="lead-fast-title-section">\n <a href="#" class="lead-fast-logo">\n ${r?`<img src="${r}" alt="${n}">`:""}\n <span>${n}</span>\n </a>\n <nav class="lead-fast-nav">\n ${i.map(e=>`\n <a href="${e.url}" class="lead-fast-nav-link" ${e.target?`target="${e.target}"`:""}>\n ${e.text}\n </a>\n `).join("")}\n </nav>\n </div>\n\n <div class="lead-fast-user-section" id="lead-fast-user-section">\n \x3c!-- User section will be populated when logged in --\x3e\n </div>\n\n \x3c!-- <a href="https://www.moneyfast.bar" target="_blank" class="lead-fast-branding" style="text-decoration: none; color: inherit;">moneyfast.bar</a>--\x3e\n </div>\n `}updateUserSection(e){const t=document.getElementById("lead-fast-user-section");if(t)if(this.currentUser){const n=this.currentUser.email.charAt(0).toUpperCase(),r=this.currentUser.email,i=e.isPremium?"premium":"free",s=e.isPremium?"Premium":"Free",o=e.isPremium?"Unlimited":`${e.currentCount}/${e.limit}`;t.innerHTML=`\n <div class="lead-fast-avatar">${n}</div>\n <div class="lead-fast-user-info">\n <div class="lead-fast-user-email">${r}</div>\n <div class="lead-fast-user-status">\n <span class="lead-fast-badge ${i}">${s}</span>\n <span class="lead-fast-count">${o}</span>\n </div>\n </div>\n <button class="lead-fast-signout">signout</button>\n `;const a=document.querySelector(".lead-fast-title-bar");a&&getComputedStyle(a);const c=t.querySelector(".lead-fast-signout");c&&c.addEventListener("click",()=>{this.signOut()})}else{const n=`Attempts: ${e.currentCount}/${e.limit}`;t.innerHTML=`\n <div class="lead-fast-anonymous-status">\n <span class="lead-fast-count">${n}</span>\n </div>\n `}}setupUIUpdates(){this.on("authChanged",async()=>{this.cachedStatus=null,this.updateStatusDisplays();const e=document.getElementById("download-limiter-paywall");e&&e.classList.contains("show")&&(this.updatePaywallDisplay(),this.currentUser&&this.config.payment&&setTimeout(async()=>{if(await this.checkPremiumStatus(this.currentUser.email))e.classList.remove("show");else{const e=await this.createPayment();e?.checkout_url&&(window.location.href=e.checkout_url)}},1e3))}),this.on("countChanged",()=>{this.updateStatusDisplays()}),this.updateStatusDisplays()}updatePaywallDisplay(){const e=document.getElementById("download-limiter-paywall");if(!e)return;const t=e.querySelector("#download-limiter-auth-section"),n=e.querySelector("#download-limiter-payment-section");this.currentUser?(t.style.display="none",n.style.display="block"):(t.style.display="block",n.style.display="none")}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t)}off(e,t){const n=this.eventListeners.get(e);if(n){const e=n.indexOf(t);e>-1&&n.splice(e,1)}}emit(e,t){const n=this.eventListeners.get(e);n&&n.forEach(n=>{try{n(t)}catch(t){console.error(`Error in ${e} listener:`,t)}})}validateConfig(){if(!this.config.appId)throw new Error("appId is required");if(!this.config.supabase?.url)throw new Error("supabase.url is required");if(!this.config.supabase?.anonKey)throw new Error("supabase.anonKey is required");if("number"!=typeof this.config.freeAttemptLimit||this.config.freeAttemptLimit<0)throw new Error("freeAttemptLimit must be a non-negative number")}async initializeSupabase(){try{this.supabase=(e=this.config.supabase.url,t=this.config.supabase.anonKey,new qr(e,t,n)),this.supabaseConnectionFailed=!1}catch(e){console.error("Failed to initialize Supabase:",e),this.supabaseConnectionFailed=!0}var e,t,n}async initializePayment(){if(!this.config.payment)return;const e=this.config.payment?.find(e=>"dodo"===e.provider);if(!e)return this.paymentConnectionFailed=!0,void(this.config.options?.debug&&console.warn("No dodo payment provider configured"));const t=e.productId;if(!t||!t.startsWith("pdt_")||t.length<10)return this.paymentConnectionFailed=!0,void(this.config.options?.debug&&console.warn("Invalid payment product ID format:",t));this.paymentConnectionFailed=!1}async initializeFingerprint(){try{this.userFingerprint=await this.generateFingerprint()}catch(e){this.userFingerprint=crypto.randomUUID?crypto.randomUUID():String(Date.now()),this.config.options?.debug&&console.warn("Fingerprint generation failed, using fallback:",e)}}async generateFingerprint(){const e=`${navigator.userAgent||""}||${Intl.DateTimeFormat().resolvedOptions().timeZone||""}||${`${screen.width}x${screen.height}`}||${navigator.language||""}`,t=(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")}async setupAuthListener(){this.supabase.auth.onAuthStateChange(async(e,t)=>{const n=this.currentUser;this.currentUser=t?.user||null;let r=!1;if(this.currentUser){const e=!n||n.email!==this.currentUser.email,t=!this.cachedPremiumStatus||Date.now()-this.premiumStatusCacheTime>this.STATUS_CACHE_DURATION;e||t?(console.log(`🔥 [SUPABASE API] About to call checkPremiumStatus from setupAuthListener (userChanged: ${e}, cacheExpired: ${t})`),r=await this.checkPremiumStatus(this.currentUser.email),this.cachedPremiumStatus=r,this.premiumStatusCacheTime=Date.now()):(r=this.cachedPremiumStatus,console.log(`🔍 [CACHE] Using cached premium status from auth listener: ${r}`))}else this.cachedPremiumStatus=null,this.premiumStatusCacheTime=0;const i="true"===new URLSearchParams(window.location.search).get("upgrade");if("SIGNED_IN"===e&&!n&&this.currentUser&&this.config.payment&&i)if(r){window.history.replaceState({},document.title,window.location.pathname);const e=document.getElementById("download-limiter-paywall");e&&e.classList.remove("show")}else{const e=await this.createPayment();e?.checkout_url&&(window.history.replaceState({},document.title,window.location.pathname),window.location.href=e.checkout_url)}this.emit("authChanged",{user:this.currentUser,isPremium:r})});const{data:{user:e}}=await this.supabase.auth.getUser();this.currentUser=e}async getDownloadCount(){if(!this.userFingerprint)return 0;console.log(`🔥 [SUPABASE API] getDownloadCount called | Time: ${(new Date).toISOString()}`);try{const e=await fetch(`${this.config.supabase.url}/functions/v1/check-download-limit`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.supabase.anonKey}`},body:JSON.stringify({fingerprint:this.userFingerprint,security_key:this.config.security_key,action:"check"})});if(console.log(`🔥 [SUPABASE API] getDownloadCount response: ${e.status}`),e.ok){const t=await e.json();return this.supabaseConnectionFailed=!1,t.current_count||0}if(401===e.status||403===e.status)try{const t=await e.json(),n=t.error||t.message||"Authentication failed";n.toLowerCase().includes("security key")?(console.error(`❌ Security Key Validation Failed [check-download-limit]: ${n}`),console.error("💡 Backend Function: check-download-limit"),console.error("💡 Please check your security_key in the MoneyBar configuration"),this.securityKeyFailed=!0,this.supabaseConnectionFailed=!0):(console.warn(`Supabase authentication failed [check-download-limit]: ${e.status} - ${n}`),this.supabaseConnectionFailed=!0)}catch(t){console.warn(`Supabase authentication failed: ${e.status} - Unable to parse error`),this.supabaseConnectionFailed=!0}}catch(e){this.supabaseConnectionFailed=!0,this.config.options?.debug&&console.warn("Failed to get server usage count, connection failed:",e)}return 0}async incrementDownloadCount(){if(!this.userFingerprint)return 0;const e={fingerprint:this.userFingerprint,security_key:this.config.security_key,action:"increment"};console.log(`🔥 [SUPABASE API] incrementDownloadCount called | Time: ${(new Date).toISOString()}`);try{const t=await fetch(`${this.config.supabase.url}/functions/v1/check-download-limit`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.supabase.anonKey}`},body:JSON.stringify(e)});if(console.log(`🔥 [SUPABASE API] incrementDownloadCount response: ${t.status}`),this.config.options?.debug&&!t.ok){const e=await t.text();console.error("🔍 DEBUG: Error response:",e)}if(t.ok){const e=await t.json();return this.supabaseConnectionFailed=!1,e.new_count||0}if(401===t.status||403===t.status)try{const e=await t.json(),n=e.error||e.message||"Authentication failed";n.toLowerCase().includes("security key")?(console.error(`❌ Security Key Validation Failed [check-download-limit]: ${n}`),console.error("💡 Backend Function: check-download-limit"),console.error("💡 Please check your security_key in the MoneyBar configuration"),this.securityKeyFailed=!0,this.supabaseConnectionFailed=!0):(console.warn(`Supabase authentication failed [check-download-limit]: ${t.status} - ${n}`),this.supabaseConnectionFailed=!0)}catch(e){console.warn(`Supabase authentication failed: ${t.status} - Unable to parse error`),this.supabaseConnectionFailed=!0}}catch(e){this.supabaseConnectionFailed=!0,this.config.options?.debug&&console.warn("Failed to increment server count, connection failed:",e)}return 0}async checkPremiumStatus(e){console.log(`🔥 [SUPABASE API] checkPremiumStatus called for email: ${e} | Time: ${(new Date).toISOString()}`);try{const t=await fetch(`${this.config.supabase.url}/functions/v1/check-payment-status`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.supabase.anonKey}`},body:JSON.stringify({email:e,app_id:this.config.appId})});if(console.log(`🔥 [SUPABASE API] checkPremiumStatus response: ${t.status}`),t.ok){return"completed"===(await t.json()).status}}catch(e){this.config.options?.debug&&console.warn("Failed to check premium status:",e)}return!1}getLocalDownloadCount(){const e=`download_count_${this.config.appId}`,t=parseInt(localStorage.getItem(e)||"0",10);return isNaN(t)?0:t}incrementLocalDownloadCount(){const e=`download_count_${this.config.appId}`,t=this.getLocalDownloadCount()+1;return localStorage.setItem(e,String(t)),t}handleError(e){this.config.options?.debug&&console.error("Lead Fast Error:",e),this.config.callbacks?.onError?this.config.callbacks.onError(e):console.error("Lead Fast:",e.message),this.emit("error",e)}async checkPaymentStatus(){"success"===new URLSearchParams(window.location.search).get("payment")&&setTimeout(async()=>{if(this.currentUser){await this.checkPremiumStatus(this.currentUser.email)?this.showSuccess("Payment Successful!","Welcome to premium! You now have unlimited usage."):this.showSuccess("Processing Payment","Payment is being processed. Please refresh in a few moments.")}else this.showSuccess("Processing Payment","Please wait while we verify your payment...");const e=window.location.href.split("?")[0];window.history.replaceState({},document.title,e)},2e3)}}export{Fr as MoneyBar};
1
+ function e(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if("default"!==n&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},t(e,n)};function n(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}var r=function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},r.apply(this,arguments)};function i(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}function s(e,t,n,r){var i,s=arguments.length,a=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,r);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(a=(s<3?i(a):s>3?i(t,n,a):i(t,n))||a);return s>3&&a&&Object.defineProperty(t,n,a),a}function a(e,t){return function(n,r){t(n,r,e)}}function o(e,t,n,r,i,s){function a(e){if(void 0!==e&&"function"!=typeof e)throw new TypeError("Function expected");return e}for(var o,c=r.kind,l="getter"===c?"get":"setter"===c?"set":"value",u=!t&&e?r.static?e:e.prototype:null,d=t||(u?Object.getOwnPropertyDescriptor(u,r.name):{}),h=!1,f=n.length-1;f>=0;f--){var p={};for(var m in r)p[m]="access"===m?{}:r[m];for(var m in r.access)p.access[m]=r.access[m];p.addInitializer=function(e){if(h)throw new TypeError("Cannot add initializers after decoration has completed");s.push(a(e||null))};var g=(0,n[f])("accessor"===c?{get:d.get,set:d.set}:d[l],p);if("accessor"===c){if(void 0===g)continue;if(null===g||"object"!=typeof g)throw new TypeError("Object expected");(o=a(g.get))&&(d.get=o),(o=a(g.set))&&(d.set=o),(o=a(g.init))&&i.unshift(o)}else(o=a(g))&&("field"===c?i.unshift(o):d[l]=o)}u&&Object.defineProperty(u,r.name,d),h=!0}function c(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0}function l(e){return"symbol"==typeof e?e:"".concat(e)}function u(e,t,n){return"symbol"==typeof t&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(e,"name",{configurable:!0,value:n?"".concat(n," ",t):t})}function d(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function h(e,t,n,r){return new(n||(n=Promise))(function(i,s){function a(e){try{c(r.next(e))}catch(e){s(e)}}function o(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,o)}c((r=r.apply(e,t||[])).next())})}function f(e,t){var n,r,i,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=o(0),a.throw=o(1),a.return=o(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(o){return function(c){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,o[0]&&(s=0)),s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){s.label=o[1];break}if(6===o[0]&&s.label<i[1]){s.label=i[1],i=o;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(o);break}i[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,c])}}}var p=Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]};function m(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||p(t,e,n)}function g(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function b(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,s=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)a.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}return a}function w(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(b(arguments[t]));return e}function y(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;var r=Array(e),i=0;for(t=0;t<n;t++)for(var s=arguments[t],a=0,o=s.length;a<o;a++,i++)r[i]=s[a];return r}function v(e,t,n){if(n||2===arguments.length)for(var r,i=0,s=t.length;i<s;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}function _(e){return this instanceof _?(this.v=e,this):new _(e)}function k(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,i=n.apply(e,t||[]),s=[];return r=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",function(e){return function(t){return Promise.resolve(t).then(e,l)}}),r[Symbol.asyncIterator]=function(){return this},r;function a(e,t){i[e]&&(r[e]=function(t){return new Promise(function(n,r){s.push([e,t,n,r])>1||o(e,t)})},t&&(r[e]=t(r[e])))}function o(e,t){try{(n=i[e](t)).value instanceof _?Promise.resolve(n.value.v).then(c,l):u(s[0][2],n)}catch(e){u(s[0][3],e)}var n}function c(e){o("next",e)}function l(e){o("throw",e)}function u(e,t){e(t),s.shift(),s.length&&o(s[0][0],s[0][1])}}function S(e){var t,n;return t={},r("next"),r("throw",function(e){throw e}),r("return"),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:_(e[r](t)),done:!1}:i?i(t):t}:i}}function E(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=g(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise(function(r,i){(function(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)})(r,i,(t=e[n](t)).done,t.value)})}}}function T(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}var O=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t},x=function(e){return x=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},x(e)};function j(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n=x(e),r=0;r<n.length;r++)"default"!==n[r]&&p(t,e,n[r]);return O(t,e),t}function P(e){return e&&e.__esModule?e:{default:e}}function A(e,t,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(e):r?r.value:t.get(e)}function C(e,t,n,r,i){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?i.call(e,n):i?i.value=n:t.set(e,n),n}function I(e,t){if(null===t||"object"!=typeof t&&"function"!=typeof t)throw new TypeError("Cannot use 'in' operator on non-object");return"function"==typeof e?t===e:e.has(t)}function R(e,t,n){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var r,i;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],n&&(i=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t}var $="function"==typeof SuppressedError?SuppressedError:function(e,t,n){var r=new Error(n);return r.name="SuppressedError",r.error=e,r.suppressed=t,r};function U(e){function t(t){e.error=e.hasError?new $(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var n,r=0;return function i(){for(;n=e.stack.pop();)try{if(!n.async&&1===r)return r=0,e.stack.push(n),Promise.resolve().then(i);if(n.dispose){var s=n.dispose.call(n.value);if(n.async)return r|=2,Promise.resolve(s).then(i,function(e){return t(e),i()})}else r|=1}catch(e){t(e)}if(1===r)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}function N(e,t){return"string"==typeof e&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,n,r,i,s){return n?t?".jsx":".js":!r||i&&s?r+i+"."+s.toLowerCase()+"js":e}):e}var D={__extends:n,__assign:r,__rest:i,__decorate:s,__param:a,__esDecorate:o,__runInitializers:c,__propKey:l,__setFunctionName:u,__metadata:d,__awaiter:h,__generator:f,__createBinding:p,__exportStar:m,__values:g,__read:b,__spread:w,__spreadArrays:y,__spreadArray:v,__await:_,__asyncGenerator:k,__asyncDelegator:S,__asyncValues:E,__makeTemplateObject:T,__importStar:j,__importDefault:P,__classPrivateFieldGet:A,__classPrivateFieldSet:C,__classPrivateFieldIn:I,__addDisposableResource:R,__disposeResources:U,__rewriteRelativeImportExtension:N},B=Object.freeze({__proto__:null,__extends:n,get __assign(){return r},__rest:i,__decorate:s,__param:a,__esDecorate:o,__runInitializers:c,__propKey:l,__setFunctionName:u,__metadata:d,__awaiter:h,__generator:f,__createBinding:p,__exportStar:m,__values:g,__read:b,__spread:w,__spreadArrays:y,__spreadArray:v,__await:_,__asyncGenerator:k,__asyncDelegator:S,__asyncValues:E,__makeTemplateObject:T,__importStar:j,__importDefault:P,__classPrivateFieldGet:A,__classPrivateFieldSet:C,__classPrivateFieldIn:I,__addDisposableResource:R,__disposeResources:U,__rewriteRelativeImportExtension:N,default:D});class L extends Error{constructor(e,t="FunctionsError",n){super(e),this.name=t,this.context=n}}class q extends L{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class F extends L{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class M extends L{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var K;!function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"}(K||(K={}));class z{constructor(e,{headers:t={},customFetch:n,region:r=K.Any}={}){this.url=e,this.headers=t,this.region=r,this.fetch=(e=>e?(...t)=>e(...t):(...e)=>fetch(...e))(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return h(this,arguments,void 0,function*(e,t={}){var n;let r,i;try{const{headers:s,method:a,body:o,signal:c,timeout:l}=t;let u={},{region:d}=t;d||(d=this.region);const h=new URL(`${this.url}/${e}`);let f;d&&"any"!==d&&(u["x-region"]=d,h.searchParams.set("forceFunctionRegion",d)),o&&(s&&!Object.prototype.hasOwnProperty.call(s,"Content-Type")||!s)?"undefined"!=typeof Blob&&o instanceof Blob||o instanceof ArrayBuffer?(u["Content-Type"]="application/octet-stream",f=o):"string"==typeof o?(u["Content-Type"]="text/plain",f=o):"undefined"!=typeof FormData&&o instanceof FormData?f=o:(u["Content-Type"]="application/json",f=JSON.stringify(o)):f=o;let p=c;l&&(i=new AbortController,r=setTimeout(()=>i.abort(),l),c?(p=i.signal,c.addEventListener("abort",()=>i.abort())):p=i.signal);const m=yield this.fetch(h.toString(),{method:a||"POST",headers:Object.assign(Object.assign(Object.assign({},u),this.headers),s),body:f,signal:p}).catch(e=>{throw new q(e)}),g=m.headers.get("x-relay-error");if(g&&"true"===g)throw new F(m);if(!m.ok)throw new M(m);let b,w=(null!==(n=m.headers.get("Content-Type"))&&void 0!==n?n:"text/plain").split(";")[0].trim();return b="application/json"===w?yield m.json():"application/octet-stream"===w||"application/pdf"===w?yield m.blob():"text/event-stream"===w?m:"multipart/form-data"===w?yield m.formData():yield m.text(),{data:b,error:null,response:m}}catch(e){return{data:null,error:e,response:e instanceof M||e instanceof F?e.context:void 0}}finally{r&&clearTimeout(r)}})}}function W(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function G(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var n=function e(){var n=!1;try{n=this instanceof e}catch{}return n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})}),n}var V,H,J,Y,Q,X,Z,ee={},te=G(B),ne={},re={},ie={},se={},ae={},oe={};function ce(){if(V)return oe;V=1,Object.defineProperty(oe,"__esModule",{value:!0});class e extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}}return oe.default=e,oe}function le(){if(H)return ae;H=1,Object.defineProperty(ae,"__esModule",{value:!0});const e=te.__importDefault(ce());return ae.default=class{constructor(e){var t,n;this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=null!==(t=e.shouldThrowOnError)&&void 0!==t&&t,this.signal=e.signal,this.isMaybeSingle=null!==(n=e.isMaybeSingle)&&void 0!==n&&n,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}then(t,n){void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),"GET"!==this.method&&"HEAD"!==this.method&&this.headers.set("Content-Type","application/json");let r=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async t=>{var n,r,i,s;let a=null,o=null,c=null,l=t.status,u=t.statusText;if(t.ok){if("HEAD"!==this.method){const e=await t.text();""===e||(o="text/csv"===this.headers.get("Accept")||this.headers.get("Accept")&&(null===(n=this.headers.get("Accept"))||void 0===n?void 0:n.includes("application/vnd.pgrst.plan+text"))?e:JSON.parse(e))}const e=null===(r=this.headers.get("Prefer"))||void 0===r?void 0:r.match(/count=(exact|planned|estimated)/),s=null===(i=t.headers.get("content-range"))||void 0===i?void 0:i.split("/");e&&s&&s.length>1&&(c=parseInt(s[1])),this.isMaybeSingle&&"GET"===this.method&&Array.isArray(o)&&(o.length>1?(a={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,c=null,l=406,u="Not Acceptable"):o=1===o.length?o[0]:null)}else{const n=await t.text();try{a=JSON.parse(n),Array.isArray(a)&&404===t.status&&(o=[],a=null,l=200,u="OK")}catch(e){404===t.status&&""===n?(l=204,u="No Content"):a={message:n}}if(a&&this.isMaybeSingle&&(null===(s=null==a?void 0:a.details)||void 0===s?void 0:s.includes("0 rows"))&&(a=null,l=200,u="OK"),a&&this.shouldThrowOnError)throw new e.default(a)}return{error:a,data:o,count:c,status:l,statusText:u}});return this.shouldThrowOnError||(r=r.catch(e=>{var t,n,r,i,s,a;let o="";const c=null==e?void 0:e.cause;if(c){const s=null!==(t=null==c?void 0:c.message)&&void 0!==t?t:"",a=null!==(n=null==c?void 0:c.code)&&void 0!==n?n:"";o=`${null!==(r=null==e?void 0:e.name)&&void 0!==r?r:"FetchError"}: ${null==e?void 0:e.message}`,o+=`\n\nCaused by: ${null!==(i=null==c?void 0:c.name)&&void 0!==i?i:"Error"}: ${s}`,a&&(o+=` (${a})`),(null==c?void 0:c.stack)&&(o+=`\n${c.stack}`)}else o=null!==(s=null==e?void 0:e.stack)&&void 0!==s?s:"";return{error:{message:`${null!==(a=null==e?void 0:e.name)&&void 0!==a?a:"FetchError"}: ${null==e?void 0:e.message}`,details:o,hint:"",code:""},data:null,count:null,status:0,statusText:""}})),r.then(t,n)}returns(){return this}overrideTypes(){return this}},ae}function ue(){if(J)return se;J=1,Object.defineProperty(se,"__esModule",{value:!0});const e=te.__importDefault(le());class t extends e.default{select(e){let t=!1;const n=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",n),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:n,foreignTable:r,referencedTable:i=r}={}){const s=i?`${i}.order`:"order",a=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${a?`${a},`:""}${e}.${t?"asc":"desc"}${void 0===n?"":n?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:n=t}={}){const r=void 0===n?"limit":`${n}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:n,referencedTable:r=n}={}){const i=void 0===r?"offset":`${r}.offset`,s=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(s,""+(t-e+1)),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return"GET"===this.method?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:n=!1,buffers:r=!1,wal:i=!1,format:s="text"}={}){var a;const o=[e?"analyze":null,t?"verbose":null,n?"settings":null,r?"buffers":null,i?"wal":null].filter(Boolean).join("|"),c=null!==(a=this.headers.get("Accept"))&&void 0!==a?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${c}"; options=${o};`),this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}}return se.default=t,se}function de(){if(Y)return ie;Y=1,Object.defineProperty(ie,"__esModule",{value:!0});const e=te.__importDefault(ue()),t=new RegExp("[,()]");class n extends e.default{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,n){const r=Array.from(new Set(n)).map(e=>"string"==typeof e&&t.test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:n,type:r}={}){let i="";"plain"===r?i="pl":"phrase"===r?i="ph":"websearch"===r&&(i="w");const s=void 0===n?"":`(${n})`;return this.url.searchParams.append(e,`${i}fts${s}.${t}`),this}match(e){return Object.entries(e).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,n){return this.url.searchParams.append(e,`not.${t}.${n}`),this}or(e,{foreignTable:t,referencedTable:n=t}={}){const r=n?`${n}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,n){return this.url.searchParams.append(e,`${t}.${n}`),this}}return ie.default=n,ie}function he(){if(Q)return re;Q=1,Object.defineProperty(re,"__esModule",{value:!0});const e=te.__importDefault(de());return re.default=class{constructor(e,{headers:t={},schema:n,fetch:r}){this.url=e,this.headers=new Headers(t),this.schema=n,this.fetch=r}select(t,n){const{head:r=!1,count:i}=null!=n?n:{},s=r?"HEAD":"GET";let a=!1;const o=(null!=t?t:"*").split("").map(e=>/\s/.test(e)&&!a?"":('"'===e&&(a=!a),e)).join("");return this.url.searchParams.set("select",o),i&&this.headers.append("Prefer",`count=${i}`),new e.default({method:s,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch})}insert(t,{count:n,defaultToNull:r=!0}={}){var i;if(n&&this.headers.append("Prefer",`count=${n}`),r||this.headers.append("Prefer","missing=default"),Array.isArray(t)){const e=t.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(e.length>0){const t=[...new Set(e)].map(e=>`"${e}"`);this.url.searchParams.set("columns",t.join(","))}}return new e.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:null!==(i=this.fetch)&&void 0!==i?i:fetch})}upsert(t,{onConflict:n,ignoreDuplicates:r=!1,count:i,defaultToNull:s=!0}={}){var a;if(this.headers.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),void 0!==n&&this.url.searchParams.set("on_conflict",n),i&&this.headers.append("Prefer",`count=${i}`),s||this.headers.append("Prefer","missing=default"),Array.isArray(t)){const e=t.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(e.length>0){const t=[...new Set(e)].map(e=>`"${e}"`);this.url.searchParams.set("columns",t.join(","))}}return new e.default({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:null!==(a=this.fetch)&&void 0!==a?a:fetch})}update(t,{count:n}={}){var r;return n&&this.headers.append("Prefer",`count=${n}`),new e.default({method:"PATCH",url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:null!==(r=this.fetch)&&void 0!==r?r:fetch})}delete({count:t}={}){var n;return t&&this.headers.append("Prefer",`count=${t}`),new e.default({method:"DELETE",url:this.url,headers:this.headers,schema:this.schema,fetch:null!==(n=this.fetch)&&void 0!==n?n:fetch})}},re}var fe=function(){if(Z)return ee;Z=1,Object.defineProperty(ee,"__esModule",{value:!0}),ee.PostgrestError=ee.PostgrestBuilder=ee.PostgrestTransformBuilder=ee.PostgrestFilterBuilder=ee.PostgrestQueryBuilder=ee.PostgrestClient=void 0;const e=te,t=e.__importDefault(function(){if(X)return ne;X=1,Object.defineProperty(ne,"__esModule",{value:!0});const e=te,t=e.__importDefault(he()),n=e.__importDefault(de());class r{constructor(e,{headers:t={},schema:n,fetch:r}={}){this.url=e,this.headers=new Headers(t),this.schemaName=n,this.fetch=r}from(e){if(!e||"string"!=typeof e||""===e.trim())throw new Error("Invalid relation name: relation must be a non-empty string.");const n=new URL(`${this.url}/${e}`);return new t.default(n,{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new r(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:i=!1,count:s}={}){var a;let o;const c=new URL(`${this.url}/rpc/${e}`);let l;r||i?(o=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{c.searchParams.append(e,t)})):(o="POST",l=t);const u=new Headers(this.headers);return s&&u.set("Prefer",`count=${s}`),new n.default({method:o,url:c,headers:u,schema:this.schemaName,body:l,fetch:null!==(a=this.fetch)&&void 0!==a?a:fetch})}}return ne.default=r,ne}());ee.PostgrestClient=t.default;const n=e.__importDefault(he());ee.PostgrestQueryBuilder=n.default;const r=e.__importDefault(de());ee.PostgrestFilterBuilder=r.default;const i=e.__importDefault(ue());ee.PostgrestTransformBuilder=i.default;const s=e.__importDefault(le());ee.PostgrestBuilder=s.default;const a=e.__importDefault(ce());return ee.PostgrestError=a.default,ee.default={PostgrestClient:t.default,PostgrestQueryBuilder:n.default,PostgrestFilterBuilder:r.default,PostgrestTransformBuilder:i.default,PostgrestBuilder:s.default,PostgrestError:a.default},ee}(),pe=W(fe),me=e({__proto__:null,default:pe},[fe]);const{PostgrestClient:ge,PostgrestQueryBuilder:be,PostgrestFilterBuilder:we,PostgrestTransformBuilder:ye,PostgrestBuilder:ve,PostgrestError:_e}=pe||me;class ke{constructor(){}static detectEnvironment(){var e;if("undefined"!=typeof WebSocket)return{type:"native",constructor:WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocket)return{type:"native",constructor:globalThis.WebSocket};if("undefined"!=typeof global&&void 0!==global.WebSocket)return{type:"native",constructor:global.WebSocket};if("undefined"!=typeof globalThis&&void 0!==globalThis.WebSocketPair&&void 0===globalThis.WebSocket)return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if("undefined"!=typeof globalThis&&globalThis.EdgeRuntime||"undefined"!=typeof navigator&&(null===(e=navigator.userAgent)||void 0===e?void 0:e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};if("undefined"!=typeof process){const e=process.versions;if(e&&e.node){const t=e.node,n=parseInt(t.replace(/^v/,"").split(".")[0]);return n>=22?void 0!==globalThis.WebSocket?{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:\nimport ws from "ws"\nnew RealtimeClient(url, { transport: ws })'}}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const e=this.detectEnvironment();if(e.constructor)return e.constructor;let t=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),new Error(t)}static createWebSocket(e,t){return new(this.getWebSocketConstructor())(e,t)}static isWebSocketSupported(){try{const e=this.detectEnvironment();return"native"===e.type||"ws"===e.type}catch(e){return!1}}}const Se="1.0.0",Ee=Se,Te=1e4;var Oe,xe,je,Pe,Ae,Ce;!function(e){e[e.connecting=0]="connecting",e[e.open=1]="open",e[e.closing=2]="closing",e[e.closed=3]="closed"}(Oe||(Oe={})),function(e){e.closed="closed",e.errored="errored",e.joined="joined",e.joining="joining",e.leaving="leaving"}(xe||(xe={})),function(e){e.close="phx_close",e.error="phx_error",e.join="phx_join",e.reply="phx_reply",e.leave="phx_leave",e.access_token="access_token"}(je||(je={})),function(e){e.websocket="websocket"}(Pe||(Pe={})),function(e){e.Connecting="connecting",e.Open="open",e.Closing="closing",e.Closed="closed"}(Ae||(Ae={}));class Ie{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=null!=e?e:[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&"string"==typeof e.payload.event)return t(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){var t;return this._isArrayBuffer(null===(t=e.payload)||void 0===t?void 0:t.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var t,n;const r=null!==(n=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==n?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,r)}_encodeJsonUserBroadcastPush(e){var t,n;const r=null!==(n=null===(t=e.payload)||void 0===t?void 0:t.payload)&&void 0!==n?n:{},i=(new TextEncoder).encode(JSON.stringify(r)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,i)}_encodeUserBroadcastPush(e,t,n){var r,i;const s=e.topic,a=null!==(r=e.ref)&&void 0!==r?r:"",o=null!==(i=e.join_ref)&&void 0!==i?i:"",c=e.payload.event,l=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},u=0===Object.keys(l).length?"":JSON.stringify(l);if(o.length>255)throw new Error(`joinRef length ${o.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(s.length>255)throw new Error(`topic length ${s.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(u.length>255)throw new Error(`metadata length ${u.length} exceeds maximum of 255`);const d=this.USER_BROADCAST_PUSH_META_LENGTH+o.length+a.length+s.length+c.length+u.length,h=new ArrayBuffer(this.HEADER_LENGTH+d);let f=new DataView(h),p=0;f.setUint8(p++,this.KINDS.userBroadcastPush),f.setUint8(p++,o.length),f.setUint8(p++,a.length),f.setUint8(p++,s.length),f.setUint8(p++,c.length),f.setUint8(p++,u.length),f.setUint8(p++,t),Array.from(o,e=>f.setUint8(p++,e.charCodeAt(0))),Array.from(a,e=>f.setUint8(p++,e.charCodeAt(0))),Array.from(s,e=>f.setUint8(p++,e.charCodeAt(0))),Array.from(c,e=>f.setUint8(p++,e.charCodeAt(0))),Array.from(u,e=>f.setUint8(p++,e.charCodeAt(0)));var m=new Uint8Array(h.byteLength+n.byteLength);return m.set(new Uint8Array(h),0),m.set(new Uint8Array(n),h.byteLength),m.buffer}decode(e,t){if(this._isArrayBuffer(e)){return t(this._binaryDecode(e))}if("string"==typeof e){const n=JSON.parse(e),[r,i,s,a,o]=n;return t({join_ref:r,ref:i,topic:s,event:a,payload:o})}return t({})}_binaryDecode(e){const t=new DataView(e),n=t.getUint8(0),r=new TextDecoder;if(n===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,t,r)}_decodeUserBroadcast(e,t,n){const r=t.getUint8(1),i=t.getUint8(2),s=t.getUint8(3),a=t.getUint8(4);let o=this.HEADER_LENGTH+4;const c=n.decode(e.slice(o,o+r));o+=r;const l=n.decode(e.slice(o,o+i));o+=i;const u=n.decode(e.slice(o,o+s));o+=s;const d=e.slice(o,e.byteLength),h=a===this.JSON_ENCODING?JSON.parse(n.decode(d)):d,f={type:this.BROADCAST_EVENT,event:l,payload:h};return s>0&&(f.meta=JSON.parse(u)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:f}}_isArrayBuffer(e){var t;return e instanceof ArrayBuffer||"ArrayBuffer"===(null===(t=null==e?void 0:e.constructor)||void 0===t?void 0:t.name)}_pick(e,t){return e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e))):{}}}class Re{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer),this.timer=void 0}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}!function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"}(Ce||(Ce={}));const $e=(e,t,n={})=>{var r;const i=null!==(r=n.skipTypes)&&void 0!==r?r:[];return t?Object.keys(t).reduce((n,r)=>(n[r]=Ue(r,e,t,i),n),{}):{}},Ue=(e,t,n,r)=>{const i=t.find(t=>t.name===e),s=null==i?void 0:i.type,a=n[e];return s&&!r.includes(s)?Ne(s,a):De(a)},Ne=(e,t)=>{if("_"===e.charAt(0)){const n=e.slice(1,e.length);return Fe(t,n)}switch(e){case Ce.bool:return Be(t);case Ce.float4:case Ce.float8:case Ce.int2:case Ce.int4:case Ce.int8:case Ce.numeric:case Ce.oid:return Le(t);case Ce.json:case Ce.jsonb:return qe(t);case Ce.timestamp:return Me(t);case Ce.abstime:case Ce.date:case Ce.daterange:case Ce.int4range:case Ce.int8range:case Ce.money:case Ce.reltime:case Ce.text:case Ce.time:case Ce.timestamptz:case Ce.timetz:case Ce.tsrange:case Ce.tstzrange:default:return De(t)}},De=e=>e,Be=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},Le=e=>{if("string"==typeof e){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},qe=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(t){return console.log(`JSON parse error: ${t}`),e}return e},Fe=(e,t)=>{if("string"!=typeof e)return e;const n=e.length-1,r=e[n];if("{"===e[0]&&"}"===r){let r;const i=e.slice(1,n);try{r=JSON.parse("["+i+"]")}catch(e){r=i?i.split(","):[]}return r.map(e=>Ne(t,e))}return e},Me=e=>"string"==typeof e?e.replace(" ","T"):e,Ke=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),""===t.pathname||"/"===t.pathname?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};class ze{constructor(e,t,n={},r=1e4){this.channel=e,this.event=t,this.payload=n,this.timeout=r,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var n;return this._hasReceived(e)&&t(null===(n=this.receivedResp)||void 0===n?void 0:n.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);this.channel._on(this.refEvent,{},e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var We,Ge,Ve,He;!function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"}(We||(We={}));class Je{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const n=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(n.state,{},e=>{const{onJoin:t,onLeave:n,onSync:r}=this.caller;this.joinRef=this.channel._joinRef(),this.state=Je.syncState(this.state,e,t,n),this.pendingDiffs.forEach(e=>{this.state=Je.syncDiff(this.state,e,t,n)}),this.pendingDiffs=[],r()}),this.channel._on(n.diff,{},e=>{const{onJoin:t,onLeave:n,onSync:r}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=Je.syncDiff(this.state,e,t,n),r())}),this.onJoin((e,t,n)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:n})}),this.onLeave((e,t,n)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:n})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,n,r){const i=this.cloneDeep(e),s=this.transformState(t),a={},o={};return this.map(i,(e,t)=>{s[e]||(o[e]=t)}),this.map(s,(e,t)=>{const n=i[e];if(n){const r=t.map(e=>e.presence_ref),i=n.map(e=>e.presence_ref),s=t.filter(e=>i.indexOf(e.presence_ref)<0),c=n.filter(e=>r.indexOf(e.presence_ref)<0);s.length>0&&(a[e]=s),c.length>0&&(o[e]=c)}else a[e]=t}),this.syncDiff(i,{joins:a,leaves:o},n,r)}static syncDiff(e,t,n,r){const{joins:i,leaves:s}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return n||(n=()=>{}),r||(r=()=>{}),this.map(i,(t,r)=>{var i;const s=null!==(i=e[t])&&void 0!==i?i:[];if(e[t]=this.cloneDeep(r),s.length>0){const n=e[t].map(e=>e.presence_ref),r=s.filter(e=>n.indexOf(e.presence_ref)<0);e[t].unshift(...r)}n(t,s,r)}),this.map(s,(t,n)=>{let i=e[t];if(!i)return;const s=n.map(e=>e.presence_ref);i=i.filter(e=>s.indexOf(e.presence_ref)<0),e[t]=i,r(t,i,n),0===i.length&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(n=>t(n,e[n]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,n)=>{const r=e[n];return t[n]="metas"in r?r.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):r,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}!function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"}(Ge||(Ge={})),function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"}(Ve||(Ve={})),function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"}(He||(He={}));class Ye{constructor(e,t={config:{}},n){var r,i;if(this.topic=e,this.params=t,this.socket=n,this.bindings={},this.state=xe.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 ze(this,je.join,this.params,this.timeout),this.rejoinTimer=new Re(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=xe.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=xe.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=xe.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=xe.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=xe.errored,this.rejoinTimer.scheduleTimeout())}),this._on(je.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new Je(this),this.broadcastEndpointURL=Ke(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(null===(i=null===(r=this.params.config)||void 0===r?void 0:r.broadcast)||void 0===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 n,r,i;if(this.socket.isConnected()||this.socket.connect(),this.state==xe.closed){const{config:{broadcast:s,presence:a,private:o}}=this.params,c=null!==(r=null===(n=this.bindings.postgres_changes)||void 0===n?void 0:n.map(e=>e.filter))&&void 0!==r?r:[],l=!!this.bindings[Ve.PRESENCE]&&this.bindings[Ve.PRESENCE].length>0||!0===(null===(i=this.params.config.presence)||void 0===i?void 0:i.enabled),u={},d={broadcast:s,presence:Object.assign(Object.assign({},a),{enabled:l}),postgres_changes:c,private:o};this.socket.accessTokenValue&&(u.access_token=this.socket.accessTokenValue),this._onError(t=>null==e?void 0:e(He.CHANNEL_ERROR,t)),this._onClose(()=>null==e?void 0:e(He.CLOSED)),this.updateJoinPayload(Object.assign({config:d},u)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",async({postgres_changes:t})=>{var n;if(this.socket.setAuth(),void 0!==t){const r=this.bindings.postgres_changes,i=null!==(n=null==r?void 0:r.length)&&void 0!==n?n:0,s=[];for(let n=0;n<i;n++){const i=r[n],{filter:{event:a,schema:o,table:c,filter:l}}=i,u=t&&t[n];if(!u||u.event!==a||u.schema!==o||u.table!==c||u.filter!==l)return this.unsubscribe(),this.state=xe.errored,void(null==e||e(He.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes")));s.push(Object.assign(Object.assign({},i),{id:u.id}))}return this.bindings.postgres_changes=s,void(e&&e(He.SUBSCRIBED))}null==e||e(He.SUBSCRIBED)}).receive("error",t=>{this.state=xe.errored,null==e||e(He.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{null==e||e(He.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,n){return this.state===xe.joined&&e===Ve.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(()=>this.subscribe())),this._on(e,t,n)}async httpSend(e,t,n={}){var r;const i=this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"";if(null==t)return Promise.reject("Payload is required for httpSend()");const s={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,s,null!==(r=n.timeout)&&void 0!==r?r:this.timeout);if(202===a.status)return{success:!0};let o=a.statusText;try{const e=await a.json();o=e.error||e.message||o}catch(e){}return Promise.reject(new Error(o))}async send(e,t={}){var n,r;if(this._canPush()||"broadcast"!==e.type)return new Promise(n=>{var r,i,s;const a=this._push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null===(s=null===(i=null===(r=this.params)||void 0===r?void 0:r.config)||void 0===i?void 0:i.broadcast)||void 0===s?void 0:s.ack)||n("ok"),a.receive("ok",()=>n("ok")),a.receive("error",()=>n("error")),a.receive("timeout",()=>n("timed out"))});{console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:i,payload:s}=e,a={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:s,private:this.private}]})};try{const e=await this._fetchWithTimeout(this.broadcastEndpointURL,a,null!==(n=t.timeout)&&void 0!==n?n:this.timeout);return await(null===(r=e.body)||void 0===r?void 0:r.cancel()),e.ok?"ok":"error"}catch(e){return"AbortError"===e.name?"timed out":"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=xe.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(je.close,"leave",this._joinRef())};this.joinPush.destroy();let n=null;return new Promise(r=>{n=new ze(this,je.leave,{},e),n.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),n.send(),this._canPush()||n.trigger("ok",{})}).finally(()=>{null==n||n.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=xe.closed,this.bindings={}}async _fetchWithTimeout(e,t,n){const r=new AbortController,i=setTimeout(()=>r.abort(),n),s=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(i),s}_push(e,t,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let r=new ze(this,e,t,n);return this._canPush()?r.send():this._addToPushBuffer(r),r}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>100){const e=this.pushBuffer.shift();e&&(e.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${e.event}`,e.payload))}}_onMessage(e,t,n){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,n){var r,i;const s=e.toLocaleLowerCase(),{close:a,error:o,leave:c,join:l}=je;if(n&&[a,o,c,l].indexOf(s)>=0&&n!==this._joinRef())return;let u=this._onMessage(s,t,n);if(t&&!u)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(s)?null===(r=this.bindings.postgres_changes)||void 0===r||r.filter(e=>{var t,n,r;return"*"===(null===(t=e.filter)||void 0===t?void 0:t.event)||(null===(r=null===(n=e.filter)||void 0===n?void 0:n.event)||void 0===r?void 0:r.toLocaleLowerCase())===s}).map(e=>e.callback(u,n)):null===(i=this.bindings[s])||void 0===i||i.filter(e=>{var n,r,i,a,o,c;if(["broadcast","presence","postgres_changes"].includes(s)){if("id"in e){const s=e.id,a=null===(n=e.filter)||void 0===n?void 0:n.event;return s&&(null===(r=t.ids)||void 0===r?void 0:r.includes(s))&&("*"===a||(null==a?void 0:a.toLocaleLowerCase())===(null===(i=t.data)||void 0===i?void 0:i.type.toLocaleLowerCase()))}{const n=null===(o=null===(a=null==e?void 0:e.filter)||void 0===a?void 0:a.event)||void 0===o?void 0:o.toLocaleLowerCase();return"*"===n||n===(null===(c=null==t?void 0:t.event)||void 0===c?void 0:c.toLocaleLowerCase())}}return e.type.toLocaleLowerCase()===s}).map(e=>{if("object"==typeof u&&"ids"in u){const e=u.data,{schema:t,table:n,commit_timestamp:r,type:i,errors:s}=e,a={schema:t,table:n,commit_timestamp:r,eventType:i,new:{},old:{},errors:s};u=Object.assign(Object.assign({},a),this._getPayloadRecords(e))}e.callback(u,n)})}_isClosed(){return this.state===xe.closed}_isJoined(){return this.state===xe.joined}_isJoining(){return this.state===xe.joining}_isLeaving(){return this.state===xe.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,n){const r=e.toLocaleLowerCase(),i={type:r,filter:t,callback:n};return this.bindings[r]?this.bindings[r].push(i):this.bindings[r]=[i],this}_off(e,t){const n=e.toLocaleLowerCase();return this.bindings[n]&&(this.bindings[n]=this.bindings[n].filter(e=>{var r;return!((null===(r=e.type)||void 0===r?void 0:r.toLocaleLowerCase())===n&&Ye.isEqual(e.filter,t))})),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(je.close,{},e)}_onError(e){this._on(je.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=xe.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return"INSERT"!==e.type&&"UPDATE"!==e.type||(t.new=$e(e.columns,e.record)),"UPDATE"!==e.type&&"DELETE"!==e.type||(t.old=$e(e.columns,e.old_record)),t}}const Qe=()=>{},Xe=25e3,Ze=10,et=100,tt=[1e3,2e3,5e3,1e4];class nt{constructor(e,t){var n;if(this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=Te,this.transport=null,this.heartbeatIntervalMs=Xe,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Qe,this.ref=0,this.reconnectTimer=null,this.vsn=Ee,this.logger=Qe,this.conn=null,this.sendBuffer=[],this.serializer=new Ie,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!(null===(n=null==t?void 0:t.params)||void 0===n?void 0:n.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=t.params.apikey,this.endPoint=`${e}/${Pe.websocket}`,this.httpEndpoint=Ke(e),this._initializeOptions(t),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(null==t?void 0:t.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||null!==this.conn&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=ke.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");const t=e.message;if(t.includes("Node.js"))throw new Error(`${t}\n\nTo use Realtime in Node.js, you need to provide a WebSocket implementation:\n\nOption 1: Use Node.js 22+ which has native WebSocket support\nOption 2: Install and provide the "ws" package:\n\n npm install ws\n\n import ws from "ws"\n const client = new RealtimeClient(url, {\n ...options,\n transport: ws\n })`);throw new Error(`WebSocket not available: ${t}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,t){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){const n=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(n),this._setConnectionState("disconnected")},"function"==typeof this.conn.close&&(e?this.conn.close(e,null!=t?t:""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){const t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){const e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,t,n){this.logger(e,t,n)}connectionState(){switch(this.conn&&this.conn.readyState){case Oe.connecting:return Ae.Connecting;case Oe.open:return Ae.Open;case Oe.closing:return Ae.Closing;default:return Ae.Closed}}isConnected(){return this.connectionState()===Ae.Open}isConnecting(){return"connecting"===this._connectionState}isDisconnecting(){return"disconnecting"===this._connectionState}channel(e,t={config:{}}){const n=`realtime:${e}`,r=this.getChannels().find(e=>e.topic===n);if(r)return r;{const n=new Ye(`realtime:${e}`,t,this);return this.channels.push(n),n}}push(e){const{topic:t,event:n,payload:r,ref:i}=e,s=()=>{this.encode(e,e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)})};this.log("push",`${t} ${n} (${i})`,r),this.isConnected()?s():this.sendBuffer.push(s)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}async sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}return this._wasManualDisconnect=!1,null===(e=this.conn)||void 0===e||e.close(1e3,"heartbeat timeout"),void setTimeout(()=>{var e;this.isConnected()||null===(e=this.reconnectTimer)||void 0===e||e.scheduleTimeout()},et)}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this._setAuthSafely("heartbeat")}else try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,e=>{if("phoenix"===e.topic&&"phx_reply"===e.event)try{this.heartbeatCallback("ok"===e.payload.status?"ok":"error")}catch(e){this.log("error","error in heartbeat callback",e)}e.ref&&e.ref===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null);const{topic:t,event:n,payload:r,ref:i}=e,s=i?`(${i})`:"",a=r.status||"";this.log("receive",`${a} ${t} ${n} ${s}`.trim(),r),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(n,r,i)),this._triggerStateCallbacks("message",e)})}_clearTimer(e){var t;"heartbeat"===e&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):"reconnect"===e&&(null===(t=this.reconnectTimer)||void 0===t||t.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_teardownConnection(){if(this.conn){if(this.conn.readyState===Oe.open||this.conn.readyState===Oe.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(e=>{this.log("error","error waiting for auth on connect",e),this.flushSendBuffer()}),this._clearTimer("reconnect"),this.worker?this.workerRef||this._startWorkerHeartbeat():this._startHeartbeat(),this._triggerStateCallbacks("open")}_startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs)}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log("worker","worker error",e.message),this.workerRef.terminate()},this.workerRef.onmessage=e=>{"keepAlive"===e.data.event&&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||null===(t=this.reconnectTimer)||void 0===t||t.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e)}_triggerChanError(){this.channels.forEach(e=>e._trigger(je.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;const n=e.match(/\?/)?"&":"?";return`${e}${n}${new URLSearchParams(t)}`}_workerObjectUrl(e){let t;if(e)t=e;else{const e=new Blob(['\n addEventListener("message", (e) => {\n if (e.data.event === "start") {\n setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);\n }\n });'],{type:"application/javascript"});t=URL.createObjectURL(e)}return t}_setConnectionState(e,t=!1){this._connectionState=e,"connecting"===e?this._wasManualDisconnect=!1:"disconnecting"===e&&(this._wasManualDisconnect=t)}async _performAuth(e=null){let t;t=e||(this.accessToken?await this.accessToken():this.accessTokenValue),this.accessTokenValue!=t&&(this.accessTokenValue=t,this.channels.forEach(e=>{const n={access_token:t,version:"realtime-js/2.86.0"};t&&e.updateJoinPayload(n),e.joinedOnce&&e._isJoined()&&e._push(je.access_token,{access_token:t})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this.setAuth().catch(t=>{this.log("error",`error setting auth in ${e}`,t)})}_triggerStateCallbacks(e,t){try{this.stateChangeCallbacks[e].forEach(n=>{try{n(t)}catch(t){this.log("error",`error in ${e} callback`,t)}})}catch(t){this.log("error",`error triggering ${e} callbacks`,t)}}_setupReconnectionTimer(){this.reconnectTimer=new Re(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Ze)},this.reconnectAfterMs)}_initializeOptions(e){var t,n,r,i,s,a,o,c,l,u,d,h;switch(this.transport=null!==(t=null==e?void 0:e.transport)&&void 0!==t?t:null,this.timeout=null!==(n=null==e?void 0:e.timeout)&&void 0!==n?n:Te,this.heartbeatIntervalMs=null!==(r=null==e?void 0:e.heartbeatIntervalMs)&&void 0!==r?r:Xe,this.worker=null!==(i=null==e?void 0:e.worker)&&void 0!==i&&i,this.accessToken=null!==(s=null==e?void 0:e.accessToken)&&void 0!==s?s:null,this.heartbeatCallback=null!==(a=null==e?void 0:e.heartbeatCallback)&&void 0!==a?a:Qe,this.vsn=null!==(o=null==e?void 0:e.vsn)&&void 0!==o?o:Ee,(null==e?void 0:e.params)&&(this.params=e.params),(null==e?void 0:e.logger)&&(this.logger=e.logger),((null==e?void 0:e.logLevel)||(null==e?void 0:e.log_level))&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=null!==(c=null==e?void 0:e.reconnectAfterMs)&&void 0!==c?c:e=>tt[e-1]||1e4,this.vsn){case Se:this.encode=null!==(l=null==e?void 0:e.encode)&&void 0!==l?l:(e,t)=>t(JSON.stringify(e)),this.decode=null!==(u=null==e?void 0:e.decode)&&void 0!==u?u:(e,t)=>t(JSON.parse(e));break;case"2.0.0":this.encode=null!==(d=null==e?void 0:e.encode)&&void 0!==d?d:this.serializer.encode.bind(this.serializer),this.decode=null!==(h=null==e?void 0:e.decode)&&void 0!==h?h:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if("undefined"!=typeof window&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=null==e?void 0:e.workerUrl}}}class rt extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function it(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}class st extends rt{constructor(e,t,n){super(e),this.name="StorageApiError",this.status=t,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class at extends rt{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}const ot=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),ct=e=>{if(Array.isArray(e))return e.map(e=>ct(e));if("function"==typeof e||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([e,n])=>{const r=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,""));t[r]=ct(n)}),t},lt=e=>{var t;return e.msg||e.message||e.error_description||("string"==typeof e.error?e.error:null===(t=e.error)||void 0===t?void 0:t.message)||JSON.stringify(e)},ut=(e,t,n)=>h(void 0,void 0,void 0,function*(){const r=yield Response;e instanceof r&&!(null==n?void 0:n.noResolveJson)?e.json().then(n=>{const r=e.status||500,i=(null==n?void 0:n.statusCode)||r+"";t(new st(lt(n),r,i))}).catch(e=>{t(new at(lt(e),e))}):t(new at(lt(e),e))}),dt=(e,t,n,r)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&r?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(r)?(i.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),i.body=JSON.stringify(r)):i.body=r,(null==t?void 0:t.duplex)&&(i.duplex=t.duplex),Object.assign(Object.assign({},i),n)):i};function ht(e,t,n,r,i,s){return h(this,void 0,void 0,function*(){return new Promise((a,o)=>{e(n,dt(t,r,i,s)).then(e=>{if(!e.ok)throw e;return(null==r?void 0:r.noResolveJson)?e:e.json()}).then(e=>a(e)).catch(e=>ut(e,o,r))})})}function ft(e,t,n,r){return h(this,void 0,void 0,function*(){return ht(e,"GET",t,n,r)})}function pt(e,t,n,r,i){return h(this,void 0,void 0,function*(){return ht(e,"POST",t,r,i,n)})}function mt(e,t,n,r,i){return h(this,void 0,void 0,function*(){return ht(e,"PUT",t,r,i,n)})}function gt(e,t,n,r,i){return h(this,void 0,void 0,function*(){return ht(e,"DELETE",t,r,i,n)})}class bt{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t}then(e,t){return this.execute().then(e,t)}execute(){return h(this,void 0,void 0,function*(){try{return{data:(yield this.downloadFn()).body,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}}var wt;wt=Symbol.toStringTag;var yt=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[wt]="BlobDownloadBuilder",this.promise=null}asStream(){return new bt(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 h(this,void 0,void 0,function*(){try{const e=yield this.downloadFn();return{data:yield e.blob(),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}};const vt={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},_t={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class kt{constructor(e,t={},n,r){this.shouldThrowOnError=!1,this.url=e,this.headers=t,this.bucketId=n,this.fetch=ot(r)}throwOnError(){return this.shouldThrowOnError=!0,this}uploadOrUpdate(e,t,n,r){return h(this,void 0,void 0,function*(){try{let i;const s=Object.assign(Object.assign({},_t),r);let a=Object.assign(Object.assign({},this.headers),"POST"===e&&{"x-upsert":String(s.upsert)});const o=s.metadata;if("undefined"!=typeof Blob&&n instanceof Blob)i=new FormData,i.append("cacheControl",s.cacheControl),o&&i.append("metadata",this.encodeMetadata(o)),i.append("",n);else if("undefined"!=typeof FormData&&n instanceof FormData)i=n,i.has("cacheControl")||i.append("cacheControl",s.cacheControl),o&&!i.has("metadata")&&i.append("metadata",this.encodeMetadata(o));else{i=n,a["cache-control"]=`max-age=${s.cacheControl}`,a["content-type"]=s.contentType,o&&(a["x-metadata"]=this.toBase64(this.encodeMetadata(o)));("undefined"!=typeof ReadableStream&&i instanceof ReadableStream||i&&"object"==typeof i&&"pipe"in i&&"function"==typeof i.pipe)&&!s.duplex&&(s.duplex="half")}(null==r?void 0:r.headers)&&(a=Object.assign(Object.assign({},a),r.headers));const c=this._removeEmptyFolders(t),l=this._getFinalPath(c),u=yield("PUT"==e?mt:pt)(this.fetch,`${this.url}/object/${l}`,i,Object.assign({headers:a},(null==s?void 0:s.duplex)?{duplex:s.duplex}:{}));return{data:{path:c,id:u.Id,fullPath:u.Key},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}upload(e,t,n){return h(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,n)})}uploadToSignedUrl(e,t,n,r){return h(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(e),s=this._getFinalPath(i),a=new URL(this.url+`/object/upload/sign/${s}`);a.searchParams.set("token",t);try{let e;const t=Object.assign({upsert:_t.upsert},r),s=Object.assign(Object.assign({},this.headers),{"x-upsert":String(t.upsert)});"undefined"!=typeof Blob&&n instanceof Blob?(e=new FormData,e.append("cacheControl",t.cacheControl),e.append("",n)):"undefined"!=typeof FormData&&n instanceof FormData?(e=n,e.append("cacheControl",t.cacheControl)):(e=n,s["cache-control"]=`max-age=${t.cacheControl}`,s["content-type"]=t.contentType);return{data:{path:i,fullPath:(yield mt(this.fetch,a.toString(),e,{headers:s})).Key},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}createSignedUploadUrl(e,t){return h(this,void 0,void 0,function*(){try{let n=this._getFinalPath(e);const r=Object.assign({},this.headers);(null==t?void 0:t.upsert)&&(r["x-upsert"]="true");const i=yield pt(this.fetch,`${this.url}/object/upload/sign/${n}`,{},{headers:r}),s=new URL(this.url+i.url),a=s.searchParams.get("token");if(!a)throw new rt("No token returned by API");return{data:{signedUrl:s.toString(),path:e,token:a},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}update(e,t,n){return h(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,n)})}move(e,t,n){return h(this,void 0,void 0,function*(){try{return{data:yield pt(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==n?void 0:n.destinationBucket},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}copy(e,t,n){return h(this,void 0,void 0,function*(){try{return{data:{path:(yield pt(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t,destinationBucket:null==n?void 0:n.destinationBucket},{headers:this.headers})).Key},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}createSignedUrl(e,t,n){return h(this,void 0,void 0,function*(){try{let r=this._getFinalPath(e),i=yield pt(this.fetch,`${this.url}/object/sign/${r}`,Object.assign({expiresIn:t},(null==n?void 0:n.transform)?{transform:n.transform}:{}),{headers:this.headers});const s=(null==n?void 0:n.download)?`&download=${!0===n.download?"":n.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${s}`)},{data:i,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}createSignedUrls(e,t,n){return h(this,void 0,void 0,function*(){try{const r=yield pt(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=(null==n?void 0:n.download)?`&download=${!0===n.download?"":n.download}`:"";return{data:r.map(e=>Object.assign(Object.assign({},e),{signedUrl:e.signedURL?encodeURI(`${this.url}${e.signedURL}${i}`):null})),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}download(e,t){const n=void 0!==(null==t?void 0:t.transform)?"render/image/authenticated":"object",r=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),i=r?`?${r}`:"",s=this._getFinalPath(e);return new yt(()=>ft(this.fetch,`${this.url}/${n}/${s}${i}`,{headers:this.headers,noResolveJson:!0}),this.shouldThrowOnError)}info(e){return h(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{const e=yield ft(this.fetch,`${this.url}/object/info/${t}`,{headers:this.headers});return{data:ct(e),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}exists(e){return h(this,void 0,void 0,function*(){const t=this._getFinalPath(e);try{return yield function(e,t,n,r){return h(this,void 0,void 0,function*(){return ht(e,"HEAD",t,Object.assign(Object.assign({},n),{noResolveJson:!0}),r)})}(this.fetch,`${this.url}/object/${t}`,{headers:this.headers}),{data:!0,error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e)&&e instanceof at){const t=e.originalError;if([400,404].includes(null==t?void 0:t.status))return{data:!1,error:e}}throw e}})}getPublicUrl(e,t){const n=this._getFinalPath(e),r=[],i=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==i&&r.push(i);const s=void 0!==(null==t?void 0:t.transform)?"render/image":"object",a=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==a&&r.push(a);let o=r.join("&");return""!==o&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${s}/public/${n}${o}`)}}}remove(e){return h(this,void 0,void 0,function*(){try{return{data:yield gt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}list(e,t,n){return h(this,void 0,void 0,function*(){try{const r=Object.assign(Object.assign(Object.assign({},vt),t),{prefix:e||""});return{data:yield pt(this.fetch,`${this.url}/object/list/${this.bucketId}`,r,{headers:this.headers},n),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}listV2(e,t){return h(this,void 0,void 0,function*(){try{const n=Object.assign({},e);return{data:yield pt(this.fetch,`${this.url}/object/list-v2/${this.bucketId}`,n,{headers:this.headers},t),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return"undefined"!=typeof Buffer?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}const St="2.86.0",Et={"X-Client-Info":`storage-js/${St}`};class Tt{constructor(e,t={},n,r){this.shouldThrowOnError=!1;const i=new URL(e);if(null==r?void 0:r.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({},Et),t),this.fetch=ot(n)}throwOnError(){return this.shouldThrowOnError=!0,this}listBuckets(e){return h(this,void 0,void 0,function*(){try{const t=this.listBucketOptionsToQueryString(e);return{data:yield ft(this.fetch,`${this.url}/bucket${t}`,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}getBucket(e){return h(this,void 0,void 0,function*(){try{return{data:yield ft(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}createBucket(e){return h(this,arguments,void 0,function*(e,t={public:!1}){try{return{data:yield pt(this.fetch,`${this.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}updateBucket(e,t){return h(this,void 0,void 0,function*(){try{return{data:yield mt(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(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}emptyBucket(e){return h(this,void 0,void 0,function*(){try{return{data:yield pt(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}deleteBucket(e){return h(this,void 0,void 0,function*(){try{return{data:yield gt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}}var Ot=class extends Error{constructor(e,t){super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown="CommitStateUnknownException"===t.icebergType||[500,502,504].includes(t.status)&&!0===t.icebergType?.includes("CommitState")}isNotFound(){return 404===this.status}isConflict(){return 409===this.status}isAuthenticationTimeout(){return 419===this.status}};function xt(e){const t=e.fetchImpl??globalThis.fetch;return{async request({method:n,path:r,query:i,body:s,headers:a}){const o=function(e,t,n){const r=new URL(t,e);if(n)for(const[e,t]of Object.entries(n))void 0!==t&&r.searchParams.set(e,t);return r.toString()}(e.baseUrl,r,i),c=await async function(e){return e&&"none"!==e.type?"bearer"===e.type?{Authorization:`Bearer ${e.token}`}:"header"===e.type?{[e.name]:e.value}:"custom"===e.type?await e.getHeaders():{}:{}}(e.auth),l=await t(o,{method:n,headers:{...s?{"Content-Type":"application/json"}:{},...c,...a},body:s?JSON.stringify(s):void 0}),u=await l.text(),d=(l.headers.get("content-type")||"").includes("application/json"),h=d&&u?JSON.parse(u):u;if(!l.ok){const e=d?h:void 0,t=e?.error;throw new Ot(t?.message??`Request failed with status ${l.status}`,{status:l.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:l.status,headers:l.headers,data:h}}}}function jt(e){return e.join("")}var Pt=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){const t=e?{parent:jt(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){const n={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:n})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${jt(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${jt(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${jt(e.namespace)}`}),!0}catch(e){if(e instanceof Ot&&404===e.status)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof Ot&&409===e.status)return;throw e}}};function At(e){return e.join("")}var Ct=class{constructor(e,t="",n){this.client=e,this.prefix=t,this.accessDelegation=n}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${At(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){const n={};this.accessDelegation&&(n["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${At(e.namespace)}/tables`,body:t,headers:n})).data.metadata}async updateTable(e,t){const n=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${At(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":n.data["metadata-location"],metadata:n.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${At(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${At(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${At(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof Ot&&404===e.status)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(n){if(n instanceof Ot&&409===n.status)return await this.loadTable({namespace:e.namespace,name:t.name});throw n}}},It=class{constructor(e){let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const n=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=xt({baseUrl:n,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(","),this.namespaceOps=new Pt(this.client,t),this.tableOps=new Ct(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}};class Rt{constructor(e,t={},n){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},Et),t),this.fetch=ot(n)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return h(this,void 0,void 0,function*(){try{return{data:yield pt(this.fetch,`${this.url}/bucket`,{name:e},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}listBuckets(e){return h(this,void 0,void 0,function*(){try{const t=new URLSearchParams;void 0!==(null==e?void 0:e.limit)&&t.set("limit",e.limit.toString()),void 0!==(null==e?void 0:e.offset)&&t.set("offset",e.offset.toString()),(null==e?void 0:e.sortColumn)&&t.set("sortColumn",e.sortColumn),(null==e?void 0:e.sortOrder)&&t.set("sortOrder",e.sortOrder),(null==e?void 0:e.search)&&t.set("search",e.search);const n=t.toString(),r=n?`${this.url}/bucket?${n}`:`${this.url}/bucket`;return{data:yield ft(this.fetch,r,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}deleteBucket(e){return h(this,void 0,void 0,function*(){try{return{data:yield gt(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(it(e))return{data:null,error:e};throw e}})}from(e){if(!(e=>!(!e||"string"!=typeof e)&&(!(0===e.length||e.length>100)&&(e.trim()===e&&(!e.includes("/")&&!e.includes("\\")&&/^[\w!.\*'() &$@=;:+,?-]+$/.test(e)))))(e))throw new rt("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");return new It({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:()=>h(this,void 0,void 0,function*(){return this.headers})},fetch:this.fetch})}}const $t={"X-Client-Info":`storage-js/${St}`,"Content-Type":"application/json"};class Ut extends Error{constructor(e){super(e),this.__isStorageVectorsError=!0,this.name="StorageVectorsError"}}function Nt(e){return"object"==typeof e&&null!==e&&"__isStorageVectorsError"in e}class Dt extends Ut{constructor(e,t,n){super(e),this.name="StorageVectorsApiError",this.status=t,this.statusCode=n}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}}class Bt extends Ut{constructor(e,t){super(e),this.name="StorageVectorsUnknownError",this.originalError=t}}var Lt;!function(e){e.InternalError="InternalError",e.S3VectorConflictException="S3VectorConflictException",e.S3VectorNotFoundException="S3VectorNotFoundException",e.S3VectorBucketNotEmpty="S3VectorBucketNotEmpty",e.S3VectorMaxBucketsExceeded="S3VectorMaxBucketsExceeded",e.S3VectorMaxIndexesExceeded="S3VectorMaxIndexesExceeded"}(Lt||(Lt={}));const qt=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Ft=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),Mt=(e,t,n,r)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"!==e&&r?((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)})(r)?(i.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),i.body=JSON.stringify(r)):i.body=r,Object.assign(Object.assign({},i),n)):i};function Kt(e,t,n,r,i,s){return h(this,void 0,void 0,function*(){return new Promise((a,o)=>{e(n,Mt(t,r,i,s)).then(e=>{if(!e.ok)throw e;if(null==r?void 0:r.noResolveJson)return e;const t=e.headers.get("content-type");return t&&t.includes("application/json")?e.json():{}}).then(e=>a(e)).catch(e=>((e,t,n)=>h(void 0,void 0,void 0,function*(){if(e&&"object"==typeof e&&"status"in e&&"ok"in e&&"number"==typeof e.status&&!(null==n?void 0:n.noResolveJson)){const n=e.status||500,r=e;if("function"==typeof r.json)r.json().then(e=>{const r=(null==e?void 0:e.statusCode)||(null==e?void 0:e.code)||n+"";t(new Dt(Ft(e),n,r))}).catch(()=>{const e=n+"",i=r.statusText||`HTTP ${n} error`;t(new Dt(i,n,e))});else{const e=n+"",i=r.statusText||`HTTP ${n} error`;t(new Dt(i,n,e))}}else t(new Bt(Ft(e),e))}))(e,o,r))})})}function zt(e,t,n,r,i){return h(this,void 0,void 0,function*(){return Kt(e,"POST",t,r,i,n)})}class Wt{constructor(e,t={},n){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},$t),t),this.fetch=qt(n)}throwOnError(){return this.shouldThrowOnError=!0,this}createIndex(e){return h(this,void 0,void 0,function*(){try{return{data:(yield zt(this.fetch,`${this.url}/CreateIndex`,e,{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}getIndex(e,t){return h(this,void 0,void 0,function*(){try{return{data:yield zt(this.fetch,`${this.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}listIndexes(e){return h(this,void 0,void 0,function*(){try{return{data:yield zt(this.fetch,`${this.url}/ListIndexes`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}deleteIndex(e,t){return h(this,void 0,void 0,function*(){try{return{data:(yield zt(this.fetch,`${this.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}}class Gt{constructor(e,t={},n){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},$t),t),this.fetch=qt(n)}throwOnError(){return this.shouldThrowOnError=!0,this}putVectors(e){return h(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 zt(this.fetch,`${this.url}/PutVectors`,e,{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}getVectors(e){return h(this,void 0,void 0,function*(){try{return{data:yield zt(this.fetch,`${this.url}/GetVectors`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}listVectors(e){return h(this,void 0,void 0,function*(){try{if(void 0!==e.segmentCount){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(void 0!==e.segmentIndex&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error("segmentIndex must be between 0 and "+(e.segmentCount-1))}return{data:yield zt(this.fetch,`${this.url}/ListVectors`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}queryVectors(e){return h(this,void 0,void 0,function*(){try{return{data:yield zt(this.fetch,`${this.url}/QueryVectors`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}deleteVectors(e){return h(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 zt(this.fetch,`${this.url}/DeleteVectors`,e,{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}}class Vt{constructor(e,t={},n){this.shouldThrowOnError=!1,this.url=e.replace(/\/$/,""),this.headers=Object.assign(Object.assign({},$t),t),this.fetch=qt(n)}throwOnError(){return this.shouldThrowOnError=!0,this}createBucket(e){return h(this,void 0,void 0,function*(){try{return{data:(yield zt(this.fetch,`${this.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}getBucket(e){return h(this,void 0,void 0,function*(){try{return{data:yield zt(this.fetch,`${this.url}/GetVectorBucket`,{vectorBucketName:e},{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}listBuckets(){return h(this,arguments,void 0,function*(e={}){try{return{data:yield zt(this.fetch,`${this.url}/ListVectorBuckets`,e,{headers:this.headers}),error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}deleteBucket(e){return h(this,void 0,void 0,function*(){try{return{data:(yield zt(this.fetch,`${this.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:this.headers}))||{},error:null}}catch(e){if(this.shouldThrowOnError)throw e;if(Nt(e))return{data:null,error:e};throw e}})}}class Ht extends Vt{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new Jt(this.url,this.headers,e,this.fetch)}createBucket(e){const t=Object.create(null,{createBucket:{get:()=>super.createBucket}});return h(this,void 0,void 0,function*(){return t.createBucket.call(this,e)})}getBucket(e){const t=Object.create(null,{getBucket:{get:()=>super.getBucket}});return h(this,void 0,void 0,function*(){return t.getBucket.call(this,e)})}listBuckets(){const e=Object.create(null,{listBuckets:{get:()=>super.listBuckets}});return h(this,arguments,void 0,function*(t={}){return e.listBuckets.call(this,t)})}deleteBucket(e){const t=Object.create(null,{deleteBucket:{get:()=>super.deleteBucket}});return h(this,void 0,void 0,function*(){return t.deleteBucket.call(this,e)})}}class Jt extends Wt{constructor(e,t,n,r){super(e,t,r),this.vectorBucketName=n}createIndex(e){const t=Object.create(null,{createIndex:{get:()=>super.createIndex}});return h(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 h(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 h(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 h(this,void 0,void 0,function*(){return t.deleteIndex.call(this,this.vectorBucketName,e)})}index(e){return new Yt(this.url,this.headers,this.vectorBucketName,e,this.fetch)}}class Yt extends Gt{constructor(e,t,n,r,i){super(e,t,i),this.vectorBucketName=n,this.indexName=r}putVectors(e){const t=Object.create(null,{putVectors:{get:()=>super.putVectors}});return h(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 h(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 h(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 h(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 h(this,void 0,void 0,function*(){return t.deleteVectors.call(this,Object.assign(Object.assign({},e),{vectorBucketName:this.vectorBucketName,indexName:this.indexName}))})}}class Qt extends Tt{constructor(e,t={},n,r){super(e,t,n,r)}from(e){return new kt(this.url,this.headers,e,this.fetch)}get vectors(){return new Ht(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new Rt(this.url+"/iceberg",this.headers,this.fetch)}}let Xt="";Xt="undefined"!=typeof Deno?"deno":"undefined"!=typeof document?"web":"undefined"!=typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";const Zt={headers:{"X-Client-Info":`supabase-js-${Xt}/2.86.0`}},en={schema:"public"},tn={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},nn={},rn=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),sn=(e,t,n)=>{const r=rn(n),i=Headers;return async(n,s)=>{var a;const o=null!==(a=await t())&&void 0!==a?a:e;let c=new i(null==s?void 0:s.headers);return c.has("apikey")||c.set("apikey",e),c.has("Authorization")||c.set("Authorization",`Bearer ${o}`),r(n,Object.assign(Object.assign({},s),{headers:c}))}};const an="2.86.0",on=3e4,cn=9e4,ln={"X-Client-Info":`gotrue-js/${an}`},un="X-Supabase-Api-Version",dn={timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"},hn=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;class fn extends Error{constructor(e,t,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=n}}function pn(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class mn extends fn{constructor(e,t,n){super(e,t,n),this.name="AuthApiError",this.status=t,this.code=n}}class gn extends fn{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class bn extends fn{constructor(e,t,n,r){super(e,n,r),this.name=t,this.status=n}}class wn extends bn{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class yn extends bn{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class vn extends bn{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class _n extends bn{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class kn extends bn{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class Sn extends bn{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function En(e){return pn(e)&&"AuthRetryableFetchError"===e.name}class Tn extends bn{constructor(e,t,n){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=n}}class On extends bn{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}}const xn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),jn=" \t\n\r=".split(""),Pn=(()=>{const e=new Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<jn.length;t+=1)e[jn[t].charCodeAt(0)]=-2;for(let t=0;t<xn.length;t+=1)e[xn[t].charCodeAt(0)]=t;return e})();function An(e,t,n){if(null!==e)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;n(xn[e]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const e=t.queue>>t.queuedBits-6&63;n(xn[e]),t.queuedBits-=6}}function Cn(e,t,n){const r=Pn[e];if(!(r>-1)){if(-2===r)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)n(t.queue>>t.queuedBits-8&255),t.queuedBits-=8}function In(e){const t=[],n=e=>{t.push(String.fromCodePoint(e))},r={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},s=e=>{!function(e,t,n){if(0===t.utf8seq){if(e<=127)return void n(e);for(let n=1;n<6;n+=1)if(!(e>>7-n&1)){t.utf8seq=n;break}if(2===t.utf8seq)t.codepoint=31&e;else if(3===t.utf8seq)t.codepoint=15&e;else{if(4!==t.utf8seq)throw new Error("Invalid UTF-8 sequence");t.codepoint=7&e}t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|63&e,t.utf8seq-=1,0===t.utf8seq&&n(t.codepoint)}}(e,r,n)};for(let t=0;t<e.length;t+=1)Cn(e.charCodeAt(t),i,s);return t.join("")}function Rn(e,t){if(!(e<=127)){if(e<=2047)return t(192|e>>6),void t(128|63&e);if(e<=65535)return t(224|e>>12),t(128|e>>6&63),void t(128|63&e);if(e<=1114111)return t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),void t(128|63&e);throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}t(e)}function $n(e){const t=[],n={queue:0,queuedBits:0},r=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)Cn(e.charCodeAt(t),n,r);return new Uint8Array(t)}function Un(e){const t=[];return function(e,t){for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);if(r>55295&&r<=56319){const t=1024*(r-55296)&65535;r=65536+(e.charCodeAt(n+1)-56320&65535|t),n+=1}Rn(r,t)}}(e,e=>t.push(e)),new Uint8Array(t)}function Nn(e){const t=[],n={queue:0,queuedBits:0},r=e=>{t.push(e)};return e.forEach(e=>An(e,n,r)),An(null,n,r),t.join("")}const Dn=()=>"undefined"!=typeof window&&"undefined"!=typeof document,Bn={tested:!1,writable:!1},Ln=()=>{if(!Dn())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(Bn.tested)return Bn.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Bn.tested=!0,Bn.writable=!0}catch(e){Bn.tested=!0,Bn.writable=!1}return Bn.writable};const qn=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Fn=async(e,t,n)=>{await e.setItem(t,JSON.stringify(n))},Mn=async(e,t)=>{const n=await e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch(e){return n}},Kn=async(e,t)=>{await e.removeItem(t)};class zn{constructor(){this.promise=new zn.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function Wn(e){const t=e.split(".");if(3!==t.length)throw new On("Invalid JWT structure");for(let e=0;e<t.length;e++)if(!hn.test(t[e]))throw new On("JWT not in base64url format");return{header:JSON.parse(In(t[0])),payload:JSON.parse(In(t[1])),signature:$n(t[2]),raw:{header:t[0],payload:t[1]}}}function Gn(e){return("0"+e.toString(16)).substr(-2)}async function Vn(e){if(!("undefined"!=typeof crypto&&void 0!==crypto.subtle&&"undefined"!=typeof TextEncoder))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;const t=await async function(e){const t=(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t),r=new Uint8Array(n);return Array.from(r).map(e=>String.fromCharCode(e)).join("")}(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Hn(e,t,n=!1){const r=function(){const e=new Uint32Array(56);if("undefined"==typeof crypto){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length;let n="";for(let r=0;r<56;r++)n+=e.charAt(Math.floor(Math.random()*t));return n}return crypto.getRandomValues(e),Array.from(e,Gn).join("")}();let i=r;n&&(i+="/PASSWORD_RECOVERY"),await Fn(e,`${t}-code-verifier`,i);const s=await Vn(r);return[s,r===s?"plain":"s256"]}zn.promiseConstructor=Promise;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;const Yn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Qn(e){if(!Yn.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Xn(){return new Proxy({},{get:(e,t)=>{if("__isUserNotAvailableProxy"===t)return!0;if("symbol"==typeof t){const e=t.toString();if("Symbol(Symbol.toPrimitive)"===e||"Symbol(Symbol.toStringTag)"===e||"Symbol(util.inspect.custom)"===e)return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Zn(e){return JSON.parse(JSON.stringify(e))}const er=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),tr=[502,503,504];async function nr(e){var t,n;if(!("object"==typeof(n=e)&&null!==n&&"status"in n&&"ok"in n&&"json"in n&&"function"==typeof n.json))throw new Sn(er(e),0);if(tr.includes(e.status))throw new Sn(er(e),e.status);let r,i;try{r=await e.json()}catch(e){throw new gn(er(e),e)}const s=function(e){const t=e.headers.get(un);if(!t)return null;if(!t.match(Jn))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(e){return null}}(e);if(s&&s.getTime()>=dn.timestamp&&"object"==typeof r&&r&&"string"==typeof r.code?i=r.code:"object"==typeof r&&r&&"string"==typeof r.error_code&&(i=r.error_code),i){if("weak_password"===i)throw new Tn(er(r),e.status,(null===(t=r.weak_password)||void 0===t?void 0:t.reasons)||[]);if("session_not_found"===i)throw new wn}else if("object"==typeof r&&r&&"object"==typeof r.weak_password&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new Tn(er(r),e.status,r.weak_password.reasons);throw new mn(er(r),e.status||500,i)}async function rr(e,t,n,r){var i;const s=Object.assign({},null==r?void 0:r.headers);s[un]||(s[un]=dn.name),(null==r?void 0:r.jwt)&&(s.Authorization=`Bearer ${r.jwt}`);const a=null!==(i=null==r?void 0:r.query)&&void 0!==i?i:{};(null==r?void 0:r.redirectTo)&&(a.redirect_to=r.redirectTo);const o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",c=await async function(e,t,n,r,i,s){const a=((e,t,n,r)=>{const i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),n))})(t,r,i,s);let o;try{o=await e(n,Object.assign({},a))}catch(e){throw console.error(e),new Sn(er(e),0)}o.ok||await nr(o);if(null==r?void 0:r.noResolveJson)return o;try{return await o.json()}catch(e){await nr(e)}}(e,t,n+o,{headers:s,noResolveJson:null==r?void 0:r.noResolveJson},{},null==r?void 0:r.body);return(null==r?void 0:r.xform)?null==r?void 0:r.xform(c):{data:Object.assign({},c),error:null}}function ir(e){var t;let n=null;var r;(function(e){return e.access_token&&e.refresh_token&&e.expires_in})(e)&&(n=Object.assign({},e),e.expires_at||(n.expires_at=(r=e.expires_in,Math.round(Date.now()/1e3)+r)));return{data:{session:n,user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function sr(e){const t=ir(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function ar(e){var t;return{data:{user:null!==(t=e.user)&&void 0!==t?t:e},error:null}}function or(e){return{data:e,error:null}}function cr(e){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:s,verification_type:a}=e,o=i(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]);return{data:{properties:{action_link:t,email_otp:n,hashed_token:r,redirect_to:s,verification_type:a},user:Object.assign({},o)},error:null}}function lr(e){return e}const ur=["global","local","others"];class dr{constructor({url:e="",headers:t={},fetch:n}){this.url=e,this.headers=t,this.fetch=qn(n),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=ur[0]){if(ur.indexOf(t)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ur.join(", ")}`);try{return await rr(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(pn(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await rr(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:ar})}catch(e){if(pn(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{const{options:t}=e,n=i(e,["options"]),r=Object.assign(Object.assign({},n),t);return"newEmail"in n&&(r.new_email=null==n?void 0:n.newEmail,delete r.newEmail),await rr(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:r,headers:this.headers,xform:cr,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(pn(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await rr(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ar})}catch(e){if(pn(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,n,r,i,s,a,o;try{const c={nextPage:null,lastPage:0,total:0},l=await rr(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(n=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==n?n:"",per_page:null!==(i=null===(r=null==e?void 0:e.perPage)||void 0===r?void 0:r.toString())&&void 0!==i?i:""},xform:lr});if(l.error)throw l.error;const u=await l.json(),d=null!==(s=l.headers.get("x-total-count"))&&void 0!==s?s:0,h=null!==(o=null===(a=l.headers.get("link"))||void 0===a?void 0:a.split(","))&&void 0!==o?o:[];return h.length>0&&(h.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),n=JSON.parse(e.split(";")[1].split("=")[1]);c[`${n}Page`]=t}),c.total=parseInt(d)),{data:Object.assign(Object.assign({},u),c),error:null}}catch(e){if(pn(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){Qn(e);try{return await rr(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ar})}catch(e){if(pn(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){Qn(e);try{return await rr(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:ar})}catch(e){if(pn(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){Qn(e);try{return await rr(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:ar})}catch(e){if(pn(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){Qn(e.userId);try{const{data:t,error:n}=await rr(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:n}}catch(e){if(pn(e))return{data:null,error:e};throw e}}async _deleteFactor(e){Qn(e.userId),Qn(e.id);try{return{data:await rr(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(pn(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){var t,n,r,i,s,a,o;try{const c={nextPage:null,lastPage:0,total:0},l=await rr(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(n=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==n?n:"",per_page:null!==(i=null===(r=null==e?void 0:e.perPage)||void 0===r?void 0:r.toString())&&void 0!==i?i:""},xform:lr});if(l.error)throw l.error;const u=await l.json(),d=null!==(s=l.headers.get("x-total-count"))&&void 0!==s?s:0,h=null!==(o=null===(a=l.headers.get("link"))||void 0===a?void 0:a.split(","))&&void 0!==o?o:[];return h.length>0&&(h.forEach(e=>{const t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),n=JSON.parse(e.split(";")[1].split("=")[1]);c[`${n}Page`]=t}),c.total=parseInt(d)),{data:Object.assign(Object.assign({},u),c),error:null}}catch(e){if(pn(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await rr(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(pn(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await rr(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(pn(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await rr(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(pn(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await rr(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if(pn(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await rr(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if(pn(e))return{data:null,error:e};throw e}}}function hr(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}const fr=!!(globalThis&&Ln()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"));class pr extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class mr extends pr{}async function gr(e,t,n){fr&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),fr&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async r=>{if(!r){if(0===t)throw fr&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new mr(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(fr)try{const e=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(e,null," "))}catch(e){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",e)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await n()}fr&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,r.name);try{return await n()}finally{fr&&console.log("@supabase/gotrue-js: navigatorLock: released",e,r.name)}}))}function br(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function wr(e){const t=(new TextEncoder).encode(e);return"0x"+Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}class yr extends Error{constructor({message:e,code:t,cause:n,name:r}){var i;super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=null!==(i=null!=r?r:n instanceof Error?n.name:void 0)&&void 0!==i?i:"Unknown Error",this.code=t}}class vr extends yr{constructor(e,t){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t,message:e}),this.name="WebAuthnUnknownError",this.originalError=t}}function _r({error:e,options:t}){var n,r,i;const{publicKey:s}=t;if(!s)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new yr({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===(null===(n=s.authenticatorSelection)||void 0===n?void 0:n.requireResidentKey))return new yr({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===(null===(r=s.authenticatorSelection)||void 0===r?void 0:r.userVerification))return new yr({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===(null===(i=s.authenticatorSelection)||void 0===i?void 0:i.userVerification))return new yr({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new yr({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new yr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name){return 0===s.pubKeyCredParams.filter(e=>"public-key"===e.type).length?new yr({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new yr({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e})}if("SecurityError"===e.name){const t=window.location.hostname;if(!jr(t))return new yr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(s.rp.id!==t)return new yr({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new yr({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new yr({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new yr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function kr({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new yr({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new yr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!jr(t))return new yr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rpId!==t)return new yr({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new yr({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new yr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}const Sr=new class{createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};function Er(e){if(!e)throw new Error("Credential creation options are required");if("undefined"!=typeof PublicKeyCredential&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseCreationOptionsFromJSON)return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:t,user:n,excludeCredentials:r}=e,s=i(e,["challenge","user","excludeCredentials"]),a=$n(t).buffer,o=Object.assign(Object.assign({},n),{id:$n(n.id).buffer}),c=Object.assign(Object.assign({},s),{challenge:a,user:o});if(r&&r.length>0){c.excludeCredentials=new Array(r.length);for(let e=0;e<r.length;e++){const t=r[e];c.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:$n(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return c}function Tr(e){if(!e)throw new Error("Credential request options are required");if("undefined"!=typeof PublicKeyCredential&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&"function"==typeof PublicKeyCredential.parseRequestOptionsFromJSON)return PublicKeyCredential.parseRequestOptionsFromJSON(e);const{challenge:t,allowCredentials:n}=e,r=i(e,["challenge","allowCredentials"]),s=$n(t).buffer,a=Object.assign(Object.assign({},r),{challenge:s});if(n&&n.length>0){a.allowCredentials=new Array(n.length);for(let e=0;e<n.length;e++){const t=n[e];a.allowCredentials[e]=Object.assign(Object.assign({},t),{id:$n(t.id).buffer,type:t.type||"public-key",transports:t.transports})}}return a}function Or(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const n=e;return{id:e.id,rawId:e.id,response:{attestationObject:Nn(new Uint8Array(e.response.attestationObject)),clientDataJSON:Nn(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:null!==(t=n.authenticatorAttachment)&&void 0!==t?t:void 0}}function xr(e){var t;if("toJSON"in e&&"function"==typeof e.toJSON)return e.toJSON();const n=e,r=e.getClientExtensionResults(),i=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:Nn(new Uint8Array(i.authenticatorData)),clientDataJSON:Nn(new Uint8Array(i.clientDataJSON)),signature:Nn(new Uint8Array(i.signature)),userHandle:i.userHandle?Nn(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:null!==(t=n.authenticatorAttachment)&&void 0!==t?t:void 0}}function jr(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function Pr(){var e,t;return!!(Dn()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&"function"==typeof(null===(e=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===e?void 0:e.create)&&"function"==typeof(null===(t=null===navigator||void 0===navigator?void 0:navigator.credentials)||void 0===t?void 0:t.get))}const Ar={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Cr={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Ir(...e){const t=e=>null!==e&&"object"==typeof e&&!Array.isArray(e),n=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),r={};for(const i of e)if(i)for(const e in i){const s=i[e];if(void 0!==s)if(Array.isArray(s))r[e]=s;else if(n(s))r[e]=s;else if(t(s)){const n=r[e];t(n)?r[e]=Ir(n,s):r[e]=Ir(s)}else r[e]=s}return r}class Rr{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:n,signal:r},i){try{const{data:s,error:a}=await this.client.mfa.challenge({factorId:e,webauthn:t});if(!s)return{data:null,error:a};const o=null!=r?r:Sr.createNewAbortSignal();if("create"===s.webauthn.type){const{user:e}=s.webauthn.credential_options.publicKey;e.name||(e.name=`${e.id}:${n}`),e.displayName||(e.displayName=e.name)}switch(s.webauthn.type){case"create":{const t=function(e,t){return Ir(Ar,e,t||{})}(s.webauthn.credential_options.publicKey,null==i?void 0:i.create),{data:n,error:r}=await async function(e){try{const t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new vr("Browser returned unexpected credential type",t)}:{data:null,error:new vr("Empty credential response",t)}}catch(t){return{data:null,error:_r({error:t,options:e})}}}({publicKey:t,signal:o});return n?{data:{factorId:e,challengeId:s.id,webauthn:{type:s.webauthn.type,credential_response:n}},error:null}:{data:null,error:r}}case"request":{const t=function(e,t){return Ir(Cr,e,t||{})}(s.webauthn.credential_options.publicKey,null==i?void 0:i.request),{data:n,error:r}=await async function(e){try{const t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new vr("Browser returned unexpected credential type",t)}:{data:null,error:new vr("Empty credential response",t)}}catch(t){return{data:null,error:kr({error:t,options:e})}}}(Object.assign(Object.assign({},s.webauthn.credential_options),{publicKey:t,signal:o}));return n?{data:{factorId:e,challengeId:s.id,webauthn:{type:s.webauthn.type,credential_response:n}},error:null}:{data:null,error:r}}}}catch(e){return pn(e)?{data:null,error:e}:{data:null,error:new gn("Unexpected error in challenge",e)}}}async _verify({challengeId:e,factorId:t,webauthn:n}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:n=("undefined"!=typeof window?[window.location.origin]:void 0),signal:r}={}},i){if(!t)return{data:null,error:new fn("rpId is required for WebAuthn authentication")};try{if(!Pr())return{data:null,error:new gn("Browser does not support WebAuthn",null)};const{data:s,error:a}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:n},signal:r},{request:i});if(!s)return{data:null,error:a};const{webauthn:o}=s;return this._verify({factorId:e,challengeId:s.challengeId,webauthn:{type:o.type,rpId:t,rpOrigins:n,credential_response:o.credential_response}})}catch(e){return pn(e)?{data:null,error:e}:{data:null,error:new gn("Unexpected error in authenticate",e)}}}async _register({friendlyName:e,webauthn:{rpId:t=("undefined"!=typeof window?window.location.hostname:void 0),rpOrigins:n=("undefined"!=typeof window?[window.location.origin]:void 0),signal:r}={}},i){if(!t)return{data:null,error:new fn("rpId is required for WebAuthn registration")};try{if(!Pr())return{data:null,error:new gn("Browser does not support WebAuthn",null)};const{data:s,error:a}=await this._enroll({friendlyName:e});if(!s)return await this.client.mfa.listFactors().then(t=>{var n;return null===(n=t.data)||void 0===n?void 0:n.all.find(t=>"webauthn"===t.factor_type&&t.friendly_name===e&&"unverified"!==t.status)}).then(e=>e?this.client.mfa.unenroll({factorId:null==e?void 0:e.id}):void 0),{data:null,error:a};const{data:o,error:c}=await this._challenge({factorId:s.id,friendlyName:s.friendly_name,webauthn:{rpId:t,rpOrigins:n},signal:r},{create:i});return o?this._verify({factorId:s.id,challengeId:o.challengeId,webauthn:{rpId:t,rpOrigins:n,type:o.webauthn.type,credential_response:o.webauthn.credential_response}}):{data:null,error:c}}catch(e){return pn(e)?{data:null,error:e}:{data:null,error:new gn("Unexpected error in register",e)}}}}!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();const $r={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:ln,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1};async function Ur(e,t,n){return await n()}const Nr={};class Dr{get jwks(){var e,t;return null!==(t=null===(e=Nr[this.storageKey])||void 0===e?void 0:e.jwks)&&void 0!==t?t:{keys:[]}}set jwks(e){Nr[this.storageKey]=Object.assign(Object.assign({},Nr[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,t;return null!==(t=null===(e=Nr[this.storageKey])||void 0===e?void 0:e.cachedAt)&&void 0!==t?t:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Nr[this.storageKey]=Object.assign(Object.assign({},Nr[this.storageKey]),{cachedAt:e})}constructor(e){var t,n,r;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({},$r),e);if(this.storageKey=i.storageKey,this.instanceID=null!==(t=Dr.nextInstanceID[this.storageKey])&&void 0!==t?t:0,Dr.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,"function"==typeof i.debug&&(this.logger=i.debug),this.instanceID>0&&Dn()){const e=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new dr({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=qn(i.fetch),this.lock=i.lock||Ur,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,i.lock?this.lock=i.lock:Dn()&&(null===(n=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===n?void 0:n.locks)?this.lock=gr:this.lock=Ur,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 Rr(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:Ln()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=hr(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=hr(this.memoryStorage)),Dn()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null===(r=this.broadcastChannel)||void 0===r||r.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)})}this.initialize()}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${an}) ${(new Date).toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){var e;try{let t={},n="none";if(Dn()&&(t=function(e){const t={},n=new URL(e);if(n.hash&&"#"===n.hash[0])try{new URLSearchParams(n.hash.substring(1)).forEach((e,n)=>{t[n]=e})}catch(e){}return n.searchParams.forEach((e,n)=>{t[n]=e}),t}(window.location.href),this._isImplicitGrantCallback(t)?n="implicit":await this._isPKCECallback(t)&&(n="pkce")),Dn()&&this.detectSessionInUrl&&"none"!==n){const{data:r,error:i}=await this._getSessionFromURL(t,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),function(e){return pn(e)&&"AuthImplicitGrantRedirectError"===e.name}(i)){const t=null===(e=i.details)||void 0===e?void 0:e.code;if("identity_already_exists"===t||"identity_not_found"===t||"single_identity_not_deletable"===t)return{error:i}}return await this._removeSession(),{error:i}}const{session:s,redirectType:a}=r;return this._debug("#_initialize()","detected session in URL",s,"redirect type",a),await this._saveSession(s),setTimeout(async()=>{"recovery"===a?await this._notifyAllSubscribers("PASSWORD_RECOVERY",s):await this._notifyAllSubscribers("SIGNED_IN",s)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return pn(e)?this._returnResult({error:e}):this._returnResult({error:new gn("Unexpected error during initialization",e)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,n,r;try{const i=await rr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!==(n=null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.data)&&void 0!==n?n:{},gotrue_meta_security:{captcha_token:null===(r=null==e?void 0:e.options)||void 0===r?void 0:r.captchaToken}},xform:ir}),{data:s,error:a}=i;if(a||!s)return this._returnResult({data:{user:null,session:null},error:a});const o=s.session,c=s.user;return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:c,session:o},error:null})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){var t,n,r;try{let i;if("email"in e){const{email:n,password:r,options:s}=e;let a=null,o=null;"pkce"===this.flowType&&([a,o]=await Hn(this.storage,this.storageKey)),i=await rr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==s?void 0:s.emailRedirectTo,body:{email:n,password:r,data:null!==(t=null==s?void 0:s.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken},code_challenge:a,code_challenge_method:o},xform:ir})}else{if(!("phone"in e))throw new vn("You must provide either an email or phone number and a password");{const{phone:t,password:s,options:a}=e;i=await rr(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:s,data:null!==(n=null==a?void 0:a.data)&&void 0!==n?n:{},channel:null!==(r=null==a?void 0:a.channel)&&void 0!==r?r:"sms",gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}},xform:ir})}}const{data:s,error:a}=i;if(a||!s)return this._returnResult({data:{user:null,session:null},error:a});const o=s.session,c=s.user;return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",o)),this._returnResult({data:{user:c,session:o},error:null})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if("email"in e){const{email:n,password:r,options:i}=e;t=await rr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:sr})}else{if(!("phone"in e))throw new vn("You must provide either an email or phone number and a password");{const{phone:n,password:r,options:i}=e;t=await rr(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:sr})}}const{data:n,error:r}=t;if(r)return this._returnResult({data:{user:null,session:null},error:r});if(!n||!n.session||!n.user){const e=new yn;return this._returnResult({data:{user:null,session:null},error:e})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:r})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){var t,n,r,i;return await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(n=e.options)||void 0===n?void 0:n.scopes,queryParams:null===(r=e.options)||void 0===r?void 0:r.queryParams,skipBrowserRedirect:null===(i=e.options)||void 0===i?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,n,r,i,s,a,o,c,l,u,d;let h,f;if("message"in e)h=e.message,f=e.signature;else{const{chain:u,wallet:d,statement:p,options:m}=e;let g;if(Dn())if("object"==typeof d)g=d;else{const e=window;if(!("ethereum"in e)||"object"!=typeof e.ethereum||!("request"in e.ethereum)||"function"!=typeof e.ethereum.request)throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.");g=e.ethereum}else{if("object"!=typeof d||!(null==m?void 0:m.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");g=d}const b=new URL(null!==(t=null==m?void 0:m.url)&&void 0!==t?t:window.location.href),w=await g.request({method:"eth_requestAccounts"}).then(e=>e).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!w||0===w.length)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const y=br(w[0]);let v=null===(n=null==m?void 0:m.signInWithEthereum)||void 0===n?void 0:n.chainId;if(!v){const e=await g.request({method:"eth_chainId"});v=parseInt(e,16)}h=function(e){var t;const{chainId:n,domain:r,expirationTime:i,issuedAt:s=new Date,nonce:a,notBefore:o,requestId:c,resources:l,scheme:u,uri:d,version:h}=e;if(!Number.isInteger(n))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${n}`);if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if("1"!==h)throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${h}`);if(null===(t=e.statement)||void 0===t?void 0:t.includes("\n"))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);const f=`${u?`${u}://${r}`:r} wants you to sign in with your Ethereum account:\n${br(e.address)}\n\n${e.statement?`${e.statement}\n`:""}`;let p=`URI: ${d}\nVersion: ${h}\nChain ID: ${n}${a?`\nNonce: ${a}`:""}\nIssued At: ${s.toISOString()}`;if(i&&(p+=`\nExpiration Time: ${i.toISOString()}`),o&&(p+=`\nNot Before: ${o.toISOString()}`),c&&(p+=`\nRequest ID: ${c}`),l){let e="\nResources:";for(const t of l){if(!t||"string"!=typeof t)throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}p+=e}return`${f}\n${p}`}({domain:b.host,address:y,statement:p,uri:b.href,version:"1",chainId:v,nonce:null===(r=null==m?void 0:m.signInWithEthereum)||void 0===r?void 0:r.nonce,issuedAt:null!==(s=null===(i=null==m?void 0:m.signInWithEthereum)||void 0===i?void 0:i.issuedAt)&&void 0!==s?s:new Date,expirationTime:null===(a=null==m?void 0:m.signInWithEthereum)||void 0===a?void 0:a.expirationTime,notBefore:null===(o=null==m?void 0:m.signInWithEthereum)||void 0===o?void 0:o.notBefore,requestId:null===(c=null==m?void 0:m.signInWithEthereum)||void 0===c?void 0:c.requestId,resources:null===(l=null==m?void 0:m.signInWithEthereum)||void 0===l?void 0:l.resources}),f=await g.request({method:"personal_sign",params:[wr(h),y]})}try{const{data:t,error:n}=await rr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:h,signature:f},(null===(u=e.options)||void 0===u?void 0:u.captchaToken)?{gotrue_meta_security:{captcha_token:null===(d=e.options)||void 0===d?void 0:d.captchaToken}}:null),xform:ir});if(n)throw n;if(!t||!t.session||!t.user){const e=new yn;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:n})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){var t,n,r,i,s,a,o,c,l,u,d,h;let f,p;if("message"in e)f=e.message,p=e.signature;else{const{chain:d,wallet:h,statement:m,options:g}=e;let b;if(Dn())if("object"==typeof h)b=h;else{const e=window;if(!("solana"in e)||"object"!=typeof e.solana||!("signIn"in e.solana&&"function"==typeof e.solana.signIn||"signMessage"in e.solana&&"function"==typeof e.solana.signMessage))throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.");b=e.solana}else{if("object"!=typeof h||!(null==g?void 0:g.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");b=h}const w=new URL(null!==(t=null==g?void 0:g.url)&&void 0!==t?t:window.location.href);if("signIn"in b&&b.signIn){const e=await b.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(new Date).toISOString()},null==g?void 0:g.signInWithSolana),{version:"1",domain:w.host,uri:w.href}),m?{statement:m}:null));let t;if(Array.isArray(e)&&e[0]&&"object"==typeof e[0])t=e[0];else{if(!(e&&"object"==typeof e&&"signedMessage"in e&&"signature"in e))throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");t=e}if(!("signedMessage"in t&&"signature"in t&&("string"==typeof t.signedMessage||t.signedMessage instanceof Uint8Array)&&t.signature instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields");f="string"==typeof t.signedMessage?t.signedMessage:(new TextDecoder).decode(t.signedMessage),p=t.signature}else{if(!("signMessage"in b&&"function"==typeof b.signMessage&&"publicKey"in b&&"object"==typeof b&&b.publicKey&&"toBase58"in b.publicKey&&"function"==typeof b.publicKey.toBase58))throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");f=[`${w.host} wants you to sign in with your Solana account:`,b.publicKey.toBase58(),...m?["",m,""]:[""],"Version: 1",`URI: ${w.href}`,`Issued At: ${null!==(r=null===(n=null==g?void 0:g.signInWithSolana)||void 0===n?void 0:n.issuedAt)&&void 0!==r?r:(new Date).toISOString()}`,...(null===(i=null==g?void 0:g.signInWithSolana)||void 0===i?void 0:i.notBefore)?[`Not Before: ${g.signInWithSolana.notBefore}`]:[],...(null===(s=null==g?void 0:g.signInWithSolana)||void 0===s?void 0:s.expirationTime)?[`Expiration Time: ${g.signInWithSolana.expirationTime}`]:[],...(null===(a=null==g?void 0:g.signInWithSolana)||void 0===a?void 0:a.chainId)?[`Chain ID: ${g.signInWithSolana.chainId}`]:[],...(null===(o=null==g?void 0:g.signInWithSolana)||void 0===o?void 0:o.nonce)?[`Nonce: ${g.signInWithSolana.nonce}`]:[],...(null===(c=null==g?void 0:g.signInWithSolana)||void 0===c?void 0:c.requestId)?[`Request ID: ${g.signInWithSolana.requestId}`]:[],...(null===(u=null===(l=null==g?void 0:g.signInWithSolana)||void 0===l?void 0:l.resources)||void 0===u?void 0:u.length)?["Resources",...g.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join("\n");const e=await b.signMessage((new TextEncoder).encode(f),"utf8");if(!(e&&e instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");p=e}}try{const{data:t,error:n}=await rr(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:f,signature:Nn(p)},(null===(d=e.options)||void 0===d?void 0:d.captchaToken)?{gotrue_meta_security:{captcha_token:null===(h=e.options)||void 0===h?void 0:h.captchaToken}}:null),xform:ir});if(n)throw n;if(!t||!t.session||!t.user){const e=new yn;return this._returnResult({data:{user:null,session:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign({},t),error:n})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e){const t=await Mn(this.storage,`${this.storageKey}-code-verifier`),[n,r]=(null!=t?t:"").split("/");try{const{data:t,error:i}=await rr(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:ir});if(await Kn(this.storage,`${this.storageKey}-code-verifier`),i)throw i;if(!t||!t.session||!t.user){const e=new yn;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers("SIGNED_IN",t.session)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:null!=r?r:null}),error:i})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{const{options:t,provider:n,token:r,access_token:i,nonce:s}=e,a=await rr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:r,access_token:i,nonce:s,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:ir}),{data:o,error:c}=a;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!o||!o.session||!o.user){const e=new yn;return this._returnResult({data:{user:null,session:null},error:e})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),this._returnResult({data:o,error:c})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){var t,n,r,i,s;try{if("email"in e){const{email:r,options:i}=e;let s=null,a=null;"pkce"===this.flowType&&([s,a]=await Hn(this.storage,this.storageKey));const{error:o}=await rr(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:r,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},create_user:null===(n=null==i?void 0:i.shouldCreateUser)||void 0===n||n,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:s,code_challenge_method:a},redirectTo:null==i?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}if("phone"in e){const{phone:t,options:n}=e,{data:a,error:o}=await rr(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(r=null==n?void 0:n.data)&&void 0!==r?r:{},create_user:null===(i=null==n?void 0:n.shouldCreateUser)||void 0===i||i,gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},channel:null!==(s=null==n?void 0:n.channel)&&void 0!==s?s:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:null==a?void 0:a.message_id},error:o})}throw new vn("You must provide either an email or phone number.")}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){var t,n;try{let r,i;"options"in e&&(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo,i=null===(n=e.options)||void 0===n?void 0:n.captchaToken);const{data:s,error:a}=await rr(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:r,xform:ir});if(a)throw a;if(!s){throw new Error("An error occurred on token verification.")}const o=s.session,c=s.user;return(null==o?void 0:o.access_token)&&(await this._saveSession(o),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",o)),this._returnResult({data:{user:c,session:o},error:null})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){var t,n,r,i,s;try{let a=null,o=null;"pkce"===this.flowType&&([a,o]=await Hn(this.storage,this.storageKey));const c=await rr(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:null!==(n=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==n?n:void 0}),(null===(r=null==e?void 0:e.options)||void 0===r?void 0:r.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:o}),headers:this.headers,xform:or});return(null===(i=c.data)||void 0===i?void 0:i.url)&&Dn()&&!(null===(s=e.options)||void 0===s?void 0:s.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}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:n}=e;if(n)throw n;if(!t)throw new wn;const{error:r}=await rr(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:r})})}catch(e){if(pn(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:n,type:r,options:i}=e,{error:s}=await rr(this.fetch,"POST",t,{headers:this.headers,body:{email:n,type:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},redirectTo:null==i?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:s})}if("phone"in e){const{phone:n,type:r,options:i}=e,{data:s,error:a}=await rr(this.fetch,"POST",t,{headers:this.headers,body:{phone:n,type:r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:null==s?void 0:s.message_id},error:a})}throw new vn("You must provide either an email or phone number and a type")}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){await this.initializePromise;return await this._acquireLock(-1,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await n}catch(e){}})()),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 e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){const e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{const t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",(new Error).stack);try{let e=null;const t=await Mn(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const n=!!e.expires_at&&1e3*e.expires_at-Date.now()<cn;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){const t=await Mn(this.userStorage,this.storageKey+"-user");(null==t?void 0:t.user)?e.user=t.user:e.user=Xn()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const t={value:this.suppressGetSessionWarning};e.user=function(e,t){return new Proxy(e,{get:(e,n,r)=>{if("__isInsecureUserWarningProxy"===n)return!0;if("symbol"==typeof n){const t=n.toString();if("Symbol(Symbol.toPrimitive)"===t||"Symbol(Symbol.toStringTag)"===t||"Symbol(util.inspect.custom)"===t||"Symbol(nodejs.util.inspect.custom)"===t)return Reflect.get(e,n,r)}return t.value||"string"!=typeof n||(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),t.value=!0),Reflect.get(e,n,r)}})}(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:r},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;return await this._acquireLock(-1,async()=>await this._getUser())}async _getUser(e){try{return e?await rr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ar}):await this._useSession(async e=>{var t,n,r;const{data:i,error:s}=e;if(s)throw s;return(null===(t=i.session)||void 0===t?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await rr(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(r=null===(n=i.session)||void 0===n?void 0:n.access_token)&&void 0!==r?r:void 0,xform:ar}):{data:{user:null},error:new wn}})}catch(e){if(pn(e))return function(e){return pn(e)&&"AuthSessionMissingError"===e.name}(e)&&(await this._removeSession(),await Kn(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async n=>{const{data:r,error:i}=n;if(i)throw i;if(!r.session)throw new wn;const s=r.session;let a=null,o=null;"pkce"===this.flowType&&null!=e.email&&([a,o]=await Hn(this.storage,this.storageKey));const{data:c,error:l}=await rr(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:o}),jwt:s.access_token,xform:ar});if(l)throw l;return s.user=c.user,await this._saveSession(s),await this._notifyAllSubscribers("USER_UPDATED",s),this._returnResult({data:{user:s.user},error:null})})}catch(e){if(pn(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new wn;const t=Date.now()/1e3;let n=t,r=!0,i=null;const{payload:s}=Wn(e.access_token);if(s.exp&&(n=s.exp,r=n<=t),r){const{data:t,error:n}=await this._callRefreshToken(e.refresh_token);if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!t)return{data:{user:null,session:null},error:null};i=t}else{const{data:r,error:s}=await this._getUser(e.access_token);if(s)throw s;i={access_token:e.access_token,refresh_token:e.refresh_token,user:r.user,token_type:"bearer",expires_in:n-t,expires_at:n},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(e){if(pn(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var n;if(!e){const{data:r,error:i}=t;if(i)throw i;e=null!==(n=r.session)&&void 0!==n?n:void 0}if(!(null==e?void 0:e.refresh_token))throw new wn;const{data:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):r?this._returnResult({data:{user:r.user,session:r},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!Dn())throw new _n("No browser detected.");if(e.error||e.error_description||e.error_code)throw new _n(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(t){case"implicit":if("pkce"===this.flowType)throw new kn("Not a valid PKCE flow url.");break;case"pkce":if("implicit"===this.flowType)throw new _n("Not a valid implicit grant flow url.")}if("pkce"===t){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new kn("No code detected.");const{data:t,error:n}=await this._exchangeCodeForSession(e.code);if(n)throw n;const r=new URL(window.location.href);return r.searchParams.delete("code"),window.history.replaceState(window.history.state,"",r.toString()),{data:{session:t.session,redirectType:null},error:null}}const{provider_token:n,provider_refresh_token:r,access_token:i,refresh_token:s,expires_in:a,expires_at:o,token_type:c}=e;if(!(i&&a&&s&&c))throw new _n("No session defined in URL");const l=Math.round(Date.now()/1e3),u=parseInt(a);let d=l+u;o&&(d=parseInt(o));const h=d-l;1e3*h<=on&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${h}s, should have been closer to ${u}s`);const f=d-u;l-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,d,l):l-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",f,d,l);const{data:p,error:m}=await this._getUser(i);if(m)throw m;const g={provider_token:n,provider_refresh_token:r,access_token:i,expires_in:u,expires_at:d,refresh_token:s,token_type:c,user:p.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:g,redirectType:e.type},error:null})}catch(e){if(pn(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return Boolean(e.access_token||e.error_description)}async _isPKCECallback(e){const t=await Mn(this.storage,`${this.storageKey}-code-verifier`);return!(!e.code||!t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var n;const{data:r,error:i}=t;if(i)return this._returnResult({error:i});const s=null===(n=r.session)||void 0===n?void 0:n.access_token;if(s){const{error:t}=await this.admin.signOut(s,e);if(t&&(!function(e){return pn(e)&&"AuthApiError"===e.name}(t)||404!==t.status&&401!==t.status&&403!==t.status))return this._returnResult({error:t})}return"others"!==e&&(await this._removeSession(),await Kn(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const t=Symbol("auth-callback"),n={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,n),(async()=>{await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async t=>{var n,r;try{const{data:{session:r},error:i}=t;if(i)throw i;await(null===(n=this.stateChangeEmitters.get(e))||void 0===n?void 0:n.callback("INITIAL_SESSION",r)),this._debug("INITIAL_SESSION","callback id",e,"session",r)}catch(t){await(null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let n=null,r=null;"pkce"===this.flowType&&([n,r]=await Hn(this.storage,this.storageKey,!0));try{return await rr(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:r,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){var e;try{const{data:t,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:null!==(e=t.user.identities)&&void 0!==e?e:[]},error:null})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var t;try{const{data:n,error:r}=await this._useSession(async t=>{var n,r,i,s,a;const{data:o,error:c}=t;if(c)throw c;const l=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null===(n=e.options)||void 0===n?void 0:n.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(i=e.options)||void 0===i?void 0:i.queryParams,skipBrowserRedirect:!0});return await rr(this.fetch,"GET",l,{headers:this.headers,jwt:null!==(a=null===(s=o.session)||void 0===s?void 0:s.access_token)&&void 0!==a?a:void 0})});if(r)throw r;return Dn()&&!(null===(t=e.options)||void 0===t?void 0:t.skipBrowserRedirect)&&window.location.assign(null==n?void 0:n.url),this._returnResult({data:{provider:e.provider,url:null==n?void 0:n.url},error:null})}catch(t){if(pn(t))return this._returnResult({data:{provider:e.provider,url:null},error:t});throw t}}async linkIdentityIdToken(e){return await this._useSession(async t=>{var n;try{const{error:r,data:{session:i}}=t;if(r)throw r;const{options:s,provider:a,token:o,access_token:c,nonce:l}=e,u=await rr(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:null!==(n=null==i?void 0:i.access_token)&&void 0!==n?n:void 0,body:{provider:a,id_token:o,access_token:c,nonce:l,link_identity:!0,gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken}},xform:ir}),{data:d,error:h}=u;return h?this._returnResult({data:{user:null,session:null},error:h}):d&&d.session&&d.user?(d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("USER_UPDATED",d.session)),this._returnResult({data:d,error:h})):this._returnResult({data:{user:null,session:null},error:new yn})}catch(e){if(pn(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{var n,r;const{data:i,error:s}=t;if(s)throw s;return await rr(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!==(r=null===(n=i.session)||void 0===n?void 0:n.access_token)&&void 0!==r?r:void 0})})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const i=Date.now();return await(n=async n=>(n>0&&await async function(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}(200*Math.pow(2,n-1)),this._debug(t,"refreshing attempt",n),await rr(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:ir})),r=(e,t)=>{const n=200*Math.pow(2,e);return t&&En(t)&&Date.now()+n-i<on},new Promise((e,t)=>{(async()=>{for(let i=0;i<1/0;i++)try{const t=await n(i);if(!r(i,null,t))return void e(t)}catch(e){if(!r(i,e))return void t(e)}})()}))}catch(e){if(this._debug(t,"error",e),pn(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,"end")}var n,r}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",n),Dn()&&!t.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,t;const n="#_recoverAndRefresh()";this._debug(n,"begin");try{const r=await Mn(this.storage,this.storageKey);if(r&&this.userStorage){let t=await Mn(this.userStorage,this.storageKey+"-user");this.storage.isServer||!Object.is(this.storage,this.userStorage)||t||(t={user:r.user},await Fn(this.userStorage,this.storageKey+"-user",t)),r.user=null!==(e=null==t?void 0:t.user)&&void 0!==e?e:Xn()}else if(r&&!r.user&&!r.user){const e=await Mn(this.storage,this.storageKey+"-user");e&&(null==e?void 0:e.user)?(r.user=e.user,await Kn(this.storage,this.storageKey+"-user"),await Fn(this.storage,this.storageKey,r)):r.user=Xn()}if(this._debug(n,"session from storage",r),!this._isValidSession(r))return this._debug(n,"session is not valid"),void(null!==r&&await this._removeSession());const i=1e3*(null!==(t=r.expires_at)&&void 0!==t?t:1/0)-Date.now()<cn;if(this._debug(n,`session has${i?"":" not"} expired with margin of 90000s`),i){if(this.autoRefreshToken&&r.refresh_token){const{error:e}=await this._callRefreshToken(r.refresh_token);e&&(console.error(e),En(e)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else if(r.user&&!0===r.user.__isUserNotAvailableProxy)try{const{data:e,error:t}=await this._getUser(r.access_token);!t&&(null==e?void 0:e.user)?(r.user=e.user,await this._saveSession(r),await this._notifyAllSubscribers("SIGNED_IN",r)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(e){console.error("Error getting user data:",e),this._debug(n,"error getting user data, skipping SIGNED_IN notification",e)}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(e){return this._debug(n,"error",e),void console.error(e)}finally{this._debug(n,"end")}}async _callRefreshToken(e){var t,n;if(!e)throw new wn;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const r=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{this.refreshingDeferred=new zn;const{data:t,error:n}=await this._refreshAccessToken(e);if(n)throw n;if(!t.session)throw new wn;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);const r={data:t.session,error:null};return this.refreshingDeferred.resolve(r),r}catch(e){if(this._debug(r,"error",e),pn(e)){const n={data:null,error:e};return En(e)||await this._removeSession(),null===(t=this.refreshingDeferred)||void 0===t||t.resolve(n),n}throw null===(n=this.refreshingDeferred)||void 0===n||n.reject(e),e}finally{this.refreshingDeferred=null,this._debug(r,"end")}}async _notifyAllSubscribers(e,t,n=!0){const r=`#_notifyAllSubscribers(${e})`;this._debug(r,"begin",t,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:t});const r=[],i=Array.from(this.stateChangeEmitters.values()).map(async n=>{try{await n.callback(e,t)}catch(e){r.push(e)}});if(await Promise.all(i),r.length>0){for(let e=0;e<r.length;e+=1)console.error(r[e]);throw r[0]}}finally{this._debug(r,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0;const t=Object.assign({},e),n=t.user&&!0===t.user.__isUserNotAvailableProxy;if(this.userStorage){!n&&t.user&&await Fn(this.userStorage,this.storageKey+"-user",{user:t.user});const e=Object.assign({},t);delete e.user;const r=Zn(e);await Fn(this.storage,this.storageKey,r)}else{const e=Zn(t);await Fn(this.storage,this.storageKey,e)}}async _removeSession(){this._debug("#_removeSession()"),await Kn(this.storage,this.storageKey),await Kn(this.storage,this.storageKey+"-code-verifier"),await Kn(this.storage,this.storageKey+"-user"),this.userStorage&&await Kn(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Dn()&&(null===window||void 0===window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),on);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&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:n}}=t;if(!n||!n.refresh_token||!n.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");const r=Math.floor((1e3*n.expires_at-e)/on);this._debug("#_autoRefreshTokenTick()",`access token expires in ${r} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),r<=3&&await this._callRefreshToken(n.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(!(e.isAcquireTimeout||e instanceof pr))throw e;this._debug("auto refresh token tick lock not available")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Dn()||!(null===window||void 0===window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null===window||void 0===window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{"visible"===document.visibilityState?await this._recoverAndRefresh():this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting")}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,n){const r=[`provider=${encodeURIComponent(t)}`];if((null==n?void 0:n.redirectTo)&&r.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),(null==n?void 0:n.scopes)&&r.push(`scopes=${encodeURIComponent(n.scopes)}`),"pkce"===this.flowType){const[e,t]=await Hn(this.storage,this.storageKey),n=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});r.push(n.toString())}if(null==n?void 0:n.queryParams){const e=new URLSearchParams(n.queryParams);r.push(e.toString())}return(null==n?void 0:n.skipBrowserRedirect)&&r.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var n;const{data:r,error:i}=t;return i?this._returnResult({data:null,error:i}):await rr(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(n=null==r?void 0:r.session)||void 0===n?void 0:n.access_token})})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{var n,r;const{data:i,error:s}=t;if(s)return this._returnResult({data:null,error:s});const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},"phone"===e.factorType?{phone:e.phone}:"totp"===e.factorType?{issuer:e.issuer}:{}),{data:o,error:c}=await rr(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:null===(n=null==i?void 0:i.session)||void 0===n?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):("totp"===e.factorType&&"totp"===o.type&&(null===(r=null==o?void 0:o.totp)||void 0===r?void 0:r.qr_code)&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),this._returnResult({data:o,error:null}))})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var n;const{data:r,error:i}=t;if(i)return this._returnResult({data:null,error:i});const s=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:"create"===e.webauthn.type?Or(e.webauthn.credential_response):xr(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:o}=await rr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:s,headers:this.headers,jwt:null===(n=null==r?void 0:r.session)||void 0===n?void 0:n.access_token});return o?this._returnResult({data:null,error:o}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:o}))})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var n;const{data:r,error:i}=t;if(i)return this._returnResult({data:null,error:i});const s=await rr(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:null===(n=null==r?void 0:r.session)||void 0===n?void 0:n.access_token});if(s.error)return s;const{data:a}=s;if("webauthn"!==a.type)return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:Er(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:Tr(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}})}async _challengeAndVerify(e){const{data:t,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){var e;const{data:{user:t},error:n}=await this.getUser();if(n)return{data:null,error:n};const r={all:[],phone:[],totp:[],webauthn:[]};for(const n of null!==(e=null==t?void 0:t.factors)&&void 0!==e?e:[])r.all.push(n),"verified"===n.status&&r[n.factor_type].push(n);return{data:r,error:null}}async _getAuthenticatorAssuranceLevel(){var e,t;const{data:{session:n},error:r}=await this.getSession();if(r)return this._returnResult({data:null,error:r});if(!n)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:i}=Wn(n.access_token);let s=null;i.aal&&(s=i.aal);let a=s;(null!==(t=null===(e=n.user.factors)||void 0===e?void 0:e.filter(e=>"verified"===e.status))&&void 0!==t?t:[]).length>0&&(a="aal2");return{data:{currentLevel:s,nextLevel:a,currentAuthenticationMethods:i.amr||[]},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;return r?this._returnResult({data:null,error:r}):n?await rr(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new wn})})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async n=>{const{data:{session:r},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!r)return this._returnResult({data:null,error:new wn});const s=await rr(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:r.access_token,body:{action:"approve"},xform:e=>({data:e,error:null})});return s.data&&s.data.redirect_url&&Dn()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(s.data.redirect_url),s})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async n=>{const{data:{session:r},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!r)return this._returnResult({data:null,error:new wn});const s=await rr(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:r.access_token,body:{action:"deny"},xform:e=>({data:e,error:null})});return s.data&&s.data.redirect_url&&Dn()&&!(null==t?void 0:t.skipBrowserRedirect)&&window.location.assign(s.data.redirect_url),s})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:t},error:n}=e;return n?this._returnResult({data:null,error:n}):t?await rr(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new wn})})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;return r?this._returnResult({data:null,error:r}):n?(await rr(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new wn})})}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let n=t.keys.find(t=>t.kid===e);if(n)return n;const r=Date.now();if(n=this.jwks.keys.find(t=>t.kid===e),n&&this.jwks_cached_at+6e5>r)return n;const{data:i,error:s}=await rr(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(s)throw s;return i.keys&&0!==i.keys.length?(this.jwks=i,this.jwks_cached_at=r,n=i.keys.find(t=>t.kid===e),n||null):null}async getClaims(e,t={}){try{let n=e;if(!n){const{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});n=e.session.access_token}const{header:r,payload:i,signature:s,raw:{header:a,payload:o}}=Wn(n);(null==t?void 0:t.allowExpired)||function(e){if(!e)throw new Error("Missing exp claim");if(e<=Math.floor(Date.now()/1e3))throw new Error("JWT has expired")}(i.exp);const c=r.alg&&!r.alg.startsWith("HS")&&r.kid&&"crypto"in globalThis&&"subtle"in globalThis.crypto?await this.fetchJwk(r.kid,(null==t?void 0:t.keys)?{keys:t.keys}:null==t?void 0:t.jwks):null;if(!c){const{error:e}=await this.getUser(n);if(e)throw e;return{data:{claims:i,header:r,signature:s},error:null}}const l=function(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}(r.alg),u=await crypto.subtle.importKey("jwk",c,l,!0,["verify"]);if(!await crypto.subtle.verify(l,u,s,Un(`${a}.${o}`)))throw new On("Invalid JWT signature");return{data:{claims:i,header:r,signature:s},error:null}}catch(e){if(pn(e))return this._returnResult({data:null,error:e});throw e}}}Dr.nextInstanceID={};const Br=Dr;class Lr extends Br{constructor(e){super(e)}}class qr{constructor(e,t,n){var r,i,s;this.supabaseUrl=e,this.supabaseKey=t;const a=function(e){const t=null==e?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL((n=t).endsWith("/")?n:n+"/")}catch(e){throw Error("Invalid supabaseUrl: Provided URL is malformed.")}var n}(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 o=`sb-${a.hostname.split(".")[0]}-auth-token`,c=function(e,t){var n,r;const{db:i,auth:s,realtime:a,global:o}=e,{db:c,auth:l,realtime:u,global:d}=t,h={db:Object.assign(Object.assign({},c),i),auth:Object.assign(Object.assign({},l),s),realtime:Object.assign(Object.assign({},u),a),storage:{},global:Object.assign(Object.assign(Object.assign({},d),o),{headers:Object.assign(Object.assign({},null!==(n=null==d?void 0:d.headers)&&void 0!==n?n:{}),null!==(r=null==o?void 0:o.headers)&&void 0!==r?r:{})}),accessToken:async()=>""};return e.accessToken?h.accessToken=e.accessToken:delete h.accessToken,h}(null!=n?n:{},{db:en,realtime:nn,auth:Object.assign(Object.assign({},tn),{storageKey:o}),global:Zt});this.storageKey=null!==(r=c.auth.storageKey)&&void 0!==r?r:"",this.headers=null!==(i=c.global.headers)&&void 0!==i?i:{},c.accessToken?(this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(null!==(s=c.auth)&&void 0!==s?s:{},this.headers,c.global.fetch),this.fetch=sn(t,this._getAccessToken.bind(this),c.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},c.realtime)),this.accessToken&&this.accessToken().then(e=>this.realtime.setAuth(e)).catch(e=>console.warn("Failed to set initial Realtime auth token:",e)),this.rest=new ge(new URL("rest/v1",a).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch}),this.storage=new Qt(this.storageUrl.href,this.headers,this.fetch,null==n?void 0:n.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new z(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={},n={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,n)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var e,t;if(this.accessToken)return await this.accessToken();const{data:n}=await this.auth.getSession();return null!==(t=null===(e=n.session)||void 0===e?void 0:e.access_token)&&void 0!==t?t:this.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:i,storageKey:s,flowType:a,lock:o,debug:c,throwOnError:l},u,d){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Lr({url:this.authUrl.href,headers:Object.assign(Object.assign({},h),u),storageKey:s,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:i,flowType:a,lock:o,debug:c,throwOnError:l,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>"authorization"===e.toLowerCase())})}_initRealtimeClient(e){return new nt(this.realtimeUrl.href,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,n){"TOKEN_REFRESHED"!==e&&"SIGNED_IN"!==e||this.changedAccessToken===n?"SIGNED_OUT"===e&&(this.realtime.setAuth(),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0):(this.changedAccessToken=n,this.realtime.setAuth(n))}}(function(){if("undefined"!=typeof window)return!1;if("undefined"==typeof process)return!1;const e=process.version;if(null==e)return!1;const t=e.match(/^v(\d+)\./);return!!t&&parseInt(t[1],10)<=18})()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");class Fr{mergeConfigs(e){const t="undefined"!=typeof window?window.APP_CONFIG:null;if(!e&&!t)throw new Error("MoneyBar: No configuration provided. Either pass config to constructor or set window.APP_CONFIG");return e?t?{...t,...e}:e:t}constructor(e){this.currentUser=null,this.userFingerprint=null,this.eventListeners=new Map,this.supabaseConnectionFailed=!1,this.paymentConnectionFailed=!1,this.securityKeyFailed=!1,this.isLoadingStatus=!1,this.cachedStatus=null,this.statusCacheTime=0,this.STATUS_CACHE_DURATION=5e3,this.initializationPromise=null,this.cachedPremiumStatus=null,this.premiumStatusCacheTime=0,this.config=this.mergeConfigs(e),this.config.options,this.validateConfig(),this.initializeSupabase(),this.initializePayment(),this.initializeFingerprint(),this.setupAuthListener(),this.checkPaymentStatus()}async handleDownload(){try{if(this.securityKeyFailed)return void this.showError("Invalid Security Key","Your security key is invalid, expired, or not found. Please check your MoneyBar configuration and ensure you have a valid security_key.");if(this.supabaseConnectionFailed)return void this.config.callbacks?.onError?.(new Error("Server connection required for download verification. Please check your configuration."));if(this.config.payment&&this.paymentConnectionFailed)return void this.config.callbacks?.onError?.(new Error("Payment configuration error. Please contact support."));if(this.currentUser){if(await this.checkPremiumStatus(this.currentUser.email))return void this.config.callbacks?.onPremiumDownload()}const e=await this.getDownloadStatus();if(e.currentCount>=e.limit)return void this.config.callbacks?.onLimitReached(e.currentCount,e.limit);await this.incrementDownloadCount(),this.config.callbacks?.onDownloadAllowed(),this.cachedStatus=null;const t=await this.getDownloadStatus();this.emit("countChanged",{count:t.currentCount,limit:t.limit}),t.currentCount>=t.limit&&setTimeout(()=>{this.config.callbacks?.onLimitReached(t.currentCount,t.limit)},100)}catch(e){this.handleError(e)}}async getDownloadStatus(e=!1){console.log(`🔍 [INIT] getDownloadStatus called (forceRefresh: ${e}) at ${(new Date).toISOString()}`);const t=this.cachedStatus?Date.now()-this.statusCacheTime:-1;if(!e&&this.cachedStatus&&t<this.STATUS_CACHE_DURATION)return console.log(`🔍 [INIT] Using cached status (age: ${t}ms)`),this.cachedStatus;if(!e&&this.initializationPromise)return console.log("🔍 [INIT] Waiting for existing initialization promise"),await this.initializationPromise;console.log(`🔍 [INIT] Starting new status fetch (cache age: ${t}ms)`),this.initializationPromise=this.fetchFreshStatus(e);try{const e=await this.initializationPromise;return console.log("🔍 [INIT] Status fetch completed successfully"),e}finally{this.initializationPromise=null}}async fetchFreshStatus(e){try{let t=0,n=!1;if(e||!this.cachedStatus){if(t=await this.getDownloadCount(),this.securityKeyFailed)return{currentCount:0,limit:this.config.freeAttemptLimit,isPremium:!1,isAuthenticated:!1,remaining:0}}else t=this.cachedStatus.currentCount;if(this.currentUser){const t=null!==this.cachedPremiumStatus&&Date.now()-this.premiumStatusCacheTime<this.STATUS_CACHE_DURATION;e||!t?(n=await this.checkPremiumStatus(this.currentUser.email),this.cachedPremiumStatus=n,this.premiumStatusCacheTime=Date.now()):(n=this.cachedPremiumStatus,console.log(`🔍 [CACHE] Using cached premium status from getDownloadStatus: ${n}`))}else n=!1;const r={currentCount:t,limit:this.config.freeAttemptLimit,isPremium:n,isAuthenticated:!!this.currentUser,remaining:Math.max(0,this.config.freeAttemptLimit-t)};return this.cachedStatus=r,this.statusCacheTime=Date.now(),r}catch(e){this.handleError(e);const t={currentCount:0,limit:this.config.freeAttemptLimit,isPremium:!1,isAuthenticated:!1,remaining:this.config.freeAttemptLimit};return this.cachedStatus=t,this.statusCacheTime=Date.now(),t}}async getUserContext(){const e=await this.getDownloadStatus();return{isPremium:e.isPremium,isAuthenticated:e.isAuthenticated,email:this.currentUser?.email,name:this.currentUser?.user_metadata?.full_name||this.currentUser?.user_metadata?.name,currentCount:e.currentCount,remaining:e.remaining,limit:e.limit,user:this.currentUser}}async signIn(){try{const{error:e}=await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}${window.location.pathname}`}});if(e)throw e}catch(e){this.handleError(e)}}async signOut(){try{await this.supabase.auth.signOut(),this.currentUser=null,this.emit("authChanged",{user:null,isPremium:!1})}catch(e){this.handleError(e)}}async createPayment(){if(!this.currentUser)throw new Error("User must be signed in to create payment");if(!this.config.payment)throw new Error("Payment configuration not provided");const e=this.config.payment?.find(e=>"dodo"===e.provider);if(!e)throw new Error("No dodo payment provider configured");const t={email:this.currentUser.email,product_id:e.productId,mode:e.mode||"test",app_id:this.config.appId,return_url:`${window.location.origin}${window.location.pathname}?payment=success`};console.log(`🔥 [PAYMENT API] createPayment called for provider: ${e.provider}, email: ${this.currentUser.email} | Time: ${(new Date).toISOString()}`);try{let n;if("dodo"!==e.provider)throw new Error(`Payment provider '${e.provider}' is not yet supported`);if(n=await fetch(`${this.config.supabase.url}/functions/v1/create-payment`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.supabase.anonKey}`},body:JSON.stringify(t)}),console.log(`🔥 [PAYMENT API] createPayment response for ${e.provider}: ${n.status}`),this.config.options,!n.ok){const e=await n.text();let t;this.config.options?.debug&&console.error("🔍 DEBUG: createPayment error response:",e);try{t=JSON.parse(e)}catch{t={error:e}}throw(e.includes("404")||e.includes("could not be found"))&&(this.paymentConnectionFailed=!0,this.config.options?.debug&&console.warn("Invalid payment product ID detected, disabling downloads"),this.updateStatusDisplays()),new Error(t.error||"Payment creation failed")}const r=await n.json();return this.config.options,r}catch(e){return this.handleError(e),null}}attachToButton(e,t){const n=document.querySelector(e);if(!n)throw new Error(`Button not found: ${e}`);this.injectBaseStyles(),this.createTitleBar(),this.createPaywallModal(),this.createSuccessModal(),this.createAuthUI(),this.createStatusDisplay(),n.setAttribute("data-leadfast-attached","true"),n.onclick=async e=>{e.preventDefault(),await this.handleButtonClick(t)},this.setupUIUpdates()}attachToButtons(e){this.injectBaseStyles(),this.createTitleBar(),this.createPaywallModal(),this.createSuccessModal(),this.createAuthUI(),e.buttons.forEach(e=>{const t=document.querySelector(e.selector);t?(t.setAttribute("data-leadfast-attached","true"),t.onclick=async t=>{t.preventDefault(),await this.handleButtonClick(e.downloadCallback)},this.setupUIUpdates()):console.warn(`Button not found: ${e.selector}`)}),this.createGlobalStatusDisplay()}async handleButtonClick(e){const t=document.querySelector('[data-leadfast-attached="true"]');if(t&&t.disabled)console.log("⚠️ Button click ignored - operation already in progress");else{t&&(t.disabled=!0,t.style.opacity="0.6");try{await this.handleButtonClickInternal(e)}finally{t&&(t.disabled=!1,t.style.opacity="1")}}}async handleButtonClickInternal(e){if(this.supabaseConnectionFailed)return void this.showConnectionError();if(this.config.payment&&this.paymentConnectionFailed)return void this.showPaymentConfigError();const t=this.cachedStatus&&Date.now()-this.statusCacheTime<this.STATUS_CACHE_DURATION?this.cachedStatus:await this.getDownloadStatus();if(t.isPremium){const t=await this.getUserContext();return void(e.length>0?e(t):e())}if(t.currentCount>=t.limit)this.showPaywallInstant(t);else{try{if(e.length>0){const t=await this.getUserContext();t.isPremium||(t.currentCount+=1,t.remaining=Math.max(0,t.limit-t.currentCount)),e(t)}else e();const t=await this.getDownloadStatus(!0);if(t.currentCount>=t.limit)return console.warn(`⚠️ Limit reached during execution (${t.currentCount}/${t.limit}) - canceling increment`),void alert("⚠️ You reached the limit while this action was processing. No attempt was counted.");const n=await this.incrementDownloadCount();if(n>this.config.freeAttemptLimit)return void console.error(`⚠️ Server returned count (${n}) exceeding limit (${this.config.freeAttemptLimit})`);if(!0===this.config.successMessage?.enabled){const e=this.config.successMessage?.title||"Action Completed!",t=this.config.successMessage?.message||"Your action completed successfully!";this.showSuccess(e,t)}}catch(e){return console.error("User function failed:",e),void alert("Action failed. Please check the console for details. No attempt was counted.")}this.cachedStatus=null,this.updateStatusDisplays()}}injectBaseStyles(){if(document.getElementById("lead-fast-styles"))return;this.config.theme?.name&&this.injectDaisyUI();const e=document.createElement("style");e.id="lead-fast-styles";const t=this.config.theme?.primaryColor||"#3182ce";e.textContent=`\n /* User Profile Card - Top Right */\n .lead-fast-profile {\n position: fixed;\n top: 20px;\n left: 50%;\n transform: translateX(-50%);\n z-index: 1000;\n font-family: system-ui, -apple-system, sans-serif;\n width: 90%;\n max-width: 1200px;\n }\n\n .lead-fast-title-bar {\n background: rgba(250, 247, 245, 0.9) !important;\n border: 1px solid rgba(231, 226, 223, 0.6) !important;\n color: #291334 !important;\n border-radius: 16px;\n padding: 12px 24px;\n box-shadow: 0 8px 32px rgb(0 0 0 / 0.1), 0 2px 8px rgb(0 0 0 / 0.05);\n backdrop-filter: blur(20px);\n display: flex;\n align-items: center;\n justify-content: space-between;\n min-height: 60px;\n font-family: system-ui, -apple-system, sans-serif;\n }\n\n /* Theme variations for floating title bar */\n [data-theme="bumblebee"] .lead-fast-title-bar {\n background: rgba(255, 248, 220, 0.9) !important;\n border-color: rgba(254, 215, 170, 0.6) !important;\n color: #1c1917 !important;\n }\n\n [data-theme="garden"] .lead-fast-title-bar {\n background: rgba(240, 253, 244, 0.9) !important;\n border-color: rgba(134, 239, 172, 0.6) !important;\n color: #14532d !important;\n }\n\n [data-theme="emerald"] .lead-fast-title-bar {\n background: rgba(236, 253, 245, 0.9) !important;\n border-color: rgba(167, 243, 208, 0.6) !important;\n color: #065f46 !important;\n }\n\n [data-theme="corporate"] .lead-fast-title-bar {\n background: rgba(248, 250, 252, 0.9) !important;\n border-color: rgba(226, 232, 240, 0.6) !important;\n color: #1e293b !important;\n }\n\n [data-theme="dark"] .lead-fast-title-bar {\n background: rgba(31, 41, 55, 0.9) !important;\n border-color: rgba(55, 65, 81, 0.6) !important;\n color: #f9fafb !important;\n }\n\n [data-theme="cyberpunk"] .lead-fast-title-bar {\n background: rgba(0, 20, 36, 0.9) !important;\n border-color: rgba(7, 89, 133, 0.6) !important;\n color: #0ea5e9 !important;\n box-shadow: 0 8px 32px rgba(14, 165, 233, 0.2), 0 2px 8px rgba(14, 165, 233, 0.1);\n }\n\n [data-theme="valentine"] .lead-fast-title-bar {\n background: rgba(233, 30, 122, 0.15) !important;\n border-color: rgba(233, 30, 122, 0.6) !important;\n color: #831843 !important;\n }\n\n [data-theme="synthwave"] .lead-fast-title-bar {\n background: rgba(32, 20, 64, 0.9) !important;\n border-color: rgba(186, 85, 211, 0.6) !important;\n color: #ff00ff !important;\n box-shadow: 0 8px 32px rgba(255, 0, 255, 0.2), 0 2px 8px rgba(255, 0, 255, 0.1);\n }\n\n [data-theme="dracula"] .lead-fast-title-bar {\n background: rgba(40, 42, 54, 0.9) !important;\n border-color: rgba(98, 114, 164, 0.6) !important;\n color: #f8f8f2 !important;\n }\n\n [data-theme="halloween"] .lead-fast-title-bar {\n background: rgba(26, 26, 26, 0.9) !important;\n border-color: rgba(255, 165, 0, 0.6) !important;\n color: #ff6600 !important;\n }\n\n [data-theme="forest"] .lead-fast-title-bar {\n background: rgba(23, 46, 23, 0.9) !important;\n border-color: rgba(34, 197, 94, 0.6) !important;\n color: #22c55e !important;\n }\n\n [data-theme="luxury"] .lead-fast-title-bar {\n background: rgba(9, 9, 11, 0.9) !important;\n border-color: rgba(212, 175, 55, 0.6) !important;\n color: #d4af37 !important;\n }\n\n [data-theme="night"] .lead-fast-title-bar {\n background: rgba(15, 23, 42, 0.9) !important;\n border-color: rgba(30, 58, 138, 0.6) !important;\n color: #60a5fa !important;\n }\n\n [data-theme="light"] .lead-fast-title-bar {\n background: rgba(255, 255, 255, 0.9) !important;\n border-color: rgba(229, 231, 235, 0.6) !important;\n color: #1f2937 !important;\n }\n\n [data-theme="cupcake"] .lead-fast-title-bar {\n background: rgba(250, 235, 215, 0.9) !important;\n border-color: rgba(219, 185, 156, 0.6) !important;\n color: #8b4513 !important;\n }\n\n [data-theme="retro"] .lead-fast-title-bar {\n background: rgba(212, 165, 116, 0.9) !important;\n border-color: rgba(185, 144, 102, 0.6) !important;\n color: #5d4037 !important;\n }\n\n [data-theme="aqua"] .lead-fast-title-bar {\n background: rgba(240, 253, 250, 0.9) !important;\n border-color: rgba(125, 211, 252, 0.6) !important;\n color: #155e75 !important;\n }\n\n [data-theme="lofi"] .lead-fast-title-bar {\n background: rgba(248, 248, 248, 0.9) !important;\n border-color: rgba(68, 68, 68, 0.6) !important;\n color: #1a1a1a !important;\n }\n\n [data-theme="pastel"] .lead-fast-title-bar {\n background: rgba(254, 251, 255, 0.9) !important;\n border-color: rgba(209, 196, 233, 0.6) !important;\n color: #7c3aed !important;\n }\n\n [data-theme="fantasy"] .lead-fast-title-bar {\n background: rgba(255, 247, 237, 0.9) !important;\n border-color: rgba(249, 168, 212, 0.6) !important;\n color: #be185d !important;\n }\n\n [data-theme="wireframe"] .lead-fast-title-bar {\n background: rgba(223, 223, 223, 0.9) !important;\n border-color: rgba(0, 0, 0, 0.3) !important;\n color: #000000 !important;\n }\n\n [data-theme="black"] .lead-fast-title-bar {\n background: rgba(0, 0, 0, 0.9) !important;\n border-color: rgba(55, 55, 55, 0.6) !important;\n color: #ffffff !important;\n }\n\n [data-theme="cmyk"] .lead-fast-title-bar {\n background: rgba(0, 255, 255, 0.9) !important;\n border-color: rgba(255, 0, 255, 0.6) !important;\n color: #000000 !important;\n }\n\n [data-theme="autumn"] .lead-fast-title-bar {\n background: rgba(139, 69, 19, 0.9) !important;\n border-color: rgba(255, 140, 0, 0.6) !important;\n color: #ff8c00 !important;\n }\n\n [data-theme="business"] .lead-fast-title-bar {\n background: rgba(29, 78, 216, 0.9) !important;\n border-color: rgba(59, 130, 246, 0.6) !important;\n color: #3b82f6 !important;\n }\n\n [data-theme="acid"] .lead-fast-title-bar {\n background: rgba(255, 255, 0, 0.9) !important;\n border-color: rgba(255, 0, 255, 0.6) !important;\n color: #000000 !important;\n }\n\n [data-theme="lemonade"] .lead-fast-title-bar {\n background: rgba(255, 255, 224, 0.9) !important;\n border-color: rgba(34, 197, 94, 0.6) !important;\n color: #15803d !important;\n }\n\n [data-theme="coffee"] .lead-fast-title-bar {\n background: rgba(101, 67, 33, 0.9) !important;\n border-color: rgba(160, 82, 45, 0.6) !important;\n color: #d2b48c !important;\n }\n\n [data-theme="winter"] .lead-fast-title-bar {\n background: rgba(248, 250, 252, 0.9) !important;\n border-color: rgba(59, 130, 246, 0.6) !important;\n color: #1e40af !important;\n }\n\n .lead-fast-title-section {\n display: flex;\n align-items: center;\n gap: 16px;\n }\n\n .lead-fast-logo {\n font-size: 20px;\n font-weight: 700;\n display: flex;\n align-items: center;\n gap: 8px;\n color: inherit;\n text-decoration: none;\n }\n\n .lead-fast-logo img {\n width: 32px;\n height: 32px;\n border-radius: 6px;\n }\n\n .lead-fast-nav {\n display: flex;\n align-items: center;\n gap: 32px;\n margin-left: 24px;\n }\n\n .lead-fast-nav-link {\n color: inherit;\n text-decoration: none;\n font-weight: 500;\n font-size: 14px;\n opacity: 0.8;\n transition: all 0.2s;\n }\n\n .lead-fast-nav-link:hover {\n opacity: 1;\n text-decoration: none;\n }\n\n .lead-fast-user-section {\n display: flex;\n align-items: center;\n gap: 12px;\n }\n\n .lead-fast-avatar {\n width: 36px;\n height: 36px;\n border-radius: 50%;\n background: linear-gradient(135deg, ${t}, #4f46e5);\n display: flex;\n align-items: center;\n justify-content: center;\n color: white;\n font-weight: 600;\n font-size: 14px;\n }\n\n .lead-fast-user-info {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n gap: 2px;\n }\n\n .lead-fast-user-email {\n color: inherit !important;\n font-size: 13px;\n font-weight: 500;\n line-height: 1;\n }\n\n .lead-fast-user-status {\n display: flex;\n align-items: center;\n gap: 6px;\n }\n\n .lead-fast-badge {\n padding: 2px 6px;\n border-radius: 12px;\n font-size: 10px;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.025em;\n line-height: 1;\n }\n\n .lead-fast-badge.premium {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n .lead-fast-badge.free {\n background: #65c3c8 !important;\n color: #291334 !important;\n }\n\n [data-theme="dark"] .lead-fast-badge.premium {\n background: #059669 !important;\n color: #ffffff !important;\n }\n\n [data-theme="dark"] .lead-fast-badge.free {\n background: #374151 !important;\n color: #f9fafb !important;\n }\n\n .lead-fast-count {\n font-size: 10px;\n color: inherit !important;\n opacity: 0.7;\n line-height: 1;\n }\n\n .lead-fast-signout {\n background: rgba(0, 0, 0, 0.1) !important;\n border: none;\n color: inherit !important;\n cursor: pointer;\n padding: 6px 12px;\n border-radius: 8px;\n transition: all 0.2s;\n font-size: 11px;\n font-weight: 500;\n margin-left: 8px;\n }\n\n [data-theme="dark"] .lead-fast-signout {\n background: rgba(255, 255, 255, 0.1) !important;\n }\n\n [data-theme="cyberpunk"] .lead-fast-signout {\n background: rgba(14, 165, 233, 0.2) !important;\n }\n\n .lead-fast-signout:hover {\n background: rgba(0, 0, 0, 0.2) !important;\n transform: translateY(-1px);\n }\n\n [data-theme="dark"] .lead-fast-signout:hover {\n background: rgba(255, 255, 255, 0.2) !important;\n }\n\n [data-theme="cyberpunk"] .lead-fast-signout:hover {\n background: rgba(14, 165, 233, 0.3) !important;\n }\n\n .lead-fast-branding {\n position: absolute;\n bottom: -20px;\n left: 24px;\n font-size: 9px;\n color: inherit !important;\n opacity: 0.4;\n font-weight: 500;\n letter-spacing: 0.05em;\n text-transform: lowercase;\n background: rgba(255, 255, 255, 0.8);\n padding: 2px 6px;\n border-radius: 4px;\n backdrop-filter: blur(8px);\n }\n\n [data-theme="dark"] .lead-fast-branding {\n background: rgba(0, 0, 0, 0.6);\n }\n\n [data-theme="cyberpunk"] .lead-fast-branding {\n background: rgba(0, 20, 36, 0.8);\n }\n\n /* Modal Theming */\n .download-limiter-modal {\n display: none;\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0,0,0,0.5);\n z-index: 9999;\n align-items: center;\n justify-content: center;\n }\n .download-limiter-modal.show { display: flex; }\n\n .download-limiter-content {\n background: #faf7f5 !important;\n color: #291334 !important;\n padding: 2rem;\n border-radius: 12px;\n max-width: 400px;\n text-align: center;\n box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1);\n border: 1px solid #e7e2df !important;\n font-family: system-ui, -apple-system, sans-serif;\n }\n\n [data-theme="dark"] .download-limiter-content {\n background: #1f2937 !important;\n color: #f9fafb !important;\n border-color: #374151 !important;\n }\n\n [data-theme="cyberpunk"] .download-limiter-content {\n background: #001424 !important;\n color: #0ea5e9 !important;\n border-color: #075985 !important;\n }\n\n [data-theme="valentine"] .download-limiter-content {\n background: rgba(233, 30, 122, 0.05) !important;\n color: #831843 !important;\n border-color: #e91e7a !important;\n }\n\n [data-theme="bumblebee"] .download-limiter-content {\n background: rgba(255, 248, 220, 0.95) !important;\n color: #1c1917 !important;\n border-color: rgba(254, 215, 170, 0.8) !important;\n }\n\n [data-theme="garden"] .download-limiter-content {\n background: rgba(240, 253, 244, 0.95) !important;\n color: #14532d !important;\n border-color: rgba(134, 239, 172, 0.8) !important;\n }\n\n [data-theme="emerald"] .download-limiter-content {\n background: rgba(236, 253, 245, 0.95) !important;\n color: #065f46 !important;\n border-color: rgba(167, 243, 208, 0.8) !important;\n }\n\n [data-theme="corporate"] .download-limiter-content {\n background: rgba(248, 250, 252, 0.95) !important;\n color: #1e293b !important;\n border-color: rgba(226, 232, 240, 0.8) !important;\n }\n\n [data-theme="forest"] .download-limiter-content {\n background: rgba(23, 46, 23, 0.95) !important;\n color: #22c55e !important;\n border-color: rgba(34, 197, 94, 0.8) !important;\n }\n\n [data-theme="halloween"] .download-limiter-content {\n background: rgba(26, 26, 26, 0.95) !important;\n color: #ff6500 !important;\n border-color: rgba(255, 165, 0, 0.3) !important;\n }\n\n [data-theme="synthwave"] .download-limiter-content {\n background: rgba(32, 20, 64, 0.95) !important;\n color: #ba55d3 !important;\n border-color: rgba(186, 85, 211, 0.3) !important;\n }\n\n [data-theme="dracula"] .download-limiter-content {\n background: rgba(40, 42, 54, 0.95) !important;\n color: #f8f8f2 !important;\n border-color: rgba(98, 114, 164, 0.3) !important;\n }\n\n [data-theme="luxury"] .download-limiter-content {\n background: rgba(9, 9, 11, 0.95) !important;\n color: #d4af37 !important;\n border-color: rgba(212, 175, 55, 0.3) !important;\n }\n\n [data-theme="night"] .download-limiter-content {\n background: rgba(15, 23, 42, 0.95) !important;\n color: #1e40af !important;\n border-color: rgba(30, 58, 138, 0.3) !important;\n }\n\n [data-theme="light"] .download-limiter-content {\n background: rgba(255, 255, 255, 0.95) !important;\n color: #1f2937 !important;\n border-color: rgba(229, 231, 235, 0.8) !important;\n }\n\n [data-theme="cupcake"] .download-limiter-content {\n background: rgba(250, 235, 215, 0.95) !important;\n color: #8b4513 !important;\n border-color: rgba(219, 185, 156, 0.8) !important;\n }\n\n [data-theme="retro"] .download-limiter-content {\n background: rgba(212, 165, 116, 0.95) !important;\n color: #5d4037 !important;\n border-color: rgba(185, 144, 102, 0.8) !important;\n }\n\n [data-theme="aqua"] .download-limiter-content {\n background: rgba(240, 253, 250, 0.95) !important;\n color: #155e75 !important;\n border-color: rgba(125, 211, 252, 0.8) !important;\n }\n\n [data-theme="lofi"] .download-limiter-content {\n background: rgba(248, 248, 248, 0.95) !important;\n color: #1a1a1a !important;\n border-color: rgba(68, 68, 68, 0.8) !important;\n }\n\n [data-theme="pastel"] .download-limiter-content {\n background: rgba(254, 251, 255, 0.95) !important;\n color: #7c3aed !important;\n border-color: rgba(209, 196, 233, 0.8) !important;\n }\n\n [data-theme="fantasy"] .download-limiter-content {\n background: rgba(255, 247, 237, 0.95) !important;\n color: #be185d !important;\n border-color: rgba(249, 168, 212, 0.8) !important;\n }\n\n [data-theme="wireframe"] .download-limiter-content {\n background: rgba(255, 255, 255, 0.95) !important;\n color: #000000 !important;\n border-color: rgba(0, 0, 0, 0.3) !important;\n }\n\n [data-theme="black"] .download-limiter-content {\n background: rgba(0, 0, 0, 0.95) !important;\n color: #ffffff !important;\n border-color: rgba(55, 55, 55, 0.8) !important;\n }\n\n [data-theme="cmyk"] .download-limiter-content {\n background: rgba(0, 255, 255, 0.95) !important;\n color: #000000 !important;\n border-color: rgba(255, 0, 255, 0.8) !important;\n }\n\n [data-theme="autumn"] .download-limiter-content {\n background: rgba(139, 69, 19, 0.95) !important;\n color: #ff8c00 !important;\n border-color: rgba(255, 140, 0, 0.8) !important;\n }\n\n [data-theme="business"] .download-limiter-content {\n background: rgba(29, 78, 216, 0.95) !important;\n color: #3b82f6 !important;\n border-color: rgba(59, 130, 246, 0.8) !important;\n }\n\n [data-theme="acid"] .download-limiter-content {\n background: rgba(255, 255, 0, 0.95) !important;\n color: #000000 !important;\n border-color: rgba(255, 0, 255, 0.8) !important;\n }\n\n [data-theme="lemonade"] .download-limiter-content {\n background: rgba(255, 255, 224, 0.95) !important;\n color: #15803d !important;\n border-color: rgba(34, 197, 94, 0.8) !important;\n }\n\n [data-theme="coffee"] .download-limiter-content {\n background: rgba(101, 67, 33, 0.95) !important;\n color: #d2b48c !important;\n border-color: rgba(160, 82, 45, 0.8) !important;\n }\n\n [data-theme="winter"] .download-limiter-content {\n background: rgba(248, 250, 252, 0.95) !important;\n color: #1e40af !important;\n border-color: rgba(59, 130, 246, 0.8) !important;\n }\n\n .download-limiter-content h2 {\n color: inherit !important;\n margin: 0 0 1rem 0;\n font-size: 1.5rem;\n font-weight: 600;\n }\n .download-limiter-content p {\n color: inherit !important;\n margin: 0 0 1.5rem 0;\n line-height: 1.6;\n }\n .download-limiter-signin-btn {\n display: inline-flex;\n align-items: center;\n gap: 8px;\n background: #65c3c8 !important;\n color: #291334 !important;\n border: none;\n padding: 12px 20px;\n border-radius: 8px;\n font-size: 14px;\n font-weight: 500;\n cursor: pointer;\n text-decoration: none;\n transition: all 0.2s;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n }\n\n [data-theme="dark"] .download-limiter-signin-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cyberpunk"] .download-limiter-signin-btn {\n background: #f59e0b !important;\n color: #000000 !important;\n }\n\n [data-theme="valentine"] .download-limiter-signin-btn {\n background: #e91e7a !important;\n color: #ffffff !important;\n }\n\n [data-theme="bumblebee"] .download-limiter-signin-btn {\n background: #fbbf24 !important;\n color: #1c1917 !important;\n }\n\n [data-theme="garden"] .download-limiter-signin-btn {\n background: #22c55e !important;\n color: #ffffff !important;\n }\n\n [data-theme="emerald"] .download-limiter-signin-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="corporate"] .download-limiter-signin-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="forest"] .download-limiter-signin-btn {\n background: #22c55e !important;\n color: #1a1a1a !important;\n }\n\n [data-theme="halloween"] .download-limiter-signin-btn {\n background: #ff6500 !important;\n color: #1a1a1a !important;\n }\n\n [data-theme="synthwave"] .download-limiter-signin-btn {\n background: #ba55d3 !important;\n color: #201040 !important;\n }\n\n [data-theme="dracula"] .download-limiter-signin-btn {\n background: #8be9fd !important;\n color: #282a36 !important;\n }\n\n [data-theme="luxury"] .download-limiter-signin-btn {\n background: #d4af37 !important;\n color: #09090b !important;\n }\n\n [data-theme="night"] .download-limiter-signin-btn {\n background: #1e40af !important;\n color: #ffffff !important;\n }\n\n [data-theme="light"] .download-limiter-signin-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cupcake"] .download-limiter-signin-btn {\n background: #8b4513 !important;\n color: #ffffff !important;\n }\n\n [data-theme="retro"] .download-limiter-signin-btn {\n background: #d4a574 !important;\n color: #ffffff !important;\n }\n\n [data-theme="aqua"] .download-limiter-signin-btn {\n background: #0891b2 !important;\n color: #ffffff !important;\n }\n\n [data-theme="lofi"] .download-limiter-signin-btn {\n background: #1a1a1a !important;\n color: #ffffff !important;\n }\n\n [data-theme="pastel"] .download-limiter-signin-btn {\n background: #7c3aed !important;\n color: #ffffff !important;\n }\n\n [data-theme="fantasy"] .download-limiter-signin-btn {\n background: #be185d !important;\n color: #ffffff !important;\n }\n\n [data-theme="wireframe"] .download-limiter-signin-btn {\n background: #dfdfdf !important;\n color: #000000 !important;\n border: 1px solid #000000 !important;\n }\n\n [data-theme="black"] .download-limiter-signin-btn {\n background: #ffffff !important;\n color: #000000 !important;\n }\n\n [data-theme="cmyk"] .download-limiter-signin-btn {\n background: #ff00ff !important;\n color: #000000 !important;\n }\n\n [data-theme="autumn"] .download-limiter-signin-btn {\n background: #ff8c00 !important;\n color: #ffffff !important;\n }\n\n [data-theme="business"] .download-limiter-signin-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="acid"] .download-limiter-signin-btn {\n background: #ff00ff !important;\n color: #000000 !important;\n }\n\n [data-theme="lemonade"] .download-limiter-signin-btn {\n background: #22c55e !important;\n color: #ffffff !important;\n }\n\n [data-theme="coffee"] .download-limiter-signin-btn {\n background: #a0522d !important;\n color: #ffffff !important;\n }\n\n [data-theme="winter"] .download-limiter-signin-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n .download-limiter-signin-btn:hover {\n opacity: 0.9;\n transform: translateY(-1px);\n box-shadow: 0 4px 8px rgba(0,0,0,0.15);\n }\n\n /* Upgrade Button Styles for All Themes */\n [data-theme="dark"] .upgrade-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cyberpunk"] .upgrade-btn {\n background: #ff073a !important;\n color: #ffffff !important;\n }\n\n [data-theme="valentine"] .upgrade-btn {\n background: #e91e7a !important;\n color: #ffffff !important;\n }\n\n [data-theme="bumblebee"] .upgrade-btn {\n background: #f59e0b !important;\n color: #ffffff !important;\n }\n\n [data-theme="garden"] .upgrade-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="emerald"] .upgrade-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="corporate"] .upgrade-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="forest"] .upgrade-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="halloween"] .upgrade-btn {\n background: #ff7b00 !important;\n color: #000000 !important;\n }\n\n [data-theme="synthwave"] .upgrade-btn {\n background: #e879f9 !important;\n color: #ffffff !important;\n }\n\n [data-theme="dracula"] .upgrade-btn {\n background: #bd93f9 !important;\n color: #ffffff !important;\n }\n\n [data-theme="luxury"] .upgrade-btn {\n background: #d4af37 !important;\n color: #000000 !important;\n }\n\n [data-theme="night"] .upgrade-btn {\n background: #38bdf8 !important;\n color: #ffffff !important;\n }\n\n [data-theme="light"] .upgrade-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cupcake"] .upgrade-btn {\n background: #f472b6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="retro"] .upgrade-btn {\n background: #d4a574 !important;\n color: #ffffff !important;\n }\n\n [data-theme="aqua"] .upgrade-btn {\n background: #06b6d4 !important;\n color: #ffffff !important;\n }\n\n [data-theme="lofi"] .upgrade-btn {\n background: #a3a3a3 !important;\n color: #000000 !important;\n }\n\n [data-theme="pastel"] .upgrade-btn {\n background: #a78bfa !important;\n color: #ffffff !important;\n }\n\n [data-theme="fantasy"] .upgrade-btn {\n background: #f472b6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="wireframe"] .upgrade-btn {\n background: #dfdfdf !important;\n color: #000000 !important;\n border: 1px solid #000000 !important;\n }\n\n [data-theme="black"] .upgrade-btn {\n background: #ffffff !important;\n color: #000000 !important;\n }\n\n [data-theme="cmyk"] .upgrade-btn {\n background: #0891b2 !important;\n color: #ffffff !important;\n }\n\n [data-theme="autumn"] .upgrade-btn {\n background: #d97706 !important;\n color: #ffffff !important;\n }\n\n [data-theme="business"] .upgrade-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="acid"] .upgrade-btn {\n background: #84cc16 !important;\n color: #000000 !important;\n }\n\n [data-theme="lemonade"] .upgrade-btn {\n background: #22c55e !important;\n color: #ffffff !important;\n }\n\n [data-theme="coffee"] .upgrade-btn {\n background: #a0522d !important;\n color: #ffffff !important;\n }\n\n [data-theme="winter"] .upgrade-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n\n /* Cancel Button Styles for All Themes */\n [data-theme="dark"] .cancel-btn {\n background: #4b5563 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cyberpunk"] .cancel-btn {\n background: #7e22ce !important;\n color: #ffffff !important;\n }\n\n [data-theme="valentine"] .cancel-btn {\n background: #c11560 !important;\n color: #ffffff !important;\n }\n\n [data-theme="bumblebee"] .cancel-btn {\n background: #d97706 !important;\n color: #ffffff !important;\n }\n\n [data-theme="garden"] .cancel-btn {\n background: #059669 !important;\n color: #ffffff !important;\n }\n\n [data-theme="emerald"] .cancel-btn {\n background: #059669 !important;\n color: #ffffff !important;\n }\n\n [data-theme="corporate"] .cancel-btn {\n background: #6b7280 !important;\n color: #ffffff !important;\n }\n\n [data-theme="forest"] .cancel-btn {\n background: #059669 !important;\n color: #ffffff !important;\n }\n\n [data-theme="halloween"] .cancel-btn {\n background: #7c3aed !important;\n color: #ffffff !important;\n }\n\n [data-theme="synthwave"] .cancel-btn {\n background: #7e22ce !important;\n color: #ffffff !important;\n }\n\n [data-theme="dracula"] .cancel-btn {\n background: #6272a4 !important;\n color: #ffffff !important;\n }\n\n [data-theme="luxury"] .cancel-btn {\n background: #8b5cf6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="night"] .cancel-btn {\n background: #0284c7 !important;\n color: #ffffff !important;\n }\n\n [data-theme="light"] .cancel-btn {\n background: #6b7280 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cupcake"] .cancel-btn {\n background: #ec4899 !important;\n color: #ffffff !important;\n }\n\n [data-theme="retro"] .cancel-btn {\n background: #b8925c !important;\n color: #ffffff !important;\n }\n\n [data-theme="aqua"] .cancel-btn {\n background: #0891b2 !important;\n color: #ffffff !important;\n }\n\n [data-theme="lofi"] .cancel-btn {\n background: #6b7280 !important;\n color: #ffffff !important;\n }\n\n [data-theme="pastel"] .cancel-btn {\n background: #8b5cf6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="fantasy"] .cancel-btn {\n background: #ec4899 !important;\n color: #ffffff !important;\n }\n\n [data-theme="wireframe"] .cancel-btn {\n background: #f5f5f5 !important;\n color: #000000 !important;\n border: 1px solid #000000 !important;\n }\n\n [data-theme="black"] .cancel-btn {\n background: #6b7280 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cmyk"] .cancel-btn {\n background: #0369a1 !important;\n color: #ffffff !important;\n }\n\n [data-theme="autumn"] .cancel-btn {\n background: #c2410c !important;\n color: #ffffff !important;\n }\n\n [data-theme="business"] .cancel-btn {\n background: #6b7280 !important;\n color: #ffffff !important;\n }\n\n [data-theme="acid"] .cancel-btn {\n background: #65a30d !important;\n color: #ffffff !important;\n }\n\n [data-theme="lemonade"] .cancel-btn {\n background: #16a34a !important;\n color: #ffffff !important;\n }\n\n [data-theme="coffee"] .cancel-btn {\n background: #8b4513 !important;\n color: #ffffff !important;\n }\n\n [data-theme="winter"] .cancel-btn {\n background: #1e40af !important;\n color: #ffffff !important;\n }\n\n /* Success Button Styles for All Themes */\n [data-theme="dark"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cyberpunk"] .success-btn {\n background: #00ff41 !important;\n color: #000000 !important;\n }\n\n [data-theme="valentine"] .success-btn {\n background: #e91e7a !important;\n color: #ffffff !important;\n }\n\n [data-theme="bumblebee"] .success-btn {\n background: #f59e0b !important;\n color: #ffffff !important;\n }\n\n [data-theme="garden"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="emerald"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="corporate"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="forest"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="halloween"] .success-btn {\n background: #ff7b00 !important;\n color: #000000 !important;\n }\n\n [data-theme="synthwave"] .success-btn {\n background: #00ff41 !important;\n color: #000000 !important;\n }\n\n [data-theme="dracula"] .success-btn {\n background: #50fa7b !important;\n color: #000000 !important;\n }\n\n [data-theme="luxury"] .success-btn {\n background: #d4af37 !important;\n color: #000000 !important;\n }\n\n [data-theme="night"] .success-btn {\n background: #22d3ee !important;\n color: #ffffff !important;\n }\n\n [data-theme="light"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cupcake"] .success-btn {\n background: #f472b6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="retro"] .success-btn {\n background: #d4a574 !important;\n color: #ffffff !important;\n }\n\n [data-theme="aqua"] .success-btn {\n background: #06b6d4 !important;\n color: #ffffff !important;\n }\n\n [data-theme="lofi"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="pastel"] .success-btn {\n background: #34d399 !important;\n color: #ffffff !important;\n }\n\n [data-theme="fantasy"] .success-btn {\n background: #f472b6 !important;\n color: #ffffff !important;\n }\n\n [data-theme="wireframe"] .success-btn {\n background: #dfdfdf !important;\n color: #000000 !important;\n border: 1px solid #000000 !important;\n }\n\n [data-theme="black"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="cmyk"] .success-btn {\n background: #06b6d4 !important;\n color: #ffffff !important;\n }\n\n [data-theme="autumn"] .success-btn {\n background: #d97706 !important;\n color: #ffffff !important;\n }\n\n [data-theme="business"] .success-btn {\n background: #10b981 !important;\n color: #ffffff !important;\n }\n\n [data-theme="acid"] .success-btn {\n background: #84cc16 !important;\n color: #000000 !important;\n }\n\n [data-theme="lemonade"] .success-btn {\n background: #22c55e !important;\n color: #ffffff !important;\n }\n\n [data-theme="coffee"] .success-btn {\n background: #a0522d !important;\n color: #ffffff !important;\n }\n\n [data-theme="winter"] .success-btn {\n background: #3b82f6 !important;\n color: #ffffff !important;\n }\n .download-limiter-signout-btn {\n background: #dc3545;\n color: white;\n border: none;\n padding: 6px 12px;\n border-radius: 4px;\n font-size: 12px;\n cursor: pointer;\n margin-left: 8px;\n }\n .download-limiter-premium-badge {\n background: linear-gradient(45deg, #f39c12, #e74c3c);\n color: white;\n padding: 2px 6px;\n border-radius: 3px;\n font-size: 10px;\n margin-left: 8px;\n font-weight: bold;\n }\n .download-limiter-btn-premium {\n opacity: 0.7;\n }\n .download-limiter-success-modal {\n display: none;\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: rgba(0,0,0,0.5);\n z-index: 10000;\n align-items: center;\n justify-content: center;\n }\n .download-limiter-success-modal.show { display: flex; }\n .download-limiter-success-content {\n background: white;\n padding: 2rem;\n border-radius: 8px;\n max-width: 400px;\n text-align: center;\n box-shadow: 0 4px 20px rgba(0,0,0,0.15);\n border-left: 4px solid #38a169;\n }\n\n /* Single upgrade flow styles */\n .single-upgrade-container {\n margin: 20px 0;\n text-align: center;\n }\n\n .single-upgrade-content .upgrade-btn {\n background: linear-gradient(135deg, #059669, #0d9488) !important;\n color: white !important;\n border: none !important;\n padding: 16px 32px !important;\n border-radius: 12px !important;\n font-size: 18px !important;\n font-weight: 600 !important;\n cursor: pointer !important;\n transition: all 0.3s ease !important;\n box-shadow: 0 4px 12px rgba(5, 150, 105, 0.3) !important;\n margin-bottom: 16px !important;\n min-width: 200px !important;\n }\n\n .single-upgrade-content .upgrade-btn:hover {\n background: linear-gradient(135deg, #047857, #0f766e) !important;\n transform: translateY(-2px) !important;\n box-shadow: 0 6px 20px rgba(5, 150, 105, 0.4) !important;\n }\n\n .single-upgrade-content .upgrade-description {\n font-size: 14px !important;\n color: #6b7280 !important;\n margin: 12px 0 0 0 !important;\n line-height: 1.5 !important;\n max-width: 300px !important;\n margin-left: auto !important;\n margin-right: auto !important;\n }\n\n /* Anonymous user usage count styles */\n .lead-fast-anonymous-status {\n display: flex;\n align-items: center;\n gap: 12px;\n }\n\n .lead-fast-anonymous-status .lead-fast-count {\n background: rgba(59, 130, 246, 0.1);\n color: #1d4ed8;\n padding: 6px 12px;\n border-radius: 8px;\n font-size: 14px;\n font-weight: 500;\n border: 1px solid rgba(59, 130, 246, 0.2);\n }\n\n /* Loading state styles */\n .lead-fast-loading-status {\n display: flex;\n align-items: center;\n gap: 10px;\n }\n\n .lead-fast-spinner {\n width: 20px;\n height: 20px;\n color: #3b82f6;\n }\n\n .lead-fast-loading-text {\n font-size: 14px;\n color: #6b7280;\n font-weight: 500;\n }\n\n /* Success button theming */\n .download-limiter-btn.success-btn {\n background: #059669 !important;\n color: white !important;\n border: none !important;\n padding: 12px 24px !important;\n border-radius: 8px !important;\n cursor: pointer !important;\n margin-top: 20px !important;\n font-size: 16px !important;\n font-weight: 500 !important;\n transition: all 0.2s ease !important;\n }\n\n .download-limiter-btn.success-btn:hover {\n background: #047857 !important;\n transform: translateY(-1px) !important;\n }\n\n /* Theme-specific success button colors */\n [data-theme="cyberpunk"] .download-limiter-btn.success-btn {\n background: #0ea5e9 !important;\n box-shadow: 0 4px 12px rgba(14, 165, 233, 0.3) !important;\n }\n\n [data-theme="cyberpunk"] .download-limiter-btn.success-btn:hover {\n background: #0284c7 !important;\n }\n\n [data-theme="valentine"] .download-limiter-btn.success-btn {\n background: #be185d !important;\n }\n\n [data-theme="valentine"] .download-limiter-btn.success-btn:hover {\n background: #9d174d !important;\n }\n\n [data-theme="bumblebee"] .download-limiter-btn.success-btn {\n background: #f59e0b !important;\n }\n\n [data-theme="bumblebee"] .download-limiter-btn.success-btn:hover {\n background: #d97706 !important;\n }\n\n [data-theme="garden"] .download-limiter-btn.success-btn {\n background: #16a34a !important;\n }\n\n [data-theme="garden"] .download-limiter-btn.success-btn:hover {\n background: #15803d !important;\n }\n\n /* Google Sign-in button theming */\n .download-limiter-btn.google-signin-btn {\n background: #4285f4 !important;\n color: white !important;\n border: none !important;\n padding: 12px 24px !important;\n border-radius: 8px !important;\n cursor: pointer !important;\n margin-right: 10px !important;\n display: inline-flex !important;\n align-items: center !important;\n gap: 8px !important;\n font-size: 14px !important;\n font-weight: 500 !important;\n transition: all 0.2s ease !important;\n }\n\n .download-limiter-btn.google-signin-btn:hover {\n background: #3367d6 !important;\n transform: translateY(-1px) !important;\n }\n\n /* Upgrade button theming */\n .download-limiter-btn.upgrade-btn {\n background: #059669 !important;\n color: white !important;\n border: none !important;\n padding: 12px 24px !important;\n border-radius: 8px !important;\n cursor: pointer !important;\n margin-right: 10px !important;\n font-size: 16px !important;\n font-weight: 500 !important;\n transition: all 0.2s ease !important;\n }\n\n .download-limiter-btn.upgrade-btn:hover {\n background: #047857 !important;\n transform: translateY(-1px) !important;\n }\n\n /* Theme-specific button colors */\n [data-theme="cyberpunk"] .download-limiter-btn.upgrade-btn {\n background: #0ea5e9 !important;\n box-shadow: 0 4px 12px rgba(14, 165, 233, 0.3) !important;\n }\n\n [data-theme="valentine"] .download-limiter-btn.upgrade-btn {\n background: #be185d !important;\n }\n\n [data-theme="bumblebee"] .download-limiter-btn.upgrade-btn {\n background: #f59e0b !important;\n }\n\n [data-theme="garden"] .download-limiter-btn.upgrade-btn {\n background: #16a34a !important;\n }\n\n /* Cancel button container and styling - positioned at very bottom */\n .download-limiter-cancel-container {\n margin-top: 30px !important;\n padding-top: 20px !important;\n border-top: 1px solid rgba(0, 0, 0, 0.1) !important;\n text-align: center !important;\n position: relative !important;\n bottom: 0 !important;\n }\n\n .download-limiter-btn.cancel-btn {\n background: transparent !important;\n color: #6b7280 !important;\n border: none !important;\n padding: 8px 16px !important;\n border-radius: 6px !important;\n cursor: pointer !important;\n font-size: 13px !important;\n font-weight: 400 !important;\n transition: all 0.2s ease !important;\n text-decoration: underline !important;\n margin: 0 auto !important;\n display: block !important;\n }\n\n .download-limiter-btn.cancel-btn:hover {\n color: #374151 !important;\n background: rgba(107, 114, 128, 0.1) !important;\n text-decoration: none !important;\n }\n\n /* Theme-specific cancel button border */\n [data-theme="dark"] .download-limiter-cancel-container {\n border-top-color: rgba(255, 255, 255, 0.1) !important;\n }\n\n [data-theme="dark"] .download-limiter-btn.cancel-btn {\n color: #9ca3af !important;\n }\n\n [data-theme="dark"] .download-limiter-btn.cancel-btn:hover {\n color: #d1d5db !important;\n background: rgba(156, 163, 175, 0.1) !important;\n }\n\n [data-theme="cyberpunk"] .download-limiter-cancel-container {\n border-top-color: rgba(14, 165, 233, 0.2) !important;\n }\n\n [data-theme="cyberpunk"] .download-limiter-btn.cancel-btn {\n color: #0ea5e9 !important;\n }\n\n [data-theme="cyberpunk"] .download-limiter-btn.cancel-btn:hover {\n color: #38bdf8 !important;\n background: rgba(14, 165, 233, 0.1) !important;\n }\n `,document.head.appendChild(e)}injectDaisyUI(){if(document.querySelector('link[href*="daisyui"]')){if(this.config.theme?.name){const e=this.config.theme.name.toLowerCase();document.documentElement.setAttribute("data-theme",e)}}else if(this.config.theme?.name){const e=this.config.theme.name.toLowerCase();document.documentElement.setAttribute("data-theme",e),this.updateStatusDisplays()}}createPaywallModal(){if(document.getElementById("download-limiter-paywall"))return;const e=document.createElement("div");e.id="download-limiter-paywall",e.className="download-limiter-modal",e.innerHTML='\n <div class="download-limiter-content">\n <h3 id="download-limiter-paywall-title">Usage Limit Reached</h3>\n <p id="download-limiter-paywall-subtitle">You\'ve used all your free attempts. Upgrade to premium for unlimited usage!</p>\n\n \x3c!-- Auth Section (shows when not signed in) --\x3e\n <div id="download-limiter-auth-section" style="margin: 20px 0;">\n <p>Sign in to continue or upgrade to premium</p>\n <button id="download-limiter-signin-btn" class="download-limiter-btn google-signin-btn">\n <svg width="18" height="18" viewBox="0 0 18 18" fill="none">\n <path d="M16.51 8H8.98v3h4.3c-.18 1-.74 1.48-1.6 2.04v2.01h2.6a8.8 8.8 0 0 0 2.38-5.88c0-.57-.05-.66-.15-1.18z" fill="white"/>\n <path d="M8.98 17c2.16 0 3.97-.72 5.3-1.94l-2.6-2.04a4.8 4.8 0 0 1-2.7.75 4.8 4.8 0 0 1-4.52-3.4H1.83v2.07A8 8 0 0 0 8.98 17z" fill="white"/>\n <path d="M4.46 10.37a4.8 4.8 0 0 1-.25-1.37c0-.48.09-.94.25-1.37V5.56H1.83a8 8 0 0 0 0 6.88l2.63-2.07z" fill="white"/>\n <path d="M8.98 3.77c1.32 0 2.5.45 3.44 1.35l2.58-2.58C13.94.64 11.66 0 8.98 0A8 8 0 0 0 1.83 5.56l2.63 2.07c.61-1.8 2.26-3.86 4.52-3.86z" fill="white"/>\n </svg>\n Sign in with Google\n </button>\n </div>\n\n \x3c!-- Payment Section (shows when signed in) --\x3e\n <div id="download-limiter-payment-section" style="margin: 20px 0; display: none;">\n <button id="download-limiter-upgrade-btn" class="download-limiter-btn upgrade-btn">\n Upgrade to Premium\n </button>\n </div>\n\n <div class="download-limiter-cancel-container">\n <button id="download-limiter-close-btn" class="download-limiter-btn cancel-btn">\n Cancel\n </button>\n </div>\n </div>\n ',document.body.appendChild(e),e.querySelector("#download-limiter-signin-btn").addEventListener("click",async()=>{await this.signIn()}),e.querySelector("#download-limiter-upgrade-btn").addEventListener("click",async()=>{const e=await this.createPayment();e?.checkout_url&&(window.location.href=e.checkout_url)}),e.querySelector("#download-limiter-close-btn").addEventListener("click",()=>{this.config.options?.debug&&(console.log("🔍 DEBUG: Cancel button clicked"),console.log("🔍 DEBUG: this.config.feedback:",this.config.feedback),console.log("🔍 DEBUG: this.config.email:",this.config.email),console.log("🔍 DEBUG: Feedback config exists:",!(!this.config.feedback&&!this.config.email))),this.config.feedback||this.config.email?(this.config.options?.debug&&console.log("🔍 DEBUG: Showing feedback form"),this.showFeedbackForm()):(this.config.options?.debug&&console.log("🔍 DEBUG: No email config, just closing modal"),e.classList.remove("show"))})}createSuccessModal(){if(document.getElementById("download-limiter-success"))return;const e=document.createElement("div");e.id="download-limiter-success",e.className="download-limiter-modal",e.innerHTML='\n <div class="download-limiter-content"> \x3c!-- Use same content class as paywall for theming --\x3e\n <h3 id="download-limiter-success-title">Action Started!</h3>\n <p id="download-limiter-success-message">Your action completed successfully!</p>\n <button id="download-limiter-success-close" class="download-limiter-btn success-btn">\n OK\n </button>\n </div>\n ',document.body.appendChild(e),e.querySelector("#download-limiter-success-close").addEventListener("click",()=>{e.classList.remove("show")}),e.addEventListener("click",t=>{t.target===e&&e.classList.remove("show")})}showFeedbackForm(){const e=document.getElementById("download-limiter-paywall");e&&e.classList.remove("show"),this.createFeedbackModal();const t=document.getElementById("download-limiter-feedback");t&&t.classList.add("show")}createFeedbackModal(){if(document.getElementById("download-limiter-feedback"))return void(this.config.options?.debug&&console.log("🔍 DEBUG: Feedback modal already exists"));const e=this.config.feedback||(this.config.email?{form:{title:"Quick Feedback",description:"Why didn't you upgrade?",option1:"Not useful for my needs",option2:"Didn't find what I was looking for",option3:"Just trying it out"},email:this.config.email}:null);if(this.config.options?.debug&&(console.log("🔍 DEBUG: Feedback config:",e),console.log("🔍 DEBUG: this.config.feedback:",this.config.feedback),console.log("🔍 DEBUG: this.config.email:",this.config.email)),!e)return void(this.config.options?.debug&&console.log("🔍 DEBUG: No feedback config found, not creating modal"));const t=document.createElement("div");t.id="download-limiter-feedback",t.className="download-limiter-modal",t.innerHTML=`\n <div class="download-limiter-content">\n <h3>${e.form.title}</h3>\n <p style="margin-bottom: 20px;">${e.form.description}</p>\n\n <form id="feedback-form" style="text-align: left;">\n <div style="margin-bottom: 15px;">\n <label style="display: block; margin-bottom: 8px;">\n <input type="radio" name="reason" value="option1" style="margin-right: 8px;">\n ${e.form.option1}\n </label>\n <label style="display: block; margin-bottom: 8px;">\n <input type="radio" name="reason" value="option2" style="margin-right: 8px;">\n ${e.form.option2}\n </label>\n <label style="display: block; margin-bottom: 8px;">\n <input type="radio" name="reason" value="option3" style="margin-right: 8px;">\n ${e.form.option3}\n </label>\n </div>\n\n <div style="margin-bottom: 15px;">\n <label for="feedback-details" style="display: block; margin-bottom: 5px;">Tell us more:</label>\n <textarea\n id="feedback-details"\n name="details"\n rows="3"\n style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;"\n placeholder="Your feedback helps us improve..." maxlength="200"></textarea>\n </div>\n\n <div style="margin-bottom: 20px;">\n <label for="feedback-email" style="display: block; margin-bottom: 5px;">\n Email (optional):\n </label>\n <input\n type="email"\n id="feedback-email"\n name="email"\n style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px;"\n placeholder="your@email.com">\n <small style="color: #666; display: block; margin-top: 4px;">\n Only if you want us to reach out about what you mentioned above. We don't follow up unless you want us to\n </small>\n </div>\n\n \n <div style="text-align: center;">\n <button type="submit" class="download-limiter-btn success-btn" style="margin-right: 10px;">\n Submit Feedback\n </button>\n <button type="button" id="feedback-skip-btn" class="download-limiter-btn cancel-btn">\n Skip\n </button>\n </div>\n </form>\n </div>\n `,document.body.appendChild(t),this.config.options?.debug&&console.log("🔍 DEBUG: Feedback modal created and added to DOM");const n=t.querySelector("#feedback-form");n.addEventListener("submit",e=>{e.preventDefault(),this.submitFeedback(n)}),t.querySelector("#feedback-skip-btn").addEventListener("click",()=>{t.classList.remove("show")}),t.addEventListener("click",e=>{e.target===t&&t.classList.remove("show")})}async submitFeedback(e){const t=new FormData(e),n=t.get("reason"),r=t.get("details"),i=t.get("email");if(!n)return void alert("Please select a reason");const s={reason:n,details:r,email:i||void 0,timestamp:(new Date).toISOString(),userAgent:navigator.userAgent,appId:this.config.appId};try{await this.sendFeedbackEmail(s);const e=document.getElementById("download-limiter-feedback");e&&e.classList.remove("show"),alert("Thank you for your feedback!")}catch(e){console.error("Failed to send feedback:",e),alert("Failed to send feedback. Please try again.")}}async sendFeedbackEmail(e){let t;if(this.config.feedback?.email?t=Array.isArray(this.config.feedback.email)?this.config.feedback.email[0]:this.config.feedback.email:this.config.email&&(t={provider:"resend",apiKey:this.config.email.resendApiKey,fromEmail:this.config.email.fromEmail}),!t)throw new Error("Email configuration not available");const n=`\nNew Feedback from ${this.config.appId}\n\nReason: ${e.reason}\nDetails: ${e.details}\nUser Email: ${e.email||"Not provided"}\nTimestamp: ${e.timestamp}\nUser Agent: ${e.userAgent}\n `.trim();let r;if("resend"!==t.provider&&t.provider)throw new Error(`Unsupported email provider: ${t.provider}`);if(r=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.apiKey||t.resendApiKey}`},body:JSON.stringify({from:t.fromEmail,to:[t.fromEmail],subject:`Feedback from ${this.config.appId}`,text:n})}),!r.ok)throw new Error(`Email API error: ${r.status}`)}createAuthUI(){if(document.getElementById("lead-fast-profile"))return;const e=document.createElement("div");e.id="lead-fast-profile",e.className="lead-fast-profile",document.body.appendChild(e)}createStatusDisplay(){if(document.getElementById("download-limiter-status"))return;const e=document.createElement("div");e.id="download-limiter-status",e.className="download-limiter-status",document.body.appendChild(e)}createGlobalStatusDisplay(){this.createStatusDisplay()}showPaywallInstant(e){this.createPaywallModal();const t=document.getElementById("download-limiter-paywall");if(t){const n=t.querySelector("#download-limiter-paywall-title");n&&(n.textContent=`You've used ${e.limit} free attempts`);const r=t.querySelector("#download-limiter-auth-section"),i=t.querySelector("#download-limiter-payment-section");if(this.currentUser)r.style.display="none",i.style.display="block";else{const e=t.querySelector("#download-limiter-paywall-subtitle");e&&(e.textContent="Sign in to continue. If you're already premium, you'll get unlimited access. New users can upgrade after signing in."),r.style.display="none",i.style.display="none",this.showSingleUpgradeFlow(t)}t.classList.add("show")}}async showPaywall(){const e=await this.getDownloadStatus();this.showPaywallInstant(e)}showSingleUpgradeFlow(e){let t=e.querySelector(".single-upgrade-container");if(!t){t=document.createElement("div"),t.className="single-upgrade-container",t.innerHTML='\n <div class="single-upgrade-content">\n <button class="download-limiter-btn upgrade-btn" id="single-upgrade-btn">\n Continue with Google\n </button>\n \x3c!--<p class="upgrade-description">\n Sign in to restore access. Premium members get unlimited usage immediately.\n </p>--\x3e\n </div>\n ';const n=e.querySelector(".download-limiter-cancel-container");n?e.querySelector(".download-limiter-content")?.insertBefore(t,n):e.querySelector(".download-limiter-content")?.appendChild(t)}t.style.display="block";const n=e.querySelector("#single-upgrade-btn");if(n){n.replaceWith(n.cloneNode(!0));const t=e.querySelector("#single-upgrade-btn");t?.addEventListener("click",async()=>{try{const{error:e}=await this.supabase.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}${window.location.pathname}?upgrade=true`}});e&&(console.error("Sign in error:",e),this.showError("Sign In Failed","Failed to sign in with Google. Please try again."))}catch(e){console.error("Upgrade flow error:",e),this.showError("Upgrade Failed","Failed to start upgrade process. Please try again.")}})}}showSuccess(e,t){const n=document.getElementById("download-limiter-success");if(n){const r=n.querySelector("#download-limiter-success-title"),i=n.querySelector("#download-limiter-success-message");r&&(r.textContent=e),i&&(i.textContent=t),n.classList.add("show")}}showError(e,t){const n=document.createElement("div");n.style.cssText="\n position: fixed;\n top: 20px;\n right: 20px;\n background: #fee2e2;\n border: 1px solid #fecaca;\n color: #dc2626;\n padding: 12px 16px;\n border-radius: 8px;\n font-size: 14px;\n font-weight: 500;\n line-height: 1.4;\n max-width: 300px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);\n z-index: 10000;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n ",n.innerHTML=`\n <div style="font-weight: 600; margin-bottom: 4px;">${e}</div>\n <div style="font-size: 13px; opacity: 0.9;">${t}</div>\n `,document.body.appendChild(n),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n)},5e3),n.addEventListener("click",()=>{n.parentNode&&n.parentNode.removeChild(n)})}showConnectionError(){this.showError("Connection Error","Server connection required for download verification. Please check your configuration and try again.")}showPaymentConfigError(){this.showError("Payment Configuration Error","Payment system is not properly configured. Please contact support.")}disableDownloadButtons(e){const t=document.querySelectorAll("[data-leadfast-attached]"),n={connection:"Download disabled: Server connection required",payment:"Download disabled: Payment configuration error",security_key:"Download disabled: Invalid or missing security key"},r={connection:"⚠️ Connection Error - Downloads Disabled",payment:"⚠️ Payment Config Error - Downloads Disabled",security_key:"🔐 Invalid Security Key - Please Update Configuration"};t.forEach(t=>{const r=t;r.disabled=!0,r.style.opacity="0.5",r.style.cursor="not-allowed",r.title=n[e]});const i=document.querySelector(".lead-fast-user-section");i&&(i.innerHTML=`\n <div style="\n color: #ef4444;\n padding: 6px 8px;\n font-size: 12px;\n font-weight: 500;\n line-height: 1.2;\n border-radius: 4px;\n background: rgba(239, 68, 68, 0.05);\n border: 1px solid rgba(239, 68, 68, 0.2);\n max-width: 200px;\n text-align: center;\n ">\n ${r[e]}\n </div>\n `)}async updateStatusDisplays(){if(this.securityKeyFailed)return void this.disableDownloadButtons("security_key");if(this.supabaseConnectionFailed)return void this.disableDownloadButtons("connection");if(this.config.payment&&this.paymentConnectionFailed)return void this.disableDownloadButtons("payment");this.isLoadingStatus=!0,this.updateUserSection(null);const e=await this.getDownloadStatus();this.isLoadingStatus=!1,this.securityKeyFailed?this.disableDownloadButtons("security_key"):this.supabaseConnectionFailed?this.disableDownloadButtons("connection"):this.updateUserSection(e)}createTitleBar(){let e=document.getElementById("lead-fast-profile");e||(e=document.createElement("div"),e.id="lead-fast-profile",e.className="lead-fast-profile",document.body.appendChild(e));const t=this.config.titleBar||{},n=t.title||"My App",r=t.titleImage,i=t.links||[];e.innerHTML=`\n <div class="lead-fast-title-bar">\n <div class="lead-fast-title-section">\n <a href="#" class="lead-fast-logo">\n ${r?`<img src="${r}" alt="${n}">`:""}\n <span>${n}</span>\n </a>\n <nav class="lead-fast-nav">\n ${i.map(e=>`\n <a href="${e.url}" class="lead-fast-nav-link" ${e.target?`target="${e.target}"`:""}>\n ${e.text}\n </a>\n `).join("")}\n </nav>\n </div>\n\n <div class="lead-fast-user-section" id="lead-fast-user-section">\n \x3c!-- User section will be populated when logged in --\x3e\n </div>\n\n \x3c!-- <a href="https://www.moneyfast.bar" target="_blank" class="lead-fast-branding" style="text-decoration: none; color: inherit;">moneyfast.bar</a>--\x3e\n </div>\n `}updateUserSection(e){const t=document.getElementById("lead-fast-user-section");if(t)if(null===e||this.isLoadingStatus)t.innerHTML='\n <div class="lead-fast-loading-status">\n <svg class="lead-fast-spinner" viewBox="0 0 24 24">\n <circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="3" fill="none" stroke-dasharray="31.4 31.4" stroke-linecap="round">\n <animateTransform attributeName="transform" type="rotate" from="0 12 12" to="360 12 12" dur="1s" repeatCount="indefinite"/>\n </circle>\n </svg>\n <span class="lead-fast-loading-text">Loading...</span>\n </div>\n ';else if(this.currentUser){const n=this.currentUser.email.charAt(0).toUpperCase(),r=this.currentUser.email,i=e.isPremium?"premium":"free",s=e.isPremium?"Premium":"Free",a=e.isPremium?"Unlimited":`${e.currentCount}/${e.limit}`;t.innerHTML=`\n <div class="lead-fast-avatar">${n}</div>\n <div class="lead-fast-user-info">\n <div class="lead-fast-user-email">${r}</div>\n <div class="lead-fast-user-status">\n <span class="lead-fast-badge ${i}">${s}</span>\n <span class="lead-fast-count">${a}</span>\n </div>\n </div>\n <button class="lead-fast-signout">signout</button>\n `;const o=document.querySelector(".lead-fast-title-bar");o&&getComputedStyle(o);const c=t.querySelector(".lead-fast-signout");c&&c.addEventListener("click",()=>{this.signOut()})}else{const n=`Attempts: ${e.currentCount}/${e.limit}`;t.innerHTML=`\n <div class="lead-fast-anonymous-status">\n <span class="lead-fast-count">${n}</span>\n </div>\n `}}setupUIUpdates(){this.on("authChanged",async()=>{this.cachedStatus=null,this.updateStatusDisplays();const e=document.getElementById("download-limiter-paywall");e&&e.classList.contains("show")&&(this.updatePaywallDisplay(),this.currentUser&&this.config.payment&&setTimeout(async()=>{if(await this.checkPremiumStatus(this.currentUser.email))e.classList.remove("show");else{const e=await this.createPayment();e?.checkout_url&&(window.location.href=e.checkout_url)}},1e3))}),this.on("countChanged",()=>{this.updateStatusDisplays()}),this.updateStatusDisplays()}updatePaywallDisplay(){const e=document.getElementById("download-limiter-paywall");if(!e)return;const t=e.querySelector("#download-limiter-auth-section"),n=e.querySelector("#download-limiter-payment-section");this.currentUser?(t.style.display="none",n.style.display="block"):(t.style.display="block",n.style.display="none")}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,[]),this.eventListeners.get(e).push(t)}off(e,t){const n=this.eventListeners.get(e);if(n){const e=n.indexOf(t);e>-1&&n.splice(e,1)}}emit(e,t){const n=this.eventListeners.get(e);n&&n.forEach(n=>{try{n(t)}catch(t){console.error(`Error in ${e} listener:`,t)}})}validateConfig(){if(!this.config.appId)throw new Error("appId is required");if(!this.config.supabase?.url)throw new Error("supabase.url is required");if(!this.config.supabase?.anonKey)throw new Error("supabase.anonKey is required");if("number"!=typeof this.config.freeAttemptLimit||this.config.freeAttemptLimit<0)throw new Error("freeAttemptLimit must be a non-negative number")}async initializeSupabase(){try{this.supabase=(e=this.config.supabase.url,t=this.config.supabase.anonKey,new qr(e,t,n)),this.supabaseConnectionFailed=!1}catch(e){console.error("Failed to initialize Supabase:",e),this.supabaseConnectionFailed=!0}var e,t,n}async initializePayment(){if(!this.config.payment)return;const e=this.config.payment?.find(e=>"dodo"===e.provider);if(!e)return this.paymentConnectionFailed=!0,void(this.config.options?.debug&&console.warn("No dodo payment provider configured"));const t=e.productId;if(!t||!t.startsWith("pdt_")||t.length<10)return this.paymentConnectionFailed=!0,void(this.config.options?.debug&&console.warn("Invalid payment product ID format:",t));this.paymentConnectionFailed=!1}async initializeFingerprint(){try{this.userFingerprint=await this.generateFingerprint()}catch(e){this.userFingerprint=crypto.randomUUID?crypto.randomUUID():String(Date.now()),this.config.options?.debug&&console.warn("Fingerprint generation failed, using fallback:",e)}}async generateFingerprint(){const e=`${navigator.userAgent||""}||${Intl.DateTimeFormat().resolvedOptions().timeZone||""}||${`${screen.width}x${screen.height}`}||${navigator.language||""}`,t=(new TextEncoder).encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join("")}async setupAuthListener(){this.supabase.auth.onAuthStateChange(async(e,t)=>{const n=this.currentUser;this.currentUser=t?.user||null;let r=!1;if(this.currentUser){const e=!n||n.email!==this.currentUser.email,t=!this.cachedPremiumStatus||Date.now()-this.premiumStatusCacheTime>this.STATUS_CACHE_DURATION;e||t?(r=await this.checkPremiumStatus(this.currentUser.email),this.cachedPremiumStatus=r,this.premiumStatusCacheTime=Date.now()):(r=this.cachedPremiumStatus,console.log(`🔍 [CACHE] Using cached premium status from auth listener: ${r}`))}else this.cachedPremiumStatus=null,this.premiumStatusCacheTime=0;const i="true"===new URLSearchParams(window.location.search).get("upgrade");if("SIGNED_IN"===e&&!n&&this.currentUser&&this.config.payment&&i)if(r){window.history.replaceState({},document.title,window.location.pathname);const e=document.getElementById("download-limiter-paywall");e&&e.classList.remove("show")}else{const e=await this.createPayment();e?.checkout_url&&(window.history.replaceState({},document.title,window.location.pathname),window.location.href=e.checkout_url)}this.emit("authChanged",{user:this.currentUser,isPremium:r})});const{data:{user:e}}=await this.supabase.auth.getUser();this.currentUser=e}async getDownloadCount(){if(!this.userFingerprint)return 0;try{const e=await fetch(`${this.config.supabase.url}/functions/v1/check-download-limit`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.supabase.anonKey}`},body:JSON.stringify({fingerprint:this.userFingerprint,security_key:this.config.security_key,action:"check"})});if(e.ok){const t=await e.json();return this.supabaseConnectionFailed=!1,t.current_count||0}if(401===e.status||403===e.status)try{const t=await e.json(),n=t.error||t.message||"Authentication failed";n.toLowerCase().includes("security key")?(console.error(`❌ Security Key Validation Failed [check-download-limit]: ${n}`),console.error("💡 Backend Function: check-download-limit"),console.error("💡 Please check your security_key in the MoneyBar configuration"),this.securityKeyFailed=!0,this.supabaseConnectionFailed=!0):(console.warn(`Supabase authentication failed [check-download-limit]: ${e.status} - ${n}`),this.supabaseConnectionFailed=!0)}catch(t){console.warn(`Supabase authentication failed: ${e.status} - Unable to parse error`),this.supabaseConnectionFailed=!0}}catch(e){this.supabaseConnectionFailed=!0,this.config.options?.debug&&console.warn("Failed to get server usage count, connection failed:",e)}return 0}async incrementDownloadCount(){if(!this.userFingerprint)return 0;const e={fingerprint:this.userFingerprint,security_key:this.config.security_key,action:"increment"};try{const t=await fetch(`${this.config.supabase.url}/functions/v1/check-download-limit`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.supabase.anonKey}`},body:JSON.stringify(e)});if(this.config.options?.debug&&!t.ok){const e=await t.text();console.error("🔍 DEBUG: Error response:",e)}if(t.ok){const e=await t.json();return this.supabaseConnectionFailed=!1,e.new_count||0}if(401===t.status||403===t.status)try{const e=await t.json(),n=e.error||e.message||"Authentication failed";n.toLowerCase().includes("security key")?(console.error(`❌ Security Key Validation Failed [check-download-limit]: ${n}`),console.error("💡 Backend Function: check-download-limit"),console.error("💡 Please check your security_key in the MoneyBar configuration"),this.securityKeyFailed=!0,this.supabaseConnectionFailed=!0):(console.warn(`Supabase authentication failed [check-download-limit]: ${t.status} - ${n}`),this.supabaseConnectionFailed=!0)}catch(e){console.warn(`Supabase authentication failed: ${t.status} - Unable to parse error`),this.supabaseConnectionFailed=!0}}catch(e){this.supabaseConnectionFailed=!0,this.config.options?.debug&&console.warn("Failed to increment server count, connection failed:",e)}return 0}async checkPremiumStatus(e){try{const t=await fetch(`${this.config.supabase.url}/functions/v1/check-payment-status`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.supabase.anonKey}`},body:JSON.stringify({email:e,app_id:this.config.appId})});if(t.ok){return"completed"===(await t.json()).status}}catch(e){this.config.options?.debug&&console.warn("Failed to check premium status:",e)}return!1}getLocalDownloadCount(){const e=`download_count_${this.config.appId}`,t=parseInt(localStorage.getItem(e)||"0",10);return isNaN(t)?0:t}incrementLocalDownloadCount(){const e=`download_count_${this.config.appId}`,t=this.getLocalDownloadCount()+1;return localStorage.setItem(e,String(t)),t}handleError(e){this.config.options?.debug&&console.error("Lead Fast Error:",e),this.config.callbacks?.onError?this.config.callbacks.onError(e):console.error("Lead Fast:",e.message),this.emit("error",e)}async checkPaymentStatus(){"success"===new URLSearchParams(window.location.search).get("payment")&&setTimeout(async()=>{if(this.currentUser){await this.checkPremiumStatus(this.currentUser.email)?this.showSuccess("Payment Successful!","Welcome to premium! You now have unlimited usage."):this.showSuccess("Processing Payment","Payment is being processed. Please refresh in a few moments.")}else this.showSuccess("Processing Payment","Please wait while we verify your payment...");const e=window.location.href.split("?")[0];window.history.replaceState({},document.title,e)},2e3)}}export{Fr as MoneyBar};
2
2
  //# sourceMappingURL=index.bundle.js.map