conformtools 0.6.22 → 0.6.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-hook-setup-ZY4UBZIG.js → agent-hook-setup-IACTYSVL.js} +1 -1
- package/dist/{bridge-56MINHUF.js → bridge-6XEVB67I.js} +1 -1
- package/dist/browser/timeline_core_bg.wasm +0 -0
- package/dist/{chunk-OVBFJOO2.js → chunk-3AR7KSPH.js} +1 -1
- package/dist/{chunk-64AMZWOI.js → chunk-3LGFQ42R.js} +1 -1
- package/dist/{chunk-REGL3GQB.js → chunk-5JDF2IUF.js} +1 -1
- package/dist/{chunk-Z3LQ56WS.js → chunk-5VQ2IHWO.js} +1 -1
- package/dist/{chunk-JUJESM4P.js → chunk-6U2DUMIM.js} +1 -1
- package/dist/{chunk-QNVFSA7C.js → chunk-BHBBS26Z.js} +1 -1
- package/dist/{chunk-4I4MV3DE.js → chunk-DCO5D65W.js} +1 -1
- package/dist/{chunk-65SLDY2M.js → chunk-DESBZZGR.js} +92 -92
- package/dist/{chunk-JGI5YEGH.js → chunk-EZYCCYY7.js} +1 -1
- package/dist/{chunk-DHDSDH6R.js → chunk-GN5T5S6K.js} +2 -2
- package/dist/chunk-IDADYIY6.js +7 -0
- package/dist/{chunk-BFN565RJ.js → chunk-ISG6PEOD.js} +1 -1
- package/dist/{chunk-6C3EEZH3.js → chunk-KDNIWB5V.js} +1 -1
- package/dist/{chunk-M3DXHHD7.js → chunk-LBROV5JN.js} +1 -1
- package/dist/{chunk-REBF4U5B.js → chunk-NQDVV2PX.js} +1 -1
- package/dist/{chunk-FSXF4K3J.js → chunk-Q72JSDNU.js} +1 -1
- package/dist/{chunk-PKKUIGZ5.js → chunk-V6MI7VE3.js} +1 -1
- package/dist/{chunk-ZCQTIYXB.js → chunk-XIFURVIB.js} +1 -1
- package/dist/{chunk-TFKKODSA.js → chunk-XX7QQIBI.js} +1 -1
- package/dist/{chunk-CHEQJC4U.js → chunk-ZEVOSOP4.js} +187 -186
- package/dist/{chunk-O5HYVCFL.js → chunk-ZNUIZEPF.js} +1 -1
- package/dist/cli.js +2 -2
- package/dist/{cr3-wasm-HWPQ3QAN.js → cr3-wasm-CQ5YEFUF.js} +1 -1
- package/dist/{demo-engine-MOHHYVGV.js → demo-engine-O5T6QRYL.js} +1 -1
- package/dist/{dng-wasm-D7HO2OUE.js → dng-wasm-K6PWOV4P.js} +1 -1
- package/dist/{dpx-wasm-ASRFRLRT.js → dpx-wasm-RJZANW6N.js} +1 -1
- package/dist/{engine-WMOJ3HRU.js → engine-WEGECPAH.js} +2 -2
- package/dist/{exr-wasm-Y53DGEKJ.js → exr-wasm-EZY3GZ2L.js} +1 -1
- package/dist/{framing-JYGNU6TH.js → framing-V3AI35RV.js} +1 -1
- package/dist/gfx-worker.js +1 -1
- package/dist/{h264-ZJCLCYYY.js → h264-KMDAFD3Q.js} +1 -1
- package/dist/{h264-mxf-BI4ACQUH.js → h264-mxf-IJYHBYKB.js} +1 -1
- package/dist/hook.js +3 -3
- package/dist/{host-relink-XMVOQYKN.js → host-relink-IDTSHA4V.js} +1 -1
- package/dist/hosts-5VFREDGW.js +3 -0
- package/dist/http.js +2 -2
- package/dist/{inspect-4RF2SDJR.js → inspect-VS5N6SKX.js} +15 -15
- package/dist/isobmff-4FUKPUL3.js +3 -0
- package/dist/{mc-video-IUPFHPIS.js → mc-video-DTMHUECT.js} +1 -1
- package/dist/mcp.js +1 -1
- package/dist/{media-R677IADY.js → media-3XXQBZNW.js} +1 -1
- package/dist/{mxf-IUCZVILV.js → mxf-LGRSWF7S.js} +1 -1
- package/dist/{ops-L5X3Q6SQ.js → ops-QAML7C35.js} +1 -1
- package/dist/{r3d-EIQEVYGC.js → r3d-AWQQHTQC.js} +1 -1
- package/dist/{r3d-VBXKIIRY.js → r3d-OL6DVR3C.js} +1 -1
- package/dist/{still-XAFHXXC3.js → still-CDF26BQZ.js} +1 -1
- package/dist/{still-wasm-ZG6PA67L.js → still-wasm-3EBYMLVL.js} +1 -1
- package/dist/{tiff-wasm-AHQJJAK2.js → tiff-wasm-JIBA5AI4.js} +1 -1
- package/dist/{timeline-LJYGRP3R.js → timeline-BAMMSL7B.js} +1 -1
- package/dist/wasm/media_core_bg.wasm +0 -0
- package/dist/{wav-4COVRAK3.js → wav-N6EWJR2P.js} +1 -1
- package/package.json +5 -5
- package/dist/chunk-QPSQQEO6.js +0 -7
- package/dist/hosts-ZPBLYFYP.js +0 -3
- package/dist/isobmff-FZBZCEYH.js +0 -3
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
|
|
3
|
-
import{a as ri}from"./chunk-OVBFJOO2.js";import"./chunk-IN6XVTUS.js";import"./chunk-3PVQ5QP4.js";import"./chunk-VFXMP7IF.js";import"./chunk-BBCQMZQN.js";import"./chunk-REGL3GQB.js";import{a as Vr,b as Zs,d as ei,g as ti}from"./chunk-NHWWMLZW.js";import"./chunk-C2ESM27Z.js";import{b as Ru,c as $,d as Qs,e as k,f as ze,g as Se}from"./chunk-PSANHDZM.js";var _e={};Qs(_e,{__addDisposableResource:()=>Ci,__assign:()=>Ft,__asyncDelegator:()=>bi,__asyncGenerator:()=>wi,__asyncValues:()=>Ei,__await:()=>Ge,__awaiter:()=>pi,__classPrivateFieldGet:()=>Ri,__classPrivateFieldIn:()=>Oi,__classPrivateFieldSet:()=>ki,__createBinding:()=>qt,__decorate:()=>ai,__disposeResources:()=>Pi,__esDecorate:()=>li,__exportStar:()=>_i,__extends:()=>ii,__generator:()=>mi,__importDefault:()=>Ai,__importStar:()=>Ti,__makeTemplateObject:()=>Si,__metadata:()=>fi,__param:()=>ui,__propKey:()=>di,__read:()=>Gr,__rest:()=>oi,__rewriteRelativeImportExtension:()=>Ii,__runInitializers:()=>ci,__setFunctionName:()=>hi,__spread:()=>gi,__spreadArray:()=>vi,__spreadArrays:()=>yi,__values:()=>Bt,default:()=>Iu});function ii(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Kr(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function oi(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r}function ai(t,e,r,n){var s=arguments.length,i=s<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,r,i):o(e,r))||i);return s>3&&i&&Object.defineProperty(e,r,i),i}function ui(t,e){return function(r,n){e(r,n,t)}}function li(t,e,r,n,s,i){function o(T){if(T!==void 0&&typeof T!="function")throw new TypeError("Function expected");return T}for(var a=n.kind,l=a==="getter"?"get":a==="setter"?"set":"value",c=!e&&t?n.static?t:t.prototype:null,h=e||(c?Object.getOwnPropertyDescriptor(c,n.name):{}),m,_=!1,f=r.length-1;f>=0;f--){var y={};for(var v in n)y[v]=v==="access"?{}:n[v];for(var v in n.access)y.access[v]=n.access[v];y.addInitializer=function(T){if(_)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(T||null))};var w=(0,r[f])(a==="accessor"?{get:h.get,set:h.set}:h[l],y);if(a==="accessor"){if(w===void 0)continue;if(w===null||typeof w!="object")throw new TypeError("Object expected");(m=o(w.get))&&(h.get=m),(m=o(w.set))&&(h.set=m),(m=o(w.init))&&s.unshift(m)}else(m=o(w))&&(a==="field"?s.unshift(m):h[l]=m)}c&&Object.defineProperty(c,n.name,h),_=!0}function ci(t,e,r){for(var n=arguments.length>2,s=0;s<e.length;s++)r=n?e[s].call(t,r):e[s].call(t);return n?r:void 0}function di(t){return typeof t=="symbol"?t:"".concat(t)}function hi(t,e,r){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:r?"".concat(r," ",e):e})}function fi(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function pi(t,e,r,n){function s(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function a(h){try{c(n.next(h))}catch(m){o(m)}}function l(h){try{c(n.throw(h))}catch(m){o(m)}}function c(h){h.done?i(h.value):s(h.value).then(a,l)}c((n=n.apply(t,e||[])).next())})}function mi(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,s,i,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(h){return l([c,h])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(r=0)),r;)try{if(n=1,s&&(i=c[0]&2?s.return:c[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,c[1])).done)return i;switch(s=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,s=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){r.label=c[1];break}if(c[0]===6&&r.label<i[1]){r.label=i[1],i=c;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(c);break}i[2]&&r.ops.pop(),r.trys.pop();continue}c=e.call(t,r)}catch(h){c=[6,h],s=0}finally{n=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function _i(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&qt(e,t,r)}function Bt(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Gr(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)i.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return i}function gi(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Gr(arguments[e]));return t}function yi(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),s=0,e=0;e<r;e++)for(var i=arguments[e],o=0,a=i.length;o<a;o++,s++)n[s]=i[o];return n}function vi(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,i;n<s;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))}function Ge(t){return this instanceof Ge?(this.v=t,this):new Ge(t)}function wi(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),s,i=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),s[Symbol.asyncIterator]=function(){return this},s;function o(f){return function(y){return Promise.resolve(y).then(f,m)}}function a(f,y){n[f]&&(s[f]=function(v){return new Promise(function(w,T){i.push([f,v,w,T])>1||l(f,v)})},y&&(s[f]=y(s[f])))}function l(f,y){try{c(n[f](y))}catch(v){_(i[0][3],v)}}function c(f){f.value instanceof Ge?Promise.resolve(f.value.v).then(h,m):_(i[0][2],f)}function h(f){l("next",f)}function m(f){l("throw",f)}function _(f,y){f(y),i.shift(),i.length&&l(i[0][0],i[0][1])}}function bi(t){var e,r;return e={},n("next"),n("throw",function(s){throw s}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(s,i){e[s]=t[s]?function(o){return(r=!r)?{value:Ge(t[s](o)),done:!1}:i?i(o):o}:i}}function Ei(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Bt=="function"?Bt(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(i){r[i]=t[i]&&function(o){return new Promise(function(a,l){o=t[i](o),s(a,l,o.done,o.value)})}}function s(i,o,a,l){Promise.resolve(l).then(function(c){i({value:c,done:a})},o)}}function Si(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function Ti(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r=zr(t),n=0;n<r.length;n++)r[n]!=="default"&&qt(e,t,r[n]);return Cu(e,t),e}function Ai(t){return t&&t.__esModule?t:{default:t}}function Ri(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}function ki(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r}function Oi(t,e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof t=="function"?e===t:t.has(e)}function Ci(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],r&&(s=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(i){return Promise.reject(i)}}),t.stack.push({value:e,dispose:n,async:r})}else r&&t.stack.push({async:!0});return e}function Pi(t){function e(i){t.error=t.hasError?new Pu(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,n=0;function s(){for(;r=t.stack.pop();)try{if(!r.async&&n===1)return n=0,t.stack.push(r),Promise.resolve().then(s);if(r.dispose){var i=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(i).then(s,function(o){return e(o),s()})}else n|=1}catch(o){e(o)}if(n===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return s()}function Ii(t,e){return typeof t=="string"&&/^\.\.?\//.test(t)?t.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(r,n,s,i,o){return n?e?".jsx":".js":s&&(!i||!o)?r:s+i+"."+o.toLowerCase()+"js"}):t}var Kr,Ft,qt,Cu,zr,Pu,Iu,ge=Ru(()=>{Kr=function(t,e){return Kr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[s]=n[s])},Kr(t,e)};Ft=function(){return Ft=Object.assign||function(e){for(var r,n=1,s=arguments.length;n<s;n++){r=arguments[n];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},Ft.apply(this,arguments)};qt=Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]});Cu=Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e},zr=function(t){return zr=Object.getOwnPropertyNames||function(e){var r=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[r.length]=n);return r},zr(t)};Pu=typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var n=new Error(r);return n.name="SuppressedError",n.error=t,n.suppressed=e,n};Iu={__extends:ii,__assign:Ft,__rest:oi,__decorate:ai,__param:ui,__esDecorate:li,__runInitializers:ci,__propKey:di,__setFunctionName:hi,__metadata:fi,__awaiter:pi,__generator:mi,__createBinding:qt,__exportStar:_i,__values:Bt,__read:Gr,__spread:gi,__spreadArrays:yi,__spreadArray:vi,__await:Ge,__asyncGenerator:wi,__asyncDelegator:bi,__asyncValues:Ei,__makeTemplateObject:Si,__importStar:Ti,__importDefault:Ai,__classPrivateFieldGet:Ri,__classPrivateFieldSet:ki,__classPrivateFieldIn:Oi,__addDisposableResource:Ci,__disposeResources:Pi,__rewriteRelativeImportExtension:Ii}});var xi=$(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.resolveFetch=void 0;var xu=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);Mt.resolveFetch=xu});var Qr=$(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.FunctionRegion=ye.FunctionsHttpError=ye.FunctionsRelayError=ye.FunctionsFetchError=ye.FunctionsError=void 0;var Je=class extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n}};ye.FunctionsError=Je;var Jr=class extends Je{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}};ye.FunctionsFetchError=Jr;var Yr=class extends Je{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}};ye.FunctionsRelayError=Yr;var Xr=class extends Je{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}};ye.FunctionsHttpError=Xr;var Ni;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(Ni||(ye.FunctionRegion=Ni={}))});var ji=$(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.FunctionsClient=void 0;var Nu=(ge(),Se(_e)),ju=xi(),Ye=Qr(),Zr=class{constructor(e,{headers:r={},customFetch:n,region:s=Ye.FunctionRegion.Any}={}){this.url=e,this.headers=r,this.region=s,this.fetch=(0,ju.resolveFetch)(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Nu.__awaiter(this,arguments,void 0,function*(r,n={}){var s;let i,o;try{let{headers:a,method:l,body:c,signal:h,timeout:m}=n,_={},{region:f}=n;f||(f=this.region);let y=new URL(`${this.url}/${r}`);f&&f!=="any"&&(_["x-region"]=f,y.searchParams.set("forceFunctionRegion",f));let v;c&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(_["Content-Type"]="application/octet-stream",v=c):typeof c=="string"?(_["Content-Type"]="text/plain",v=c):typeof FormData<"u"&&c instanceof FormData?v=c:(_["Content-Type"]="application/json",v=JSON.stringify(c)):c&&typeof c!="string"&&!(typeof Blob<"u"&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<"u"&&c instanceof FormData)?v=JSON.stringify(c):v=c;let w=h;m&&(o=new AbortController,i=setTimeout(()=>o.abort(),m),h?(w=o.signal,h.addEventListener("abort",()=>o.abort())):w=o.signal);let T=yield this.fetch(y.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},_),this.headers),a),body:v,signal:w}).catch(Z=>{throw new Ye.FunctionsFetchError(Z)}),O=T.headers.get("x-relay-error");if(O&&O==="true")throw new Ye.FunctionsRelayError(T);if(!T.ok)throw new Ye.FunctionsHttpError(T);let E=((s=T.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),x;return E==="application/json"?x=yield T.json():E==="application/octet-stream"||E==="application/pdf"?x=yield T.blob():E==="text/event-stream"?x=T:E==="multipart/form-data"?x=yield T.formData():x=yield T.text(),{data:x,error:null,response:T}}catch(a){return{data:null,error:a,response:a instanceof Ye.FunctionsHttpError||a instanceof Ye.FunctionsRelayError?a.context:void 0}}finally{i&&clearTimeout(i)}})}};Wt.FunctionsClient=Zr});var Li=$(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.FunctionRegion=fe.FunctionsRelayError=fe.FunctionsHttpError=fe.FunctionsFetchError=fe.FunctionsError=fe.FunctionsClient=void 0;var Lu=ji();Object.defineProperty(fe,"FunctionsClient",{enumerable:!0,get:function(){return Lu.FunctionsClient}});var lt=Qr();Object.defineProperty(fe,"FunctionsError",{enumerable:!0,get:function(){return lt.FunctionsError}});Object.defineProperty(fe,"FunctionsFetchError",{enumerable:!0,get:function(){return lt.FunctionsFetchError}});Object.defineProperty(fe,"FunctionsHttpError",{enumerable:!0,get:function(){return lt.FunctionsHttpError}});Object.defineProperty(fe,"FunctionsRelayError",{enumerable:!0,get:function(){return lt.FunctionsRelayError}});Object.defineProperty(fe,"FunctionRegion",{enumerable:!0,get:function(){return lt.FunctionRegion}})});var tn=$(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.WebSocketFactory=void 0;var Ht=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let r=globalThis.process;if(r){let n=r.versions;if(n&&n.node){let s=n.node,i=parseInt(s.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
3
|
+
import{a as ri}from"./chunk-3AR7KSPH.js";import"./chunk-IN6XVTUS.js";import"./chunk-3PVQ5QP4.js";import"./chunk-VFXMP7IF.js";import"./chunk-BBCQMZQN.js";import"./chunk-5JDF2IUF.js";import{a as Vr,b as Zs,d as ei,g as ti}from"./chunk-NHWWMLZW.js";import"./chunk-C2ESM27Z.js";import{b as Ou,c as $,d as Qs,e as k,f as ze,g as Se}from"./chunk-PSANHDZM.js";var _e={};Qs(_e,{__addDisposableResource:()=>Pi,__assign:()=>Bt,__asyncDelegator:()=>bi,__asyncGenerator:()=>wi,__asyncValues:()=>Ei,__await:()=>Ge,__awaiter:()=>pi,__classPrivateFieldGet:()=>Ri,__classPrivateFieldIn:()=>Oi,__classPrivateFieldSet:()=>ki,__createBinding:()=>Mt,__decorate:()=>ai,__disposeResources:()=>Ci,__esDecorate:()=>li,__exportStar:()=>_i,__extends:()=>ii,__generator:()=>mi,__importDefault:()=>Ai,__importStar:()=>Ti,__makeTemplateObject:()=>Si,__metadata:()=>fi,__param:()=>ui,__propKey:()=>di,__read:()=>Gr,__rest:()=>oi,__rewriteRelativeImportExtension:()=>Ii,__runInitializers:()=>ci,__setFunctionName:()=>hi,__spread:()=>gi,__spreadArray:()=>vi,__spreadArrays:()=>yi,__values:()=>qt,default:()=>Nu});function ii(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Kr(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function oi(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(r[n[s]]=t[n[s]]);return r}function ai(t,e,r,n){var s=arguments.length,i=s<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,r,i):o(e,r))||i);return s>3&&i&&Object.defineProperty(e,r,i),i}function ui(t,e){return function(r,n){e(r,n,t)}}function li(t,e,r,n,s,i){function o(T){if(T!==void 0&&typeof T!="function")throw new TypeError("Function expected");return T}for(var a=n.kind,l=a==="getter"?"get":a==="setter"?"set":"value",c=!e&&t?n.static?t:t.prototype:null,h=e||(c?Object.getOwnPropertyDescriptor(c,n.name):{}),m,_=!1,f=r.length-1;f>=0;f--){var y={};for(var v in n)y[v]=v==="access"?{}:n[v];for(var v in n.access)y.access[v]=n.access[v];y.addInitializer=function(T){if(_)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(T||null))};var w=(0,r[f])(a==="accessor"?{get:h.get,set:h.set}:h[l],y);if(a==="accessor"){if(w===void 0)continue;if(w===null||typeof w!="object")throw new TypeError("Object expected");(m=o(w.get))&&(h.get=m),(m=o(w.set))&&(h.set=m),(m=o(w.init))&&s.unshift(m)}else(m=o(w))&&(a==="field"?s.unshift(m):h[l]=m)}c&&Object.defineProperty(c,n.name,h),_=!0}function ci(t,e,r){for(var n=arguments.length>2,s=0;s<e.length;s++)r=n?e[s].call(t,r):e[s].call(t);return n?r:void 0}function di(t){return typeof t=="symbol"?t:"".concat(t)}function hi(t,e,r){return typeof e=="symbol"&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:r?"".concat(r," ",e):e})}function fi(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function pi(t,e,r,n){function s(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function a(h){try{c(n.next(h))}catch(m){o(m)}}function l(h){try{c(n.throw(h))}catch(m){o(m)}}function c(h){h.done?i(h.value):s(h.value).then(a,l)}c((n=n.apply(t,e||[])).next())})}function mi(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},n,s,i,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(h){return l([c,h])}}function l(c){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(r=0)),r;)try{if(n=1,s&&(i=c[0]&2?s.return:c[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,c[1])).done)return i;switch(s=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,s=c[1],c=[0];continue;case 7:c=r.ops.pop(),r.trys.pop();continue;default:if(i=r.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){r=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){r.label=c[1];break}if(c[0]===6&&r.label<i[1]){r.label=i[1],i=c;break}if(i&&r.label<i[2]){r.label=i[2],r.ops.push(c);break}i[2]&&r.ops.pop(),r.trys.pop();continue}c=e.call(t,r)}catch(h){c=[6,h],s=0}finally{n=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function _i(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Mt(e,t,r)}function qt(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Gr(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=n.next()).done;)i.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return i}function gi(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Gr(arguments[e]));return t}function yi(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),s=0,e=0;e<r;e++)for(var i=arguments[e],o=0,a=i.length;o<a;o++,s++)n[s]=i[o];return n}function vi(t,e,r){if(r||arguments.length===2)for(var n=0,s=e.length,i;n<s;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))}function Ge(t){return this instanceof Ge?(this.v=t,this):new Ge(t)}function wi(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),s,i=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),s[Symbol.asyncIterator]=function(){return this},s;function o(f){return function(y){return Promise.resolve(y).then(f,m)}}function a(f,y){n[f]&&(s[f]=function(v){return new Promise(function(w,T){i.push([f,v,w,T])>1||l(f,v)})},y&&(s[f]=y(s[f])))}function l(f,y){try{c(n[f](y))}catch(v){_(i[0][3],v)}}function c(f){f.value instanceof Ge?Promise.resolve(f.value.v).then(h,m):_(i[0][2],f)}function h(f){l("next",f)}function m(f){l("throw",f)}function _(f,y){f(y),i.shift(),i.length&&l(i[0][0],i[0][1])}}function bi(t){var e,r;return e={},n("next"),n("throw",function(s){throw s}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(s,i){e[s]=t[s]?function(o){return(r=!r)?{value:Ge(t[s](o)),done:!1}:i?i(o):o}:i}}function Ei(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof qt=="function"?qt(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(i){r[i]=t[i]&&function(o){return new Promise(function(a,l){o=t[i](o),s(a,l,o.done,o.value)})}}function s(i,o,a,l){Promise.resolve(l).then(function(c){i({value:c,done:a})},o)}}function Si(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function Ti(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r=zr(t),n=0;n<r.length;n++)r[n]!=="default"&&Mt(e,t,r[n]);return Iu(e,t),e}function Ai(t){return t&&t.__esModule?t:{default:t}}function Ri(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}function ki(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r}function Oi(t,e){if(e===null||typeof e!="object"&&typeof e!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof t=="function"?e===t:t.has(e)}function Pi(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var n,s;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=e[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=e[Symbol.dispose],r&&(s=n)}if(typeof n!="function")throw new TypeError("Object not disposable.");s&&(n=function(){try{s.call(this)}catch(i){return Promise.reject(i)}}),t.stack.push({value:e,dispose:n,async:r})}else r&&t.stack.push({async:!0});return e}function Ci(t){function e(i){t.error=t.hasError?new xu(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,n=0;function s(){for(;r=t.stack.pop();)try{if(!r.async&&n===1)return n=0,t.stack.push(r),Promise.resolve().then(s);if(r.dispose){var i=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(i).then(s,function(o){return e(o),s()})}else n|=1}catch(o){e(o)}if(n===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return s()}function Ii(t,e){return typeof t=="string"&&/^\.\.?\//.test(t)?t.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(r,n,s,i,o){return n?e?".jsx":".js":s&&(!i||!o)?r:s+i+"."+o.toLowerCase()+"js"}):t}var Kr,Bt,Mt,Iu,zr,xu,Nu,ge=Ou(()=>{Kr=function(t,e){return Kr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[s]=n[s])},Kr(t,e)};Bt=function(){return Bt=Object.assign||function(e){for(var r,n=1,s=arguments.length;n<s;n++){r=arguments[n];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},Bt.apply(this,arguments)};Mt=Object.create?(function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]});Iu=Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e},zr=function(t){return zr=Object.getOwnPropertyNames||function(e){var r=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[r.length]=n);return r},zr(t)};xu=typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var n=new Error(r);return n.name="SuppressedError",n.error=t,n.suppressed=e,n};Nu={__extends:ii,__assign:Bt,__rest:oi,__decorate:ai,__param:ui,__esDecorate:li,__runInitializers:ci,__propKey:di,__setFunctionName:hi,__metadata:fi,__awaiter:pi,__generator:mi,__createBinding:Mt,__exportStar:_i,__values:qt,__read:Gr,__spread:gi,__spreadArrays:yi,__spreadArray:vi,__await:Ge,__asyncGenerator:wi,__asyncDelegator:bi,__asyncValues:Ei,__makeTemplateObject:Si,__importStar:Ti,__importDefault:Ai,__classPrivateFieldGet:Ri,__classPrivateFieldSet:ki,__classPrivateFieldIn:Oi,__addDisposableResource:Pi,__disposeResources:Ci,__rewriteRelativeImportExtension:Ii}});var xi=$(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.resolveFetch=void 0;var ju=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);Wt.resolveFetch=ju});var Qr=$(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.FunctionRegion=ye.FunctionsHttpError=ye.FunctionsRelayError=ye.FunctionsFetchError=ye.FunctionsError=void 0;var Je=class extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n}};ye.FunctionsError=Je;var Jr=class extends Je{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}};ye.FunctionsFetchError=Jr;var Yr=class extends Je{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}};ye.FunctionsRelayError=Yr;var Xr=class extends Je{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}};ye.FunctionsHttpError=Xr;var Ni;(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2"})(Ni||(ye.FunctionRegion=Ni={}))});var ji=$(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.FunctionsClient=void 0;var Lu=(ge(),Se(_e)),Uu=xi(),Ye=Qr(),Zr=class{constructor(e,{headers:r={},customFetch:n,region:s=Ye.FunctionRegion.Any}={}){this.url=e,this.headers=r,this.region=s,this.fetch=(0,Uu.resolveFetch)(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Lu.__awaiter(this,arguments,void 0,function*(r,n={}){var s;let i,o;try{let{headers:a,method:l,body:c,signal:h,timeout:m}=n,_={},{region:f}=n;f||(f=this.region);let y=new URL(`${this.url}/${r}`);f&&f!=="any"&&(_["x-region"]=f,y.searchParams.set("forceFunctionRegion",f));let v;c&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(_["Content-Type"]="application/octet-stream",v=c):typeof c=="string"?(_["Content-Type"]="text/plain",v=c):typeof FormData<"u"&&c instanceof FormData?v=c:(_["Content-Type"]="application/json",v=JSON.stringify(c)):c&&typeof c!="string"&&!(typeof Blob<"u"&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<"u"&&c instanceof FormData)?v=JSON.stringify(c):v=c;let w=h;m&&(o=new AbortController,i=setTimeout(()=>o.abort(),m),h?(w=o.signal,h.addEventListener("abort",()=>o.abort())):w=o.signal);let T=yield this.fetch(y.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},_),this.headers),a),body:v,signal:w}).catch(Z=>{throw new Ye.FunctionsFetchError(Z)}),O=T.headers.get("x-relay-error");if(O&&O==="true")throw new Ye.FunctionsRelayError(T);if(!T.ok)throw new Ye.FunctionsHttpError(T);let E=((s=T.headers.get("Content-Type"))!==null&&s!==void 0?s:"text/plain").split(";")[0].trim(),x;return E==="application/json"?x=yield T.json():E==="application/octet-stream"||E==="application/pdf"?x=yield T.blob():E==="text/event-stream"?x=T:E==="multipart/form-data"?x=yield T.formData():x=yield T.text(),{data:x,error:null,response:T}}catch(a){return{data:null,error:a,response:a instanceof Ye.FunctionsHttpError||a instanceof Ye.FunctionsRelayError?a.context:void 0}}finally{i&&clearTimeout(i)}})}};Vt.FunctionsClient=Zr});var Li=$(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.FunctionRegion=fe.FunctionsRelayError=fe.FunctionsHttpError=fe.FunctionsFetchError=fe.FunctionsError=fe.FunctionsClient=void 0;var $u=ji();Object.defineProperty(fe,"FunctionsClient",{enumerable:!0,get:function(){return $u.FunctionsClient}});var lt=Qr();Object.defineProperty(fe,"FunctionsError",{enumerable:!0,get:function(){return lt.FunctionsError}});Object.defineProperty(fe,"FunctionsFetchError",{enumerable:!0,get:function(){return lt.FunctionsFetchError}});Object.defineProperty(fe,"FunctionsHttpError",{enumerable:!0,get:function(){return lt.FunctionsHttpError}});Object.defineProperty(fe,"FunctionsRelayError",{enumerable:!0,get:function(){return lt.FunctionsRelayError}});Object.defineProperty(fe,"FunctionRegion",{enumerable:!0,get:function(){return lt.FunctionRegion}})});var tn=$(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.WebSocketFactory=void 0;var Kt=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return{type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return{type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return{type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return{type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let r=globalThis.process;if(r){let n=r.versions;if(n&&n.node){let s=n.node,i=parseInt(s.replace(/^v/,"").split(".")[0]);return i>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${i} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${i} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
4
4
|
import ws from "ws"
|
|
5
5
|
new 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(){let e=this.detectEnvironment();if(e.constructor)return e.constructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=`
|
|
6
6
|
|
|
7
|
-
Suggested solution: ${e.workaround}`),new Error(r)}static createWebSocket(e,r){let n=this.getWebSocketConstructor();return new n(e,r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}};dt.WebSocketFactory=Ht;dt.default=Ht});var Bi=$(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.version=void 0;Kt.version="2.97.0"});var zt=$(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.CONNECTION_STATE=H.TRANSPORTS=H.CHANNEL_EVENTS=H.CHANNEL_STATES=H.SOCKET_STATES=H.MAX_PUSH_BUFFER_SIZE=H.WS_CLOSE_NORMAL=H.DEFAULT_TIMEOUT=H.VERSION=H.DEFAULT_VSN=H.VSN_2_0_0=H.VSN_1_0_0=H.DEFAULT_VERSION=void 0;var Ki=Bi();H.DEFAULT_VERSION=`realtime-js/${Ki.version}`;H.VSN_1_0_0="1.0.0";H.VSN_2_0_0="2.0.0";H.DEFAULT_VSN=H.VSN_2_0_0;H.VERSION=Ki.version;H.DEFAULT_TIMEOUT=1e4;H.WS_CLOSE_NORMAL=1e3;H.MAX_PUSH_BUFFER_SIZE=100;var qi;(function(t){t[t.connecting=0]="connecting",t[t.open=1]="open",t[t.closing=2]="closing",t[t.closed=3]="closed"})(qi||(H.SOCKET_STATES=qi={}));var Mi;(function(t){t.closed="closed",t.errored="errored",t.joined="joined",t.joining="joining",t.leaving="leaving"})(Mi||(H.CHANNEL_STATES=Mi={}));var Wi;(function(t){t.close="phx_close",t.error="phx_error",t.join="phx_join",t.reply="phx_reply",t.leave="phx_leave",t.access_token="access_token"})(Wi||(H.CHANNEL_EVENTS=Wi={}));var Vi;(function(t){t.websocket="websocket"})(Vi||(H.TRANSPORTS=Vi={}));var Hi;(function(t){t.Connecting="connecting",t.Open="open",t.Closing="closing",t.Closed="closed"})(Hi||(H.CONNECTION_STATE=Hi={}))});var zi=$(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});var rn=class{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,n;let s=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(e){var r,n;let s=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:{},o=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,n){var s,i;let o=e.topic,a=(s=e.ref)!==null&&s!==void 0?s:"",l=(i=e.join_ref)!==null&&i!==void 0?i:"",c=e.payload.event,h=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},m=Object.keys(h).length===0?"":JSON.stringify(h);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(m.length>255)throw new Error(`metadata length ${m.length} exceeds maximum of 255`);let _=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+o.length+c.length+m.length,f=new ArrayBuffer(this.HEADER_LENGTH+_),y=new DataView(f),v=0;y.setUint8(v++,this.KINDS.userBroadcastPush),y.setUint8(v++,l.length),y.setUint8(v++,a.length),y.setUint8(v++,o.length),y.setUint8(v++,c.length),y.setUint8(v++,m.length),y.setUint8(v++,r),Array.from(l,T=>y.setUint8(v++,T.charCodeAt(0))),Array.from(a,T=>y.setUint8(v++,T.charCodeAt(0))),Array.from(o,T=>y.setUint8(v++,T.charCodeAt(0))),Array.from(c,T=>y.setUint8(v++,T.charCodeAt(0))),Array.from(m,T=>y.setUint8(v++,T.charCodeAt(0)));var w=new Uint8Array(f.byteLength+n.byteLength);return w.set(new Uint8Array(f),0),w.set(new Uint8Array(n),f.byteLength),w.buffer}decode(e,r){if(this._isArrayBuffer(e)){let n=this._binaryDecode(e);return r(n)}if(typeof e=="string"){let n=JSON.parse(e),[s,i,o,a,l]=n;return r({join_ref:s,ref:i,topic:o,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),n=r.getUint8(0),s=new TextDecoder;switch(n){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,r,s)}}_decodeUserBroadcast(e,r,n){let s=r.getUint8(1),i=r.getUint8(2),o=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,c=n.decode(e.slice(l,l+s));l=l+s;let h=n.decode(e.slice(l,l+i));l=l+i;let m=n.decode(e.slice(l,l+o));l=l+o;let _=e.slice(l,e.byteLength),f=a===this.JSON_ENCODING?JSON.parse(n.decode(_)):_,y={type:this.BROADCAST_EVENT,event:h,payload:f};return o>0&&(y.meta=JSON.parse(m)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:y}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([n])=>r.includes(n)))}};nn.default=rn});var an=$(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});var sn=class{constructor(e,r){this.callback=e,this.timerCalc=r,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=r}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))}};on.default=sn});var Gt=$(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.httpEndpointURL=V.toTimestampString=V.toArray=V.toJson=V.toNumber=V.toBoolean=V.convertCell=V.convertColumn=V.convertChangeData=V.PostgresTypes=void 0;var G;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(G||(V.PostgresTypes=G={}));var Mu=(t,e,r={})=>{var n;let s=(n=r.skipTypes)!==null&&n!==void 0?n:[];return e?Object.keys(e).reduce((i,o)=>(i[o]=(0,V.convertColumn)(o,t,e,s),i),{}):{}};V.convertChangeData=Mu;var Wu=(t,e,r,n)=>{let s=e.find(a=>a.name===t),i=s?.type,o=r[t];return i&&!n.includes(i)?(0,V.convertCell)(i,o):un(o)};V.convertColumn=Wu;var Vu=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return(0,V.toArray)(e,r)}switch(t){case G.bool:return(0,V.toBoolean)(e);case G.float4:case G.float8:case G.int2:case G.int4:case G.int8:case G.numeric:case G.oid:return(0,V.toNumber)(e);case G.json:case G.jsonb:return(0,V.toJson)(e);case G.timestamp:return(0,V.toTimestampString)(e);case G.abstime:case G.date:case G.daterange:case G.int4range:case G.int8range:case G.money:case G.reltime:case G.text:case G.time:case G.timestamptz:case G.timetz:case G.tsrange:case G.tstzrange:return un(e);default:return un(e)}};V.convertCell=Vu;var un=t=>t,Hu=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}};V.toBoolean=Hu;var Ku=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t};V.toNumber=Ku;var zu=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t};V.toJson=zu;var Gu=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,n=t[r];if(t[0]==="{"&&n==="}"){let i,o=t.slice(1,r);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>(0,V.convertCell)(e,a))}return t};V.toArray=Gu;var Ju=t=>typeof t=="string"?t.replace(" ","T"):t;V.toTimestampString=Ju;var Yu=t=>{let e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};V.httpEndpointURL=Yu});var Gi=$(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});var Xu=zt(),ln=class{constructor(e,r,n={},s=Xu.DEFAULT_TIMEOUT){this.channel=e,this.event=r,this.payload=n,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,r){var n;return this._hasReceived(e)&&r((n=this.receivedResp)===null||n===void 0?void 0:n.response),this.recHooks.push({status:e,callback:r}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=r=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=r,this._matchReceive(r)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,r){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:r})}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:r}){this.recHooks.filter(n=>n.status===e).forEach(n=>n.callback(r))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};cn.default=ln});var hn=$(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.REALTIME_PRESENCE_LISTEN_EVENTS=void 0;var Ji;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Ji||(ht.REALTIME_PRESENCE_LISTEN_EVENTS=Ji={}));var dn=class t{constructor(e,r){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let n=r?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(n.state,{},s=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=t.syncState(this.state,s,i,o),this.pendingDiffs.forEach(l=>{this.state=t.syncDiff(this.state,l,i,o)}),this.pendingDiffs=[],a()}),this.channel._on(n.diff,{},s=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=t.syncDiff(this.state,s,i,o),a())}),this.onJoin((s,i,o)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:i,newPresences:o})}),this.onLeave((s,i,o)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,r,n,s){let i=this.cloneDeep(e),o=this.transformState(r),a={},l={};return this.map(i,(c,h)=>{o[c]||(l[c]=h)}),this.map(o,(c,h)=>{let m=i[c];if(m){let _=h.map(w=>w.presence_ref),f=m.map(w=>w.presence_ref),y=h.filter(w=>f.indexOf(w.presence_ref)<0),v=m.filter(w=>_.indexOf(w.presence_ref)<0);y.length>0&&(a[c]=y),v.length>0&&(l[c]=v)}else a[c]=h}),this.syncDiff(i,{joins:a,leaves:l},n,s)}static syncDiff(e,r,n,s){let{joins:i,leaves:o}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return n||(n=()=>{}),s||(s=()=>{}),this.map(i,(a,l)=>{var c;let h=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),h.length>0){let m=e[a].map(f=>f.presence_ref),_=h.filter(f=>m.indexOf(f.presence_ref)<0);e[a].unshift(..._)}n(a,h,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;let h=l.map(m=>m.presence_ref);c=c.filter(m=>h.indexOf(m.presence_ref)<0),e[a]=c,s(a,c,l),c.length===0&&delete e[a]}),e}static map(e,r){return Object.getOwnPropertyNames(e).map(n=>r(n,e[n]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{let s=e[n];return"metas"in s?r[n]=s.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):r[n]=s,r},{})}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()}};ht.default=dn});var mn=$(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.REALTIME_CHANNEL_STATES=Te.REALTIME_SUBSCRIBE_STATES=Te.REALTIME_LISTEN_TYPES=Te.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=void 0;var Jt=(ge(),Se(_e)),J=zt(),fn=Jt.__importDefault(Gi()),Qu=Jt.__importDefault(an()),Zu=Jt.__importDefault(hn()),Yi=Jt.__importStar(Gt()),el=Gt(),Xi;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Xi||(Te.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=Xi={}));var ft;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(ft||(Te.REALTIME_LISTEN_TYPES=ft={}));var xe;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(xe||(Te.REALTIME_SUBSCRIBE_STATES=xe={}));Te.REALTIME_CHANNEL_STATES=J.CHANNEL_STATES;var pn=class t{constructor(e,r={config:{}},n){var s,i;if(this.topic=e,this.params=r,this.socket=n,this.bindings={},this.state=J.CHANNEL_STATES.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},r.config),this.timeout=this.socket.timeout,this.joinPush=new fn.default(this,J.CHANNEL_EVENTS.join,this.params,this.timeout),this.rejoinTimer=new Qu.default(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=J.CHANNEL_STATES.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=J.CHANNEL_STATES.closed,this.socket._remove(this)}),this._onError(o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=J.CHANNEL_STATES.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=J.CHANNEL_STATES.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=J.CHANNEL_STATES.errored,this.rejoinTimer.scheduleTimeout())}),this._on(J.CHANNEL_EVENTS.reply,{},(o,a)=>{this._trigger(this._replyEventName(a),o)}),this.presence=new Zu.default(this),this.broadcastEndpointURL=(0,el.httpEndpointURL)(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((i=(s=this.params.config)===null||s===void 0?void 0:s.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var n,s,i;if(this.socket.isConnected()||this.socket.connect(),this.state==J.CHANNEL_STATES.closed){let{config:{broadcast:o,presence:a,private:l}}=this.params,c=(s=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(f=>f.filter))!==null&&s!==void 0?s:[],h=!!this.bindings[ft.PRESENCE]&&this.bindings[ft.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,m={},_={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:h}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(m.access_token=this.socket.accessTokenValue),this._onError(f=>e?.(xe.CHANNEL_ERROR,f)),this._onClose(()=>e?.(xe.CLOSED)),this.updateJoinPayload(Object.assign({config:_},m)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:f})=>{var y;if(this.socket._isManualToken()||this.socket.setAuth(),f===void 0){e?.(xe.SUBSCRIBED);return}else{let v=this.bindings.postgres_changes,w=(y=v?.length)!==null&&y!==void 0?y:0,T=[];for(let O=0;O<w;O++){let E=v[O],{filter:{event:x,schema:Z,table:W,filter:re}}=E,ke=f&&f[O];if(ke&&ke.event===x&&t.isFilterValueEqual(ke.schema,Z)&&t.isFilterValueEqual(ke.table,W)&&t.isFilterValueEqual(ke.filter,re))T.push(Object.assign(Object.assign({},E),{id:ke.id}));else{this.unsubscribe(),this.state=J.CHANNEL_STATES.errored,e?.(xe.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=T,e&&e(xe.SUBSCRIBED);return}}).receive("error",f=>{this.state=J.CHANNEL_STATES.errored,e?.(xe.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e?.(xe.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,n){return this.state===J.CHANNEL_STATES.joined&&e===ft.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,r,n)}async httpSend(e,r,n={}){var s;if(r==null)return Promise.reject("Payload is required for httpSend()");let i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);let o={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(s=n.timeout)!==null&&s!==void 0?s:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;try{let c=await a.json();l=c.error||c.message||l}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var n,s;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");let{event:i,payload:o}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let l={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((s=c.body)===null||s===void 0?void 0:s.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,l;let c=this._push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),c.receive("ok",()=>i("ok")),c.receive("error",()=>i("error")),c.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=J.CHANNEL_STATES.leaving;let r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(J.CHANNEL_EVENTS.close,"leave",this._joinRef())};this.joinPush.destroy();let n=null;return new Promise(s=>{n=new fn.default(this,J.CHANNEL_EVENTS.leave,{},e),n.receive("ok",()=>{r(),s("ok")}).receive("timeout",()=>{r(),s("timed out")}).receive("error",()=>{s("error")}),n.send(),this._canPush()||n.trigger("ok",{})}).finally(()=>{n?.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=J.CHANNEL_STATES.closed,this.bindings={}}async _fetchWithTimeout(e,r,n){let s=new AbortController,i=setTimeout(()=>s.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:s.signal}));return clearTimeout(i),o}_push(e,r,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new fn.default(this,e,r,n);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>J.MAX_PUSH_BUFFER_SIZE){let r=this.pushBuffer.shift();r&&(r.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${r.event}`,r.payload))}}_onMessage(e,r,n){return r}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,r,n){var s,i;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:h}=J.CHANNEL_EVENTS;if(n&&[a,l,c,h].indexOf(o)>=0&&n!==this._joinRef())return;let _=this._onMessage(o,r,n);if(r&&!_)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(f=>{var y,v,w;return((y=f.filter)===null||y===void 0?void 0:y.event)==="*"||((w=(v=f.filter)===null||v===void 0?void 0:v.event)===null||w===void 0?void 0:w.toLocaleLowerCase())===o}).map(f=>f.callback(_,n)):(i=this.bindings[o])===null||i===void 0||i.filter(f=>{var y,v,w,T,O,E;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let x=f.id,Z=(y=f.filter)===null||y===void 0?void 0:y.event;return x&&((v=r.ids)===null||v===void 0?void 0:v.includes(x))&&(Z==="*"||Z?.toLocaleLowerCase()===((w=r.data)===null||w===void 0?void 0:w.type.toLocaleLowerCase()))}else{let x=(O=(T=f?.filter)===null||T===void 0?void 0:T.event)===null||O===void 0?void 0:O.toLocaleLowerCase();return x==="*"||x===((E=r?.event)===null||E===void 0?void 0:E.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof _=="object"&&"ids"in _){let y=_.data,{schema:v,table:w,commit_timestamp:T,type:O,errors:E}=y;_=Object.assign(Object.assign({},{schema:v,table:w,commit_timestamp:T,eventType:O,new:{},old:{},errors:E}),this._getPayloadRecords(y))}f.callback(_,n)})}_isClosed(){return this.state===J.CHANNEL_STATES.closed}_isJoined(){return this.state===J.CHANNEL_STATES.joined}_isJoining(){return this.state===J.CHANNEL_STATES.joining}_isLeaving(){return this.state===J.CHANNEL_STATES.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,r,n){let s=e.toLocaleLowerCase(),i={type:s,filter:r,callback:n};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(e,r){let n=e.toLocaleLowerCase();return this.bindings[n]&&(this.bindings[n]=this.bindings[n].filter(s=>{var i;return!(((i=s.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===n&&t.isEqual(s.filter,r))})),this}static isEqual(e,r){if(Object.keys(e).length!==Object.keys(r).length)return!1;for(let n in e)if(e[n]!==r[n])return!1;return!0}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(J.CHANNEL_EVENTS.close,{},e)}_onError(e){this._on(J.CHANNEL_EVENTS.error,{},r=>e(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=J.CHANNEL_STATES.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Yi.convertChangeData(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Yi.convertChangeData(e.columns,e.old_record)),r}};Te.default=pn});var Qi=$(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});var Xt=(ge(),Se(_e)),tl=Xt.__importDefault(tn()),ne=zt(),rl=Xt.__importDefault(zi()),nl=Xt.__importDefault(an()),sl=Gt(),il=Xt.__importDefault(mn()),_n=()=>{},Yt={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},ol=[1e3,2e3,5e3,1e4],al=1e4,ul=`
|
|
7
|
+
Suggested solution: ${e.workaround}`),new Error(r)}static createWebSocket(e,r){let n=this.getWebSocketConstructor();return new n(e,r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}};dt.WebSocketFactory=Kt;dt.default=Kt});var Bi=$(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.version=void 0;zt.version="2.97.0"});var Gt=$(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.CONNECTION_STATE=H.TRANSPORTS=H.CHANNEL_EVENTS=H.CHANNEL_STATES=H.SOCKET_STATES=H.MAX_PUSH_BUFFER_SIZE=H.WS_CLOSE_NORMAL=H.DEFAULT_TIMEOUT=H.VERSION=H.DEFAULT_VSN=H.VSN_2_0_0=H.VSN_1_0_0=H.DEFAULT_VERSION=void 0;var Ki=Bi();H.DEFAULT_VERSION=`realtime-js/${Ki.version}`;H.VSN_1_0_0="1.0.0";H.VSN_2_0_0="2.0.0";H.DEFAULT_VSN=H.VSN_2_0_0;H.VERSION=Ki.version;H.DEFAULT_TIMEOUT=1e4;H.WS_CLOSE_NORMAL=1e3;H.MAX_PUSH_BUFFER_SIZE=100;var qi;(function(t){t[t.connecting=0]="connecting",t[t.open=1]="open",t[t.closing=2]="closing",t[t.closed=3]="closed"})(qi||(H.SOCKET_STATES=qi={}));var Mi;(function(t){t.closed="closed",t.errored="errored",t.joined="joined",t.joining="joining",t.leaving="leaving"})(Mi||(H.CHANNEL_STATES=Mi={}));var Wi;(function(t){t.close="phx_close",t.error="phx_error",t.join="phx_join",t.reply="phx_reply",t.leave="phx_leave",t.access_token="access_token"})(Wi||(H.CHANNEL_EVENTS=Wi={}));var Vi;(function(t){t.websocket="websocket"})(Vi||(H.TRANSPORTS=Vi={}));var Hi;(function(t){t.Connecting="connecting",t.Open="open",t.Closing="closing",t.Closed="closed"})(Hi||(H.CONNECTION_STATE=Hi={}))});var zi=$(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});var rn=class{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,n;let s=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,s)}_encodeJsonUserBroadcastPush(e){var r,n;let s=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:{},o=new TextEncoder().encode(JSON.stringify(s)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,n){var s,i;let o=e.topic,a=(s=e.ref)!==null&&s!==void 0?s:"",l=(i=e.join_ref)!==null&&i!==void 0?i:"",c=e.payload.event,h=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},m=Object.keys(h).length===0?"":JSON.stringify(h);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(m.length>255)throw new Error(`metadata length ${m.length} exceeds maximum of 255`);let _=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+o.length+c.length+m.length,f=new ArrayBuffer(this.HEADER_LENGTH+_),y=new DataView(f),v=0;y.setUint8(v++,this.KINDS.userBroadcastPush),y.setUint8(v++,l.length),y.setUint8(v++,a.length),y.setUint8(v++,o.length),y.setUint8(v++,c.length),y.setUint8(v++,m.length),y.setUint8(v++,r),Array.from(l,T=>y.setUint8(v++,T.charCodeAt(0))),Array.from(a,T=>y.setUint8(v++,T.charCodeAt(0))),Array.from(o,T=>y.setUint8(v++,T.charCodeAt(0))),Array.from(c,T=>y.setUint8(v++,T.charCodeAt(0))),Array.from(m,T=>y.setUint8(v++,T.charCodeAt(0)));var w=new Uint8Array(f.byteLength+n.byteLength);return w.set(new Uint8Array(f),0),w.set(new Uint8Array(n),f.byteLength),w.buffer}decode(e,r){if(this._isArrayBuffer(e)){let n=this._binaryDecode(e);return r(n)}if(typeof e=="string"){let n=JSON.parse(e),[s,i,o,a,l]=n;return r({join_ref:s,ref:i,topic:o,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),n=r.getUint8(0),s=new TextDecoder;switch(n){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,r,s)}}_decodeUserBroadcast(e,r,n){let s=r.getUint8(1),i=r.getUint8(2),o=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,c=n.decode(e.slice(l,l+s));l=l+s;let h=n.decode(e.slice(l,l+i));l=l+i;let m=n.decode(e.slice(l,l+o));l=l+o;let _=e.slice(l,e.byteLength),f=a===this.JSON_ENCODING?JSON.parse(n.decode(_)):_,y={type:this.BROADCAST_EVENT,event:h,payload:f};return o>0&&(y.meta=JSON.parse(m)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:y}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return!e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([n])=>r.includes(n)))}};nn.default=rn});var an=$(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});var sn=class{constructor(e,r){this.callback=e,this.timerCalc=r,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=r}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))}};on.default=sn});var Jt=$(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.httpEndpointURL=V.toTimestampString=V.toArray=V.toJson=V.toNumber=V.toBoolean=V.convertCell=V.convertColumn=V.convertChangeData=V.PostgresTypes=void 0;var G;(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange"})(G||(V.PostgresTypes=G={}));var Vu=(t,e,r={})=>{var n;let s=(n=r.skipTypes)!==null&&n!==void 0?n:[];return e?Object.keys(e).reduce((i,o)=>(i[o]=(0,V.convertColumn)(o,t,e,s),i),{}):{}};V.convertChangeData=Vu;var Hu=(t,e,r,n)=>{let s=e.find(a=>a.name===t),i=s?.type,o=r[t];return i&&!n.includes(i)?(0,V.convertCell)(i,o):un(o)};V.convertColumn=Hu;var Ku=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return(0,V.toArray)(e,r)}switch(t){case G.bool:return(0,V.toBoolean)(e);case G.float4:case G.float8:case G.int2:case G.int4:case G.int8:case G.numeric:case G.oid:return(0,V.toNumber)(e);case G.json:case G.jsonb:return(0,V.toJson)(e);case G.timestamp:return(0,V.toTimestampString)(e);case G.abstime:case G.date:case G.daterange:case G.int4range:case G.int8range:case G.money:case G.reltime:case G.text:case G.time:case G.timestamptz:case G.timetz:case G.tsrange:case G.tstzrange:return un(e);default:return un(e)}};V.convertCell=Ku;var un=t=>t,zu=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}};V.toBoolean=zu;var Gu=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t};V.toNumber=Gu;var Ju=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t};V.toJson=Ju;var Yu=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,n=t[r];if(t[0]==="{"&&n==="}"){let i,o=t.slice(1,r);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>(0,V.convertCell)(e,a))}return t};V.toArray=Yu;var Xu=t=>typeof t=="string"?t.replace(" ","T"):t;V.toTimestampString=Xu;var Qu=t=>{let e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};V.httpEndpointURL=Qu});var Gi=$(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});var Zu=Gt(),ln=class{constructor(e,r,n={},s=Zu.DEFAULT_TIMEOUT){this.channel=e,this.event=r,this.payload=n,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,r){var n;return this._hasReceived(e)&&r((n=this.receivedResp)===null||n===void 0?void 0:n.response),this.recHooks.push({status:e,callback:r}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=r=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=r,this._matchReceive(r)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,r){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:r})}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:r}){this.recHooks.filter(n=>n.status===e).forEach(n=>n.callback(r))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};cn.default=ln});var hn=$(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.REALTIME_PRESENCE_LISTEN_EVENTS=void 0;var Ji;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(Ji||(ht.REALTIME_PRESENCE_LISTEN_EVENTS=Ji={}));var dn=class t{constructor(e,r){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let n=r?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(n.state,{},s=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=t.syncState(this.state,s,i,o),this.pendingDiffs.forEach(l=>{this.state=t.syncDiff(this.state,l,i,o)}),this.pendingDiffs=[],a()}),this.channel._on(n.diff,{},s=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(s):(this.state=t.syncDiff(this.state,s,i,o),a())}),this.onJoin((s,i,o)=>{this.channel._trigger("presence",{event:"join",key:s,currentPresences:i,newPresences:o})}),this.onLeave((s,i,o)=>{this.channel._trigger("presence",{event:"leave",key:s,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,r,n,s){let i=this.cloneDeep(e),o=this.transformState(r),a={},l={};return this.map(i,(c,h)=>{o[c]||(l[c]=h)}),this.map(o,(c,h)=>{let m=i[c];if(m){let _=h.map(w=>w.presence_ref),f=m.map(w=>w.presence_ref),y=h.filter(w=>f.indexOf(w.presence_ref)<0),v=m.filter(w=>_.indexOf(w.presence_ref)<0);y.length>0&&(a[c]=y),v.length>0&&(l[c]=v)}else a[c]=h}),this.syncDiff(i,{joins:a,leaves:l},n,s)}static syncDiff(e,r,n,s){let{joins:i,leaves:o}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return n||(n=()=>{}),s||(s=()=>{}),this.map(i,(a,l)=>{var c;let h=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),h.length>0){let m=e[a].map(f=>f.presence_ref),_=h.filter(f=>m.indexOf(f.presence_ref)<0);e[a].unshift(..._)}n(a,h,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;let h=l.map(m=>m.presence_ref);c=c.filter(m=>h.indexOf(m.presence_ref)<0),e[a]=c,s(a,c,l),c.length===0&&delete e[a]}),e}static map(e,r){return Object.getOwnPropertyNames(e).map(n=>r(n,e[n]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{let s=e[n];return"metas"in s?r[n]=s.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):r[n]=s,r},{})}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()}};ht.default=dn});var mn=$(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.REALTIME_CHANNEL_STATES=Te.REALTIME_SUBSCRIBE_STATES=Te.REALTIME_LISTEN_TYPES=Te.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=void 0;var Yt=(ge(),Se(_e)),J=Gt(),fn=Yt.__importDefault(Gi()),el=Yt.__importDefault(an()),tl=Yt.__importDefault(hn()),Yi=Yt.__importStar(Jt()),rl=Jt(),Xi;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Xi||(Te.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=Xi={}));var ft;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(ft||(Te.REALTIME_LISTEN_TYPES=ft={}));var xe;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(xe||(Te.REALTIME_SUBSCRIBE_STATES=xe={}));Te.REALTIME_CHANNEL_STATES=J.CHANNEL_STATES;var pn=class t{constructor(e,r={config:{}},n){var s,i;if(this.topic=e,this.params=r,this.socket=n,this.bindings={},this.state=J.CHANNEL_STATES.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},r.config),this.timeout=this.socket.timeout,this.joinPush=new fn.default(this,J.CHANNEL_EVENTS.join,this.params,this.timeout),this.rejoinTimer=new el.default(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=J.CHANNEL_STATES.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(o=>o.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=J.CHANNEL_STATES.closed,this.socket._remove(this)}),this._onError(o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=J.CHANNEL_STATES.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=J.CHANNEL_STATES.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("error",o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=J.CHANNEL_STATES.errored,this.rejoinTimer.scheduleTimeout())}),this._on(J.CHANNEL_EVENTS.reply,{},(o,a)=>{this._trigger(this._replyEventName(a),o)}),this.presence=new tl.default(this),this.broadcastEndpointURL=(0,rl.httpEndpointURL)(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((i=(s=this.params.config)===null||s===void 0?void 0:s.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var n,s,i;if(this.socket.isConnected()||this.socket.connect(),this.state==J.CHANNEL_STATES.closed){let{config:{broadcast:o,presence:a,private:l}}=this.params,c=(s=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(f=>f.filter))!==null&&s!==void 0?s:[],h=!!this.bindings[ft.PRESENCE]&&this.bindings[ft.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,m={},_={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:h}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(m.access_token=this.socket.accessTokenValue),this._onError(f=>e?.(xe.CHANNEL_ERROR,f)),this._onClose(()=>e?.(xe.CLOSED)),this.updateJoinPayload(Object.assign({config:_},m)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:f})=>{var y;if(this.socket._isManualToken()||this.socket.setAuth(),f===void 0){e?.(xe.SUBSCRIBED);return}else{let v=this.bindings.postgres_changes,w=(y=v?.length)!==null&&y!==void 0?y:0,T=[];for(let O=0;O<w;O++){let E=v[O],{filter:{event:x,schema:Z,table:W,filter:re}}=E,ke=f&&f[O];if(ke&&ke.event===x&&t.isFilterValueEqual(ke.schema,Z)&&t.isFilterValueEqual(ke.table,W)&&t.isFilterValueEqual(ke.filter,re))T.push(Object.assign(Object.assign({},E),{id:ke.id}));else{this.unsubscribe(),this.state=J.CHANNEL_STATES.errored,e?.(xe.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=T,e&&e(xe.SUBSCRIBED);return}}).receive("error",f=>{this.state=J.CHANNEL_STATES.errored,e?.(xe.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(f).join(", ")||"error")))}).receive("timeout",()=>{e?.(xe.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,n){return this.state===J.CHANNEL_STATES.joined&&e===ft.PRESENCE&&(this.socket.log("channel",`resubscribe to ${this.topic} due to change in presence callbacks on joined channel`),this.unsubscribe().then(async()=>await this.subscribe())),this._on(e,r,n)}async httpSend(e,r,n={}){var s;if(r==null)return Promise.reject("Payload is required for httpSend()");let i={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);let o={method:"POST",headers:i,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(s=n.timeout)!==null&&s!==void 0?s:this.timeout);if(a.status===202)return{success:!0};let l=a.statusText;try{let c=await a.json();l=c.error||c.message||l}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var n,s;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");let{event:i,payload:o}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let l={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((s=c.body)===null||s===void 0?void 0:s.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,l;let c=this._push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&i("ok"),c.receive("ok",()=>i("ok")),c.receive("error",()=>i("error")),c.receive("timeout",()=>i("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=J.CHANNEL_STATES.leaving;let r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(J.CHANNEL_EVENTS.close,"leave",this._joinRef())};this.joinPush.destroy();let n=null;return new Promise(s=>{n=new fn.default(this,J.CHANNEL_EVENTS.leave,{},e),n.receive("ok",()=>{r(),s("ok")}).receive("timeout",()=>{r(),s("timed out")}).receive("error",()=>{s("error")}),n.send(),this._canPush()||n.trigger("ok",{})}).finally(()=>{n?.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=J.CHANNEL_STATES.closed,this.bindings={}}async _fetchWithTimeout(e,r,n){let s=new AbortController,i=setTimeout(()=>s.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:s.signal}));return clearTimeout(i),o}_push(e,r,n=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new fn.default(this,e,r,n);return this._canPush()?s.send():this._addToPushBuffer(s),s}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>J.MAX_PUSH_BUFFER_SIZE){let r=this.pushBuffer.shift();r&&(r.destroy(),this.socket.log("channel",`discarded push due to buffer overflow: ${r.event}`,r.payload))}}_onMessage(e,r,n){return r}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,r,n){var s,i;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:h}=J.CHANNEL_EVENTS;if(n&&[a,l,c,h].indexOf(o)>=0&&n!==this._joinRef())return;let _=this._onMessage(o,r,n);if(r&&!_)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(s=this.bindings.postgres_changes)===null||s===void 0||s.filter(f=>{var y,v,w;return((y=f.filter)===null||y===void 0?void 0:y.event)==="*"||((w=(v=f.filter)===null||v===void 0?void 0:v.event)===null||w===void 0?void 0:w.toLocaleLowerCase())===o}).map(f=>f.callback(_,n)):(i=this.bindings[o])===null||i===void 0||i.filter(f=>{var y,v,w,T,O,E;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in f){let x=f.id,Z=(y=f.filter)===null||y===void 0?void 0:y.event;return x&&((v=r.ids)===null||v===void 0?void 0:v.includes(x))&&(Z==="*"||Z?.toLocaleLowerCase()===((w=r.data)===null||w===void 0?void 0:w.type.toLocaleLowerCase()))}else{let x=(O=(T=f?.filter)===null||T===void 0?void 0:T.event)===null||O===void 0?void 0:O.toLocaleLowerCase();return x==="*"||x===((E=r?.event)===null||E===void 0?void 0:E.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===o}).map(f=>{if(typeof _=="object"&&"ids"in _){let y=_.data,{schema:v,table:w,commit_timestamp:T,type:O,errors:E}=y;_=Object.assign(Object.assign({},{schema:v,table:w,commit_timestamp:T,eventType:O,new:{},old:{},errors:E}),this._getPayloadRecords(y))}f.callback(_,n)})}_isClosed(){return this.state===J.CHANNEL_STATES.closed}_isJoined(){return this.state===J.CHANNEL_STATES.joined}_isJoining(){return this.state===J.CHANNEL_STATES.joining}_isLeaving(){return this.state===J.CHANNEL_STATES.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,r,n){let s=e.toLocaleLowerCase(),i={type:s,filter:r,callback:n};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(e,r){let n=e.toLocaleLowerCase();return this.bindings[n]&&(this.bindings[n]=this.bindings[n].filter(s=>{var i;return!(((i=s.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===n&&t.isEqual(s.filter,r))})),this}static isEqual(e,r){if(Object.keys(e).length!==Object.keys(r).length)return!1;for(let n in e)if(e[n]!==r[n])return!1;return!0}static isFilterValueEqual(e,r){return(e??void 0)===(r??void 0)}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(J.CHANNEL_EVENTS.close,{},e)}_onError(e){this._on(J.CHANNEL_EVENTS.error,{},r=>e(r))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=J.CHANNEL_STATES.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Yi.convertChangeData(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Yi.convertChangeData(e.columns,e.old_record)),r}};Te.default=pn});var Qi=$(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});var Qt=(ge(),Se(_e)),nl=Qt.__importDefault(tn()),ne=Gt(),sl=Qt.__importDefault(zi()),il=Qt.__importDefault(an()),ol=Jt(),al=Qt.__importDefault(mn()),_n=()=>{},Xt={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},ul=[1e3,2e3,5e3,1e4],ll=1e4,cl=`
|
|
8
8
|
addEventListener("message", (e) => {
|
|
9
9
|
if (e.data.event === "start") {
|
|
10
10
|
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
|
|
11
11
|
}
|
|
12
|
-
});`,gn=class{constructor(e,r){var n;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=ne.DEFAULT_TIMEOUT,this.transport=null,this.heartbeatIntervalMs=
|
|
12
|
+
});`,gn=class{constructor(e,r){var n;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=ne.DEFAULT_TIMEOUT,this.transport=null,this.heartbeatIntervalMs=Xt.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=_n,this.ref=0,this.reconnectTimer=null,this.vsn=ne.DEFAULT_VSN,this.logger=_n,this.conn=null,this.sendBuffer=[],this.serializer=new sl.default,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=s=>s?(...i)=>s(...i):(...i)=>fetch(...i),!(!((n=r?.params)===null||n===void 0)&&n.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey,this.endPoint=`${e}/${ne.TRANSPORTS.websocket}`,this.httpEndpoint=(0,ol.httpEndpointURL)(e),this._initializeOptions(r),this._setupReconnectionTimer(),this.fetch=this._resolveFetch(r?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.conn!==null&&this.isConnected())){if(this._setConnectionState("connecting"),this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this.transport)this.conn=new this.transport(this.endpointURL());else try{this.conn=nl.default.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");let r=e.message;throw r.includes("Node.js")?new Error(`${r}
|
|
13
13
|
|
|
14
14
|
To use Realtime in Node.js, you need to provide a WebSocket implementation:
|
|
15
15
|
|
|
@@ -22,8 +22,8 @@ Option 2: Install and provide the "ws" package:
|
|
|
22
22
|
const client = new RealtimeClient(url, {
|
|
23
23
|
...options,
|
|
24
24
|
transport: ws
|
|
25
|
-
})`):new Error(`WebSocket not available: ${r}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,r){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){let n=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(n),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&(e?this.conn.close(e,r??""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){let e=await Promise.all(this.channels.map(r=>r.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,r,n){this.logger(e,r,n)}connectionState(){switch(this.conn&&this.conn.readyState){case ne.SOCKET_STATES.connecting:return ne.CONNECTION_STATE.Connecting;case ne.SOCKET_STATES.open:return ne.CONNECTION_STATE.Open;case ne.SOCKET_STATES.closing:return ne.CONNECTION_STATE.Closing;default:return ne.CONNECTION_STATE.Closed}}isConnected(){return this.connectionState()===ne.CONNECTION_STATE.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,r={config:{}}){let n=`realtime:${e}`,s=this.getChannels().find(i=>i.topic===n);if(s)return s;{let i=new il.default(`realtime:${e}`,r,this);return this.channels.push(i),i}}push(e){let{topic:r,event:n,payload:s,ref:i}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${r} ${n} (${i})`,s),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(r){this.log("error","error in heartbeat callback",r)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(r){this.log("error","error in heartbeat callback",r)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(ne.WS_CLOSE_NORMAL,"heartbeat timeout"),setTimeout(()=>{var r;this.isConnected()||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout()},Yt.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(r){this.log("error","error in heartbeat callback",r)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let r=this.channels.find(n=>n.topic===e&&(n._isJoined()||n._isJoining()));r&&(this.log("transport",`leaving duplicate topic "${e}"`),r.unsubscribe())}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,r=>{if(r.topic==="phoenix"&&r.event==="phx_reply"&&r.ref&&r.ref===this.pendingHeartbeatRef){let c=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(r.payload.status==="ok"?"ok":"error",c)}catch(h){this.log("error","error in heartbeat callback",h)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}let{topic:n,event:s,payload:i,ref:o}=r,a=o?`(${o})`:"",l=i.status||"";this.log("receive",`${l} ${n} ${s} ${a}`.trim(),i),this.channels.filter(c=>c._isMember(n)).forEach(c=>c._trigger(s,i,o)),this._triggerStateCallbacks("message",r)})}_clearTimer(e){var r;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((r=this.reconnectTimer)===null||r===void 0||r.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===ne.SOCKET_STATES.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===ne.SOCKET_STATES.open||this.conn.readyState===ne.SOCKET_STATES.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(r=>{this.log("error","error waiting for auth on connect",r),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");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_onConnClose(e){var r;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e);try{this.heartbeatCallback("error")}catch(r){this.log("error","error in heartbeat callback",r)}}_triggerChanError(){this.channels.forEach(e=>e._trigger(ne.CHANNEL_EVENTS.error))}_appendParams(e,r){if(Object.keys(r).length===0)return e;let n=e.match(/\?/)?"&":"?",s=new URLSearchParams(r);return`${e}${n}${s}`}_workerObjectUrl(e){let r;if(e)r=e;else{let n=new Blob([ul],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}_setConnectionState(e,r=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=r)}async _performAuth(e=null){let r,n=!1;if(e)r=e,n=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(s){this.log("error","Error fetching access token from callback",s),r=this.accessTokenValue}else r=this.accessTokenValue;n?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(s=>{let i={access_token:r,version:ne.DEFAULT_VERSION};r&&s.updateJoinPayload(i),s.joinedOnce&&s._isJoined()&&s._push(ne.CHANNEL_EVENTS.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_triggerStateCallbacks(e,r){try{this.stateChangeCallbacks[e].forEach(n=>{try{n(r)}catch(s){this.log("error",`error in ${e} callback`,s)}})}catch(n){this.log("error",`error triggering ${e} callbacks`,n)}}_setupReconnectionTimer(){this.reconnectTimer=new nl.default(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Yt.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var r,n,s,i,o,a,l,c,h,m,_,f;switch(this.transport=(r=e?.transport)!==null&&r!==void 0?r:null,this.timeout=(n=e?.timeout)!==null&&n!==void 0?n:ne.DEFAULT_TIMEOUT,this.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:Yt.HEARTBEAT_INTERVAL,this.worker=(i=e?.worker)!==null&&i!==void 0?i:!1,this.accessToken=(o=e?.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(a=e?.heartbeatCallback)!==null&&a!==void 0?a:_n,this.vsn=(l=e?.vsn)!==null&&l!==void 0?l:ne.DEFAULT_VSN,e?.params&&(this.params=e.params),e?.logger&&(this.logger=e.logger),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(c=e?.reconnectAfterMs)!==null&&c!==void 0?c:(y=>ol[y-1]||al),this.vsn){case ne.VSN_1_0_0:this.encode=(h=e?.encode)!==null&&h!==void 0?h:((y,v)=>v(JSON.stringify(y))),this.decode=(m=e?.decode)!==null&&m!==void 0?m:((y,v)=>v(JSON.parse(y)));break;case ne.VSN_2_0_0:this.encode=(_=e?.encode)!==null&&_!==void 0?_:this.serializer.encode.bind(this.serializer),this.decode=(f=e?.decode)!==null&&f!==void 0?f:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl}}};yn.default=gn});var vn=$(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.WebSocketFactory=oe.REALTIME_CHANNEL_STATES=oe.REALTIME_SUBSCRIBE_STATES=oe.REALTIME_PRESENCE_LISTEN_EVENTS=oe.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=oe.REALTIME_LISTEN_TYPES=oe.RealtimeClient=oe.RealtimeChannel=oe.RealtimePresence=void 0;var Qt=(ge(),Se(_e)),ll=Qt.__importDefault(Qi());oe.RealtimeClient=ll.default;var pt=Qt.__importStar(mn());oe.RealtimeChannel=pt.default;Object.defineProperty(oe,"REALTIME_LISTEN_TYPES",{enumerable:!0,get:function(){return pt.REALTIME_LISTEN_TYPES}});Object.defineProperty(oe,"REALTIME_POSTGRES_CHANGES_LISTEN_EVENT",{enumerable:!0,get:function(){return pt.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT}});Object.defineProperty(oe,"REALTIME_SUBSCRIBE_STATES",{enumerable:!0,get:function(){return pt.REALTIME_SUBSCRIBE_STATES}});Object.defineProperty(oe,"REALTIME_CHANNEL_STATES",{enumerable:!0,get:function(){return pt.REALTIME_CHANNEL_STATES}});var Zi=Qt.__importStar(hn());oe.RealtimePresence=Zi.default;Object.defineProperty(oe,"REALTIME_PRESENCE_LISTEN_EVENTS",{enumerable:!0,get:function(){return Zi.REALTIME_PRESENCE_LISTEN_EVENTS}});var cl=Qt.__importDefault(tn());oe.WebSocketFactory=cl.default});var Sn=$(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.version=void 0;nr.version="2.97.0"});var sr=$(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.JWKS_TTL=K.BASE64URL_REGEX=K.API_VERSIONS=K.API_VERSION_HEADER_NAME=K.NETWORK_FAILURE=K.DEFAULT_HEADERS=K.AUDIENCE=K.STORAGE_KEY=K.GOTRUE_URL=K.EXPIRY_MARGIN_MS=K.AUTO_REFRESH_TICK_THRESHOLD=K.AUTO_REFRESH_TICK_DURATION_MS=void 0;var Fl=Sn();K.AUTO_REFRESH_TICK_DURATION_MS=30*1e3;K.AUTO_REFRESH_TICK_THRESHOLD=3;K.EXPIRY_MARGIN_MS=K.AUTO_REFRESH_TICK_THRESHOLD*K.AUTO_REFRESH_TICK_DURATION_MS;K.GOTRUE_URL="http://localhost:9999";K.STORAGE_KEY="supabase.auth.token";K.AUDIENCE="";K.DEFAULT_HEADERS={"X-Client-Info":`gotrue-js/${Fl.version}`};K.NETWORK_FAILURE={MAX_RETRIES:10,RETRY_INTERVAL:2};K.API_VERSION_HEADER_NAME="X-Supabase-Api-Version";K.API_VERSIONS={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};K.BASE64URL_REGEX=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;K.JWKS_TTL=600*1e3});var De=$(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.AuthInvalidJwtError=F.AuthWeakPasswordError=F.AuthRetryableFetchError=F.AuthPKCECodeVerifierMissingError=F.AuthPKCEGrantCodeExchangeError=F.AuthImplicitGrantRedirectError=F.AuthInvalidCredentialsError=F.AuthInvalidTokenResponseError=F.AuthSessionMissingError=F.CustomAuthError=F.AuthUnknownError=F.AuthApiError=F.AuthError=void 0;F.isAuthError=$e;F.isAuthApiError=Bl;F.isAuthSessionMissingError=ql;F.isAuthImplicitGrantRedirectError=Ml;F.isAuthPKCECodeVerifierMissingError=Wl;F.isAuthRetryableFetchError=Vl;F.isAuthWeakPasswordError=Hl;var et=class extends Error{constructor(e,r,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}};F.AuthError=et;function $e(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var Tn=class extends et{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n}};F.AuthApiError=Tn;function Bl(t){return $e(t)&&t.name==="AuthApiError"}var An=class extends et{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}};F.AuthUnknownError=An;var ve=class extends et{constructor(e,r,n,s){super(e,n,s),this.name=r,this.status=n}};F.CustomAuthError=ve;var Rn=class extends ve{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};F.AuthSessionMissingError=Rn;function ql(t){return $e(t)&&t.name==="AuthSessionMissingError"}var kn=class extends ve{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}};F.AuthInvalidTokenResponseError=kn;var On=class extends ve{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}};F.AuthInvalidCredentialsError=On;var Cn=class extends ve{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};F.AuthImplicitGrantRedirectError=Cn;function Ml(t){return $e(t)&&t.name==="AuthImplicitGrantRedirectError"}var Pn=class extends ve{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};F.AuthPKCEGrantCodeExchangeError=Pn;var In=class extends ve{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}};F.AuthPKCECodeVerifierMissingError=In;function Wl(t){return $e(t)&&t.name==="AuthPKCECodeVerifierMissingError"}var xn=class extends ve{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};F.AuthRetryableFetchError=xn;function Vl(t){return $e(t)&&t.name==="AuthRetryableFetchError"}var Nn=class extends ve{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}};F.AuthWeakPasswordError=Nn;function Hl(t){return $e(t)&&t.name==="AuthWeakPasswordError"}var jn=class extends ve{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};F.AuthInvalidJwtError=jn});var or=$(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.byteToBase64URL=wt;we.byteFromBase64URL=Ln;we.stringToBase64URL=zl;we.stringFromBase64URL=Gl;we.codepointToUTF8=lo;we.stringToUTF8=Un;we.stringFromUTF8=co;we.base64UrlToUint8Array=Jl;we.stringToUint8Array=Yl;we.bytesToBase64URL=Xl;var ir="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),uo=`
|
|
26
|
-
\r=`.split(""),Kl=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<uo.length;e+=1)t[uo[e].charCodeAt(0)]=-2;for(let e=0;e<ir.length;e+=1)t[ir[e].charCodeAt(0)]=e;return t})();function wt(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(ir[n]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(ir[n]),e.queuedBits-=6}}function Ln(t,e,r){let n=Kl[t];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function zl(t){let e=[],r=s=>{e.push(s)},n={queue:0,queuedBits:0};return Un(t,s=>{wt(s,n,r)}),wt(null,n,r),e.join("")}function Gl(t){let e=[],r=o=>{e.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=o=>{co(o,n,r)};for(let o=0;o<t.length;o+=1)Ln(t.charCodeAt(o),s,i);return e.join("")}function lo(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function Un(t,e){for(let r=0;r<t.length;r+=1){let n=t.charCodeAt(r);if(n>55295&&n<=56319){let s=(n-55296)*1024&65535;n=(t.charCodeAt(r+1)-56320&65535|s)+65536,r+=1}lo(n,e)}}function co(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let n=1;n<6;n+=1)if((t>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function Jl(t){let e=[],r={queue:0,queuedBits:0},n=s=>{e.push(s)};for(let s=0;s<t.length;s+=1)Ln(t.charCodeAt(s),r,n);return new Uint8Array(e)}function Yl(t){let e=[];return Un(t,r=>e.push(r)),new Uint8Array(e)}function Xl(t){let e=[],r={queue:0,queuedBits:0},n=s=>{e.push(s)};return t.forEach(s=>wt(s,r,n)),wt(null,r,n),e.join("")}});var tt=$(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.Deferred=D.removeItemAsync=D.getItemAsync=D.setItemAsync=D.looksLikeFetchResponse=D.resolveFetch=D.supportsLocalStorage=D.isBrowser=void 0;D.expiresAt=Ql;D.generateCallbackId=Zl;D.parseParametersFromURL=rc;D.decodeJWT=uc;D.sleep=lc;D.retryable=cc;D.generatePKCEVerifier=po;D.generatePKCEChallenge=mo;D.getCodeChallengeAndMethod=fc;D.parseResponseAPIVersion=mc;D.validateExp=_c;D.getAlgorithm=gc;D.validateUUID=vc;D.userNotAvailableProxy=wc;D.insecureUserWarningProxy=bc;D.deepClone=Ec;var fo=sr(),ho=De(),$n=or();function Ql(t){return Math.round(Date.now()/1e3)+t}function Zl(){return Symbol("auth-callback")}var ec=()=>typeof window<"u"&&typeof document<"u";D.isBrowser=ec;var Fe={tested:!1,writable:!1},tc=()=>{if(!(0,D.isBrowser)())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Fe.tested)return Fe.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),Fe.tested=!0,Fe.writable=!0}catch{Fe.tested=!0,Fe.writable=!1}return Fe.writable};D.supportsLocalStorage=tc;function rc(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return r.searchParams.forEach((n,s)=>{e[s]=n}),e}var nc=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);D.resolveFetch=nc;var sc=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function";D.looksLikeFetchResponse=sc;var ic=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))};D.setItemAsync=ic;var oc=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}};D.getItemAsync=oc;var ac=async(t,e)=>{await t.removeItem(e)};D.removeItemAsync=ac;var ar=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};D.Deferred=ar;ar.promiseConstructor=Promise;function uc(t){let e=t.split(".");if(e.length!==3)throw new ho.AuthInvalidJwtError("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!fo.BASE64URL_REGEX.test(e[n]))throw new ho.AuthInvalidJwtError("JWT not in base64url format");return{header:JSON.parse((0,$n.stringFromBase64URL)(e[0])),payload:JSON.parse((0,$n.stringFromBase64URL)(e[1])),signature:(0,$n.base64UrlToUint8Array)(e[2]),raw:{header:e[0],payload:e[1]}}}async function lc(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function cc(t,e){return new Promise((n,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let o=await t(i);if(!e(i,null,o)){n(o);return}}catch(o){if(!e(i,o)){s(o);return}}})()})}function dc(t){return("0"+t.toString(16)).substr(-2)}function po(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length,s="";for(let i=0;i<56;i++)s+=r.charAt(Math.floor(Math.random()*n));return s}return crypto.getRandomValues(e),Array.from(e,dc).join("")}async function hc(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r),s=new Uint8Array(n);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function mo(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;let r=await hc(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function fc(t,e,r=!1){let n=po(),s=n;r&&(s+="/PASSWORD_RECOVERY"),await(0,D.setItemAsync)(t,`${e}-code-verifier`,s);let i=await mo(n);return[i,n===i?"plain":"s256"]}var pc=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function mc(t){let e=t.headers.get(fo.API_VERSION_HEADER_NAME);if(!e||!e.match(pc))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function _c(t){if(!t)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function gc(t){switch(t){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")}}var yc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function vc(t){if(!yc.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function wc(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let n=r.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function bc(t,e){return new Proxy(t,{get:(r,n,s)=>{if(n==="__isInsecureUserWarningProxy")return!0;if(typeof n=="symbol"){let i=n.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,n,s)}return!e.value&&typeof n=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(r,n,s)}})}function Ec(t){return JSON.parse(JSON.stringify(t))}});var Bn=$(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.handleError=Fn;Oe._request=Rc;Oe._sessionResponse=_o;Oe._sessionResponsePassword=Oc;Oe._userResponse=Cc;Oe._ssoResponse=Pc;Oe._generateLinkResponse=Ic;Oe._noResolveJsonResponse=xc;var Sc=(ge(),Se(_e)),ur=sr(),Dn=tt(),Le=De(),Be=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Tc=[502,503,504];async function Fn(t){var e;if(!(0,Dn.looksLikeFetchResponse)(t))throw new Le.AuthRetryableFetchError(Be(t),0);if(Tc.includes(t.status))throw new Le.AuthRetryableFetchError(Be(t),t.status);let r;try{r=await t.json()}catch(i){throw new Le.AuthUnknownError(Be(i),i)}let n,s=(0,Dn.parseResponseAPIVersion)(t);if(s&&s.getTime()>=ur.API_VERSIONS["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new Le.AuthWeakPasswordError(Be(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new Le.AuthSessionMissingError}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new Le.AuthWeakPasswordError(Be(r),t.status,r.weak_password.reasons);throw new Le.AuthApiError(Be(r),t.status||500,n)}var Ac=(t,e,r,n)=>{let s={method:t,headers:e?.headers||{}};return t==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),s.body=JSON.stringify(n),Object.assign(Object.assign({},s),r))};async function Rc(t,e,r,n){var s;let i=Object.assign({},n?.headers);i[ur.API_VERSION_HEADER_NAME]||(i[ur.API_VERSION_HEADER_NAME]=ur.API_VERSIONS["2024-01-01"].name),n?.jwt&&(i.Authorization=`Bearer ${n.jwt}`);let o=(s=n?.query)!==null&&s!==void 0?s:{};n?.redirectTo&&(o.redirect_to=n.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await kc(t,e,r+a,{headers:i,noResolveJson:n?.noResolveJson},{},n?.body);return n?.xform?n?.xform(l):{data:Object.assign({},l),error:null}}async function kc(t,e,r,n,s,i){let o=Ac(e,n,s,i),a;try{a=await t(r,Object.assign({},o))}catch(l){throw console.error(l),new Le.AuthRetryableFetchError(Be(l),0)}if(a.ok||await Fn(a),n?.noResolveJson)return a;try{return await a.json()}catch(l){await Fn(l)}}function _o(t){var e;let r=null;Nc(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=(0,Dn.expiresAt)(t.expires_in)));let n=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:n},error:null}}function Oc(t){let e=_o(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",!0)&&(e.data.weak_password=t.weak_password),e}function Cc(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Pc(t){return{data:t,error:null}}function Ic(t){let{action_link:e,email_otp:r,hashed_token:n,redirect_to:s,verification_type:i}=t,o=Sc.__rest(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:n,redirect_to:s,verification_type:i},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function xc(t){return t}function Nc(t){return t.access_token&&t.refresh_token&&t.expires_in}});var qn=$(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.SIGN_OUT_SCOPES=void 0;lr.SIGN_OUT_SCOPES=["global","local","others"]});var cr=$(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});var jc=(ge(),Se(_e)),Q=Bn(),qe=tt(),Mn=qn(),ce=De(),Wn=class{constructor({url:e="",headers:r={},fetch:n}){this.url=e,this.headers=r,this.fetch=(0,qe.resolveFetch)(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,r=Mn.SIGN_OUT_SCOPES[0]){if(Mn.SIGN_OUT_SCOPES.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Mn.SIGN_OUT_SCOPES.join(", ")}`);try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if((0,ce.isAuthError)(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,r={}){try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Q._userResponse})}catch(n){if((0,ce.isAuthError)(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:r}=e,n=jc.__rest(e,["options"]),s=Object.assign(Object.assign({},n),r);return"newEmail"in n&&(s.new_email=n?.newEmail,delete s.newEmail),await(0,Q._request)(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:Q._generateLinkResponse,redirectTo:r?.redirectTo})}catch(r){if((0,ce.isAuthError)(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Q._userResponse})}catch(r){if((0,ce.isAuthError)(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,n,s,i,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},h=await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Q._noResolveJsonResponse});if(h.error)throw h.error;let m=await h.json(),_=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(a=h.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(y=>{let v=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),w=JSON.parse(y.split(";")[1].split("=")[1]);c[`${w}Page`]=v}),c.total=parseInt(_)),{data:Object.assign(Object.assign({},m),c),error:null}}catch(c){if((0,ce.isAuthError)(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){(0,qe.validateUUID)(e);try{return await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Q._userResponse})}catch(r){if((0,ce.isAuthError)(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){(0,qe.validateUUID)(e);try{return await(0,Q._request)(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Q._userResponse})}catch(n){if((0,ce.isAuthError)(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,r=!1){(0,qe.validateUUID)(e);try{return await(0,Q._request)(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Q._userResponse})}catch(n){if((0,ce.isAuthError)(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){(0,qe.validateUUID)(e.userId);try{let{data:r,error:n}=await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:r,error:n}}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _deleteFactor(e){(0,qe.validateUUID)(e.userId),(0,qe.validateUUID)(e.id);try{return{data:await(0,Q._request)(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,n,s,i,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},h=await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Q._noResolveJsonResponse});if(h.error)throw h.error;let m=await h.json(),_=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(a=h.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(y=>{let v=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),w=JSON.parse(y.split(";")[1].split("=")[1]);c[`${w}Page`]=v}),c.total=parseInt(_)),{data:Object.assign(Object.assign({},m),c),error:null}}catch(c){if((0,ce.isAuthError)(c))return{data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await(0,Q._request)(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if((0,ce.isAuthError)(n))return{data:null,error:n};throw n}}async _deleteOAuthClient(e){try{return await(0,Q._request)(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}};Vn.default=Wn});var go=$(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.memoryLocalStorageAdapter=Lc;function Lc(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}});var Kn=$(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.ProcessLockAcquireTimeoutError=ue.NavigatorLockAcquireTimeoutError=ue.LockAcquireTimeoutError=ue.internals=void 0;ue.navigatorLock=$c;ue.processLock=Dc;var Uc=tt();ue.internals={debug:!!(globalThis&&(0,Uc.supportsLocalStorage)()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};var bt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}};ue.LockAcquireTimeoutError=bt;var Et=class extends bt{};ue.NavigatorLockAcquireTimeoutError=Et;var dr=class extends bt{};ue.ProcessLockAcquireTimeoutError=dr;async function $c(t,e,r){ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let n=new globalThis.AbortController;e>0&&setTimeout(()=>{n.abort(),ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async s=>{if(s){ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name)}}else{if(e===0)throw ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Et(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(ue.internals.debug)try{let i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}})}catch(s){throw s?.name==="AbortError"?new Et(`Acquiring an exclusive Navigator LockManager lock "${t}" timed out waiting ${e}ms`):s}}var yo={};async function Dc(t,e,r){var n;let s=(n=yo[t])!==null&&n!==void 0?n:Promise.resolve(),i=(async()=>{try{return await s,null}catch{return null}})(),o=(async()=>{let a=null;try{let l=e>=0?new Promise((c,h)=>{a=setTimeout(()=>{console.warn(`@supabase/gotrue-js: Lock "${t}" acquisition timed out after ${e}ms. This may be caused by another operation holding the lock. Consider increasing lockAcquireTimeout or checking for stuck operations.`),h(new dr(`Acquiring process lock with name "${t}" timed out`))},e)}):null;await Promise.race([i,l].filter(c=>c)),a!==null&&clearTimeout(a)}catch(l){if(a!==null&&clearTimeout(a),l&&l.isAcquireTimeout)throw l}return await r()})();return yo[t]=(async()=>{try{return await o}catch(a){if(a&&a.isAcquireTimeout){try{await s}catch{}return null}throw a}})(),await o}});var vo=$(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.polyfillGlobalThis=Fc;function Fc(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}});var bo=$(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.getAddress=wo;rt.fromHex=Bc;rt.toHex=qc;rt.createSiweMessage=Mc;function wo(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Bc(t){return parseInt(t,16)}function qc(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}function Mc(t){var e;let{chainId:r,domain:n,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:h,uri:m,version:_}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)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(!m)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(_!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${_}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
|
|
25
|
+
})`):new Error(`WebSocket not available: ${r}`)}this._setupConnectionHandlers()}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:this.vsn}))}disconnect(e,r){if(!this.isDisconnecting())if(this._setConnectionState("disconnecting",!0),this.conn){let n=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(n),this._setConnectionState("disconnected")},typeof this.conn.close=="function"&&(e?this.conn.close(e,r??""):this.conn.close()),this._teardownConnection()}else this._setConnectionState("disconnected")}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){let e=await Promise.all(this.channels.map(r=>r.unsubscribe()));return this.channels=[],this.disconnect(),e}log(e,r,n){this.logger(e,r,n)}connectionState(){switch(this.conn&&this.conn.readyState){case ne.SOCKET_STATES.connecting:return ne.CONNECTION_STATE.Connecting;case ne.SOCKET_STATES.open:return ne.CONNECTION_STATE.Open;case ne.SOCKET_STATES.closing:return ne.CONNECTION_STATE.Closing;default:return ne.CONNECTION_STATE.Closed}}isConnected(){return this.connectionState()===ne.CONNECTION_STATE.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,r={config:{}}){let n=`realtime:${e}`,s=this.getChannels().find(i=>i.topic===n);if(s)return s;{let i=new al.default(`realtime:${e}`,r,this);return this.channels.push(i),i}}push(e){let{topic:r,event:n,payload:s,ref:i}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${r} ${n} (${i})`,s),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(r){this.log("error","error in heartbeat callback",r)}return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this._heartbeatSentAt=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(r){this.log("error","error in heartbeat callback",r)}this._wasManualDisconnect=!1,(e=this.conn)===null||e===void 0||e.close(ne.WS_CLOSE_NORMAL,"heartbeat timeout"),setTimeout(()=>{var r;this.isConnected()||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout()},Xt.HEARTBEAT_TIMEOUT_FALLBACK);return}this._heartbeatSentAt=Date.now(),this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(r){this.log("error","error in heartbeat callback",r)}this._setAuthSafely("heartbeat")}onHeartbeat(e){this.heartbeatCallback=e}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let r=this.channels.find(n=>n.topic===e&&(n._isJoined()||n._isJoining()));r&&(this.log("transport",`leaving duplicate topic "${e}"`),r.unsubscribe())}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic)}_onConnMessage(e){this.decode(e.data,r=>{if(r.topic==="phoenix"&&r.event==="phx_reply"&&r.ref&&r.ref===this.pendingHeartbeatRef){let c=this._heartbeatSentAt?Date.now()-this._heartbeatSentAt:void 0;try{this.heartbeatCallback(r.payload.status==="ok"?"ok":"error",c)}catch(h){this.log("error","error in heartbeat callback",h)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}let{topic:n,event:s,payload:i,ref:o}=r,a=o?`(${o})`:"",l=i.status||"";this.log("receive",`${l} ${n} ${s} ${a}`.trim(),i),this.channels.filter(c=>c._isMember(n)).forEach(c=>c._trigger(s,i,o)),this._triggerStateCallbacks("message",r)})}_clearTimer(e){var r;e==="heartbeat"&&this.heartbeatTimer?(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0):e==="reconnect"&&((r=this.reconnectTimer)===null||r===void 0||r.reset())}_clearAllTimers(){this._clearTimer("heartbeat"),this._clearTimer("reconnect")}_setupConnectionHandlers(){this.conn&&("binaryType"in this.conn&&(this.conn.binaryType="arraybuffer"),this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e),this.conn.readyState===ne.SOCKET_STATES.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===ne.SOCKET_STATES.open||this.conn.readyState===ne.SOCKET_STATES.connecting)try{this.conn.close()}catch(e){this.log("error","Error closing connection",e)}this.conn.onopen=null,this.conn.onerror=null,this.conn.onmessage=null,this.conn.onclose=null,this.conn=null}this._clearAllTimers(),this._terminateWorker(),this.channels.forEach(e=>e.teardown())}_onConnOpen(){this._setConnectionState("connected"),this.log("transport",`connected to ${this.endpointURL()}`),(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).then(()=>{this.flushSendBuffer()}).catch(r=>{this.log("error","error waiting for auth on connect",r),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");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker()},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0)}_onConnClose(e){var r;this._setConnectionState("disconnected"),this.log("transport","close",e),this._triggerChanError(),this._clearTimer("heartbeat"),this._wasManualDisconnect||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout(),this._triggerStateCallbacks("close",e)}_onConnError(e){this._setConnectionState("disconnected"),this.log("transport",`${e}`),this._triggerChanError(),this._triggerStateCallbacks("error",e);try{this.heartbeatCallback("error")}catch(r){this.log("error","error in heartbeat callback",r)}}_triggerChanError(){this.channels.forEach(e=>e._trigger(ne.CHANNEL_EVENTS.error))}_appendParams(e,r){if(Object.keys(r).length===0)return e;let n=e.match(/\?/)?"&":"?",s=new URLSearchParams(r);return`${e}${n}${s}`}_workerObjectUrl(e){let r;if(e)r=e;else{let n=new Blob([cl],{type:"application/javascript"});r=URL.createObjectURL(n)}return r}_setConnectionState(e,r=!1){this._connectionState=e,e==="connecting"?this._wasManualDisconnect=!1:e==="disconnecting"&&(this._wasManualDisconnect=r)}async _performAuth(e=null){let r,n=!1;if(e)r=e,n=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(s){this.log("error","Error fetching access token from callback",s),r=this.accessTokenValue}else r=this.accessTokenValue;n?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(s=>{let i={access_token:r,version:ne.DEFAULT_VERSION};r&&s.updateJoinPayload(i),s.joinedOnce&&s._isJoined()&&s._push(ne.CHANNEL_EVENTS.access_token,{access_token:r})}))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r)})}_triggerStateCallbacks(e,r){try{this.stateChangeCallbacks[e].forEach(n=>{try{n(r)}catch(s){this.log("error",`error in ${e} callback`,s)}})}catch(n){this.log("error",`error triggering ${e} callbacks`,n)}}_setupReconnectionTimer(){this.reconnectTimer=new il.default(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},Xt.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var r,n,s,i,o,a,l,c,h,m,_,f;switch(this.transport=(r=e?.transport)!==null&&r!==void 0?r:null,this.timeout=(n=e?.timeout)!==null&&n!==void 0?n:ne.DEFAULT_TIMEOUT,this.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:Xt.HEARTBEAT_INTERVAL,this.worker=(i=e?.worker)!==null&&i!==void 0?i:!1,this.accessToken=(o=e?.accessToken)!==null&&o!==void 0?o:null,this.heartbeatCallback=(a=e?.heartbeatCallback)!==null&&a!==void 0?a:_n,this.vsn=(l=e?.vsn)!==null&&l!==void 0?l:ne.DEFAULT_VSN,e?.params&&(this.params=e.params),e?.logger&&(this.logger=e.logger),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),this.reconnectAfterMs=(c=e?.reconnectAfterMs)!==null&&c!==void 0?c:(y=>ul[y-1]||ll),this.vsn){case ne.VSN_1_0_0:this.encode=(h=e?.encode)!==null&&h!==void 0?h:((y,v)=>v(JSON.stringify(y))),this.decode=(m=e?.decode)!==null&&m!==void 0?m:((y,v)=>v(JSON.parse(y)));break;case ne.VSN_2_0_0:this.encode=(_=e?.encode)!==null&&_!==void 0?_:this.serializer.encode.bind(this.serializer),this.decode=(f=e?.decode)!==null&&f!==void 0?f:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl}}};yn.default=gn});var vn=$(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.WebSocketFactory=oe.REALTIME_CHANNEL_STATES=oe.REALTIME_SUBSCRIBE_STATES=oe.REALTIME_PRESENCE_LISTEN_EVENTS=oe.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=oe.REALTIME_LISTEN_TYPES=oe.RealtimeClient=oe.RealtimeChannel=oe.RealtimePresence=void 0;var Zt=(ge(),Se(_e)),dl=Zt.__importDefault(Qi());oe.RealtimeClient=dl.default;var pt=Zt.__importStar(mn());oe.RealtimeChannel=pt.default;Object.defineProperty(oe,"REALTIME_LISTEN_TYPES",{enumerable:!0,get:function(){return pt.REALTIME_LISTEN_TYPES}});Object.defineProperty(oe,"REALTIME_POSTGRES_CHANGES_LISTEN_EVENT",{enumerable:!0,get:function(){return pt.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT}});Object.defineProperty(oe,"REALTIME_SUBSCRIBE_STATES",{enumerable:!0,get:function(){return pt.REALTIME_SUBSCRIBE_STATES}});Object.defineProperty(oe,"REALTIME_CHANNEL_STATES",{enumerable:!0,get:function(){return pt.REALTIME_CHANNEL_STATES}});var Zi=Zt.__importStar(hn());oe.RealtimePresence=Zi.default;Object.defineProperty(oe,"REALTIME_PRESENCE_LISTEN_EVENTS",{enumerable:!0,get:function(){return Zi.REALTIME_PRESENCE_LISTEN_EVENTS}});var hl=Zt.__importDefault(tn());oe.WebSocketFactory=hl.default});var Sn=$(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.version=void 0;sr.version="2.97.0"});var ir=$(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.JWKS_TTL=K.BASE64URL_REGEX=K.API_VERSIONS=K.API_VERSION_HEADER_NAME=K.NETWORK_FAILURE=K.DEFAULT_HEADERS=K.AUDIENCE=K.STORAGE_KEY=K.GOTRUE_URL=K.EXPIRY_MARGIN_MS=K.AUTO_REFRESH_TICK_THRESHOLD=K.AUTO_REFRESH_TICK_DURATION_MS=void 0;var ql=Sn();K.AUTO_REFRESH_TICK_DURATION_MS=30*1e3;K.AUTO_REFRESH_TICK_THRESHOLD=3;K.EXPIRY_MARGIN_MS=K.AUTO_REFRESH_TICK_THRESHOLD*K.AUTO_REFRESH_TICK_DURATION_MS;K.GOTRUE_URL="http://localhost:9999";K.STORAGE_KEY="supabase.auth.token";K.AUDIENCE="";K.DEFAULT_HEADERS={"X-Client-Info":`gotrue-js/${ql.version}`};K.NETWORK_FAILURE={MAX_RETRIES:10,RETRY_INTERVAL:2};K.API_VERSION_HEADER_NAME="X-Supabase-Api-Version";K.API_VERSIONS={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};K.BASE64URL_REGEX=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;K.JWKS_TTL=600*1e3});var De=$(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.AuthInvalidJwtError=F.AuthWeakPasswordError=F.AuthRetryableFetchError=F.AuthPKCECodeVerifierMissingError=F.AuthPKCEGrantCodeExchangeError=F.AuthImplicitGrantRedirectError=F.AuthInvalidCredentialsError=F.AuthInvalidTokenResponseError=F.AuthSessionMissingError=F.CustomAuthError=F.AuthUnknownError=F.AuthApiError=F.AuthError=void 0;F.isAuthError=$e;F.isAuthApiError=Ml;F.isAuthSessionMissingError=Wl;F.isAuthImplicitGrantRedirectError=Vl;F.isAuthPKCECodeVerifierMissingError=Hl;F.isAuthRetryableFetchError=Kl;F.isAuthWeakPasswordError=zl;var et=class extends Error{constructor(e,r,n){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=n}};F.AuthError=et;function $e(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var Tn=class extends et{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n}};F.AuthApiError=Tn;function Ml(t){return $e(t)&&t.name==="AuthApiError"}var An=class extends et{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}};F.AuthUnknownError=An;var ve=class extends et{constructor(e,r,n,s){super(e,n,s),this.name=r,this.status=n}};F.CustomAuthError=ve;var Rn=class extends ve{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};F.AuthSessionMissingError=Rn;function Wl(t){return $e(t)&&t.name==="AuthSessionMissingError"}var kn=class extends ve{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}};F.AuthInvalidTokenResponseError=kn;var On=class extends ve{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}};F.AuthInvalidCredentialsError=On;var Pn=class extends ve{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};F.AuthImplicitGrantRedirectError=Pn;function Vl(t){return $e(t)&&t.name==="AuthImplicitGrantRedirectError"}var Cn=class extends ve{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}};F.AuthPKCEGrantCodeExchangeError=Cn;var In=class extends ve{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}};F.AuthPKCECodeVerifierMissingError=In;function Hl(t){return $e(t)&&t.name==="AuthPKCECodeVerifierMissingError"}var xn=class extends ve{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};F.AuthRetryableFetchError=xn;function Kl(t){return $e(t)&&t.name==="AuthRetryableFetchError"}var Nn=class extends ve{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n}};F.AuthWeakPasswordError=Nn;function zl(t){return $e(t)&&t.name==="AuthWeakPasswordError"}var jn=class extends ve{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};F.AuthInvalidJwtError=jn});var ar=$(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.byteToBase64URL=wt;we.byteFromBase64URL=Ln;we.stringToBase64URL=Jl;we.stringFromBase64URL=Yl;we.codepointToUTF8=lo;we.stringToUTF8=Un;we.stringFromUTF8=co;we.base64UrlToUint8Array=Xl;we.stringToUint8Array=Ql;we.bytesToBase64URL=Zl;var or="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),uo=`
|
|
26
|
+
\r=`.split(""),Gl=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<uo.length;e+=1)t[uo[e].charCodeAt(0)]=-2;for(let e=0;e<or.length;e+=1)t[or[e].charCodeAt(0)]=e;return t})();function wt(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(or[n]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(or[n]),e.queuedBits-=6}}function Ln(t,e,r){let n=Gl[t];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function Jl(t){let e=[],r=s=>{e.push(s)},n={queue:0,queuedBits:0};return Un(t,s=>{wt(s,n,r)}),wt(null,n,r),e.join("")}function Yl(t){let e=[],r=o=>{e.push(String.fromCodePoint(o))},n={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},i=o=>{co(o,n,r)};for(let o=0;o<t.length;o+=1)Ln(t.charCodeAt(o),s,i);return e.join("")}function lo(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function Un(t,e){for(let r=0;r<t.length;r+=1){let n=t.charCodeAt(r);if(n>55295&&n<=56319){let s=(n-55296)*1024&65535;n=(t.charCodeAt(r+1)-56320&65535|s)+65536,r+=1}lo(n,e)}}function co(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let n=1;n<6;n+=1)if((t>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint)}}function Xl(t){let e=[],r={queue:0,queuedBits:0},n=s=>{e.push(s)};for(let s=0;s<t.length;s+=1)Ln(t.charCodeAt(s),r,n);return new Uint8Array(e)}function Ql(t){let e=[];return Un(t,r=>e.push(r)),new Uint8Array(e)}function Zl(t){let e=[],r={queue:0,queuedBits:0},n=s=>{e.push(s)};return t.forEach(s=>wt(s,r,n)),wt(null,r,n),e.join("")}});var tt=$(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.Deferred=D.removeItemAsync=D.getItemAsync=D.setItemAsync=D.looksLikeFetchResponse=D.resolveFetch=D.supportsLocalStorage=D.isBrowser=void 0;D.expiresAt=ec;D.generateCallbackId=tc;D.parseParametersFromURL=sc;D.decodeJWT=cc;D.sleep=dc;D.retryable=hc;D.generatePKCEVerifier=po;D.generatePKCEChallenge=mo;D.getCodeChallengeAndMethod=mc;D.parseResponseAPIVersion=gc;D.validateExp=yc;D.getAlgorithm=vc;D.validateUUID=bc;D.userNotAvailableProxy=Ec;D.insecureUserWarningProxy=Sc;D.deepClone=Tc;var fo=ir(),ho=De(),$n=ar();function ec(t){return Math.round(Date.now()/1e3)+t}function tc(){return Symbol("auth-callback")}var rc=()=>typeof window<"u"&&typeof document<"u";D.isBrowser=rc;var Fe={tested:!1,writable:!1},nc=()=>{if(!(0,D.isBrowser)())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Fe.tested)return Fe.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),Fe.tested=!0,Fe.writable=!0}catch{Fe.tested=!0,Fe.writable=!1}return Fe.writable};D.supportsLocalStorage=nc;function sc(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((s,i)=>{e[i]=s})}catch{}return r.searchParams.forEach((n,s)=>{e[s]=n}),e}var ic=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);D.resolveFetch=ic;var oc=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function";D.looksLikeFetchResponse=oc;var ac=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))};D.setItemAsync=ac;var uc=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}};D.getItemAsync=uc;var lc=async(t,e)=>{await t.removeItem(e)};D.removeItemAsync=lc;var ur=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};D.Deferred=ur;ur.promiseConstructor=Promise;function cc(t){let e=t.split(".");if(e.length!==3)throw new ho.AuthInvalidJwtError("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!fo.BASE64URL_REGEX.test(e[n]))throw new ho.AuthInvalidJwtError("JWT not in base64url format");return{header:JSON.parse((0,$n.stringFromBase64URL)(e[0])),payload:JSON.parse((0,$n.stringFromBase64URL)(e[1])),signature:(0,$n.base64UrlToUint8Array)(e[2]),raw:{header:e[0],payload:e[1]}}}async function dc(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function hc(t,e){return new Promise((n,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let o=await t(i);if(!e(i,null,o)){n(o);return}}catch(o){if(!e(i,o)){s(o);return}}})()})}function fc(t){return("0"+t.toString(16)).substr(-2)}function po(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length,s="";for(let i=0;i<56;i++)s+=r.charAt(Math.floor(Math.random()*n));return s}return crypto.getRandomValues(e),Array.from(e,fc).join("")}async function pc(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r),s=new Uint8Array(n);return Array.from(s).map(i=>String.fromCharCode(i)).join("")}async function mo(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;let r=await pc(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function mc(t,e,r=!1){let n=po(),s=n;r&&(s+="/PASSWORD_RECOVERY"),await(0,D.setItemAsync)(t,`${e}-code-verifier`,s);let i=await mo(n);return[i,n===i?"plain":"s256"]}var _c=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function gc(t){let e=t.headers.get(fo.API_VERSION_HEADER_NAME);if(!e||!e.match(_c))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function yc(t){if(!t)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function vc(t){switch(t){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")}}var wc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function bc(t){if(!wc.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Ec(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let n=r.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Sc(t,e){return new Proxy(t,{get:(r,n,s)=>{if(n==="__isInsecureUserWarningProxy")return!0;if(typeof n=="symbol"){let i=n.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,n,s)}return!e.value&&typeof n=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=!0),Reflect.get(r,n,s)}})}function Tc(t){return JSON.parse(JSON.stringify(t))}});var Bn=$(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.handleError=Fn;Oe._request=Oc;Oe._sessionResponse=_o;Oe._sessionResponsePassword=Cc;Oe._userResponse=Ic;Oe._ssoResponse=xc;Oe._generateLinkResponse=Nc;Oe._noResolveJsonResponse=jc;var Ac=(ge(),Se(_e)),lr=ir(),Dn=tt(),Le=De(),Be=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Rc=[502,503,504];async function Fn(t){var e;if(!(0,Dn.looksLikeFetchResponse)(t))throw new Le.AuthRetryableFetchError(Be(t),0);if(Rc.includes(t.status))throw new Le.AuthRetryableFetchError(Be(t),t.status);let r;try{r=await t.json()}catch(i){throw new Le.AuthUnknownError(Be(i),i)}let n,s=(0,Dn.parseResponseAPIVersion)(t);if(s&&s.getTime()>=lr.API_VERSIONS["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new Le.AuthWeakPasswordError(Be(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new Le.AuthSessionMissingError}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((i,o)=>i&&typeof o=="string",!0))throw new Le.AuthWeakPasswordError(Be(r),t.status,r.weak_password.reasons);throw new Le.AuthApiError(Be(r),t.status||500,n)}var kc=(t,e,r,n)=>{let s={method:t,headers:e?.headers||{}};return t==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),s.body=JSON.stringify(n),Object.assign(Object.assign({},s),r))};async function Oc(t,e,r,n){var s;let i=Object.assign({},n?.headers);i[lr.API_VERSION_HEADER_NAME]||(i[lr.API_VERSION_HEADER_NAME]=lr.API_VERSIONS["2024-01-01"].name),n?.jwt&&(i.Authorization=`Bearer ${n.jwt}`);let o=(s=n?.query)!==null&&s!==void 0?s:{};n?.redirectTo&&(o.redirect_to=n.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Pc(t,e,r+a,{headers:i,noResolveJson:n?.noResolveJson},{},n?.body);return n?.xform?n?.xform(l):{data:Object.assign({},l),error:null}}async function Pc(t,e,r,n,s,i){let o=kc(e,n,s,i),a;try{a=await t(r,Object.assign({},o))}catch(l){throw console.error(l),new Le.AuthRetryableFetchError(Be(l),0)}if(a.ok||await Fn(a),n?.noResolveJson)return a;try{return await a.json()}catch(l){await Fn(l)}}function _o(t){var e;let r=null;Lc(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=(0,Dn.expiresAt)(t.expires_in)));let n=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:n},error:null}}function Cc(t){let e=_o(t);return!e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",!0)&&(e.data.weak_password=t.weak_password),e}function Ic(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function xc(t){return{data:t,error:null}}function Nc(t){let{action_link:e,email_otp:r,hashed_token:n,redirect_to:s,verification_type:i}=t,o=Ac.__rest(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:n,redirect_to:s,verification_type:i},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function jc(t){return t}function Lc(t){return t.access_token&&t.refresh_token&&t.expires_in}});var qn=$(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.SIGN_OUT_SCOPES=void 0;cr.SIGN_OUT_SCOPES=["global","local","others"]});var dr=$(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});var Uc=(ge(),Se(_e)),Q=Bn(),qe=tt(),Mn=qn(),ce=De(),Wn=class{constructor({url:e="",headers:r={},fetch:n}){this.url=e,this.headers=r,this.fetch=(0,qe.resolveFetch)(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,r=Mn.SIGN_OUT_SCOPES[0]){if(Mn.SIGN_OUT_SCOPES.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Mn.SIGN_OUT_SCOPES.join(", ")}`);try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if((0,ce.isAuthError)(n))return{data:null,error:n};throw n}}async inviteUserByEmail(e,r={}){try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Q._userResponse})}catch(n){if((0,ce.isAuthError)(n))return{data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:r}=e,n=Uc.__rest(e,["options"]),s=Object.assign(Object.assign({},n),r);return"newEmail"in n&&(s.new_email=n?.newEmail,delete s.newEmail),await(0,Q._request)(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:Q._generateLinkResponse,redirectTo:r?.redirectTo})}catch(r){if((0,ce.isAuthError)(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Q._userResponse})}catch(r){if((0,ce.isAuthError)(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,n,s,i,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},h=await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Q._noResolveJsonResponse});if(h.error)throw h.error;let m=await h.json(),_=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(a=h.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(y=>{let v=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),w=JSON.parse(y.split(";")[1].split("=")[1]);c[`${w}Page`]=v}),c.total=parseInt(_)),{data:Object.assign(Object.assign({},m),c),error:null}}catch(c){if((0,ce.isAuthError)(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){(0,qe.validateUUID)(e);try{return await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Q._userResponse})}catch(r){if((0,ce.isAuthError)(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){(0,qe.validateUUID)(e);try{return await(0,Q._request)(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Q._userResponse})}catch(n){if((0,ce.isAuthError)(n))return{data:{user:null},error:n};throw n}}async deleteUser(e,r=!1){(0,qe.validateUUID)(e);try{return await(0,Q._request)(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Q._userResponse})}catch(n){if((0,ce.isAuthError)(n))return{data:{user:null},error:n};throw n}}async _listFactors(e){(0,qe.validateUUID)(e.userId);try{let{data:r,error:n}=await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:r,error:n}}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _deleteFactor(e){(0,qe.validateUUID)(e.userId),(0,qe.validateUUID)(e.id);try{return{data:await(0,Q._request)(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,n,s,i,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},h=await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(i=(s=e?.perPage)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""},xform:Q._noResolveJsonResponse});if(h.error)throw h.error;let m=await h.json(),_=(o=h.headers.get("x-total-count"))!==null&&o!==void 0?o:0,f=(l=(a=h.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return f.length>0&&(f.forEach(y=>{let v=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),w=JSON.parse(y.split(";")[1].split("=")[1]);c[`${w}Page`]=v}),c.total=parseInt(_)),{data:Object.assign(Object.assign({},m),c),error:null}}catch(c){if((0,ce.isAuthError)(c))return{data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await(0,Q._request)(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await(0,Q._request)(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if((0,ce.isAuthError)(n))return{data:null,error:n};throw n}}async _deleteOAuthClient(e){try{return await(0,Q._request)(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await(0,Q._request)(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if((0,ce.isAuthError)(r))return{data:null,error:r};throw r}}};Vn.default=Wn});var go=$(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.memoryLocalStorageAdapter=$c;function $c(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}});var Kn=$(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.ProcessLockAcquireTimeoutError=ue.NavigatorLockAcquireTimeoutError=ue.LockAcquireTimeoutError=ue.internals=void 0;ue.navigatorLock=Fc;ue.processLock=Bc;var Dc=tt();ue.internals={debug:!!(globalThis&&(0,Dc.supportsLocalStorage)()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};var bt=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}};ue.LockAcquireTimeoutError=bt;var Et=class extends bt{};ue.NavigatorLockAcquireTimeoutError=Et;var hr=class extends bt{};ue.ProcessLockAcquireTimeoutError=hr;async function Fc(t,e,r){ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let n=new globalThis.AbortController;e>0&&setTimeout(()=>{n.abort(),ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t)},e),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async s=>{if(s){ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name)}}else{if(e===0)throw ue.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Et(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(ue.internals.debug)try{let i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()}})}catch(s){throw s?.name==="AbortError"?new Et(`Acquiring an exclusive Navigator LockManager lock "${t}" timed out waiting ${e}ms`):s}}var yo={};async function Bc(t,e,r){var n;let s=(n=yo[t])!==null&&n!==void 0?n:Promise.resolve(),i=(async()=>{try{return await s,null}catch{return null}})(),o=(async()=>{let a=null;try{let l=e>=0?new Promise((c,h)=>{a=setTimeout(()=>{console.warn(`@supabase/gotrue-js: Lock "${t}" acquisition timed out after ${e}ms. This may be caused by another operation holding the lock. Consider increasing lockAcquireTimeout or checking for stuck operations.`),h(new hr(`Acquiring process lock with name "${t}" timed out`))},e)}):null;await Promise.race([i,l].filter(c=>c)),a!==null&&clearTimeout(a)}catch(l){if(a!==null&&clearTimeout(a),l&&l.isAcquireTimeout)throw l}return await r()})();return yo[t]=(async()=>{try{return await o}catch(a){if(a&&a.isAcquireTimeout){try{await s}catch{}return null}throw a}})(),await o}});var vo=$(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.polyfillGlobalThis=qc;function qc(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}});var bo=$(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.getAddress=wo;rt.fromHex=Mc;rt.toHex=Wc;rt.createSiweMessage=Vc;function wo(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Mc(t){return parseInt(t,16)}function Wc(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}function Vc(t){var e;let{chainId:r,domain:n,expirationTime:s,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:h,uri:m,version:_}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)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(!m)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(_!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${_}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
|
|
27
27
|
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}let f=wo(t.address),y=h?`${h}://${n}`:n,v=t.statement?`${t.statement}
|
|
28
28
|
`:"",w=`${y} wants you to sign in with your Ethereum account:
|
|
29
29
|
${f}
|
|
@@ -38,8 +38,8 @@ Not Before: ${a.toISOString()}`),l&&(T+=`
|
|
|
38
38
|
Request ID: ${l}`),c){let O=`
|
|
39
39
|
Resources:`;for(let E of c){if(!E||typeof E!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${E}`);O+=`
|
|
40
40
|
- ${E}`}T+=O}return`${w}
|
|
41
|
-
${T}`}});var So=$(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.WebAuthnUnknownError=Ne.WebAuthnError=void 0;Ne.isWebAuthnError=Wc;Ne.identifyRegistrationError=Vc;Ne.identifyAuthenticationError=Hc;var Eo=Jn(),te=class extends Error{constructor({message:e,code:r,cause:n,name:s}){var i;super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=(i=s??(n instanceof Error?n.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}};Ne.WebAuthnError=te;var Gn=class extends te{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};Ne.WebAuthnUnknownError=Gn;function Wc(t){return typeof t=="object"&&t!==null&&"__isWebAuthnError"in t}function Vc({error:t,options:e}){var r,n,s;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new te({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new te({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new te({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new te({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new te({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new te({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new te({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new te({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if((0,Eo.isValidDomain)(o)){if(i.rp.id!==o)return new te({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new te({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new te({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new te({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new te({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Hc({error:t,options:e}){let{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new te({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new te({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let n=window.location.hostname;if((0,Eo.isValidDomain)(n)){if(r.rpId!==n)return new te({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new te({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new te({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new te({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}});var Jn=$(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.WebAuthnApi=M.DEFAULT_REQUEST_OPTIONS=M.DEFAULT_CREATION_OPTIONS=M.webAuthnAbortService=M.WebAuthnAbortService=M.identifyAuthenticationError=M.identifyRegistrationError=M.isWebAuthnError=M.WebAuthnError=void 0;M.deserializeCredentialCreationOptions=zc;M.deserializeCredentialRequestOptions=Gc;M.serializeCredentialCreationResponse=Jc;M.serializeCredentialRequestResponse=Yc;M.isValidDomain=Xc;M.createCredential=Ro;M.getCredential=ko;M.mergeCredentialCreationOptions=Oo;M.mergeCredentialRequestOptions=Co;var Ao=(ge(),Se(_e)),Re=or(),Ce=De(),Kc=tt(),Pe=So();Object.defineProperty(M,"identifyAuthenticationError",{enumerable:!0,get:function(){return Pe.identifyAuthenticationError}});Object.defineProperty(M,"identifyRegistrationError",{enumerable:!0,get:function(){return Pe.identifyRegistrationError}});Object.defineProperty(M,"isWebAuthnError",{enumerable:!0,get:function(){return Pe.isWebAuthnError}});Object.defineProperty(M,"WebAuthnError",{enumerable:!0,get:function(){return Pe.WebAuthnError}});var hr=class{createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};M.WebAuthnAbortService=hr;M.webAuthnAbortService=new hr;function zc(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);let{challenge:e,user:r,excludeCredentials:n}=t,s=Ao.__rest(t,["challenge","user","excludeCredentials"]),i=(0,Re.base64UrlToUint8Array)(e).buffer,o=Object.assign(Object.assign({},r),{id:(0,Re.base64UrlToUint8Array)(r.id).buffer}),a=Object.assign(Object.assign({},s),{challenge:i,user:o});if(n&&n.length>0){a.excludeCredentials=new Array(n.length);for(let l=0;l<n.length;l++){let c=n[l];a.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:(0,Re.base64UrlToUint8Array)(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return a}function Gc(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);let{challenge:e,allowCredentials:r}=t,n=Ao.__rest(t,["challenge","allowCredentials"]),s=(0,Re.base64UrlToUint8Array)(e).buffer,i=Object.assign(Object.assign({},n),{challenge:s});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){let a=r[o];i.allowCredentials[o]=Object.assign(Object.assign({},a),{id:(0,Re.base64UrlToUint8Array)(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return i}function Jc(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t;return{id:t.id,rawId:t.id,response:{attestationObject:(0,Re.bytesToBase64URL)(new Uint8Array(t.response.attestationObject)),clientDataJSON:(0,Re.bytesToBase64URL)(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Yc(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,n=t.getClientExtensionResults(),s=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:(0,Re.bytesToBase64URL)(new Uint8Array(s.authenticatorData)),clientDataJSON:(0,Re.bytesToBase64URL)(new Uint8Array(s.clientDataJSON)),signature:(0,Re.bytesToBase64URL)(new Uint8Array(s.signature)),userHandle:s.userHandle?(0,Re.bytesToBase64URL)(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Xc(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function To(){var t,e;return!!((0,Kc.isBrowser)()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function Ro(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Pe.WebAuthnUnknownError("Browser returned unexpected credential type",e)}:{data:null,error:new Pe.WebAuthnUnknownError("Empty credential response",e)}}catch(e){return{data:null,error:(0,Pe.identifyRegistrationError)({error:e,options:t})}}}async function ko(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Pe.WebAuthnUnknownError("Browser returned unexpected credential type",e)}:{data:null,error:new Pe.WebAuthnUnknownError("Empty credential response",e)}}catch(e){return{data:null,error:(0,Pe.identifyAuthenticationError)({error:e,options:t})}}}M.DEFAULT_CREATION_OPTIONS={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"};M.DEFAULT_REQUEST_OPTIONS={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function fr(...t){let e=s=>s!==null&&typeof s=="object"&&!Array.isArray(s),r=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),n={};for(let s of t)if(s)for(let i in s){let o=s[i];if(o!==void 0)if(Array.isArray(o))n[i]=o;else if(r(o))n[i]=o;else if(e(o)){let a=n[i];e(a)?n[i]=fr(a,o):n[i]=fr(o)}else n[i]=o}return n}function Oo(t,e){return fr(M.DEFAULT_CREATION_OPTIONS,t,e||{})}function Co(t,e){return fr(M.DEFAULT_REQUEST_OPTIONS,t,e||{})}var Yn=class{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:r,friendlyName:n,signal:s},i){var o;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:l};let c=s??M.webAuthnAbortService.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:h}=a.webauthn.credential_options.publicKey;if(!h.name){let m=n;if(m)h.name=`${h.id}:${m}`;else{let f=(await this.client.getUser()).data.user,y=((o=f?.user_metadata)===null||o===void 0?void 0:o.name)||f?.email||f?.id||"User";h.name=`${h.id}:${y}`}}h.displayName||(h.displayName=h.name)}switch(a.webauthn.type){case"create":{let h=Oo(a.webauthn.credential_options.publicKey,i?.create),{data:m,error:_}=await Ro({publicKey:h,signal:c});return m?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:m}},error:null}:{data:null,error:_}}case"request":{let h=Co(a.webauthn.credential_options.publicKey,i?.request),{data:m,error:_}=await ko(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:h,signal:c}));return m?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:m}},error:null}:{data:null,error:_}}}}catch(a){return(0,Ce.isAuthError)(a)?{data:null,error:a}:{data:null,error:new Ce.AuthUnknownError("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:n}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!r)return{data:null,error:new Ce.AuthError("rpId is required for WebAuthn authentication")};try{if(!To())return{data:null,error:new Ce.AuthUnknownError("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:n},signal:s},{request:i});if(!o)return{data:null,error:a};let{webauthn:l}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:n,credential_response:l.credential_response}})}catch(o){return(0,Ce.isAuthError)(o)?{data:null,error:o}:{data:null,error:new Ce.AuthUnknownError("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!r)return{data:null,error:new Ce.AuthError("rpId is required for WebAuthn registration")};try{if(!To())return{data:null,error:new Ce.AuthUnknownError("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(h=>{var m;return(m=h.data)===null||m===void 0?void 0:m.all.find(_=>_.factor_type==="webauthn"&&_.friendly_name===e&&_.status!=="unverified")}).then(h=>h?this.client.mfa.unenroll({factorId:h?.id}):void 0),{data:null,error:a};let{data:l,error:c}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:n},signal:s},{create:i});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:n,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(o){return(0,Ce.isAuthError)(o)?{data:null,error:o}:{data:null,error:new Ce.AuthUnknownError("Unexpected error in register",o)}}}};M.WebAuthnApi=Yn});var Qn=$(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});var Qc=(ge(),Se(_e)),Zc=Qc.__importDefault(cr()),pe=sr(),S=De(),I=Bn(),R=tt(),Po=go(),Io=Kn(),ed=vo(),td=Sn(),xo=or(),pr=bo(),St=Jn();(0,ed.polyfillGlobalThis)();var rd={url:pe.GOTRUE_URL,storageKey:pe.STORAGE_KEY,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:pe.DEFAULT_HEADERS,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4,skipAutoInitialize:!1};async function No(t,e,r){return await r()}var nt={},mr=class t{get jwks(){var e,r;return(r=(e=nt[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){nt[this.storageKey]=Object.assign(Object.assign({},nt[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=nt[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){nt[this.storageKey]=Object.assign(Object.assign({},nt[this.storageKey]),{cachedAt:e})}constructor(e){var r,n,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},rd),e);if(this.storageKey=i.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&(0,R.isBrowser)()){let o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new Zc.default({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=(0,R.resolveFetch)(i.fetch),this.lock=i.lock||No,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&(0,R.isBrowser)()&&(!((n=globalThis?.navigator)===null||n===void 0)&&n.locks)?this.lock=Io.navigatorLock:this.lock=No,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 St.WebAuthnApi(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:(0,R.supportsLocalStorage)()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=(0,Po.memoryLocalStorageAdapter)(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=(0,Po.memoryLocalStorageAdapter)(this.memoryStorage)),(0,R.isBrowser)()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${td.version}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},n="none";if((0,R.isBrowser)()&&(r=(0,R.parseParametersFromURL)(window.location.href),this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce")),(0,R.isBrowser)()&&this.detectSessionInUrl&&n!=="none"){let{data:s,error:i}=await this._getSessionFromURL(r,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),(0,S.isAuthImplicitGrantRedirectError)(i)){let l=(e=i.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:o,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return(0,S.isAuthError)(r)?this._returnResult({error:r}):this._returnResult({error:new S.AuthUnknownError("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,s;try{let i=await(0,I._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:I._sessionResponse}),{data:o,error:a}=i;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if((0,S.isAuthError)(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,n,s;try{let i;if("email"in e){let{email:h,password:m,options:_}=e,f=null,y=null;this.flowType==="pkce"&&([f,y]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey)),i=await(0,I._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:_?.emailRedirectTo,body:{email:h,password:m,data:(r=_?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:_?.captchaToken},code_challenge:f,code_challenge_method:y},xform:I._sessionResponse})}else if("phone"in e){let{phone:h,password:m,options:_}=e;i=await(0,I._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:m,data:(n=_?.data)!==null&&n!==void 0?n:{},channel:(s=_?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:_?.captchaToken}},xform:I._sessionResponse})}else throw new S.AuthInvalidCredentialsError("You must provide either an email or phone number and a password");let{data:o,error:a}=i;if(a||!o)return await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let r;if("email"in e){let{email:i,password:o,options:a}=e;r=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:I._sessionResponsePassword})}else if("phone"in e){let{phone:i,password:o,options:a}=e;r=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:I._sessionResponsePassword})}else throw new S.AuthInvalidCredentialsError("You must provide either an email or phone number and a password");let{data:n,error:s}=r;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!n||!n.session||!n.user){let i=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:i})}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:s})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,n,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,n,s,i,o,a,l,c,h,m,_;let f,y;if("message"in e)f=e.message,y=e.signature;else{let{chain:v,wallet:w,statement:T,options:O}=e,E;if((0,R.isBrowser)())if(typeof w=="object")E=w;else{let Ee=window;if("ethereum"in Ee&&typeof Ee.ethereum=="object"&&"request"in Ee.ethereum&&typeof Ee.ethereum.request=="function")E=Ee.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof w!="object"||!O?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");E=w}let x=new URL((r=O?.url)!==null&&r!==void 0?r:window.location.href),Z=await E.request({method:"eth_requestAccounts"}).then(Ee=>Ee).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!Z||Z.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let W=(0,pr.getAddress)(Z[0]),re=(n=O?.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!re){let Ee=await E.request({method:"eth_chainId"});re=(0,pr.fromHex)(Ee)}let ke={domain:x.host,address:W,statement:T,uri:x.href,version:"1",chainId:re,nonce:(s=O?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=O?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=O?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=O?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=O?.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(h=O?.signInWithEthereum)===null||h===void 0?void 0:h.resources};f=(0,pr.createSiweMessage)(ke),y=await E.request({method:"personal_sign",params:[(0,pr.toHex)(f),W]})}try{let{data:v,error:w}=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:y},!((m=e.options)===null||m===void 0)&&m.captchaToken?{gotrue_meta_security:{captcha_token:(_=e.options)===null||_===void 0?void 0:_.captchaToken}}:null),xform:I._sessionResponse});if(w)throw w;if(!v||!v.session||!v.user){let T=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:T})}return v.session&&(await this._saveSession(v.session),await this._notifyAllSubscribers("SIGNED_IN",v.session)),this._returnResult({data:Object.assign({},v),error:w})}catch(v){if((0,S.isAuthError)(v))return this._returnResult({data:{user:null,session:null},error:v});throw v}}async signInWithSolana(e){var r,n,s,i,o,a,l,c,h,m,_,f;let y,v;if("message"in e)y=e.message,v=e.signature;else{let{chain:w,wallet:T,statement:O,options:E}=e,x;if((0,R.isBrowser)())if(typeof T=="object")x=T;else{let W=window;if("solana"in W&&typeof W.solana=="object"&&("signIn"in W.solana&&typeof W.solana.signIn=="function"||"signMessage"in W.solana&&typeof W.solana.signMessage=="function"))x=W.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof T!="object"||!E?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");x=T}let Z=new URL((r=E?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in x&&x.signIn){let W=await x.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},E?.signInWithSolana),{version:"1",domain:Z.host,uri:Z.href}),O?{statement:O}:null)),re;if(Array.isArray(W)&&W[0]&&typeof W[0]=="object")re=W[0];else if(W&&typeof W=="object"&&"signedMessage"in W&&"signature"in W)re=W;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in re&&"signature"in re&&(typeof re.signedMessage=="string"||re.signedMessage instanceof Uint8Array)&&re.signature instanceof Uint8Array)y=typeof re.signedMessage=="string"?re.signedMessage:new TextDecoder().decode(re.signedMessage),v=re.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in x)||typeof x.signMessage!="function"||!("publicKey"in x)||typeof x!="object"||!x.publicKey||!("toBase58"in x.publicKey)||typeof x.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");y=[`${Z.host} wants you to sign in with your Solana account:`,x.publicKey.toBase58(),...O?["",O,""]:[""],"Version: 1",`URI: ${Z.href}`,`Issued At: ${(s=(n=E?.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=E?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${E.signInWithSolana.notBefore}`]:[],...!((o=E?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${E.signInWithSolana.expirationTime}`]:[],...!((a=E?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${E.signInWithSolana.chainId}`]:[],...!((l=E?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${E.signInWithSolana.nonce}`]:[],...!((c=E?.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${E.signInWithSolana.requestId}`]:[],...!((m=(h=E?.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||m===void 0)&&m.length?["Resources",...E.signInWithSolana.resources.map(re=>`- ${re}`)]:[]].join(`
|
|
42
|
-
`);let W=await x.signMessage(new TextEncoder().encode(y),"utf8");if(!W||!(W instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=W}}try{let{data:w,error:T}=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:y,signature:(0,xo.bytesToBase64URL)(v)},!((_=e.options)===null||_===void 0)&&_.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:I._sessionResponse});if(T)throw T;if(!w||!w.session||!w.user){let O=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:O})}return w.session&&(await this._saveSession(w.session),await this._notifyAllSubscribers("SIGNED_IN",w.session)),this._returnResult({data:Object.assign({},w),error:T})}catch(w){if((0,S.isAuthError)(w))return this._returnResult({data:{user:null,session:null},error:w});throw w}}async _exchangeCodeForSession(e){let r=await(0,R.getItemAsync)(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(r??"").split("/");try{if(!n&&this.flowType==="pkce")throw new S.AuthPKCECodeVerifierMissingError;let{data:i,error:o}=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:I._sessionResponse});if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){let a=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:s??null}),error:o})}catch(i){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{let{options:r,provider:n,token:s,access_token:i,nonce:o}=e,a=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:I._sessionResponse}),{data:l,error:c}=a;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){let h=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:h})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:c})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,s,i,o;try{if("email"in e){let{email:a,options:l}=e,c=null,h=null;this.flowType==="pkce"&&([c,h]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey));let{error:m}=await(0,I._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:h},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:m})}if("phone"in e){let{phone:a,options:l}=e,{data:c,error:h}=await(0,I._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(s=l?.data)!==null&&s!==void 0?s:{},create_user:(i=l?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c?.message_id},error:h})}throw new S.AuthInvalidCredentialsError("You must provide either an email or phone number.")}catch(a){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,n;try{let s,i;"options"in e&&(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:o,error:a}=await(0,I._request)(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:I._sessionResponse});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,c=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(s){if((0,S.isAuthError)(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var r,n,s,i,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey));let c=await(0,I._request)(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((s=e?.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:I._ssoResponse});return!((i=c.data)===null||i===void 0)&&i.url&&(0,R.isBrowser)()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(a){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new S.AuthSessionMissingError;let{error:s}=await(0,I._request)(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if((0,S.isAuthError)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let r=`${this.url}/resend`;if("email"in e){let{email:n,type:s,options:i}=e,{error:o}=await(0,I._request)(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:s,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){let{phone:n,type:s,options:i}=e,{data:o,error:a}=await(0,I._request)(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:s,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:a})}throw new S.AuthInvalidCredentialsError("You must provide either an email or phone number and a type")}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let r=await this.__loadSession();return await e(r)}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,r=await(0,R.getItemAsync)(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()<pe.EXPIRY_MARGIN_MS:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){let o=await(0,R.getItemAsync)(this.userStorage,this.storageKey+"-user");o?.user?e.user=o.user:e.user=(0,R.userNotAvailableProxy)()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=(0,R.insecureUserWarningProxy)(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await(0,I._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:I._userResponse}):await this._useSession(async r=>{var n,s,i;let{data:o,error:a}=r;if(a)throw a;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new S.AuthSessionMissingError}:await(0,I._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:I._userResponse})})}catch(r){if((0,S.isAuthError)(r))return(0,S.isAuthSessionMissingError)(r)&&(await this._removeSession(),await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async n=>{let{data:s,error:i}=n;if(i)throw i;if(!s.session)throw new S.AuthSessionMissingError;let o=s.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey));let{data:c,error:h}=await(0,I._request)(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:I._userResponse});if(h)throw h;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new S.AuthSessionMissingError;let r=Date.now()/1e3,n=r,s=!0,i=null,{payload:o}=(0,R.decodeJWT)(e.access_token);if(o.exp&&(n=o.exp,s=n<=r),s){let{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};i=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});i={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:n-r,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(r){if((0,S.isAuthError)(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var n;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!e?.refresh_token)throw new S.AuthSessionMissingError;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!(0,R.isBrowser)())throw new S.AuthImplicitGrantRedirectError("No browser detected.");if(e.error||e.error_description||e.error_code)throw new S.AuthImplicitGrantRedirectError(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new S.AuthPKCEGrantCodeExchangeError("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new S.AuthImplicitGrantRedirectError("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new S.AuthPKCEGrantCodeExchangeError("No code detected.");let{data:O,error:E}=await this._exchangeCodeForSession(e.code);if(E)throw E;let x=new URL(window.location.href);return x.searchParams.delete("code"),window.history.replaceState(window.history.state,"",x.toString()),{data:{session:O.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:s,access_token:i,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!i||!a||!o||!c)throw new S.AuthImplicitGrantRedirectError("No session defined in URL");let h=Math.round(Date.now()/1e3),m=parseInt(a),_=h+m;l&&(_=parseInt(l));let f=_-h;f*1e3<=pe.AUTO_REFRESH_TICK_DURATION_MS&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${m}s`);let y=_-m;h-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,_,h):h-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",y,_,h);let{data:v,error:w}=await this._getUser(i);if(w)throw w;let T={provider_token:n,provider_refresh_token:s,access_token:i,expires_in:m,expires_at:_,refresh_token:o,token_type:c,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:T,redirectType:e.type},error:null})}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let r=await(0,R.getItemAsync)(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var n;let{data:s,error:i}=r;if(i&&!(0,S.isAuthSessionMissingError)(i))return this._returnResult({error:i});let o=(n=s.session)===null||n===void 0?void 0:n.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!((0,S.isAuthApiError)(a)&&(a.status===404||a.status===401||a.status===403)||(0,S.isAuthSessionMissingError)(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=(0,R.generateCallbackId)(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,s;try{let{data:{session:i},error:o}=r;if(o)throw o;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,r={}){let n=null,s=null;this.flowType==="pkce"&&([n,s]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey,!0));try{return await(0,I._request)(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:s,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{let{data:r,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{let{data:n,error:s}=await this._useSession(async i=>{var o,a,l,c,h;let{data:m,error:_}=i;if(_)throw _;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await(0,I._request)(this.fetch,"GET",f,{headers:this.headers,jwt:(h=(c=m.session)===null||c===void 0?void 0:c.access_token)!==null&&h!==void 0?h:void 0})});if(s)throw s;return(0,R.isBrowser)()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url},error:null})}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var n;try{let{error:s,data:{session:i}}=r;if(s)throw s;let{options:o,provider:a,token:l,access_token:c,nonce:h}=e,m=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=i?.access_token)!==null&&n!==void 0?n:void 0,body:{provider:a,id_token:l,access_token:c,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:I._sessionResponse}),{data:_,error:f}=m;return f?this._returnResult({data:{user:null,session:null},error:f}):!_||!_.session||!_.user?this._returnResult({data:{user:null,session:null},error:new S.AuthInvalidTokenResponseError}):(_.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("USER_UPDATED",_.session)),this._returnResult({data:_,error:f}))}catch(s){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,s;let{data:i,error:o}=r;if(o)throw o;return await(0,I._request)(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{let n=Date.now();return await(0,R.retryable)(async s=>(s>0&&await(0,R.sleep)(200*Math.pow(2,s-1)),this._debug(r,"refreshing attempt",s),await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:I._sessionResponse})),(s,i)=>{let o=200*Math.pow(2,s);return i&&(0,S.isAuthRetryableFetchError)(i)&&Date.now()+o-n<pe.AUTO_REFRESH_TICK_DURATION_MS})}catch(n){if(this._debug(r,"error",n),(0,S.isAuthError)(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){let n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",n),(0,R.isBrowser)()&&!r.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,r;let n="#_recoverAndRefresh()";this._debug(n,"begin");try{let s=await(0,R.getItemAsync)(this.storage,this.storageKey);if(s&&this.userStorage){let o=await(0,R.getItemAsync)(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:s.user},await(0,R.setItemAsync)(this.userStorage,this.storageKey+"-user",o)),s.user=(e=o?.user)!==null&&e!==void 0?e:(0,R.userNotAvailableProxy)()}else if(s&&!s.user&&!s.user){let o=await(0,R.getItemAsync)(this.storage,this.storageKey+"-user");o&&o?.user?(s.user=o.user,await(0,R.removeItemAsync)(this.storage,this.storageKey+"-user"),await(0,R.setItemAsync)(this.storage,this.storageKey,s)):s.user=(0,R.userNotAvailableProxy)()}if(this._debug(n,"session from storage",s),!this._isValidSession(s)){this._debug(n,"session is not valid"),s!==null&&await this._removeSession();return}let i=((r=s.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<pe.EXPIRY_MARGIN_MS;if(this._debug(n,`session has${i?"":" not"} expired with margin of ${pe.EXPIRY_MARGIN_MS}s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),(0,S.isAuthRetryableFetchError)(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(s.user&&s.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:a}=await this._getUser(s.access_token);!a&&o?.user?(s.user=o.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(n,"error",s),console.error(s);return}finally{this._debug(n,"end")}}async _callRefreshToken(e){var r,n;if(!e)throw new S.AuthSessionMissingError;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new R.Deferred;let{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new S.AuthSessionMissingError;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let a={data:i.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(i){if(this._debug(s,"error",i),(0,S.isAuthError)(i)){let o={data:null,error:i};return(0,S.isAuthRetryableFetchError)(i)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,r,n=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(l){i.push(l)}});if(await Promise.all(o),i.length>0){for(let a=0;a<i.length;a+=1)console.error(i[a]);throw i[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),n=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&r.user&&await(0,R.setItemAsync)(this.userStorage,this.storageKey+"-user",{user:r.user});let s=Object.assign({},r);delete s.user;let i=(0,R.deepClone)(s);await(0,R.setItemAsync)(this.storage,this.storageKey,i)}else{let s=(0,R.deepClone)(r);await(0,R.setItemAsync)(this.storage,this.storageKey,s)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await(0,R.removeItemAsync)(this.storage,this.storageKey),await(0,R.removeItemAsync)(this.storage,this.storageKey+"-code-verifier"),await(0,R.removeItemAsync)(this.storage,this.storageKey+"-user"),this.userStorage&&await(0,R.removeItemAsync)(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&(0,R.isBrowser)()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),pe.AUTO_REFRESH_TICK_DURATION_MS);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async r=>{let{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((n.expires_at*1e3-e)/pe.AUTO_REFRESH_TICK_DURATION_MS);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${pe.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${pe.AUTO_REFRESH_TICK_THRESHOLD} ticks`),s<=pe.AUTO_REFRESH_TICK_THRESHOLD&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Io.LockAcquireTimeoutError)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!(0,R.isBrowser)()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,n){let s=[`provider=${encodeURIComponent(r)}`];if(n?.redirectTo&&s.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n?.scopes&&s.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){let[i,o]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});s.push(a.toString())}if(n?.queryParams){let i=new URLSearchParams(n.queryParams);s.push(i.toString())}return n?.skipBrowserRedirect&&s.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;let{data:s,error:i}=r;return i?this._returnResult({data:null,error:i}):await(0,I._request)(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await(0,I._request)(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((s=l?.totp)===null||s===void 0)&&s.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;let{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});let o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?(0,St.serializeCredentialCreationResponse)(e.webauthn.credential_response):(0,St.serializeCredentialRequestResponse)(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await(0,I._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:l}))})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;let{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});let o=await(0,I._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;let{data:a}=o;if(a.type!=="webauthn")return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:(0,St.deserializeCredentialCreationOptions)(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:(0,St.deserializeCredentialRequestOptions)(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:n}=await this.getUser();if(n)return{data:null,error:n};let s={all:[],phone:[],totp:[],webauthn:[]};for(let i of(e=r?.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,n,s,i;if(e)try{let{payload:f}=(0,R.decodeJWT)(e),y=null;f.aal&&(y=f.aal);let v=y,{data:{user:w},error:T}=await this.getUser(e);if(T)return this._returnResult({data:null,error:T});((n=(r=w?.factors)===null||r===void 0?void 0:r.filter(x=>x.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(v="aal2");let E=f.amr||[];return{data:{currentLevel:y,nextLevel:v,currentAuthenticationMethods:E},error:null}}catch(f){if((0,S.isAuthError)(f))return this._returnResult({data:null,error:f});throw f}let{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=(0,R.decodeJWT)(o.access_token),c=null;l.aal&&(c=l.aal);let h=c;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(f=>f.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(h="aal2");let _=l.amr||[];return{data:{currentLevel:c,nextLevel:h,currentAuthenticationMethods:_},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:n},error:s}=r;return s?this._returnResult({data:null,error:s}):n?await(0,I._request)(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new S.AuthSessionMissingError})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new S.AuthSessionMissingError});let o=await(0,I._request)(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&(0,R.isBrowser)()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new S.AuthSessionMissingError});let o=await(0,I._request)(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&(0,R.isBrowser)()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;return n?this._returnResult({data:null,error:n}):r?await(0,I._request)(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new S.AuthSessionMissingError})})}catch(e){if((0,S.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:n},error:s}=r;return s?this._returnResult({data:null,error:s}):n?(await(0,I._request)(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 S.AuthSessionMissingError})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(a=>a.kid===e);if(n)return n;let s=Date.now();if(n=this.jwks.keys.find(a=>a.kid===e),n&&this.jwks_cached_at+pe.JWKS_TTL>s)return n;let{data:i,error:o}=await(0,I._request)(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,n=i.keys.find(a=>a.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){let{data:f,error:y}=await this.getSession();if(y||!f.session)return this._returnResult({data:null,error:y});n=f.session.access_token}let{header:s,payload:i,signature:o,raw:{header:a,payload:l}}=(0,R.decodeJWT)(n);r?.allowExpired||(0,R.validateExp)(i.exp);let c=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!c){let{error:f}=await this.getUser(n);if(f)throw f;return{data:{claims:i,header:s,signature:o},error:null}}let h=(0,R.getAlgorithm)(s.alg),m=await crypto.subtle.importKey("jwk",c,h,!0,["verify"]);if(!await crypto.subtle.verify(h,m,o,(0,xo.stringToUint8Array)(`${a}.${l}`)))throw new S.AuthInvalidJwtError("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:null,error:n});throw n}}};mr.nextInstanceID={};Xn.default=mr});var jo=$(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});var nd=(ge(),Se(_e)),sd=nd.__importDefault(cr()),id=sd.default;Zn.default=id});var Lo=$(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});var od=(ge(),Se(_e)),ad=od.__importDefault(Qn()),ud=ad.default;es.default=ud});var ts=$(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.processLock=ae.lockInternals=ae.NavigatorLockAcquireTimeoutError=ae.navigatorLock=ae.AuthClient=ae.AuthAdminApi=ae.GoTrueClient=ae.GoTrueAdminApi=void 0;var st=(ge(),Se(_e)),ld=st.__importDefault(cr());ae.GoTrueAdminApi=ld.default;var cd=st.__importDefault(Qn());ae.GoTrueClient=cd.default;var dd=st.__importDefault(jo());ae.AuthAdminApi=dd.default;var hd=st.__importDefault(Lo());ae.AuthClient=hd.default;st.__exportStar(qn(),ae);st.__exportStar(De(),ae);var _r=Kn();Object.defineProperty(ae,"navigatorLock",{enumerable:!0,get:function(){return _r.navigatorLock}});Object.defineProperty(ae,"NavigatorLockAcquireTimeoutError",{enumerable:!0,get:function(){return _r.NavigatorLockAcquireTimeoutError}});Object.defineProperty(ae,"lockInternals",{enumerable:!0,get:function(){return _r.internals}});Object.defineProperty(ae,"processLock",{enumerable:!0,get:function(){return _r.processLock}})});var la=$(L=>{"use strict";var kt=Symbol.for("react.element"),Fd=Symbol.for("react.portal"),Bd=Symbol.for("react.fragment"),qd=Symbol.for("react.strict_mode"),Md=Symbol.for("react.profiler"),Wd=Symbol.for("react.provider"),Vd=Symbol.for("react.context"),Hd=Symbol.for("react.forward_ref"),Kd=Symbol.for("react.suspense"),zd=Symbol.for("react.memo"),Gd=Symbol.for("react.lazy"),Qo=Symbol.iterator;function Jd(t){return t===null||typeof t!="object"?null:(t=Qo&&t[Qo]||t["@@iterator"],typeof t=="function"?t:null)}var ta={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},ra=Object.assign,na={};function it(t,e,r){this.props=t,this.context=e,this.refs=na,this.updater=r||ta}it.prototype.isReactComponent={};it.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};it.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function sa(){}sa.prototype=it.prototype;function os(t,e,r){this.props=t,this.context=e,this.refs=na,this.updater=r||ta}var as=os.prototype=new sa;as.constructor=os;ra(as,it.prototype);as.isPureReactComponent=!0;var Zo=Array.isArray,ia=Object.prototype.hasOwnProperty,us={current:null},oa={key:!0,ref:!0,__self:!0,__source:!0};function aa(t,e,r){var n,s={},i=null,o=null;if(e!=null)for(n in e.ref!==void 0&&(o=e.ref),e.key!==void 0&&(i=""+e.key),e)ia.call(e,n)&&!oa.hasOwnProperty(n)&&(s[n]=e[n]);var a=arguments.length-2;if(a===1)s.children=r;else if(1<a){for(var l=Array(a),c=0;c<a;c++)l[c]=arguments[c+2];s.children=l}if(t&&t.defaultProps)for(n in a=t.defaultProps,a)s[n]===void 0&&(s[n]=a[n]);return{$$typeof:kt,type:t,key:i,ref:o,props:s,_owner:us.current}}function Yd(t,e){return{$$typeof:kt,type:t.type,key:e,ref:t.ref,props:t.props,_owner:t._owner}}function ls(t){return typeof t=="object"&&t!==null&&t.$$typeof===kt}function Xd(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(r){return e[r]})}var ea=/\/+/g;function is(t,e){return typeof t=="object"&&t!==null&&t.key!=null?Xd(""+t.key):e.toString(36)}function Er(t,e,r,n,s){var i=typeof t;(i==="undefined"||i==="boolean")&&(t=null);var o=!1;if(t===null)o=!0;else switch(i){case"string":case"number":o=!0;break;case"object":switch(t.$$typeof){case kt:case Fd:o=!0}}if(o)return o=t,s=s(o),t=n===""?"."+is(o,0):n,Zo(s)?(r="",t!=null&&(r=t.replace(ea,"$&/")+"/"),Er(s,e,r,"",function(c){return c})):s!=null&&(ls(s)&&(s=Yd(s,r+(!s.key||o&&o.key===s.key?"":(""+s.key).replace(ea,"$&/")+"/")+t)),e.push(s)),1;if(o=0,n=n===""?".":n+":",Zo(t))for(var a=0;a<t.length;a++){i=t[a];var l=n+is(i,a);o+=Er(i,e,r,l,s)}else if(l=Jd(t),typeof l=="function")for(t=l.call(t),a=0;!(i=t.next()).done;)i=i.value,l=n+is(i,a++),o+=Er(i,e,r,l,s);else if(i==="object")throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.");return o}function br(t,e,r){if(t==null)return t;var n=[],s=0;return Er(t,n,"","",function(i){return e.call(r,i,s++)}),n}function Qd(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(r){(t._status===0||t._status===-1)&&(t._status=1,t._result=r)},function(r){(t._status===0||t._status===-1)&&(t._status=2,t._result=r)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var he={current:null},Sr={transition:null},Zd={ReactCurrentDispatcher:he,ReactCurrentBatchConfig:Sr,ReactCurrentOwner:us};function ua(){throw Error("act(...) is not supported in production builds of React.")}L.Children={map:br,forEach:function(t,e,r){br(t,function(){e.apply(this,arguments)},r)},count:function(t){var e=0;return br(t,function(){e++}),e},toArray:function(t){return br(t,function(e){return e})||[]},only:function(t){if(!ls(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};L.Component=it;L.Fragment=Bd;L.Profiler=Md;L.PureComponent=os;L.StrictMode=qd;L.Suspense=Kd;L.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Zd;L.act=ua;L.cloneElement=function(t,e,r){if(t==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+t+".");var n=ra({},t.props),s=t.key,i=t.ref,o=t._owner;if(e!=null){if(e.ref!==void 0&&(i=e.ref,o=us.current),e.key!==void 0&&(s=""+e.key),t.type&&t.type.defaultProps)var a=t.type.defaultProps;for(l in e)ia.call(e,l)&&!oa.hasOwnProperty(l)&&(n[l]=e[l]===void 0&&a!==void 0?a[l]:e[l])}var l=arguments.length-2;if(l===1)n.children=r;else if(1<l){a=Array(l);for(var c=0;c<l;c++)a[c]=arguments[c+2];n.children=a}return{$$typeof:kt,type:t.type,key:s,ref:i,props:n,_owner:o}};L.createContext=function(t){return t={$$typeof:Vd,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},t.Provider={$$typeof:Wd,_context:t},t.Consumer=t};L.createElement=aa;L.createFactory=function(t){var e=aa.bind(null,t);return e.type=t,e};L.createRef=function(){return{current:null}};L.forwardRef=function(t){return{$$typeof:Hd,render:t}};L.isValidElement=ls;L.lazy=function(t){return{$$typeof:Gd,_payload:{_status:-1,_result:t},_init:Qd}};L.memo=function(t,e){return{$$typeof:zd,type:t,compare:e===void 0?null:e}};L.startTransition=function(t){var e=Sr.transition;Sr.transition={};try{t()}finally{Sr.transition=e}};L.unstable_act=ua;L.useCallback=function(t,e){return he.current.useCallback(t,e)};L.useContext=function(t){return he.current.useContext(t)};L.useDebugValue=function(){};L.useDeferredValue=function(t){return he.current.useDeferredValue(t)};L.useEffect=function(t,e){return he.current.useEffect(t,e)};L.useId=function(){return he.current.useId()};L.useImperativeHandle=function(t,e,r){return he.current.useImperativeHandle(t,e,r)};L.useInsertionEffect=function(t,e){return he.current.useInsertionEffect(t,e)};L.useLayoutEffect=function(t,e){return he.current.useLayoutEffect(t,e)};L.useMemo=function(t,e){return he.current.useMemo(t,e)};L.useReducer=function(t,e,r){return he.current.useReducer(t,e,r)};L.useRef=function(t){return he.current.useRef(t)};L.useState=function(t){return he.current.useState(t)};L.useSyncExternalStore=function(t,e,r){return he.current.useSyncExternalStore(t,e,r)};L.useTransition=function(){return he.current.useTransition()};L.version="18.3.1"});var ca=$((U,Tr)=>{"use strict";process.env.NODE_ENV!=="production"&&(function(){"use strict";typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var t="18.3.1",e=Symbol.for("react.element"),r=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),o=Symbol.for("react.provider"),a=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),h=Symbol.for("react.suspense_list"),m=Symbol.for("react.memo"),_=Symbol.for("react.lazy"),f=Symbol.for("react.offscreen"),y=Symbol.iterator,v="@@iterator";function w(u){if(u===null||typeof u!="object")return null;var d=y&&u[y]||u[v];return typeof d=="function"?d:null}var T={current:null},O={transition:null},E={current:null,isBatchingLegacy:!1,didScheduleLegacyUpdate:!1},x={current:null},Z={},W=null;function re(u){W=u}Z.setExtraStackFrame=function(u){W=u},Z.getCurrentStack=null,Z.getStackAddendum=function(){var u="";W&&(u+=W);var d=Z.getCurrentStack;return d&&(u+=d()||""),u};var ke=!1,Ee=!1,_a=!1,ga=!1,ya=!1,Me={ReactCurrentDispatcher:T,ReactCurrentBatchConfig:O,ReactCurrentOwner:x};Me.ReactDebugCurrentFrame=Z,Me.ReactCurrentActQueue=E;function We(u){{for(var d=arguments.length,p=new Array(d>1?d-1:0),g=1;g<d;g++)p[g-1]=arguments[g];ds("warn",u,p)}}function q(u){{for(var d=arguments.length,p=new Array(d>1?d-1:0),g=1;g<d;g++)p[g-1]=arguments[g];ds("error",u,p)}}function ds(u,d,p){{var g=Me.ReactDebugCurrentFrame,b=g.getStackAddendum();b!==""&&(d+="%s",p=p.concat([b]));var N=p.map(function(C){return String(C)});N.unshift("Warning: "+d),Function.prototype.apply.call(console[u],console,N)}}var hs={};function Rr(u,d){{var p=u.constructor,g=p&&(p.displayName||p.name)||"ReactClass",b=g+"."+d;if(hs[b])return;q("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",d,g),hs[b]=!0}}var fs={isMounted:function(u){return!1},enqueueForceUpdate:function(u,d,p){Rr(u,"forceUpdate")},enqueueReplaceState:function(u,d,p,g){Rr(u,"replaceState")},enqueueSetState:function(u,d,p,g){Rr(u,"setState")}},Ie=Object.assign,kr={};Object.freeze(kr);function Ue(u,d,p){this.props=u,this.context=d,this.refs=kr,this.updater=p||fs}Ue.prototype.isReactComponent={},Ue.prototype.setState=function(u,d){if(typeof u!="object"&&typeof u!="function"&&u!=null)throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,u,d,"setState")},Ue.prototype.forceUpdate=function(u){this.updater.enqueueForceUpdate(this,u,"forceUpdate")};{var Or={isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]},va=function(u,d){Object.defineProperty(Ue.prototype,u,{get:function(){We("%s(...) is deprecated in plain JavaScript React classes. %s",d[0],d[1])}})};for(var Cr in Or)Or.hasOwnProperty(Cr)&&va(Cr,Or[Cr])}function ps(){}ps.prototype=Ue.prototype;function Pr(u,d,p){this.props=u,this.context=d,this.refs=kr,this.updater=p||fs}var Ir=Pr.prototype=new ps;Ir.constructor=Pr,Ie(Ir,Ue.prototype),Ir.isPureReactComponent=!0;function wa(){var u={current:null};return Object.seal(u),u}var ba=Array.isArray;function Ot(u){return ba(u)}function Ea(u){{var d=typeof Symbol=="function"&&Symbol.toStringTag,p=d&&u[Symbol.toStringTag]||u.constructor.name||"Object";return p}}function Sa(u){try{return ms(u),!1}catch{return!0}}function ms(u){return""+u}function Ct(u){if(Sa(u))return q("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",Ea(u)),ms(u)}function Ta(u,d,p){var g=u.displayName;if(g)return g;var b=d.displayName||d.name||"";return b!==""?p+"("+b+")":p}function _s(u){return u.displayName||"Context"}function je(u){if(u==null)return null;if(typeof u.tag=="number"&&q("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof u=="function")return u.displayName||u.name||null;if(typeof u=="string")return u;switch(u){case n:return"Fragment";case r:return"Portal";case i:return"Profiler";case s:return"StrictMode";case c:return"Suspense";case h:return"SuspenseList"}if(typeof u=="object")switch(u.$$typeof){case a:var d=u;return _s(d)+".Consumer";case o:var p=u;return _s(p._context)+".Provider";case l:return Ta(u,u.render,"ForwardRef");case m:var g=u.displayName||null;return g!==null?g:je(u.type)||"Memo";case _:{var b=u,N=b._payload,C=b._init;try{return je(C(N))}catch{return null}}}return null}var ot=Object.prototype.hasOwnProperty,gs={key:!0,ref:!0,__self:!0,__source:!0},ys,vs,xr;xr={};function ws(u){if(ot.call(u,"ref")){var d=Object.getOwnPropertyDescriptor(u,"ref").get;if(d&&d.isReactWarning)return!1}return u.ref!==void 0}function bs(u){if(ot.call(u,"key")){var d=Object.getOwnPropertyDescriptor(u,"key").get;if(d&&d.isReactWarning)return!1}return u.key!==void 0}function Aa(u,d){var p=function(){ys||(ys=!0,q("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",d))};p.isReactWarning=!0,Object.defineProperty(u,"key",{get:p,configurable:!0})}function Ra(u,d){var p=function(){vs||(vs=!0,q("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",d))};p.isReactWarning=!0,Object.defineProperty(u,"ref",{get:p,configurable:!0})}function ka(u){if(typeof u.ref=="string"&&x.current&&u.__self&&x.current.stateNode!==u.__self){var d=je(x.current.type);xr[d]||(q('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref',d,u.ref),xr[d]=!0)}}var Nr=function(u,d,p,g,b,N,C){var j={$$typeof:e,type:u,key:d,ref:p,props:C,_owner:N};return j._store={},Object.defineProperty(j._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(j,"_self",{configurable:!1,enumerable:!1,writable:!1,value:g}),Object.defineProperty(j,"_source",{configurable:!1,enumerable:!1,writable:!1,value:b}),Object.freeze&&(Object.freeze(j.props),Object.freeze(j)),j};function Oa(u,d,p){var g,b={},N=null,C=null,j=null,B=null;if(d!=null){ws(d)&&(C=d.ref,ka(d)),bs(d)&&(Ct(d.key),N=""+d.key),j=d.__self===void 0?null:d.__self,B=d.__source===void 0?null:d.__source;for(g in d)ot.call(d,g)&&!gs.hasOwnProperty(g)&&(b[g]=d[g])}var z=arguments.length-2;if(z===1)b.children=p;else if(z>1){for(var Y=Array(z),X=0;X<z;X++)Y[X]=arguments[X+2];Object.freeze&&Object.freeze(Y),b.children=Y}if(u&&u.defaultProps){var ee=u.defaultProps;for(g in ee)b[g]===void 0&&(b[g]=ee[g])}if(N||C){var ie=typeof u=="function"?u.displayName||u.name||"Unknown":u;N&&Aa(b,ie),C&&Ra(b,ie)}return Nr(u,N,C,j,B,x.current,b)}function Ca(u,d){var p=Nr(u.type,d,u.ref,u._self,u._source,u._owner,u.props);return p}function Pa(u,d,p){if(u==null)throw new Error("React.cloneElement(...): The argument must be a React element, but you passed "+u+".");var g,b=Ie({},u.props),N=u.key,C=u.ref,j=u._self,B=u._source,z=u._owner;if(d!=null){ws(d)&&(C=d.ref,z=x.current),bs(d)&&(Ct(d.key),N=""+d.key);var Y;u.type&&u.type.defaultProps&&(Y=u.type.defaultProps);for(g in d)ot.call(d,g)&&!gs.hasOwnProperty(g)&&(d[g]===void 0&&Y!==void 0?b[g]=Y[g]:b[g]=d[g])}var X=arguments.length-2;if(X===1)b.children=p;else if(X>1){for(var ee=Array(X),ie=0;ie<X;ie++)ee[ie]=arguments[ie+2];b.children=ee}return Nr(u.type,N,C,j,B,z,b)}function Ve(u){return typeof u=="object"&&u!==null&&u.$$typeof===e}var Es=".",Ia=":";function xa(u){var d=/[=:]/g,p={"=":"=0",":":"=2"},g=u.replace(d,function(b){return p[b]});return"$"+g}var Ss=!1,Na=/\/+/g;function Ts(u){return u.replace(Na,"$&/")}function jr(u,d){return typeof u=="object"&&u!==null&&u.key!=null?(Ct(u.key),xa(""+u.key)):d.toString(36)}function Pt(u,d,p,g,b){var N=typeof u;(N==="undefined"||N==="boolean")&&(u=null);var C=!1;if(u===null)C=!0;else switch(N){case"string":case"number":C=!0;break;case"object":switch(u.$$typeof){case e:case r:C=!0}}if(C){var j=u,B=b(j),z=g===""?Es+jr(j,0):g;if(Ot(B)){var Y="";z!=null&&(Y=Ts(z)+"/"),Pt(B,d,Y,"",function(Au){return Au})}else B!=null&&(Ve(B)&&(B.key&&(!j||j.key!==B.key)&&Ct(B.key),B=Ca(B,p+(B.key&&(!j||j.key!==B.key)?Ts(""+B.key)+"/":"")+z)),d.push(B));return 1}var X,ee,ie=0,le=g===""?Es:g+Ia;if(Ot(u))for(var Dt=0;Dt<u.length;Dt++)X=u[Dt],ee=le+jr(X,Dt),ie+=Pt(X,d,p,ee,b);else{var Wr=w(u);if(typeof Wr=="function"){var Js=u;Wr===Js.entries&&(Ss||We("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Ss=!0);for(var Su=Wr.call(Js),Ys,Tu=0;!(Ys=Su.next()).done;)X=Ys.value,ee=le+jr(X,Tu++),ie+=Pt(X,d,p,ee,b)}else if(N==="object"){var Xs=String(u);throw new Error("Objects are not valid as a React child (found: "+(Xs==="[object Object]"?"object with keys {"+Object.keys(u).join(", ")+"}":Xs)+"). If you meant to render a collection of children, use an array instead.")}}return ie}function It(u,d,p){if(u==null)return u;var g=[],b=0;return Pt(u,g,"","",function(N){return d.call(p,N,b++)}),g}function ja(u){var d=0;return It(u,function(){d++}),d}function La(u,d,p){It(u,function(){d.apply(this,arguments)},p)}function Ua(u){return It(u,function(d){return d})||[]}function $a(u){if(!Ve(u))throw new Error("React.Children.only expected to receive a single React element child.");return u}function Da(u){var d={$$typeof:a,_currentValue:u,_currentValue2:u,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};d.Provider={$$typeof:o,_context:d};var p=!1,g=!1,b=!1;{var N={$$typeof:a,_context:d};Object.defineProperties(N,{Provider:{get:function(){return g||(g=!0,q("Rendering <Context.Consumer.Provider> is not supported and will be removed in a future major release. Did you mean to render <Context.Provider> instead?")),d.Provider},set:function(C){d.Provider=C}},_currentValue:{get:function(){return d._currentValue},set:function(C){d._currentValue=C}},_currentValue2:{get:function(){return d._currentValue2},set:function(C){d._currentValue2=C}},_threadCount:{get:function(){return d._threadCount},set:function(C){d._threadCount=C}},Consumer:{get:function(){return p||(p=!0,q("Rendering <Context.Consumer.Consumer> is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?")),d.Consumer}},displayName:{get:function(){return d.displayName},set:function(C){b||(We("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.",C),b=!0)}}}),d.Consumer=N}return d._currentRenderer=null,d._currentRenderer2=null,d}var at=-1,Lr=0,As=1,Fa=2;function Ba(u){if(u._status===at){var d=u._result,p=d();if(p.then(function(N){if(u._status===Lr||u._status===at){var C=u;C._status=As,C._result=N}},function(N){if(u._status===Lr||u._status===at){var C=u;C._status=Fa,C._result=N}}),u._status===at){var g=u;g._status=Lr,g._result=p}}if(u._status===As){var b=u._result;return b===void 0&&q(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
41
|
+
${T}`}});var So=$(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.WebAuthnUnknownError=Ne.WebAuthnError=void 0;Ne.isWebAuthnError=Hc;Ne.identifyRegistrationError=Kc;Ne.identifyAuthenticationError=zc;var Eo=Jn(),te=class extends Error{constructor({message:e,code:r,cause:n,name:s}){var i;super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=(i=s??(n instanceof Error?n.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}};Ne.WebAuthnError=te;var Gn=class extends te{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};Ne.WebAuthnUnknownError=Gn;function Hc(t){return typeof t=="object"&&t!==null&&"__isWebAuthnError"in t}function Kc({error:t,options:e}){var r,n,s;let{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new te({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new te({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new te({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new te({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new te({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new te({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new te({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new te({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if((0,Eo.isValidDomain)(o)){if(i.rp.id!==o)return new te({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new te({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new te({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new te({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new te({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function zc({error:t,options:e}){let{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new te({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new te({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let n=window.location.hostname;if((0,Eo.isValidDomain)(n)){if(r.rpId!==n)return new te({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new te({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new te({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new te({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}});var Jn=$(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.WebAuthnApi=M.DEFAULT_REQUEST_OPTIONS=M.DEFAULT_CREATION_OPTIONS=M.webAuthnAbortService=M.WebAuthnAbortService=M.identifyAuthenticationError=M.identifyRegistrationError=M.isWebAuthnError=M.WebAuthnError=void 0;M.deserializeCredentialCreationOptions=Jc;M.deserializeCredentialRequestOptions=Yc;M.serializeCredentialCreationResponse=Xc;M.serializeCredentialRequestResponse=Qc;M.isValidDomain=Zc;M.createCredential=Ro;M.getCredential=ko;M.mergeCredentialCreationOptions=Oo;M.mergeCredentialRequestOptions=Po;var Ao=(ge(),Se(_e)),Re=ar(),Pe=De(),Gc=tt(),Ce=So();Object.defineProperty(M,"identifyAuthenticationError",{enumerable:!0,get:function(){return Ce.identifyAuthenticationError}});Object.defineProperty(M,"identifyRegistrationError",{enumerable:!0,get:function(){return Ce.identifyRegistrationError}});Object.defineProperty(M,"isWebAuthnError",{enumerable:!0,get:function(){return Ce.isWebAuthnError}});Object.defineProperty(M,"WebAuthnError",{enumerable:!0,get:function(){return Ce.WebAuthnError}});var fr=class{createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}};M.WebAuthnAbortService=fr;M.webAuthnAbortService=new fr;function Jc(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);let{challenge:e,user:r,excludeCredentials:n}=t,s=Ao.__rest(t,["challenge","user","excludeCredentials"]),i=(0,Re.base64UrlToUint8Array)(e).buffer,o=Object.assign(Object.assign({},r),{id:(0,Re.base64UrlToUint8Array)(r.id).buffer}),a=Object.assign(Object.assign({},s),{challenge:i,user:o});if(n&&n.length>0){a.excludeCredentials=new Array(n.length);for(let l=0;l<n.length;l++){let c=n[l];a.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:(0,Re.base64UrlToUint8Array)(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return a}function Yc(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);let{challenge:e,allowCredentials:r}=t,n=Ao.__rest(t,["challenge","allowCredentials"]),s=(0,Re.base64UrlToUint8Array)(e).buffer,i=Object.assign(Object.assign({},n),{challenge:s});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){let a=r[o];i.allowCredentials[o]=Object.assign(Object.assign({},a),{id:(0,Re.base64UrlToUint8Array)(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return i}function Xc(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t;return{id:t.id,rawId:t.id,response:{attestationObject:(0,Re.bytesToBase64URL)(new Uint8Array(t.response.attestationObject)),clientDataJSON:(0,Re.bytesToBase64URL)(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Qc(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,n=t.getClientExtensionResults(),s=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:(0,Re.bytesToBase64URL)(new Uint8Array(s.authenticatorData)),clientDataJSON:(0,Re.bytesToBase64URL)(new Uint8Array(s.clientDataJSON)),signature:(0,Re.bytesToBase64URL)(new Uint8Array(s.signature)),userHandle:s.userHandle?(0,Re.bytesToBase64URL)(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Zc(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function To(){var t,e;return!!((0,Gc.isBrowser)()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function Ro(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ce.WebAuthnUnknownError("Browser returned unexpected credential type",e)}:{data:null,error:new Ce.WebAuthnUnknownError("Empty credential response",e)}}catch(e){return{data:null,error:(0,Ce.identifyRegistrationError)({error:e,options:t})}}}async function ko(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ce.WebAuthnUnknownError("Browser returned unexpected credential type",e)}:{data:null,error:new Ce.WebAuthnUnknownError("Empty credential response",e)}}catch(e){return{data:null,error:(0,Ce.identifyAuthenticationError)({error:e,options:t})}}}M.DEFAULT_CREATION_OPTIONS={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"};M.DEFAULT_REQUEST_OPTIONS={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function pr(...t){let e=s=>s!==null&&typeof s=="object"&&!Array.isArray(s),r=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),n={};for(let s of t)if(s)for(let i in s){let o=s[i];if(o!==void 0)if(Array.isArray(o))n[i]=o;else if(r(o))n[i]=o;else if(e(o)){let a=n[i];e(a)?n[i]=pr(a,o):n[i]=pr(o)}else n[i]=o}return n}function Oo(t,e){return pr(M.DEFAULT_CREATION_OPTIONS,t,e||{})}function Po(t,e){return pr(M.DEFAULT_REQUEST_OPTIONS,t,e||{})}var Yn=class{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:r,friendlyName:n,signal:s},i){var o;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:l};let c=s??M.webAuthnAbortService.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:h}=a.webauthn.credential_options.publicKey;if(!h.name){let m=n;if(m)h.name=`${h.id}:${m}`;else{let f=(await this.client.getUser()).data.user,y=((o=f?.user_metadata)===null||o===void 0?void 0:o.name)||f?.email||f?.id||"User";h.name=`${h.id}:${y}`}}h.displayName||(h.displayName=h.name)}switch(a.webauthn.type){case"create":{let h=Oo(a.webauthn.credential_options.publicKey,i?.create),{data:m,error:_}=await Ro({publicKey:h,signal:c});return m?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:m}},error:null}:{data:null,error:_}}case"request":{let h=Po(a.webauthn.credential_options.publicKey,i?.request),{data:m,error:_}=await ko(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:h,signal:c}));return m?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:m}},error:null}:{data:null,error:_}}}}catch(a){return(0,Pe.isAuthError)(a)?{data:null,error:a}:{data:null,error:new Pe.AuthUnknownError("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:n}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!r)return{data:null,error:new Pe.AuthError("rpId is required for WebAuthn authentication")};try{if(!To())return{data:null,error:new Pe.AuthUnknownError("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:n},signal:s},{request:i});if(!o)return{data:null,error:a};let{webauthn:l}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:n,credential_response:l.credential_response}})}catch(o){return(0,Pe.isAuthError)(o)?{data:null,error:o}:{data:null,error:new Pe.AuthUnknownError("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:s}={}},i){if(!r)return{data:null,error:new Pe.AuthError("rpId is required for WebAuthn registration")};try{if(!To())return{data:null,error:new Pe.AuthUnknownError("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(h=>{var m;return(m=h.data)===null||m===void 0?void 0:m.all.find(_=>_.factor_type==="webauthn"&&_.friendly_name===e&&_.status!=="unverified")}).then(h=>h?this.client.mfa.unenroll({factorId:h?.id}):void 0),{data:null,error:a};let{data:l,error:c}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:n},signal:s},{create:i});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:n,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(o){return(0,Pe.isAuthError)(o)?{data:null,error:o}:{data:null,error:new Pe.AuthUnknownError("Unexpected error in register",o)}}}};M.WebAuthnApi=Yn});var Qn=$(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});var ed=(ge(),Se(_e)),td=ed.__importDefault(dr()),pe=ir(),S=De(),I=Bn(),R=tt(),Co=go(),Io=Kn(),rd=vo(),nd=Sn(),xo=ar(),mr=bo(),St=Jn();(0,rd.polyfillGlobalThis)();var sd={url:pe.GOTRUE_URL,storageKey:pe.STORAGE_KEY,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:pe.DEFAULT_HEADERS,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4,skipAutoInitialize:!1};async function No(t,e,r){return await r()}var nt={},_r=class t{get jwks(){var e,r;return(r=(e=nt[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){nt[this.storageKey]=Object.assign(Object.assign({},nt[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=nt[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){nt[this.storageKey]=Object.assign(Object.assign({},nt[this.storageKey]),{cachedAt:e})}constructor(e){var r,n,s;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},sd),e);if(this.storageKey=i.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&(0,R.isBrowser)()){let o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.admin=new td.default({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=(0,R.resolveFetch)(i.fetch),this.lock=i.lock||No,this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock?this.lock=i.lock:this.persistSession&&(0,R.isBrowser)()&&(!((n=globalThis?.navigator)===null||n===void 0)&&n.locks)?this.lock=Io.navigatorLock:this.lock=No,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 St.WebAuthnApi(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:(0,R.supportsLocalStorage)()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=(0,Co.memoryLocalStorageAdapter)(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=(0,Co.memoryLocalStorageAdapter)(this.memoryStorage)),(0,R.isBrowser)()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(s=this.broadcastChannel)===null||s===void 0||s.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(a){this._debug("#broadcastChannel","error",a)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${nd.version}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},n="none";if((0,R.isBrowser)()&&(r=(0,R.parseParametersFromURL)(window.location.href),this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce")),(0,R.isBrowser)()&&this.detectSessionInUrl&&n!=="none"){let{data:s,error:i}=await this._getSessionFromURL(r,n);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),(0,S.isAuthImplicitGrantRedirectError)(i)){let l=(e=i.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return{error:i}}let{session:o,redirectType:a}=s;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return(0,S.isAuthError)(r)?this._returnResult({error:r}):this._returnResult({error:new S.AuthUnknownError("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,n,s;try{let i=await(0,I._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(s=e?.options)===null||s===void 0?void 0:s.captchaToken}},xform:I._sessionResponse}),{data:o,error:a}=i;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if((0,S.isAuthError)(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,n,s;try{let i;if("email"in e){let{email:h,password:m,options:_}=e,f=null,y=null;this.flowType==="pkce"&&([f,y]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey)),i=await(0,I._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:_?.emailRedirectTo,body:{email:h,password:m,data:(r=_?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:_?.captchaToken},code_challenge:f,code_challenge_method:y},xform:I._sessionResponse})}else if("phone"in e){let{phone:h,password:m,options:_}=e;i=await(0,I._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:m,data:(n=_?.data)!==null&&n!==void 0?n:{},channel:(s=_?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:_?.captchaToken}},xform:I._sessionResponse})}else throw new S.AuthInvalidCredentialsError("You must provide either an email or phone number and a password");let{data:o,error:a}=i;if(a||!o)return await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let r;if("email"in e){let{email:i,password:o,options:a}=e;r=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:I._sessionResponsePassword})}else if("phone"in e){let{phone:i,password:o,options:a}=e;r=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:I._sessionResponsePassword})}else throw new S.AuthInvalidCredentialsError("You must provide either an email or phone number and a password");let{data:n,error:s}=r;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!n||!n.session||!n.user){let i=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:i})}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:s})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,n,s,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(s=e.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,n,s,i,o,a,l,c,h,m,_;let f,y;if("message"in e)f=e.message,y=e.signature;else{let{chain:v,wallet:w,statement:T,options:O}=e,E;if((0,R.isBrowser)())if(typeof w=="object")E=w;else{let Ee=window;if("ethereum"in Ee&&typeof Ee.ethereum=="object"&&"request"in Ee.ethereum&&typeof Ee.ethereum.request=="function")E=Ee.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof w!="object"||!O?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");E=w}let x=new URL((r=O?.url)!==null&&r!==void 0?r:window.location.href),Z=await E.request({method:"eth_requestAccounts"}).then(Ee=>Ee).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!Z||Z.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let W=(0,mr.getAddress)(Z[0]),re=(n=O?.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!re){let Ee=await E.request({method:"eth_chainId"});re=(0,mr.fromHex)(Ee)}let ke={domain:x.host,address:W,statement:T,uri:x.href,version:"1",chainId:re,nonce:(s=O?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(o=(i=O?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=O?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=O?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=O?.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(h=O?.signInWithEthereum)===null||h===void 0?void 0:h.resources};f=(0,mr.createSiweMessage)(ke),y=await E.request({method:"personal_sign",params:[(0,mr.toHex)(f),W]})}try{let{data:v,error:w}=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:y},!((m=e.options)===null||m===void 0)&&m.captchaToken?{gotrue_meta_security:{captcha_token:(_=e.options)===null||_===void 0?void 0:_.captchaToken}}:null),xform:I._sessionResponse});if(w)throw w;if(!v||!v.session||!v.user){let T=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:T})}return v.session&&(await this._saveSession(v.session),await this._notifyAllSubscribers("SIGNED_IN",v.session)),this._returnResult({data:Object.assign({},v),error:w})}catch(v){if((0,S.isAuthError)(v))return this._returnResult({data:{user:null,session:null},error:v});throw v}}async signInWithSolana(e){var r,n,s,i,o,a,l,c,h,m,_,f;let y,v;if("message"in e)y=e.message,v=e.signature;else{let{chain:w,wallet:T,statement:O,options:E}=e,x;if((0,R.isBrowser)())if(typeof T=="object")x=T;else{let W=window;if("solana"in W&&typeof W.solana=="object"&&("signIn"in W.solana&&typeof W.solana.signIn=="function"||"signMessage"in W.solana&&typeof W.solana.signMessage=="function"))x=W.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof T!="object"||!E?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");x=T}let Z=new URL((r=E?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in x&&x.signIn){let W=await x.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},E?.signInWithSolana),{version:"1",domain:Z.host,uri:Z.href}),O?{statement:O}:null)),re;if(Array.isArray(W)&&W[0]&&typeof W[0]=="object")re=W[0];else if(W&&typeof W=="object"&&"signedMessage"in W&&"signature"in W)re=W;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in re&&"signature"in re&&(typeof re.signedMessage=="string"||re.signedMessage instanceof Uint8Array)&&re.signature instanceof Uint8Array)y=typeof re.signedMessage=="string"?re.signedMessage:new TextDecoder().decode(re.signedMessage),v=re.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in x)||typeof x.signMessage!="function"||!("publicKey"in x)||typeof x!="object"||!x.publicKey||!("toBase58"in x.publicKey)||typeof x.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");y=[`${Z.host} wants you to sign in with your Solana account:`,x.publicKey.toBase58(),...O?["",O,""]:[""],"Version: 1",`URI: ${Z.href}`,`Issued At: ${(s=(n=E?.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()}`,...!((i=E?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${E.signInWithSolana.notBefore}`]:[],...!((o=E?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${E.signInWithSolana.expirationTime}`]:[],...!((a=E?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${E.signInWithSolana.chainId}`]:[],...!((l=E?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${E.signInWithSolana.nonce}`]:[],...!((c=E?.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${E.signInWithSolana.requestId}`]:[],...!((m=(h=E?.signInWithSolana)===null||h===void 0?void 0:h.resources)===null||m===void 0)&&m.length?["Resources",...E.signInWithSolana.resources.map(re=>`- ${re}`)]:[]].join(`
|
|
42
|
+
`);let W=await x.signMessage(new TextEncoder().encode(y),"utf8");if(!W||!(W instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=W}}try{let{data:w,error:T}=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:y,signature:(0,xo.bytesToBase64URL)(v)},!((_=e.options)===null||_===void 0)&&_.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:I._sessionResponse});if(T)throw T;if(!w||!w.session||!w.user){let O=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:O})}return w.session&&(await this._saveSession(w.session),await this._notifyAllSubscribers("SIGNED_IN",w.session)),this._returnResult({data:Object.assign({},w),error:T})}catch(w){if((0,S.isAuthError)(w))return this._returnResult({data:{user:null,session:null},error:w});throw w}}async _exchangeCodeForSession(e){let r=await(0,R.getItemAsync)(this.storage,`${this.storageKey}-code-verifier`),[n,s]=(r??"").split("/");try{if(!n&&this.flowType==="pkce")throw new S.AuthPKCECodeVerifierMissingError;let{data:i,error:o}=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:I._sessionResponse});if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){let a=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:s??null}),error:o})}catch(i){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{let{options:r,provider:n,token:s,access_token:i,nonce:o}=e,a=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:s,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:I._sessionResponse}),{data:l,error:c}=a;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){let h=new S.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:h})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:c})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,s,i,o;try{if("email"in e){let{email:a,options:l}=e,c=null,h=null;this.flowType==="pkce"&&([c,h]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey));let{error:m}=await(0,I._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:h},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:m})}if("phone"in e){let{phone:a,options:l}=e,{data:c,error:h}=await(0,I._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(s=l?.data)!==null&&s!==void 0?s:{},create_user:(i=l?.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c?.message_id},error:h})}throw new S.AuthInvalidCredentialsError("You must provide either an email or phone number.")}catch(a){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,n;try{let s,i;"options"in e&&(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:o,error:a}=await(0,I._request)(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:I._sessionResponse});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,c=o.user;return l?.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(s){if((0,S.isAuthError)(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(e){var r,n,s,i,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey));let c=await(0,I._request)(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((s=e?.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:I._ssoResponse});return!((i=c.data)===null||i===void 0)&&i.url&&(0,R.isBrowser)()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(a){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new S.AuthSessionMissingError;let{error:s}=await(0,I._request)(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(e){if((0,S.isAuthError)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let r=`${this.url}/resend`;if("email"in e){let{email:n,type:s,options:i}=e,{error:o}=await(0,I._request)(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:s,gotrue_meta_security:{captcha_token:i?.captchaToken}},redirectTo:i?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){let{phone:n,type:s,options:i}=e,{data:o,error:a}=await(0,I._request)(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:s,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:a})}throw new S.AuthInvalidCredentialsError("You must provide either an email or phone number and a type")}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let n=r();for(this.pendingInLock.push((async()=>{try{await n}catch{}})()),await n;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let r=await this.__loadSession();return await e(r)}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,r=await(0,R.getItemAsync)(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let n=e.expires_at?e.expires_at*1e3-Date.now()<pe.EXPIRY_MARGIN_MS:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){let o=await(0,R.getItemAsync)(this.userStorage,this.storageKey+"-user");o?.user?e.user=o.user:e.user=(0,R.userNotAvailableProxy)()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=(0,R.insecureUserWarningProxy)(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await(0,I._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:I._userResponse}):await this._useSession(async r=>{var n,s,i;let{data:o,error:a}=r;if(a)throw a;return!(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new S.AuthSessionMissingError}:await(0,I._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(s=o.session)===null||s===void 0?void 0:s.access_token)!==null&&i!==void 0?i:void 0,xform:I._userResponse})})}catch(r){if((0,S.isAuthError)(r))return(0,S.isAuthSessionMissingError)(r)&&(await this._removeSession(),await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async n=>{let{data:s,error:i}=n;if(i)throw i;if(!s.session)throw new S.AuthSessionMissingError;let o=s.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey));let{data:c,error:h}=await(0,I._request)(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:I._userResponse});if(h)throw h;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(n){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(n))return this._returnResult({data:{user:null},error:n});throw n}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new S.AuthSessionMissingError;let r=Date.now()/1e3,n=r,s=!0,i=null,{payload:o}=(0,R.decodeJWT)(e.access_token);if(o.exp&&(n=o.exp,s=n<=r),s){let{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};i=a}else{let{data:a,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});i={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:n-r,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(r){if((0,S.isAuthError)(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var n;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(n=o.session)!==null&&n!==void 0?n:void 0}if(!e?.refresh_token)throw new S.AuthSessionMissingError;let{data:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!(0,R.isBrowser)())throw new S.AuthImplicitGrantRedirectError("No browser detected.");if(e.error||e.error_description||e.error_code)throw new S.AuthImplicitGrantRedirectError(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new S.AuthPKCEGrantCodeExchangeError("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new S.AuthImplicitGrantRedirectError("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new S.AuthPKCEGrantCodeExchangeError("No code detected.");let{data:O,error:E}=await this._exchangeCodeForSession(e.code);if(E)throw E;let x=new URL(window.location.href);return x.searchParams.delete("code"),window.history.replaceState(window.history.state,"",x.toString()),{data:{session:O.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:s,access_token:i,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!i||!a||!o||!c)throw new S.AuthImplicitGrantRedirectError("No session defined in URL");let h=Math.round(Date.now()/1e3),m=parseInt(a),_=h+m;l&&(_=parseInt(l));let f=_-h;f*1e3<=pe.AUTO_REFRESH_TICK_DURATION_MS&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${m}s`);let y=_-m;h-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,_,h):h-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",y,_,h);let{data:v,error:w}=await this._getUser(i);if(w)throw w;let T={provider_token:n,provider_refresh_token:s,access_token:i,expires_in:m,expires_at:_,refresh_token:o,token_type:c,user:v.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:T,redirectType:e.type},error:null})}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){let r=await(0,R.getItemAsync)(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var n;let{data:s,error:i}=r;if(i&&!(0,S.isAuthSessionMissingError)(i))return this._returnResult({error:i});let o=(n=s.session)===null||n===void 0?void 0:n.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!((0,S.isAuthApiError)(a)&&(a.status===404||a.status===401||a.status===403)||(0,S.isAuthSessionMissingError)(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=(0,R.generateCallbackId)(),n={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,n),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,s;try{let{data:{session:i},error:o}=r;if(o)throw o;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,r={}){let n=null,s=null;this.flowType==="pkce"&&([n,s]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey,!0));try{return await(0,I._request)(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:s,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{let{data:r,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{let{data:n,error:s}=await this._useSession(async i=>{var o,a,l,c,h;let{data:m,error:_}=i;if(_)throw _;let f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await(0,I._request)(this.fetch,"GET",f,{headers:this.headers,jwt:(h=(c=m.session)===null||c===void 0?void 0:c.access_token)!==null&&h!==void 0?h:void 0})});if(s)throw s;return(0,R.isBrowser)()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url},error:null})}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var n;try{let{error:s,data:{session:i}}=r;if(s)throw s;let{options:o,provider:a,token:l,access_token:c,nonce:h}=e,m=await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=i?.access_token)!==null&&n!==void 0?n:void 0,body:{provider:a,id_token:l,access_token:c,nonce:h,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:I._sessionResponse}),{data:_,error:f}=m;return f?this._returnResult({data:{user:null,session:null},error:f}):!_||!_.session||!_.user?this._returnResult({data:{user:null,session:null},error:new S.AuthInvalidTokenResponseError}):(_.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("USER_UPDATED",_.session)),this._returnResult({data:_,error:f}))}catch(s){if(await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,S.isAuthError)(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,s;let{data:i,error:o}=r;if(o)throw o;return await(0,I._request)(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(s=(n=i.session)===null||n===void 0?void 0:n.access_token)!==null&&s!==void 0?s:void 0})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{let n=Date.now();return await(0,R.retryable)(async s=>(s>0&&await(0,R.sleep)(200*Math.pow(2,s-1)),this._debug(r,"refreshing attempt",s),await(0,I._request)(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:I._sessionResponse})),(s,i)=>{let o=200*Math.pow(2,s);return i&&(0,S.isAuthRetryableFetchError)(i)&&Date.now()+o-n<pe.AUTO_REFRESH_TICK_DURATION_MS})}catch(n){if(this._debug(r,"error",n),(0,S.isAuthError)(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){let n=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",n),(0,R.isBrowser)()&&!r.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,r;let n="#_recoverAndRefresh()";this._debug(n,"begin");try{let s=await(0,R.getItemAsync)(this.storage,this.storageKey);if(s&&this.userStorage){let o=await(0,R.getItemAsync)(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:s.user},await(0,R.setItemAsync)(this.userStorage,this.storageKey+"-user",o)),s.user=(e=o?.user)!==null&&e!==void 0?e:(0,R.userNotAvailableProxy)()}else if(s&&!s.user&&!s.user){let o=await(0,R.getItemAsync)(this.storage,this.storageKey+"-user");o&&o?.user?(s.user=o.user,await(0,R.removeItemAsync)(this.storage,this.storageKey+"-user"),await(0,R.setItemAsync)(this.storage,this.storageKey,s)):s.user=(0,R.userNotAvailableProxy)()}if(this._debug(n,"session from storage",s),!this._isValidSession(s)){this._debug(n,"session is not valid"),s!==null&&await this._removeSession();return}let i=((r=s.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<pe.EXPIRY_MARGIN_MS;if(this._debug(n,`session has${i?"":" not"} expired with margin of ${pe.EXPIRY_MARGIN_MS}s`),i){if(this.autoRefreshToken&&s.refresh_token){let{error:o}=await this._callRefreshToken(s.refresh_token);o&&(console.error(o),(0,S.isAuthRetryableFetchError)(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(s.user&&s.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:a}=await this._getUser(s.access_token);!a&&o?.user?(s.user=o.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(n,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(n,"error",s),console.error(s);return}finally{this._debug(n,"end")}}async _callRefreshToken(e){var r,n;if(!e)throw new S.AuthSessionMissingError;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new R.Deferred;let{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new S.AuthSessionMissingError;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);let a={data:i.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(i){if(this._debug(s,"error",i),(0,S.isAuthError)(i)){let o={data:null,error:i};return(0,S.isAuthRetryableFetchError)(i)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(n=this.refreshingDeferred)===null||n===void 0||n.reject(i),i}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,r,n=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});let i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(l){i.push(l)}});if(await Promise.all(o),i.length>0){for(let a=0;a<i.length;a+=1)console.error(i[a]);throw i[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await(0,R.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),n=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&r.user&&await(0,R.setItemAsync)(this.userStorage,this.storageKey+"-user",{user:r.user});let s=Object.assign({},r);delete s.user;let i=(0,R.deepClone)(s);await(0,R.setItemAsync)(this.storage,this.storageKey,i)}else{let s=(0,R.deepClone)(r);await(0,R.setItemAsync)(this.storage,this.storageKey,s)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await(0,R.removeItemAsync)(this.storage,this.storageKey),await(0,R.removeItemAsync)(this.storage,this.storageKey+"-code-verifier"),await(0,R.removeItemAsync)(this.storage,this.storageKey+"-user"),this.userStorage&&await(0,R.removeItemAsync)(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&(0,R.isBrowser)()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),pe.AUTO_REFRESH_TICK_DURATION_MS);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async r=>{let{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((n.expires_at*1e3-e)/pe.AUTO_REFRESH_TICK_DURATION_MS);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts ${pe.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${pe.AUTO_REFRESH_TICK_THRESHOLD} ticks`),s<=pe.AUTO_REFRESH_TICK_THRESHOLD&&await this._callRefreshToken(n.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof Io.LockAcquireTimeoutError)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!(0,R.isBrowser)()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,n){let s=[`provider=${encodeURIComponent(r)}`];if(n?.redirectTo&&s.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n?.scopes&&s.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){let[i,o]=await(0,R.getCodeChallengeAndMethod)(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});s.push(a.toString())}if(n?.queryParams){let i=new URLSearchParams(n.queryParams);s.push(i.toString())}return n?.skipBrowserRedirect&&s.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${s.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;let{data:s,error:i}=r;return i?this._returnResult({data:null,error:i}):await(0,I._request)(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,s;let{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await(0,I._request)(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((s=l?.totp)===null||s===void 0)&&s.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;let{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});let o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?(0,St.serializeCredentialCreationResponse)(e.webauthn.credential_response):(0,St.serializeCredentialRequestResponse)(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await(0,I._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:l}))})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var n;let{data:s,error:i}=r;if(i)return this._returnResult({data:null,error:i});let o=await(0,I._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;let{data:a}=o;if(a.type!=="webauthn")return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:(0,St.deserializeCredentialCreationOptions)(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:(0,St.deserializeCredentialRequestOptions)(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:n}=await this.getUser();if(n)return{data:null,error:n};let s={all:[],phone:[],totp:[],webauthn:[]};for(let i of(e=r?.factors)!==null&&e!==void 0?e:[])s.all.push(i),i.status==="verified"&&s[i.factor_type].push(i);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,n,s,i;if(e)try{let{payload:f}=(0,R.decodeJWT)(e),y=null;f.aal&&(y=f.aal);let v=y,{data:{user:w},error:T}=await this.getUser(e);if(T)return this._returnResult({data:null,error:T});((n=(r=w?.factors)===null||r===void 0?void 0:r.filter(x=>x.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(v="aal2");let E=f.amr||[];return{data:{currentLevel:y,nextLevel:v,currentAuthenticationMethods:E},error:null}}catch(f){if((0,S.isAuthError)(f))return this._returnResult({data:null,error:f});throw f}let{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:l}=(0,R.decodeJWT)(o.access_token),c=null;l.aal&&(c=l.aal);let h=c;((i=(s=o.user.factors)===null||s===void 0?void 0:s.filter(f=>f.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(h="aal2");let _=l.amr||[];return{data:{currentLevel:c,nextLevel:h,currentAuthenticationMethods:_},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:n},error:s}=r;return s?this._returnResult({data:null,error:s}):n?await(0,I._request)(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new S.AuthSessionMissingError})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new S.AuthSessionMissingError});let o=await(0,I._request)(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&(0,R.isBrowser)()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:s},error:i}=n;if(i)return this._returnResult({data:null,error:i});if(!s)return this._returnResult({data:null,error:new S.AuthSessionMissingError});let o=await(0,I._request)(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&(0,R.isBrowser)()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;return n?this._returnResult({data:null,error:n}):r?await(0,I._request)(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new S.AuthSessionMissingError})})}catch(e){if((0,S.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:n},error:s}=r;return s?this._returnResult({data:null,error:s}):n?(await(0,I._request)(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 S.AuthSessionMissingError})})}catch(r){if((0,S.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(a=>a.kid===e);if(n)return n;let s=Date.now();if(n=this.jwks.keys.find(a=>a.kid===e),n&&this.jwks_cached_at+pe.JWKS_TTL>s)return n;let{data:i,error:o}=await(0,I._request)(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=s,n=i.keys.find(a=>a.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){let{data:f,error:y}=await this.getSession();if(y||!f.session)return this._returnResult({data:null,error:y});n=f.session.access_token}let{header:s,payload:i,signature:o,raw:{header:a,payload:l}}=(0,R.decodeJWT)(n);r?.allowExpired||(0,R.validateExp)(i.exp);let c=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!c){let{error:f}=await this.getUser(n);if(f)throw f;return{data:{claims:i,header:s,signature:o},error:null}}let h=(0,R.getAlgorithm)(s.alg),m=await crypto.subtle.importKey("jwk",c,h,!0,["verify"]);if(!await crypto.subtle.verify(h,m,o,(0,xo.stringToUint8Array)(`${a}.${l}`)))throw new S.AuthInvalidJwtError("Invalid JWT signature");return{data:{claims:i,header:s,signature:o},error:null}}catch(n){if((0,S.isAuthError)(n))return this._returnResult({data:null,error:n});throw n}}};_r.nextInstanceID={};Xn.default=_r});var jo=$(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});var id=(ge(),Se(_e)),od=id.__importDefault(dr()),ad=od.default;Zn.default=ad});var Lo=$(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});var ud=(ge(),Se(_e)),ld=ud.__importDefault(Qn()),cd=ld.default;es.default=cd});var ts=$(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.processLock=ae.lockInternals=ae.NavigatorLockAcquireTimeoutError=ae.navigatorLock=ae.AuthClient=ae.AuthAdminApi=ae.GoTrueClient=ae.GoTrueAdminApi=void 0;var st=(ge(),Se(_e)),dd=st.__importDefault(dr());ae.GoTrueAdminApi=dd.default;var hd=st.__importDefault(Qn());ae.GoTrueClient=hd.default;var fd=st.__importDefault(jo());ae.AuthAdminApi=fd.default;var pd=st.__importDefault(Lo());ae.AuthClient=pd.default;st.__exportStar(qn(),ae);st.__exportStar(De(),ae);var gr=Kn();Object.defineProperty(ae,"navigatorLock",{enumerable:!0,get:function(){return gr.navigatorLock}});Object.defineProperty(ae,"NavigatorLockAcquireTimeoutError",{enumerable:!0,get:function(){return gr.NavigatorLockAcquireTimeoutError}});Object.defineProperty(ae,"lockInternals",{enumerable:!0,get:function(){return gr.internals}});Object.defineProperty(ae,"processLock",{enumerable:!0,get:function(){return gr.processLock}})});var da=$(L=>{"use strict";var Ot=Symbol.for("react.element"),qd=Symbol.for("react.portal"),Md=Symbol.for("react.fragment"),Wd=Symbol.for("react.strict_mode"),Vd=Symbol.for("react.profiler"),Hd=Symbol.for("react.provider"),Kd=Symbol.for("react.context"),zd=Symbol.for("react.forward_ref"),Gd=Symbol.for("react.suspense"),Jd=Symbol.for("react.memo"),Yd=Symbol.for("react.lazy"),ea=Symbol.iterator;function Xd(t){return t===null||typeof t!="object"?null:(t=ea&&t[ea]||t["@@iterator"],typeof t=="function"?t:null)}var na={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},sa=Object.assign,ia={};function it(t,e,r){this.props=t,this.context=e,this.refs=ia,this.updater=r||na}it.prototype.isReactComponent={};it.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};it.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function oa(){}oa.prototype=it.prototype;function os(t,e,r){this.props=t,this.context=e,this.refs=ia,this.updater=r||na}var as=os.prototype=new oa;as.constructor=os;sa(as,it.prototype);as.isPureReactComponent=!0;var ta=Array.isArray,aa=Object.prototype.hasOwnProperty,us={current:null},ua={key:!0,ref:!0,__self:!0,__source:!0};function la(t,e,r){var n,s={},i=null,o=null;if(e!=null)for(n in e.ref!==void 0&&(o=e.ref),e.key!==void 0&&(i=""+e.key),e)aa.call(e,n)&&!ua.hasOwnProperty(n)&&(s[n]=e[n]);var a=arguments.length-2;if(a===1)s.children=r;else if(1<a){for(var l=Array(a),c=0;c<a;c++)l[c]=arguments[c+2];s.children=l}if(t&&t.defaultProps)for(n in a=t.defaultProps,a)s[n]===void 0&&(s[n]=a[n]);return{$$typeof:Ot,type:t,key:i,ref:o,props:s,_owner:us.current}}function Qd(t,e){return{$$typeof:Ot,type:t.type,key:e,ref:t.ref,props:t.props,_owner:t._owner}}function ls(t){return typeof t=="object"&&t!==null&&t.$$typeof===Ot}function Zd(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(r){return e[r]})}var ra=/\/+/g;function is(t,e){return typeof t=="object"&&t!==null&&t.key!=null?Zd(""+t.key):e.toString(36)}function Er(t,e,r,n,s){var i=typeof t;(i==="undefined"||i==="boolean")&&(t=null);var o=!1;if(t===null)o=!0;else switch(i){case"string":case"number":o=!0;break;case"object":switch(t.$$typeof){case Ot:case qd:o=!0}}if(o)return o=t,s=s(o),t=n===""?"."+is(o,0):n,ta(s)?(r="",t!=null&&(r=t.replace(ra,"$&/")+"/"),Er(s,e,r,"",function(c){return c})):s!=null&&(ls(s)&&(s=Qd(s,r+(!s.key||o&&o.key===s.key?"":(""+s.key).replace(ra,"$&/")+"/")+t)),e.push(s)),1;if(o=0,n=n===""?".":n+":",ta(t))for(var a=0;a<t.length;a++){i=t[a];var l=n+is(i,a);o+=Er(i,e,r,l,s)}else if(l=Xd(t),typeof l=="function")for(t=l.call(t),a=0;!(i=t.next()).done;)i=i.value,l=n+is(i,a++),o+=Er(i,e,r,l,s);else if(i==="object")throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.");return o}function br(t,e,r){if(t==null)return t;var n=[],s=0;return Er(t,n,"","",function(i){return e.call(r,i,s++)}),n}function eh(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(r){(t._status===0||t._status===-1)&&(t._status=1,t._result=r)},function(r){(t._status===0||t._status===-1)&&(t._status=2,t._result=r)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var he={current:null},Sr={transition:null},th={ReactCurrentDispatcher:he,ReactCurrentBatchConfig:Sr,ReactCurrentOwner:us};function ca(){throw Error("act(...) is not supported in production builds of React.")}L.Children={map:br,forEach:function(t,e,r){br(t,function(){e.apply(this,arguments)},r)},count:function(t){var e=0;return br(t,function(){e++}),e},toArray:function(t){return br(t,function(e){return e})||[]},only:function(t){if(!ls(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};L.Component=it;L.Fragment=Md;L.Profiler=Vd;L.PureComponent=os;L.StrictMode=Wd;L.Suspense=Gd;L.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=th;L.act=ca;L.cloneElement=function(t,e,r){if(t==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+t+".");var n=sa({},t.props),s=t.key,i=t.ref,o=t._owner;if(e!=null){if(e.ref!==void 0&&(i=e.ref,o=us.current),e.key!==void 0&&(s=""+e.key),t.type&&t.type.defaultProps)var a=t.type.defaultProps;for(l in e)aa.call(e,l)&&!ua.hasOwnProperty(l)&&(n[l]=e[l]===void 0&&a!==void 0?a[l]:e[l])}var l=arguments.length-2;if(l===1)n.children=r;else if(1<l){a=Array(l);for(var c=0;c<l;c++)a[c]=arguments[c+2];n.children=a}return{$$typeof:Ot,type:t.type,key:s,ref:i,props:n,_owner:o}};L.createContext=function(t){return t={$$typeof:Kd,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},t.Provider={$$typeof:Hd,_context:t},t.Consumer=t};L.createElement=la;L.createFactory=function(t){var e=la.bind(null,t);return e.type=t,e};L.createRef=function(){return{current:null}};L.forwardRef=function(t){return{$$typeof:zd,render:t}};L.isValidElement=ls;L.lazy=function(t){return{$$typeof:Yd,_payload:{_status:-1,_result:t},_init:eh}};L.memo=function(t,e){return{$$typeof:Jd,type:t,compare:e===void 0?null:e}};L.startTransition=function(t){var e=Sr.transition;Sr.transition={};try{t()}finally{Sr.transition=e}};L.unstable_act=ca;L.useCallback=function(t,e){return he.current.useCallback(t,e)};L.useContext=function(t){return he.current.useContext(t)};L.useDebugValue=function(){};L.useDeferredValue=function(t){return he.current.useDeferredValue(t)};L.useEffect=function(t,e){return he.current.useEffect(t,e)};L.useId=function(){return he.current.useId()};L.useImperativeHandle=function(t,e,r){return he.current.useImperativeHandle(t,e,r)};L.useInsertionEffect=function(t,e){return he.current.useInsertionEffect(t,e)};L.useLayoutEffect=function(t,e){return he.current.useLayoutEffect(t,e)};L.useMemo=function(t,e){return he.current.useMemo(t,e)};L.useReducer=function(t,e,r){return he.current.useReducer(t,e,r)};L.useRef=function(t){return he.current.useRef(t)};L.useState=function(t){return he.current.useState(t)};L.useSyncExternalStore=function(t,e,r){return he.current.useSyncExternalStore(t,e,r)};L.useTransition=function(){return he.current.useTransition()};L.version="18.3.1"});var ha=$((U,Tr)=>{"use strict";process.env.NODE_ENV!=="production"&&(function(){"use strict";typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var t="18.3.1",e=Symbol.for("react.element"),r=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),o=Symbol.for("react.provider"),a=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),h=Symbol.for("react.suspense_list"),m=Symbol.for("react.memo"),_=Symbol.for("react.lazy"),f=Symbol.for("react.offscreen"),y=Symbol.iterator,v="@@iterator";function w(u){if(u===null||typeof u!="object")return null;var d=y&&u[y]||u[v];return typeof d=="function"?d:null}var T={current:null},O={transition:null},E={current:null,isBatchingLegacy:!1,didScheduleLegacyUpdate:!1},x={current:null},Z={},W=null;function re(u){W=u}Z.setExtraStackFrame=function(u){W=u},Z.getCurrentStack=null,Z.getStackAddendum=function(){var u="";W&&(u+=W);var d=Z.getCurrentStack;return d&&(u+=d()||""),u};var ke=!1,Ee=!1,ya=!1,va=!1,wa=!1,Me={ReactCurrentDispatcher:T,ReactCurrentBatchConfig:O,ReactCurrentOwner:x};Me.ReactDebugCurrentFrame=Z,Me.ReactCurrentActQueue=E;function We(u){{for(var d=arguments.length,p=new Array(d>1?d-1:0),g=1;g<d;g++)p[g-1]=arguments[g];ds("warn",u,p)}}function q(u){{for(var d=arguments.length,p=new Array(d>1?d-1:0),g=1;g<d;g++)p[g-1]=arguments[g];ds("error",u,p)}}function ds(u,d,p){{var g=Me.ReactDebugCurrentFrame,b=g.getStackAddendum();b!==""&&(d+="%s",p=p.concat([b]));var N=p.map(function(P){return String(P)});N.unshift("Warning: "+d),Function.prototype.apply.call(console[u],console,N)}}var hs={};function Rr(u,d){{var p=u.constructor,g=p&&(p.displayName||p.name)||"ReactClass",b=g+"."+d;if(hs[b])return;q("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",d,g),hs[b]=!0}}var fs={isMounted:function(u){return!1},enqueueForceUpdate:function(u,d,p){Rr(u,"forceUpdate")},enqueueReplaceState:function(u,d,p,g){Rr(u,"replaceState")},enqueueSetState:function(u,d,p,g){Rr(u,"setState")}},Ie=Object.assign,kr={};Object.freeze(kr);function Ue(u,d,p){this.props=u,this.context=d,this.refs=kr,this.updater=p||fs}Ue.prototype.isReactComponent={},Ue.prototype.setState=function(u,d){if(typeof u!="object"&&typeof u!="function"&&u!=null)throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,u,d,"setState")},Ue.prototype.forceUpdate=function(u){this.updater.enqueueForceUpdate(this,u,"forceUpdate")};{var Or={isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]},ba=function(u,d){Object.defineProperty(Ue.prototype,u,{get:function(){We("%s(...) is deprecated in plain JavaScript React classes. %s",d[0],d[1])}})};for(var Pr in Or)Or.hasOwnProperty(Pr)&&ba(Pr,Or[Pr])}function ps(){}ps.prototype=Ue.prototype;function Cr(u,d,p){this.props=u,this.context=d,this.refs=kr,this.updater=p||fs}var Ir=Cr.prototype=new ps;Ir.constructor=Cr,Ie(Ir,Ue.prototype),Ir.isPureReactComponent=!0;function Ea(){var u={current:null};return Object.seal(u),u}var Sa=Array.isArray;function Pt(u){return Sa(u)}function Ta(u){{var d=typeof Symbol=="function"&&Symbol.toStringTag,p=d&&u[Symbol.toStringTag]||u.constructor.name||"Object";return p}}function Aa(u){try{return ms(u),!1}catch{return!0}}function ms(u){return""+u}function Ct(u){if(Aa(u))return q("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",Ta(u)),ms(u)}function Ra(u,d,p){var g=u.displayName;if(g)return g;var b=d.displayName||d.name||"";return b!==""?p+"("+b+")":p}function _s(u){return u.displayName||"Context"}function je(u){if(u==null)return null;if(typeof u.tag=="number"&&q("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof u=="function")return u.displayName||u.name||null;if(typeof u=="string")return u;switch(u){case n:return"Fragment";case r:return"Portal";case i:return"Profiler";case s:return"StrictMode";case c:return"Suspense";case h:return"SuspenseList"}if(typeof u=="object")switch(u.$$typeof){case a:var d=u;return _s(d)+".Consumer";case o:var p=u;return _s(p._context)+".Provider";case l:return Ra(u,u.render,"ForwardRef");case m:var g=u.displayName||null;return g!==null?g:je(u.type)||"Memo";case _:{var b=u,N=b._payload,P=b._init;try{return je(P(N))}catch{return null}}}return null}var ot=Object.prototype.hasOwnProperty,gs={key:!0,ref:!0,__self:!0,__source:!0},ys,vs,xr;xr={};function ws(u){if(ot.call(u,"ref")){var d=Object.getOwnPropertyDescriptor(u,"ref").get;if(d&&d.isReactWarning)return!1}return u.ref!==void 0}function bs(u){if(ot.call(u,"key")){var d=Object.getOwnPropertyDescriptor(u,"key").get;if(d&&d.isReactWarning)return!1}return u.key!==void 0}function ka(u,d){var p=function(){ys||(ys=!0,q("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",d))};p.isReactWarning=!0,Object.defineProperty(u,"key",{get:p,configurable:!0})}function Oa(u,d){var p=function(){vs||(vs=!0,q("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",d))};p.isReactWarning=!0,Object.defineProperty(u,"ref",{get:p,configurable:!0})}function Pa(u){if(typeof u.ref=="string"&&x.current&&u.__self&&x.current.stateNode!==u.__self){var d=je(x.current.type);xr[d]||(q('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref',d,u.ref),xr[d]=!0)}}var Nr=function(u,d,p,g,b,N,P){var j={$$typeof:e,type:u,key:d,ref:p,props:P,_owner:N};return j._store={},Object.defineProperty(j._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(j,"_self",{configurable:!1,enumerable:!1,writable:!1,value:g}),Object.defineProperty(j,"_source",{configurable:!1,enumerable:!1,writable:!1,value:b}),Object.freeze&&(Object.freeze(j.props),Object.freeze(j)),j};function Ca(u,d,p){var g,b={},N=null,P=null,j=null,B=null;if(d!=null){ws(d)&&(P=d.ref,Pa(d)),bs(d)&&(Ct(d.key),N=""+d.key),j=d.__self===void 0?null:d.__self,B=d.__source===void 0?null:d.__source;for(g in d)ot.call(d,g)&&!gs.hasOwnProperty(g)&&(b[g]=d[g])}var z=arguments.length-2;if(z===1)b.children=p;else if(z>1){for(var Y=Array(z),X=0;X<z;X++)Y[X]=arguments[X+2];Object.freeze&&Object.freeze(Y),b.children=Y}if(u&&u.defaultProps){var ee=u.defaultProps;for(g in ee)b[g]===void 0&&(b[g]=ee[g])}if(N||P){var ie=typeof u=="function"?u.displayName||u.name||"Unknown":u;N&&ka(b,ie),P&&Oa(b,ie)}return Nr(u,N,P,j,B,x.current,b)}function Ia(u,d){var p=Nr(u.type,d,u.ref,u._self,u._source,u._owner,u.props);return p}function xa(u,d,p){if(u==null)throw new Error("React.cloneElement(...): The argument must be a React element, but you passed "+u+".");var g,b=Ie({},u.props),N=u.key,P=u.ref,j=u._self,B=u._source,z=u._owner;if(d!=null){ws(d)&&(P=d.ref,z=x.current),bs(d)&&(Ct(d.key),N=""+d.key);var Y;u.type&&u.type.defaultProps&&(Y=u.type.defaultProps);for(g in d)ot.call(d,g)&&!gs.hasOwnProperty(g)&&(d[g]===void 0&&Y!==void 0?b[g]=Y[g]:b[g]=d[g])}var X=arguments.length-2;if(X===1)b.children=p;else if(X>1){for(var ee=Array(X),ie=0;ie<X;ie++)ee[ie]=arguments[ie+2];b.children=ee}return Nr(u.type,N,P,j,B,z,b)}function Ve(u){return typeof u=="object"&&u!==null&&u.$$typeof===e}var Es=".",Na=":";function ja(u){var d=/[=:]/g,p={"=":"=0",":":"=2"},g=u.replace(d,function(b){return p[b]});return"$"+g}var Ss=!1,La=/\/+/g;function Ts(u){return u.replace(La,"$&/")}function jr(u,d){return typeof u=="object"&&u!==null&&u.key!=null?(Ct(u.key),ja(""+u.key)):d.toString(36)}function It(u,d,p,g,b){var N=typeof u;(N==="undefined"||N==="boolean")&&(u=null);var P=!1;if(u===null)P=!0;else switch(N){case"string":case"number":P=!0;break;case"object":switch(u.$$typeof){case e:case r:P=!0}}if(P){var j=u,B=b(j),z=g===""?Es+jr(j,0):g;if(Pt(B)){var Y="";z!=null&&(Y=Ts(z)+"/"),It(B,d,Y,"",function(ku){return ku})}else B!=null&&(Ve(B)&&(B.key&&(!j||j.key!==B.key)&&Ct(B.key),B=Ia(B,p+(B.key&&(!j||j.key!==B.key)?Ts(""+B.key)+"/":"")+z)),d.push(B));return 1}var X,ee,ie=0,le=g===""?Es:g+Na;if(Pt(u))for(var Ft=0;Ft<u.length;Ft++)X=u[Ft],ee=le+jr(X,Ft),ie+=It(X,d,p,ee,b);else{var Wr=w(u);if(typeof Wr=="function"){var Js=u;Wr===Js.entries&&(Ss||We("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Ss=!0);for(var Au=Wr.call(Js),Ys,Ru=0;!(Ys=Au.next()).done;)X=Ys.value,ee=le+jr(X,Ru++),ie+=It(X,d,p,ee,b)}else if(N==="object"){var Xs=String(u);throw new Error("Objects are not valid as a React child (found: "+(Xs==="[object Object]"?"object with keys {"+Object.keys(u).join(", ")+"}":Xs)+"). If you meant to render a collection of children, use an array instead.")}}return ie}function xt(u,d,p){if(u==null)return u;var g=[],b=0;return It(u,g,"","",function(N){return d.call(p,N,b++)}),g}function Ua(u){var d=0;return xt(u,function(){d++}),d}function $a(u,d,p){xt(u,function(){d.apply(this,arguments)},p)}function Da(u){return xt(u,function(d){return d})||[]}function Fa(u){if(!Ve(u))throw new Error("React.Children.only expected to receive a single React element child.");return u}function Ba(u){var d={$$typeof:a,_currentValue:u,_currentValue2:u,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};d.Provider={$$typeof:o,_context:d};var p=!1,g=!1,b=!1;{var N={$$typeof:a,_context:d};Object.defineProperties(N,{Provider:{get:function(){return g||(g=!0,q("Rendering <Context.Consumer.Provider> is not supported and will be removed in a future major release. Did you mean to render <Context.Provider> instead?")),d.Provider},set:function(P){d.Provider=P}},_currentValue:{get:function(){return d._currentValue},set:function(P){d._currentValue=P}},_currentValue2:{get:function(){return d._currentValue2},set:function(P){d._currentValue2=P}},_threadCount:{get:function(){return d._threadCount},set:function(P){d._threadCount=P}},Consumer:{get:function(){return p||(p=!0,q("Rendering <Context.Consumer.Consumer> is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?")),d.Consumer}},displayName:{get:function(){return d.displayName},set:function(P){b||(We("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.",P),b=!0)}}}),d.Consumer=N}return d._currentRenderer=null,d._currentRenderer2=null,d}var at=-1,Lr=0,As=1,qa=2;function Ma(u){if(u._status===at){var d=u._result,p=d();if(p.then(function(N){if(u._status===Lr||u._status===at){var P=u;P._status=As,P._result=N}},function(N){if(u._status===Lr||u._status===at){var P=u;P._status=qa,P._result=N}}),u._status===at){var g=u;g._status=Lr,g._result=p}}if(u._status===As){var b=u._result;return b===void 0&&q(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
43
43
|
|
|
44
44
|
Your code should look like:
|
|
45
45
|
const MyComponent = lazy(() => import('./MyComponent'))
|
|
@@ -47,21 +47,21 @@ Your code should look like:
|
|
|
47
47
|
Did you accidentally put curly braces around the import?`,b),"default"in b||q(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
48
48
|
|
|
49
49
|
Your code should look like:
|
|
50
|
-
const MyComponent = lazy(() => import('./MyComponent'))`,b),b.default}else throw u._result}function
|
|
50
|
+
const MyComponent = lazy(() => import('./MyComponent'))`,b),b.default}else throw u._result}function Wa(u){var d={_status:at,_result:u},p={$$typeof:_,_payload:d,_init:Ma};{var g,b;Object.defineProperties(p,{defaultProps:{configurable:!0,get:function(){return g},set:function(N){q("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."),g=N,Object.defineProperty(p,"defaultProps",{enumerable:!0})}},propTypes:{configurable:!0,get:function(){return b},set:function(N){q("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."),b=N,Object.defineProperty(p,"propTypes",{enumerable:!0})}}})}return p}function Va(u){u!=null&&u.$$typeof===m?q("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."):typeof u!="function"?q("forwardRef requires a render function but was given %s.",u===null?"null":typeof u):u.length!==0&&u.length!==2&&q("forwardRef render functions accept exactly two parameters: props and ref. %s",u.length===1?"Did you forget to use the ref parameter?":"Any additional parameter will be undefined."),u!=null&&(u.defaultProps!=null||u.propTypes!=null)&&q("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?");var d={$$typeof:l,render:u};{var p;Object.defineProperty(d,"displayName",{enumerable:!1,configurable:!0,get:function(){return p},set:function(g){p=g,!u.name&&!u.displayName&&(u.displayName=g)}})}return d}var Rs;Rs=Symbol.for("react.module.reference");function ks(u){return!!(typeof u=="string"||typeof u=="function"||u===n||u===i||wa||u===s||u===c||u===h||va||u===f||ke||Ee||ya||typeof u=="object"&&u!==null&&(u.$$typeof===_||u.$$typeof===m||u.$$typeof===o||u.$$typeof===a||u.$$typeof===l||u.$$typeof===Rs||u.getModuleId!==void 0))}function Ha(u,d){ks(u)||q("memo: The first argument must be a component. Instead received: %s",u===null?"null":typeof u);var p={$$typeof:m,type:u,compare:d===void 0?null:d};{var g;Object.defineProperty(p,"displayName",{enumerable:!1,configurable:!0,get:function(){return g},set:function(b){g=b,!u.name&&!u.displayName&&(u.displayName=b)}})}return p}function de(){var u=T.current;return u===null&&q(`Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
|
|
51
51
|
1. You might have mismatching versions of React and the renderer (such as React DOM)
|
|
52
52
|
2. You might be breaking the Rules of Hooks
|
|
53
53
|
3. You might have more than one copy of React in the same app
|
|
54
|
-
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.`),u}function
|
|
55
|
-
`+$r+u}}var Dr=!1,
|
|
54
|
+
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.`),u}function Ka(u){var d=de();if(u._context!==void 0){var p=u._context;p.Consumer===u?q("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"):p.Provider===u&&q("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?")}return d.useContext(u)}function za(u){var d=de();return d.useState(u)}function Ga(u,d,p){var g=de();return g.useReducer(u,d,p)}function Ja(u){var d=de();return d.useRef(u)}function Ya(u,d){var p=de();return p.useEffect(u,d)}function Xa(u,d){var p=de();return p.useInsertionEffect(u,d)}function Qa(u,d){var p=de();return p.useLayoutEffect(u,d)}function Za(u,d){var p=de();return p.useCallback(u,d)}function eu(u,d){var p=de();return p.useMemo(u,d)}function tu(u,d,p){var g=de();return g.useImperativeHandle(u,d,p)}function ru(u,d){{var p=de();return p.useDebugValue(u,d)}}function nu(){var u=de();return u.useTransition()}function su(u){var d=de();return d.useDeferredValue(u)}function iu(){var u=de();return u.useId()}function ou(u,d,p){var g=de();return g.useSyncExternalStore(u,d,p)}var ut=0,Os,Ps,Cs,Is,xs,Ns,js;function Ls(){}Ls.__reactDisabledLog=!0;function au(){{if(ut===0){Os=console.log,Ps=console.info,Cs=console.warn,Is=console.error,xs=console.group,Ns=console.groupCollapsed,js=console.groupEnd;var u={configurable:!0,enumerable:!0,value:Ls,writable:!0};Object.defineProperties(console,{info:u,log:u,warn:u,error:u,group:u,groupCollapsed:u,groupEnd:u})}ut++}}function uu(){{if(ut--,ut===0){var u={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:Ie({},u,{value:Os}),info:Ie({},u,{value:Ps}),warn:Ie({},u,{value:Cs}),error:Ie({},u,{value:Is}),group:Ie({},u,{value:xs}),groupCollapsed:Ie({},u,{value:Ns}),groupEnd:Ie({},u,{value:js})})}ut<0&&q("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var Ur=Me.ReactCurrentDispatcher,$r;function Nt(u,d,p){{if($r===void 0)try{throw Error()}catch(b){var g=b.stack.trim().match(/\n( *(at )?)/);$r=g&&g[1]||""}return`
|
|
55
|
+
`+$r+u}}var Dr=!1,jt;{var lu=typeof WeakMap=="function"?WeakMap:Map;jt=new lu}function Us(u,d){if(!u||Dr)return"";{var p=jt.get(u);if(p!==void 0)return p}var g;Dr=!0;var b=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var N;N=Ur.current,Ur.current=null,au();try{if(d){var P=function(){throw Error()};if(Object.defineProperty(P.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(P,[])}catch(le){g=le}Reflect.construct(u,[],P)}else{try{P.call()}catch(le){g=le}u.call(P.prototype)}}else{try{throw Error()}catch(le){g=le}u()}}catch(le){if(le&&g&&typeof le.stack=="string"){for(var j=le.stack.split(`
|
|
56
56
|
`),B=g.stack.split(`
|
|
57
57
|
`),z=j.length-1,Y=B.length-1;z>=1&&Y>=0&&j[z]!==B[Y];)Y--;for(;z>=1&&Y>=0;z--,Y--)if(j[z]!==B[Y]){if(z!==1||Y!==1)do if(z--,Y--,Y<0||j[z]!==B[Y]){var X=`
|
|
58
|
-
`+j[z].replace(" at new "," at ");return u.displayName&&X.includes("<anonymous>")&&(X=X.replace("<anonymous>",u.displayName)),typeof u=="function"&&
|
|
58
|
+
`+j[z].replace(" at new "," at ");return u.displayName&&X.includes("<anonymous>")&&(X=X.replace("<anonymous>",u.displayName)),typeof u=="function"&&jt.set(u,X),X}while(z>=1&&Y>=0);break}}}finally{Dr=!1,Ur.current=N,uu(),Error.prepareStackTrace=b}var ee=u?u.displayName||u.name:"",ie=ee?Nt(ee):"";return typeof u=="function"&&jt.set(u,ie),ie}function cu(u,d,p){return Us(u,!1)}function du(u){var d=u.prototype;return!!(d&&d.isReactComponent)}function Lt(u,d,p){if(u==null)return"";if(typeof u=="function")return Us(u,du(u));if(typeof u=="string")return Nt(u);switch(u){case c:return Nt("Suspense");case h:return Nt("SuspenseList")}if(typeof u=="object")switch(u.$$typeof){case l:return cu(u.render);case m:return Lt(u.type,d,p);case _:{var g=u,b=g._payload,N=g._init;try{return Lt(N(b),d,p)}catch{}}}return""}var $s={},Ds=Me.ReactDebugCurrentFrame;function Ut(u){if(u){var d=u._owner,p=Lt(u.type,u._source,d?d.type:null);Ds.setExtraStackFrame(p)}else Ds.setExtraStackFrame(null)}function hu(u,d,p,g,b){{var N=Function.call.bind(ot);for(var P in u)if(N(u,P)){var j=void 0;try{if(typeof u[P]!="function"){var B=Error((g||"React class")+": "+p+" type `"+P+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof u[P]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw B.name="Invariant Violation",B}j=u[P](d,P,g,p,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(z){j=z}j&&!(j instanceof Error)&&(Ut(b),q("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",g||"React class",p,P,typeof j),Ut(null)),j instanceof Error&&!(j.message in $s)&&($s[j.message]=!0,Ut(b),q("Failed %s type: %s",p,j.message),Ut(null))}}}function He(u){if(u){var d=u._owner,p=Lt(u.type,u._source,d?d.type:null);re(p)}else re(null)}var Fr;Fr=!1;function Fs(){if(x.current){var u=je(x.current.type);if(u)return`
|
|
59
59
|
|
|
60
|
-
Check the render method of \``+u+"`."}return""}function
|
|
60
|
+
Check the render method of \``+u+"`."}return""}function fu(u){if(u!==void 0){var d=u.fileName.replace(/^.*[\\\/]/,""),p=u.lineNumber;return`
|
|
61
61
|
|
|
62
|
-
Check your code at `+d+":"+p+"."}return""}function
|
|
62
|
+
Check your code at `+d+":"+p+"."}return""}function pu(u){return u!=null?fu(u.__source):""}var Bs={};function mu(u){var d=Fs();if(!d){var p=typeof u=="string"?u:u.displayName||u.name;p&&(d=`
|
|
63
63
|
|
|
64
|
-
Check the top-level render call using <`+p+">.")}return d}function qs(u,d){if(!(!u._store||u._store.validated||u.key!=null)){u._store.validated=!0;var p=fu(d);if(!Bs[p]){Bs[p]=!0;var g="";u&&u._owner&&u._owner!==x.current&&(g=" It was passed a child from "+je(u._owner.type)+"."),He(u),q('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',p,g),He(null)}}}function Ms(u,d){if(typeof u=="object"){if(Ot(u))for(var p=0;p<u.length;p++){var g=u[p];Ve(g)&&qs(g,d)}else if(Ve(u))u._store&&(u._store.validated=!0);else if(u){var b=w(u);if(typeof b=="function"&&b!==u.entries)for(var N=b.call(u),C;!(C=N.next()).done;)Ve(C.value)&&qs(C.value,d)}}}function Ws(u){{var d=u.type;if(d==null||typeof d=="string")return;var p;if(typeof d=="function")p=d.propTypes;else if(typeof d=="object"&&(d.$$typeof===l||d.$$typeof===m))p=d.propTypes;else return;if(p){var g=je(d);cu(p,u.props,"prop",g,u)}else if(d.PropTypes!==void 0&&!Fr){Fr=!0;var b=je(d);q("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",b||"Unknown")}typeof d.getDefaultProps=="function"&&!d.getDefaultProps.isReactClassApproved&&q("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function pu(u){{for(var d=Object.keys(u.props),p=0;p<d.length;p++){var g=d[p];if(g!=="children"&&g!=="key"){He(u),q("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",g),He(null);break}}u.ref!==null&&(He(u),q("Invalid attribute `ref` supplied to `React.Fragment`."),He(null))}}function Vs(u,d,p){var g=ks(u);if(!g){var b="";(u===void 0||typeof u=="object"&&u!==null&&Object.keys(u).length===0)&&(b+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var N=hu(d);N?b+=N:b+=Fs();var C;u===null?C="null":Ot(u)?C="array":u!==void 0&&u.$$typeof===e?(C="<"+(je(u.type)||"Unknown")+" />",b=" Did you accidentally export a JSX literal instead of a component?"):C=typeof u,q("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",C,b)}var j=Oa.apply(this,arguments);if(j==null)return j;if(g)for(var B=2;B<arguments.length;B++)Ms(arguments[B],u);return u===n?pu(j):Ws(j),j}var Hs=!1;function mu(u){var d=Vs.bind(null,u);return d.type=u,Hs||(Hs=!0,We("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead.")),Object.defineProperty(d,"type",{enumerable:!1,get:function(){return We("Factory.type is deprecated. Access the class directly before passing it to createFactory."),Object.defineProperty(this,"type",{value:u}),u}}),d}function _u(u,d,p){for(var g=Pa.apply(this,arguments),b=2;b<arguments.length;b++)Ms(arguments[b],g.type);return Ws(g),g}function gu(u,d){var p=O.transition;O.transition={};var g=O.transition;O.transition._updatedFibers=new Set;try{u()}finally{if(O.transition=p,p===null&&g._updatedFibers){var b=g._updatedFibers.size;b>10&&We("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."),g._updatedFibers.clear()}}}var Ks=!1,Ut=null;function yu(u){if(Ut===null)try{var d=("require"+Math.random()).slice(0,7),p=Tr&&Tr[d];Ut=p.call(Tr,"timers").setImmediate}catch{Ut=function(b){Ks===!1&&(Ks=!0,typeof MessageChannel>"u"&&q("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var N=new MessageChannel;N.port1.onmessage=b,N.port2.postMessage(void 0)}}return Ut(u)}var Ke=0,zs=!1;function Gs(u){{var d=Ke;Ke++,E.current===null&&(E.current=[]);var p=E.isBatchingLegacy,g;try{if(E.isBatchingLegacy=!0,g=u(),!p&&E.didScheduleLegacyUpdate){var b=E.current;b!==null&&(E.didScheduleLegacyUpdate=!1,Mr(b))}}catch(ee){throw $t(d),ee}finally{E.isBatchingLegacy=p}if(g!==null&&typeof g=="object"&&typeof g.then=="function"){var N=g,C=!1,j={then:function(ee,ie){C=!0,N.then(function(le){$t(d),Ke===0?Br(le,ee,ie):ee(le)},function(le){$t(d),ie(le)})}};return!zs&&typeof Promise<"u"&&Promise.resolve().then(function(){}).then(function(){C||(zs=!0,q("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))}),j}else{var B=g;if($t(d),Ke===0){var z=E.current;z!==null&&(Mr(z),E.current=null);var Y={then:function(ee,ie){E.current===null?(E.current=[],Br(B,ee,ie)):ee(B)}};return Y}else{var X={then:function(ee,ie){ee(B)}};return X}}}}function $t(u){u!==Ke-1&&q("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),Ke=u}function Br(u,d,p){{var g=E.current;if(g!==null)try{Mr(g),yu(function(){g.length===0?(E.current=null,d(u)):Br(u,d,p)})}catch(b){p(b)}else d(u)}}var qr=!1;function Mr(u){if(!qr){qr=!0;var d=0;try{for(;d<u.length;d++){var p=u[d];do p=p(!0);while(p!==null)}u.length=0}catch(g){throw u=u.slice(d+1),g}finally{qr=!1}}}var vu=Vs,wu=_u,bu=mu,Eu={map:It,forEach:La,count:ja,toArray:Ua,only:$a};U.Children=Eu,U.Component=Ue,U.Fragment=n,U.Profiler=i,U.PureComponent=Pr,U.StrictMode=s,U.Suspense=c,U.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Me,U.act=Gs,U.cloneElement=wu,U.createContext=Da,U.createElement=vu,U.createFactory=bu,U.createRef=wa,U.forwardRef=Ma,U.isValidElement=Ve,U.lazy=qa,U.memo=Wa,U.startTransition=gu,U.unstable_act=Gs,U.useCallback=Xa,U.useContext=Va,U.useDebugValue=eu,U.useDeferredValue=ru,U.useEffect=Ga,U.useId=nu,U.useImperativeHandle=Za,U.useInsertionEffect=Ja,U.useLayoutEffect=Ya,U.useMemo=Qa,U.useReducer=Ka,U.useRef=za,U.useState=Ha,U.useSyncExternalStore=su,U.useTransition=tu,U.version=t,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)})()});var da=$((Gf,cs)=>{"use strict";process.env.NODE_ENV==="production"?cs.exports=la():cs.exports=ca()});var si=[{canonical:"prproj",aliases:["prproj"],extensions:["prproj"],label:"Premiere Pro Project",short_label:"Premiere Project",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!0,parse_dispatch_key:"prproj"},{canonical:"premiere-xml",aliases:["premiere-xml"],extensions:["xml"],label:"Premiere Pro XML",short_label:"Premiere XML",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!0,parse_dispatch_key:"xmeml"},{canonical:"resolve-xml",aliases:["resolve-xml"],extensions:["xml"],label:"DaVinci Resolve XML",short_label:"Resolve XML",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"xmeml"},{canonical:"resolve-fcpxml",aliases:["resolve-fcpxml"],extensions:["fcpxml"],label:"DaVinci Resolve FCPXML",short_label:"Resolve FCPXML",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!0,parse_dispatch_key:"fcpxml"},{canonical:"finalcut-fcpxml",aliases:["finalcut-fcpxml","fcpxmld"],extensions:["fcpxmld","fcpxml"],label:"Apple Final Cut Pro (.fcpxmld)",short_label:"Final Cut",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!0,parse_dispatch_key:"fcpxml"},{canonical:"resolve-drt",aliases:["resolve-drt"],extensions:["drt"],label:"DaVinci Resolve Timeline (.drt)",short_label:"Resolve DRT",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"drt"},{canonical:"fcp-xml",aliases:["fcp-xml"],extensions:["xml"],label:"Final Cut Pro 7 XML",short_label:"FCP XML",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!1,parse_dispatch_key:"xmeml"},{canonical:"aaf",aliases:["aaf"],extensions:["aaf"],label:"Avid AAF",short_label:"AAF",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!0,parse_dispatch_key:"aaf"},{canonical:"avb",aliases:["avb"],extensions:["avb"],label:"Avid Bin",short_label:"Avid Bin",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!0,parse_dispatch_key:"avb"},{canonical:"flame-archive",aliases:["flame-archive","flame"],extensions:[],label:"Autodesk Flame Archive",short_label:"Flame Archive",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"flame-archive"},{canonical:"otio",aliases:["otio"],extensions:["otio","otioz"],label:"OpenTimelineIO",short_label:"OTIO",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"otio"},{canonical:"baselight-blscene",aliases:["baselight-blscene","blscene","baselight"],extensions:["blscene"],label:"Baselight Scene",short_label:"Baselight",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"blscene"},{canonical:"capcut",aliases:["capcut","jianying"],extensions:[],label:"CapCut Project",short_label:"CapCut",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!1,parse_dispatch_key:"capcut"}],ku=new Map,ni=new Map;for(let t of si){for(let e of t.aliases)ku.set(e.toLowerCase(),t);for(let e of t.extensions){let r=ni.get(e.toLowerCase())??[];r.push(t),ni.set(e.toLowerCase(),r)}}var oh=new Set(si.map(t=>t.canonical));async function Hr(t){let e=t.name.toLowerCase();if(e.endsWith(".prproj"))return{format:"prproj",confidence:"high",details:"Premiere Pro project file (.prproj)"};if(e.endsWith(".aaf"))return{format:"aaf",confidence:"high",details:"Advanced Authoring Format (.aaf)"};if(e.endsWith(".avb"))return{format:"avb",confidence:"high",details:"Avid Bin file (.avb)"};if(e.endsWith(".otio"))return{format:"otio",confidence:"high",details:"OpenTimelineIO file (.otio)"};if(e.endsWith(".blscene"))return{format:"baselight-blscene",confidence:"high",details:"Baselight scene (.blscene)"};if(e.endsWith(".drt"))return{format:"resolve-drt",confidence:"high",details:"DaVinci Resolve Timeline (.drt)"};if(e.endsWith(".fcpxmld"))return{format:"finalcut-fcpxml",confidence:"high",details:"Final Cut Pro bundle (.fcpxmld)"};if(e.endsWith(".fcpxml")){try{let r=await t.slice(0,65536).text();if(/<library\b/.test(r)||/<fcpxml\s+version="1\.1\d"/.test(r))return{format:"finalcut-fcpxml",confidence:"high",details:"Final Cut Pro FCPXML export (.fcpxml)"}}catch{}return{format:"resolve-fcpxml",confidence:"high",details:"FCPXML file (.fcpxml) \u2014 DaVinci Resolve export"}}if(e.endsWith(".json")){if(/(^|\/)draft_(content|info)\.json$/.test(e))return{format:"capcut",confidence:"high",details:"CapCut project (draft JSON)"};try{let r=await t.slice(0,262144).text();if(/"canvas_config"\s*:/.test(r)&&/"materials"\s*:/.test(r))return{format:"capcut",confidence:"medium",details:"CapCut project (draft JSON)"}}catch{}}if(e.endsWith(".xml"))return await Ou(t);if(e.endsWith(".flame-archive.zip"))return{format:"flame-archive",confidence:"high",details:"Autodesk Flame archive (.flame-archive.zip)"};{let r=new Uint8Array(await t.slice(0,4).arrayBuffer());if(r[0]===128&&r[1]===130&&r[2]===167&&r[3]===214)return{format:"flame-archive",confidence:"high",details:"Autodesk Flame archive (bare TOC header)"};if(r[0]===80&&r[1]===75)try{let{unzipSync:n}=await import("./esm-SFFBP7PS.js"),s=n(new Uint8Array(await t.arrayBuffer()));for(let[i,o]of Object.entries(s)){let a=o;if(/_\d+\.seg$/.test(i)||a.length>=4&&a[0]===128&&a[1]===130&&a[2]===167&&a[3]===214)return{format:"flame-archive",confidence:"medium",details:"Autodesk Flame archive (zip-wrapped TOC + segs)"}}}catch{}}return{format:"unknown",confidence:"high",details:`Unsupported file extension: ${e.split(".").pop()||"none"}`}}async function Ou(t){try{let e=await t.text(),n=new DOMParser().parseFromString(e,"text/xml");if(n.querySelector("parsererror"))return{format:"unknown",confidence:"high",details:"Invalid XML file"};if(n.querySelectorAll("track[premiereTrackType]").length>0)return{format:"premiere-xml",confidence:"high",details:"Found premiereTrackType attribute on track element"};if(n.querySelector("xmeml")){let a=n.querySelectorAll("sequence > name, bin > name");for(let l of a)if(l.textContent?.includes("(Resolve)"))return{format:"resolve-xml",confidence:"high",details:'Found "(Resolve)" marker in sequence/bin name'};return{format:"fcp-xml",confidence:"medium",details:"XMEML format without Premiere/Resolve markers - likely Final Cut Pro"}}return{format:"unknown",confidence:"high",details:"No recognized XML format markers found"}}catch(e){return{format:"unknown",confidence:"high",details:`Failed to parse XML: ${e}`}}}var A={};Qs(A,{FunctionRegion:()=>be.FunctionRegion,FunctionsError:()=>be.FunctionsError,FunctionsFetchError:()=>be.FunctionsFetchError,FunctionsHttpError:()=>be.FunctionsHttpError,FunctionsRelayError:()=>be.FunctionsRelayError,PostgrestError:()=>en,SupabaseClient:()=>Fo,createClient:()=>rs});var be=ze(Li(),1);var en=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},Uu=class{constructor(t){var e,r,n;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(n=t.urlLengthLimit)!==null&&n!==void 0?n:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let n=this.fetch,s=n(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let o=null,a=null,l=null,c=i.status,h=i.statusText;if(i.ok){var m,_;if(r.method!=="HEAD"){var f;let T=await i.text();T===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((f=r.headers.get("Accept"))===null||f===void 0)&&f.includes("application/vnd.pgrst.plan+text"))?a=T:a=JSON.parse(T))}let v=(m=r.headers.get("Prefer"))===null||m===void 0?void 0:m.match(/count=(exact|planned|estimated)/),w=(_=i.headers.get("content-range"))===null||_===void 0?void 0:_.split("/");v&&w&&w.length>1&&(l=parseInt(w[1])),r.isMaybeSingle&&r.method==="GET"&&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,l=null,c=406,h="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{var y;let v=await i.text();try{o=JSON.parse(v),Array.isArray(o)&&i.status===404&&(a=[],o=null,c=200,h="OK")}catch{i.status===404&&v===""?(c=204,h="No Content"):o={message:v}}if(o&&r.isMaybeSingle&&(!(o==null||(y=o.details)===null||y===void 0)&&y.includes("0 rows"))&&(o=null,c=200,h="OK"),o&&r.shouldThrowOnError)throw new en(o)}return{error:o,data:a,count:l,status:c,statusText:h}});return this.shouldThrowOnError||(s=s.catch(i=>{var o;let a="",l="",c="",h=i?.cause;if(h){var m,_,f,y;let T=(m=h?.message)!==null&&m!==void 0?m:"",O=(_=h?.code)!==null&&_!==void 0?_:"";a=`${(f=i?.name)!==null&&f!==void 0?f:"FetchError"}: ${i?.message}`,a+=`
|
|
64
|
+
Check the top-level render call using <`+p+">.")}return d}function qs(u,d){if(!(!u._store||u._store.validated||u.key!=null)){u._store.validated=!0;var p=mu(d);if(!Bs[p]){Bs[p]=!0;var g="";u&&u._owner&&u._owner!==x.current&&(g=" It was passed a child from "+je(u._owner.type)+"."),He(u),q('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',p,g),He(null)}}}function Ms(u,d){if(typeof u=="object"){if(Pt(u))for(var p=0;p<u.length;p++){var g=u[p];Ve(g)&&qs(g,d)}else if(Ve(u))u._store&&(u._store.validated=!0);else if(u){var b=w(u);if(typeof b=="function"&&b!==u.entries)for(var N=b.call(u),P;!(P=N.next()).done;)Ve(P.value)&&qs(P.value,d)}}}function Ws(u){{var d=u.type;if(d==null||typeof d=="string")return;var p;if(typeof d=="function")p=d.propTypes;else if(typeof d=="object"&&(d.$$typeof===l||d.$$typeof===m))p=d.propTypes;else return;if(p){var g=je(d);hu(p,u.props,"prop",g,u)}else if(d.PropTypes!==void 0&&!Fr){Fr=!0;var b=je(d);q("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",b||"Unknown")}typeof d.getDefaultProps=="function"&&!d.getDefaultProps.isReactClassApproved&&q("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function _u(u){{for(var d=Object.keys(u.props),p=0;p<d.length;p++){var g=d[p];if(g!=="children"&&g!=="key"){He(u),q("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",g),He(null);break}}u.ref!==null&&(He(u),q("Invalid attribute `ref` supplied to `React.Fragment`."),He(null))}}function Vs(u,d,p){var g=ks(u);if(!g){var b="";(u===void 0||typeof u=="object"&&u!==null&&Object.keys(u).length===0)&&(b+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var N=pu(d);N?b+=N:b+=Fs();var P;u===null?P="null":Pt(u)?P="array":u!==void 0&&u.$$typeof===e?(P="<"+(je(u.type)||"Unknown")+" />",b=" Did you accidentally export a JSX literal instead of a component?"):P=typeof u,q("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",P,b)}var j=Ca.apply(this,arguments);if(j==null)return j;if(g)for(var B=2;B<arguments.length;B++)Ms(arguments[B],u);return u===n?_u(j):Ws(j),j}var Hs=!1;function gu(u){var d=Vs.bind(null,u);return d.type=u,Hs||(Hs=!0,We("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead.")),Object.defineProperty(d,"type",{enumerable:!1,get:function(){return We("Factory.type is deprecated. Access the class directly before passing it to createFactory."),Object.defineProperty(this,"type",{value:u}),u}}),d}function yu(u,d,p){for(var g=xa.apply(this,arguments),b=2;b<arguments.length;b++)Ms(arguments[b],g.type);return Ws(g),g}function vu(u,d){var p=O.transition;O.transition={};var g=O.transition;O.transition._updatedFibers=new Set;try{u()}finally{if(O.transition=p,p===null&&g._updatedFibers){var b=g._updatedFibers.size;b>10&&We("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."),g._updatedFibers.clear()}}}var Ks=!1,$t=null;function wu(u){if($t===null)try{var d=("require"+Math.random()).slice(0,7),p=Tr&&Tr[d];$t=p.call(Tr,"timers").setImmediate}catch{$t=function(b){Ks===!1&&(Ks=!0,typeof MessageChannel>"u"&&q("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var N=new MessageChannel;N.port1.onmessage=b,N.port2.postMessage(void 0)}}return $t(u)}var Ke=0,zs=!1;function Gs(u){{var d=Ke;Ke++,E.current===null&&(E.current=[]);var p=E.isBatchingLegacy,g;try{if(E.isBatchingLegacy=!0,g=u(),!p&&E.didScheduleLegacyUpdate){var b=E.current;b!==null&&(E.didScheduleLegacyUpdate=!1,Mr(b))}}catch(ee){throw Dt(d),ee}finally{E.isBatchingLegacy=p}if(g!==null&&typeof g=="object"&&typeof g.then=="function"){var N=g,P=!1,j={then:function(ee,ie){P=!0,N.then(function(le){Dt(d),Ke===0?Br(le,ee,ie):ee(le)},function(le){Dt(d),ie(le)})}};return!zs&&typeof Promise<"u"&&Promise.resolve().then(function(){}).then(function(){P||(zs=!0,q("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))}),j}else{var B=g;if(Dt(d),Ke===0){var z=E.current;z!==null&&(Mr(z),E.current=null);var Y={then:function(ee,ie){E.current===null?(E.current=[],Br(B,ee,ie)):ee(B)}};return Y}else{var X={then:function(ee,ie){ee(B)}};return X}}}}function Dt(u){u!==Ke-1&&q("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),Ke=u}function Br(u,d,p){{var g=E.current;if(g!==null)try{Mr(g),wu(function(){g.length===0?(E.current=null,d(u)):Br(u,d,p)})}catch(b){p(b)}else d(u)}}var qr=!1;function Mr(u){if(!qr){qr=!0;var d=0;try{for(;d<u.length;d++){var p=u[d];do p=p(!0);while(p!==null)}u.length=0}catch(g){throw u=u.slice(d+1),g}finally{qr=!1}}}var bu=Vs,Eu=yu,Su=gu,Tu={map:xt,forEach:$a,count:Ua,toArray:Da,only:Fa};U.Children=Tu,U.Component=Ue,U.Fragment=n,U.Profiler=i,U.PureComponent=Cr,U.StrictMode=s,U.Suspense=c,U.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Me,U.act=Gs,U.cloneElement=Eu,U.createContext=Ba,U.createElement=bu,U.createFactory=Su,U.createRef=Ea,U.forwardRef=Va,U.isValidElement=Ve,U.lazy=Wa,U.memo=Ha,U.startTransition=vu,U.unstable_act=Gs,U.useCallback=Za,U.useContext=Ka,U.useDebugValue=ru,U.useDeferredValue=su,U.useEffect=Ya,U.useId=iu,U.useImperativeHandle=tu,U.useInsertionEffect=Xa,U.useLayoutEffect=Qa,U.useMemo=eu,U.useReducer=Ga,U.useRef=Ja,U.useState=za,U.useSyncExternalStore=ou,U.useTransition=nu,U.version=t,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)})()});var fa=$((Zf,cs)=>{"use strict";process.env.NODE_ENV==="production"?cs.exports=da():cs.exports=ha()});var si=[{canonical:"prproj",aliases:["prproj"],extensions:["prproj"],label:"Premiere Pro Project",short_label:"Premiere Project",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!0,parse_dispatch_key:"prproj"},{canonical:"premiere-xml",aliases:["premiere-xml"],extensions:["xml"],label:"Premiere Pro XML",short_label:"Premiere XML",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!0,parse_dispatch_key:"xmeml"},{canonical:"resolve-xml",aliases:["resolve-xml"],extensions:["xml"],label:"DaVinci Resolve XML",short_label:"Resolve XML",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"xmeml"},{canonical:"resolve-fcpxml",aliases:["resolve-fcpxml"],extensions:["fcpxml"],label:"DaVinci Resolve FCPXML",short_label:"Resolve FCPXML",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!0,parse_dispatch_key:"fcpxml"},{canonical:"finalcut-fcpxml",aliases:["finalcut-fcpxml","fcpxmld"],extensions:["fcpxmld","fcpxml"],label:"Apple Final Cut Pro (.fcpxmld)",short_label:"Final Cut",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!0,parse_dispatch_key:"fcpxml"},{canonical:"resolve-drt",aliases:["resolve-drt"],extensions:["drt"],label:"DaVinci Resolve Timeline (.drt)",short_label:"Resolve DRT",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"drt"},{canonical:"fcp-xml",aliases:["fcp-xml"],extensions:["xml"],label:"Final Cut Pro 7 XML",short_label:"FCP XML",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!1,parse_dispatch_key:"xmeml"},{canonical:"aaf",aliases:["aaf"],extensions:["aaf"],label:"Avid AAF",short_label:"AAF",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!0,parse_dispatch_key:"aaf"},{canonical:"avb",aliases:["avb"],extensions:["avb"],label:"Avid Bin",short_label:"Avid Bin",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!0,parse_dispatch_key:"avb"},{canonical:"flame-archive",aliases:["flame-archive","flame"],extensions:[],label:"Autodesk Flame Archive",short_label:"Flame Archive",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"flame-archive"},{canonical:"otio",aliases:["otio"],extensions:["otio","otioz"],label:"OpenTimelineIO",short_label:"OTIO",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"otio"},{canonical:"baselight-blscene",aliases:["baselight-blscene","blscene","baselight"],extensions:["blscene"],label:"Baselight Scene",short_label:"Baselight",is_supported:!0,can_import:!0,can_export:!0,supports_multi_timeline:!1,parse_dispatch_key:"blscene"},{canonical:"capcut",aliases:["capcut","jianying"],extensions:[],label:"CapCut Project",short_label:"CapCut",is_supported:!0,can_import:!0,can_export:!1,supports_multi_timeline:!1,parse_dispatch_key:"capcut"}],Pu=new Map,ni=new Map;for(let t of si){for(let e of t.aliases)Pu.set(e.toLowerCase(),t);for(let e of t.extensions){let r=ni.get(e.toLowerCase())??[];r.push(t),ni.set(e.toLowerCase(),r)}}var uh=new Set(si.map(t=>t.canonical));async function Hr(t){let e=t.name.toLowerCase();if(e.endsWith(".prproj"))return{format:"prproj",confidence:"high",details:"Premiere Pro project file (.prproj)"};if(e.endsWith(".aaf"))return{format:"aaf",confidence:"high",details:"Advanced Authoring Format (.aaf)"};if(e.endsWith(".avb"))return{format:"avb",confidence:"high",details:"Avid Bin file (.avb)"};if(e.endsWith(".otio"))return{format:"otio",confidence:"high",details:"OpenTimelineIO file (.otio)"};if(e.endsWith(".blscene"))return{format:"baselight-blscene",confidence:"high",details:"Baselight scene (.blscene)"};if(e.endsWith(".drt"))return{format:"resolve-drt",confidence:"high",details:"DaVinci Resolve Timeline (.drt)"};if(e.endsWith(".fcpxmld"))return{format:"finalcut-fcpxml",confidence:"high",details:"Final Cut Pro bundle (.fcpxmld)"};if(e.endsWith(".fcpxml")){try{let r=await t.slice(0,65536).text();if(/<library\b/.test(r)||/<fcpxml\s+version="1\.1\d"/.test(r))return{format:"finalcut-fcpxml",confidence:"high",details:"Final Cut Pro FCPXML export (.fcpxml)"}}catch{}return{format:"resolve-fcpxml",confidence:"high",details:"FCPXML file (.fcpxml) \u2014 DaVinci Resolve export"}}if(e.endsWith(".json")){if(/(^|\/)draft_(content|info)\.json$/.test(e))return{format:"capcut",confidence:"high",details:"CapCut project (draft JSON)"};try{let r=await t.slice(0,262144).text();if(/"canvas_config"\s*:/.test(r)&&/"materials"\s*:/.test(r))return{format:"capcut",confidence:"medium",details:"CapCut project (draft JSON)"}}catch{}}if(e.endsWith(".xml"))return await Cu(t);if(e.endsWith(".flame-archive.zip"))return{format:"flame-archive",confidence:"high",details:"Autodesk Flame archive (.flame-archive.zip)"};{let r=new Uint8Array(await t.slice(0,4).arrayBuffer());if(r[0]===128&&r[1]===130&&r[2]===167&&r[3]===214)return{format:"flame-archive",confidence:"high",details:"Autodesk Flame archive (bare TOC header)"};if(r[0]===80&&r[1]===75)try{let{unzipSync:n}=await import("./esm-SFFBP7PS.js"),s=n(new Uint8Array(await t.arrayBuffer()));for(let[i,o]of Object.entries(s)){let a=o;if(/_\d+\.seg$/.test(i)||a.length>=4&&a[0]===128&&a[1]===130&&a[2]===167&&a[3]===214)return{format:"flame-archive",confidence:"medium",details:"Autodesk Flame archive (zip-wrapped TOC + segs)"}}}catch{}}return{format:"unknown",confidence:"high",details:`Unsupported file extension: ${e.split(".").pop()||"none"}`}}async function Cu(t){try{let e=await t.text(),n=new DOMParser().parseFromString(e,"text/xml");if(n.querySelector("parsererror"))return{format:"unknown",confidence:"high",details:"Invalid XML file"};if(n.querySelectorAll("track[premiereTrackType]").length>0)return{format:"premiere-xml",confidence:"high",details:"Found premiereTrackType attribute on track element"};if(n.querySelector("xmeml")){let a=n.querySelectorAll("sequence > name, bin > name");for(let l of a)if(l.textContent?.includes("(Resolve)"))return{format:"resolve-xml",confidence:"high",details:'Found "(Resolve)" marker in sequence/bin name'};return{format:"fcp-xml",confidence:"medium",details:"XMEML format without Premiere/Resolve markers - likely Final Cut Pro"}}return{format:"unknown",confidence:"high",details:"No recognized XML format markers found"}}catch(e){return{format:"unknown",confidence:"high",details:`Failed to parse XML: ${e}`}}}var A={};Qs(A,{FunctionRegion:()=>be.FunctionRegion,FunctionsError:()=>be.FunctionsError,FunctionsFetchError:()=>be.FunctionsFetchError,FunctionsHttpError:()=>be.FunctionsHttpError,FunctionsRelayError:()=>be.FunctionsRelayError,PostgrestError:()=>en,SupabaseClient:()=>Fo,createClient:()=>rs});var be=ze(Li(),1);var en=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},Du=class{constructor(t){var e,r,n;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(n=t.urlLengthLimit)!==null&&n!==void 0?n:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let n=this.fetch,s=n(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{let o=null,a=null,l=null,c=i.status,h=i.statusText;if(i.ok){var m,_;if(r.method!=="HEAD"){var f;let T=await i.text();T===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((f=r.headers.get("Accept"))===null||f===void 0)&&f.includes("application/vnd.pgrst.plan+text"))?a=T:a=JSON.parse(T))}let v=(m=r.headers.get("Prefer"))===null||m===void 0?void 0:m.match(/count=(exact|planned|estimated)/),w=(_=i.headers.get("content-range"))===null||_===void 0?void 0:_.split("/");v&&w&&w.length>1&&(l=parseInt(w[1])),r.isMaybeSingle&&r.method==="GET"&&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,l=null,c=406,h="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{var y;let v=await i.text();try{o=JSON.parse(v),Array.isArray(o)&&i.status===404&&(a=[],o=null,c=200,h="OK")}catch{i.status===404&&v===""?(c=204,h="No Content"):o={message:v}}if(o&&r.isMaybeSingle&&(!(o==null||(y=o.details)===null||y===void 0)&&y.includes("0 rows"))&&(o=null,c=200,h="OK"),o&&r.shouldThrowOnError)throw new en(o)}return{error:o,data:a,count:l,status:c,statusText:h}});return this.shouldThrowOnError||(s=s.catch(i=>{var o;let a="",l="",c="",h=i?.cause;if(h){var m,_,f,y;let T=(m=h?.message)!==null&&m!==void 0?m:"",O=(_=h?.code)!==null&&_!==void 0?_:"";a=`${(f=i?.name)!==null&&f!==void 0?f:"FetchError"}: ${i?.message}`,a+=`
|
|
65
65
|
|
|
66
66
|
Caused by: ${(y=h?.name)!==null&&y!==void 0?y:"Error"}: ${T}`,O&&(a+=` (${O})`),h?.stack&&(a+=`
|
|
67
|
-
${h.stack}`)}else{var v;a=(v=i?.stack)!==null&&v!==void 0?v:""}let w=this.url.toString().length;return i?.name==="AbortError"||i?.code==="ABORT_ERR"?(c="",l="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${w} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(h?.name==="HeadersOverflowError"||h?.code==="UND_ERR_HEADERS_OVERFLOW")&&(c="",l="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(l+=`. Your request URL is ${w} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(o=i?.name)!==null&&o!==void 0?o:"FetchError"}: ${i?.message}`,details:a,hint:l,code:c},data:null,count:null,status:0,statusText:""}})),s.then(t,e)}returns(){return this}overrideTypes(){return this}},$u=class extends Uu{select(t){let e=!1,r=(t??"*").split("").map(n=>/\s/.test(n)&&!e?"":(n==='"'&&(e=!e),n)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:n,referencedTable:s=n}={}){let i=s?`${s}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:n=r}={}){let s=typeof n>"u"?"offset":`${n}.offset`,i=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(s,`${t}`),this.url.searchParams.set(i,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:n=!1,wal:s=!1,format:i="text"}={}){var o;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,n?"buffers":null,s?"wal":null].filter(Boolean).join("|"),l=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${a};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},Ui=new RegExp("[,()]"),Xe=class extends $u{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Ui.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Ui.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:n}={}){let s="";n==="plain"?s="pl":n==="phrase"?s="ph":n==="websearch"&&(s="w");let i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${s}fts${i}.${e}`),this}match(t){return Object.entries(t).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Du=class{constructor(t,{headers:e={},schema:r,fetch:n,urlLengthLimit:s=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=n,this.urlLengthLimit=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:n}=e??{},s=r?"HEAD":"GET",i=!1,o=(t??"*").split("").map(c=>/\s/.test(c)&&!i?"":(c==='"'&&(i=!i),c)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",o),n&&l.append("Prefer",`count=${n}`),new Xe({method:s,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var n;let s="POST",{url:i,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(a.length>0){let l=[...new Set(a)].map(c=>`"${c}"`);i.searchParams.set("columns",l.join(","))}}return new Xe({method:s,url:i,headers:o,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:n,defaultToNull:s=!0}={}){var i;let o="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),n&&l.append("Prefer",`count=${n}`),s||l.append("Prefer","missing=default"),Array.isArray(t)){let c=t.reduce((h,m)=>h.concat(Object.keys(m)),[]);if(c.length>0){let h=[...new Set(c)].map(m=>`"${m}"`);a.searchParams.set("columns",h.join(","))}}return new Xe({method:o,url:a,headers:l,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let n="PATCH",{url:s,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Xe({method:n,url:s,headers:i,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:n,headers:s}=this.cloneRequestState();return t&&s.append("Prefer",`count=${t}`),new Xe({method:r,url:n,headers:s,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function ct(t){"@babel/helpers - typeof";return ct=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ct(t)}function Fu(t,e){if(ct(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(ct(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Bu(t){var e=Fu(t,"string");return ct(e)=="symbol"?e:e+""}function qu(t,e,r){return(e=Bu(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function $i(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),r.push.apply(r,n)}return r}function Vt(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?$i(Object(r),!0).forEach(function(n){qu(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):$i(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var Di=class Fi{constructor(e,{headers:r={},schema:n,fetch:s,timeout:i,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=n,this.urlLengthLimit=o;let a=s??globalThis.fetch;i!==void 0&&i>0?this.fetch=(l,c)=>{let h=new AbortController,m=setTimeout(()=>h.abort(),i),_=c?.signal;if(_){if(_.aborted)return clearTimeout(m),a(l,c);let f=()=>{clearTimeout(m),h.abort()};return _.addEventListener("abort",f,{once:!0}),a(l,Vt(Vt({},c),{},{signal:h.signal})).finally(()=>{clearTimeout(m),_.removeEventListener("abort",f)})}return a(l,Vt(Vt({},c),{},{signal:h.signal})).finally(()=>clearTimeout(m))}:this.fetch=a}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Du(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Fi(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:n=!1,get:s=!1,count:i}={}){var o;let a,l=new URL(`${this.url}/rpc/${e}`),c,h=f=>f!==null&&typeof f=="object"&&(!Array.isArray(f)||f.some(h)),m=n&&Object.values(r).some(h);m?(a="POST",c=r):n||s?(a=n?"HEAD":"GET",Object.entries(r).filter(([f,y])=>y!==void 0).map(([f,y])=>[f,Array.isArray(y)?`{${y.join(",")}}`:`${y}`]).forEach(([f,y])=>{l.searchParams.append(f,y)})):(a="POST",c=r);let _=new Headers(this.headers);return m?_.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&_.set("Prefer",`count=${i}`),new Xe({method:a,url:l,headers:_,schema:this.schemaName,body:c,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}};var $o=ze(vn(),1);var mt=class extends Error{constructor(t,e){super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function dl(t,e,r){let n=new URL(e,t);if(r)for(let[s,i]of Object.entries(r))i!==void 0&&n.searchParams.set(s,i);return n.toString()}async function hl(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function fl(t){let e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:n,query:s,body:i,headers:o}){let a=dl(t.baseUrl,n,s),l=await hl(t.auth),c=await e(a,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...o},body:i?JSON.stringify(i):void 0}),h=await c.text(),m=(c.headers.get("content-type")||"").includes("application/json"),_=m&&h?JSON.parse(h):h;if(!c.ok){let f=m?_:void 0,y=f?.error;throw new mt(y?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:y?.type,icebergCode:y?.code,details:f})}return{status:c.status,headers:c.headers,data:_}}}}function Zt(t){return t.join("")}var pl=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){let e=t?{parent:Zt(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(n=>({namespace:n}))}async createNamespace(t,e){let r={namespace:t.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Zt(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Zt(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Zt(t.namespace)}`}),!0}catch(e){if(e instanceof mt&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof mt&&r.status===409)return;throw r}}};function Qe(t){return t.join("")}var ml=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??!1)}})}async loadTable(t){let e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){let e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof mt&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof mt&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},eo=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=fl({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new pl(this.client,e),this.tableOps=new ml(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};var tr=class extends Error{constructor(t,e="storage",r,n){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=n}};function rr(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var er=class extends tr{constructor(t,e,r,n="storage"){super(t,n,e,r),this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},so=class extends tr{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var _l=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),gl=t=>{if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},wn=t=>{if(Array.isArray(t))return t.map(r=>wn(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,n])=>{let s=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[s]=wn(n)}),e},yl=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function gt(t){"@babel/helpers - typeof";return gt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},gt(t)}function vl(t,e){if(gt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(gt(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function wl(t){var e=vl(t,"string");return gt(e)=="symbol"?e:e+""}function bl(t,e,r){return(e=wl(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function to(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),r.push.apply(r,n)}return r}function P(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?to(Object(r),!0).forEach(function(n){bl(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):to(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var ro=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},El=async(t,e,r,n)=>{if(t&&typeof t=="object"&&"status"in t&&"ok"in t&&typeof t.status=="number"&&!r?.noResolveJson){let s=t,i=s.status||500;if(typeof s.json=="function")s.json().then(o=>{let a=o?.statusCode||o?.code||i+"";e(new er(ro(o),i,a,n))}).catch(()=>{if(n==="vectors"){let o=i+"";e(new er(s.statusText||`HTTP ${i} error`,i,o,n))}else{let o=i+"";e(new er(s.statusText||`HTTP ${i} error`,i,o,n))}});else{let o=i+"";e(new er(s.statusText||`HTTP ${i} error`,i,o,n))}}else e(new so(ro(t),t,n))},Sl=(t,e,r,n)=>{let s={method:t,headers:e?.headers||{}};return t==="GET"||t==="HEAD"||!n?P(P({},s),r):(gl(n)?(s.headers=P({"Content-Type":"application/json"},e?.headers),s.body=JSON.stringify(n)):s.body=n,e?.duplex&&(s.duplex=e.duplex),P(P({},s),r))};async function _t(t,e,r,n,s,i,o){return new Promise((a,l)=>{t(r,Sl(e,n,s,i)).then(c=>{if(!c.ok)throw c;if(n?.noResolveJson)return c;if(o==="vectors"){let h=c.headers.get("content-type");if(c.headers.get("content-length")==="0"||c.status===204)return{};if(!h||!h.includes("application/json"))return{}}return c.json()}).then(c=>a(c)).catch(c=>El(c,l,n,o))})}function io(t="storage"){return{get:async(e,r,n,s)=>_t(e,"GET",r,n,s,void 0,t),post:async(e,r,n,s,i)=>_t(e,"POST",r,s,i,n,t),put:async(e,r,n,s,i)=>_t(e,"PUT",r,s,i,n,t),head:async(e,r,n,s)=>_t(e,"HEAD",r,P(P({},n),{},{noResolveJson:!0}),s,void 0,t),remove:async(e,r,n,s,i)=>_t(e,"DELETE",r,s,i,n,t)}}var Tl=io("storage"),{get:yt,post:Ae,put:bn,head:Al,remove:En}=Tl,me=io("vectors"),Ze=class{constructor(t,e={},r,n="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=_l(r),this.namespace=n}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=P(P({},this.headers),{},{[t]:e}),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(rr(r))return{data:null,error:r};throw r}}},Rl=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(rr(e))return{data:null,error:e};throw e}}},oo;oo=Symbol.toStringTag;var kl=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[oo]="BlobDownloadBuilder",this.promise=null}asStream(){return new Rl(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(rr(e))return{data:null,error:e};throw e}}},Ol={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},no={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Cl=class extends Ze{constructor(t,e={},r,n){super(t,e,n,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,n){var s=this;return s.handleOperation(async()=>{let i,o=P(P({},no),n),a=P(P({},s.headers),t==="POST"&&{"x-upsert":String(o.upsert)}),l=o.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",s.encodeMetadata(l)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),l&&!i.has("metadata")&&i.append("metadata",s.encodeMetadata(l))):(i=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=s.toBase64(s.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),n?.headers&&(a=P(P({},a),n.headers));let c=s._removeEmptyFolders(e),h=s._getFinalPath(c),m=await(t=="PUT"?bn:Ae)(s.fetch,`${s.url}/object/${h}`,i,P({headers:a},o?.duplex?{duplex:o.duplex}:{}));return{path:c,id:m.Id,fullPath:m.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,n){var s=this;let i=s._removeEmptyFolders(t),o=s._getFinalPath(i),a=new URL(s.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",e),s.handleOperation(async()=>{let l,c=P({upsert:no.upsert},n),h=P(P({},s.headers),{"x-upsert":String(c.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,h["cache-control"]=`max-age=${c.cacheControl}`,h["content-type"]=c.contentType),{path:i,fullPath:(await bn(s.fetch,a.toString(),l,{headers:h})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let n=r._getFinalPath(t),s=P({},r.headers);e?.upsert&&(s["x-upsert"]="true");let i=await Ae(r.fetch,`${r.url}/object/upload/sign/${n}`,{},{headers:s}),o=new URL(r.url+i.url),a=o.searchParams.get("token");if(!a)throw new tr("No token returned by API");return{signedUrl:o.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var n=this;return n.handleOperation(async()=>await Ae(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers}))}async copy(t,e,r){var n=this;return n.handleOperation(async()=>({path:(await Ae(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(t,e,r){var n=this;return n.handleOperation(async()=>{let s=n._getFinalPath(t),i=await Ae(n.fetch,`${n.url}/object/sign/${s}`,P({expiresIn:e},r?.transform?{transform:r.transform}:{}),{headers:n.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{signedUrl:encodeURI(`${n.url}${i.signedURL}${o}`)}})}async createSignedUrls(t,e,r){var n=this;return n.handleOperation(async()=>{let s=await Ae(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:e,paths:t},{headers:n.headers}),i=r?.download?`&download=${r.download===!0?"":r.download}`:"";return s.map(o=>P(P({},o),{},{signedUrl:o.signedURL?encodeURI(`${n.url}${o.signedURL}${i}`):null}))})}download(t,e,r){let n=typeof e?.transform<"u"?"render/image/authenticated":"object",s=this.transformOptsToQueryString(e?.transform||{}),i=s?`?${s}`:"",o=this._getFinalPath(t),a=()=>yt(this.fetch,`${this.url}/${n}/${o}${i}`,{headers:this.headers,noResolveJson:!0},r);return new kl(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>wn(await yt(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await Al(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(rr(n)&&n instanceof so){let s=n.originalError;if([400,404].includes(s?.status))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){let r=this._getFinalPath(t),n=[],s=e?.download?`download=${e.download===!0?"":e.download}`:"";s!==""&&n.push(s);let i=typeof e?.transform<"u"?"render/image":"object",o=this.transformOptsToQueryString(e?.transform||{});o!==""&&n.push(o);let a=n.join("&");return a!==""&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}${a}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await En(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var n=this;return n.handleOperation(async()=>{let s=P(P(P({},Ol),e),{},{prefix:t||""});return await Ae(n.fetch,`${n.url}/object/list/${n.bucketId}`,s,{headers:n.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let n=P({},t);return await Ae(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){let e=[];return t.width&&e.push(`width=${t.width}`),t.height&&e.push(`height=${t.height}`),t.resize&&e.push(`resize=${t.resize}`),t.format&&e.push(`format=${t.format}`),t.quality&&e.push(`quality=${t.quality}`),e.join("&")}},Pl="2.97.0",vt={"X-Client-Info":`storage-js/${Pl}`},Il=class extends Ze{constructor(t,e={},r,n){let s=new URL(t);n?.useNewHostname&&/supabase\.(co|in|red)$/.test(s.hostname)&&!s.hostname.includes("storage.supabase.")&&(s.hostname=s.hostname.replace("supabase.","storage.supabase."));let i=s.href.replace(/\/$/,""),o=P(P({},vt),e);super(i,o,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await yt(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await yt(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await Ae(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await bn(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await Ae(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await En(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){let e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},xl=class extends Ze{constructor(t,e={},r){let n=t.replace(/\/$/,""),s=P(P({},vt),e);super(n,s,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ae(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);let n=r.toString(),s=n?`${e.url}/bucket?${n}`:`${e.url}/bucket`;return await yt(e.fetch,s,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await En(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!yl(t))throw new tr("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new eo({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(s,i){let o=s[i];return typeof o!="function"?o:async(...a)=>{try{return{data:await o.apply(s,a),error:null}}catch(l){if(n)throw l;return{data:null,error:l}}}}})}},Nl=class extends Ze{constructor(t,e={},r){let n=t.replace(/\/$/,""),s=P(P({},vt),{},{"Content-Type":"application/json"},e);super(n,s,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await me.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await me.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},jl=class extends Ze{constructor(t,e={},r){let n=t.replace(/\/$/,""),s=P(P({},vt),{},{"Content-Type":"application/json"},e);super(n,s,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},Ll=class extends Ze{constructor(t,e={},r){let n=t.replace(/\/$/,""),s=P(P({},vt),{},{"Content-Type":"application/json"},e);super(n,s,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Ul=class extends Ll{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new $l(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},$l=class extends Nl{constructor(t,e,r,n){super(t,e,n),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new Dl(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Dl=class extends jl{constructor(t,e,r,n,s){super(t,e,s),this.vectorBucketName=r,this.indexName=n}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,P(P({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},ao=class extends Il{constructor(t,e={},r,n){super(t,e,r,n)}from(t){return new Cl(this.url,this.headers,t,this.fetch)}get vectors(){return new Ul(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new xl(this.url+"/iceberg",this.headers,this.fetch)}};var Do=ze(ts(),1);k(A,ze(vn(),1));k(A,ze(ts(),1));var fd="2.97.0",Tt="";typeof Deno<"u"?Tt="deno":typeof document<"u"?Tt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Tt="react-native":Tt="node";var pd={"X-Client-Info":`supabase-js-${Tt}/${fd}`},md={headers:pd},_d={schema:"public"},gd={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},yd={};function At(t){"@babel/helpers - typeof";return At=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},At(t)}function vd(t,e){if(At(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(At(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function wd(t){var e=vd(t,"string");return At(e)=="symbol"?e:e+""}function bd(t,e,r){return(e=wd(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Uo(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),r.push.apply(r,n)}return r}function se(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Uo(Object(r),!0).forEach(function(n){bd(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Uo(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var Ed=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Sd=()=>Headers,Td=(t,e,r)=>{let n=Ed(r),s=Sd();return async(i,o)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,c=new s(o?.headers);return c.has("apikey")||c.set("apikey",t),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),n(i,se(se({},o),{},{headers:c}))}};function Ad(t){return t.endsWith("/")?t:t+"/"}function Rd(t,e){var r,n;let{db:s,auth:i,realtime:o,global:a}=t,{db:l,auth:c,realtime:h,global:m}=e,_={db:se(se({},l),s),auth:se(se({},c),i),realtime:se(se({},h),o),storage:{},global:se(se(se({},m),a),{},{headers:se(se({},(r=m?.headers)!==null&&r!==void 0?r:{}),(n=a?.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};return t.accessToken?_.accessToken=t.accessToken:delete _.accessToken,_}function kd(t){let e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(Ad(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Od=class extends Do.AuthClient{constructor(t){super(t)}},Fo=class{constructor(t,e,r){var n,s;this.supabaseUrl=t,this.supabaseKey=e;let i=kd(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);let o=`sb-${i.hostname.split(".")[0]}-auth-token`,a={db:_d,realtime:yd,auth:se(se({},gd),{},{storageKey:o}),global:md},l=Rd(r??{},a);if(this.storageKey=(n=l.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(s=l.global.headers)!==null&&s!==void 0?s:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(h,m)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(m)} is not possible`)}});else{var c;this.auth=this._initSupabaseAuthClient((c=l.auth)!==null&&c!==void 0?c:{},this.headers,l.global.fetch)}this.fetch=Td(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(se({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(h=>this.realtime.setAuth(h)).catch(h=>console.warn("Failed to set initial Realtime auth token:",h)),this.rest=new Di(new URL("rest/v1",i).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new ao(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new be.FunctionsClient(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();let{data:n}=await t.auth.getSession();return(e=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:s,storageKey:i,flowType:o,lock:a,debug:l,throwOnError:c},h,m){let _={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Od({url:this.authUrl.href,headers:se(se({},_),h),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:s,flowType:o,lock:a,debug:l,throwOnError:c,fetch:m,hasCustomAuthorizationHeader:Object.keys(this.headers).some(f=>f.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new $o.RealtimeClient(this.realtimeUrl.href,se(se({},t),{},{params:se(se({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},rs=(t,e,r)=>new Fo(t,e,r);function Cd(){if(typeof window<"u")return!1;let t=globalThis.process;if(!t)return!1;let e=t.version;if(e==null)return!1;let r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}Cd()&&console.warn("\u26A0\uFE0F 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");function Bo(t,e){return async(r,n,s)=>{let i,o=()=>i??=s(),a=l=>i&&l?.name==="AbortError";try{return await t(r,n,o)}catch(l){if(a(l))return i;if(!l?.isAcquireTimeout)throw l;try{return await e(r,o)}catch(c){if(a(c))return i;throw c}}}}var Rt=typeof window<"u"&&!!window.__CONFORM_ENGINE__,qo=Rt?"http://127.0.0.1:9":import.meta.env.VITE_SUPABASE_URL,Mo=Rt?"offline":import.meta.env.VITE_SUPABASE_ANON_KEY;if(!qo)throw console.error("Missing VITE_SUPABASE_URL environment variable"),new Error("Missing Supabase URL environment variable");if(!Mo)throw console.error("Missing VITE_SUPABASE_ANON_KEY environment variable"),new Error("Missing Supabase anon key environment variable");var gr=rs(qo,Mo,{auth:{autoRefreshToken:!Rt,persistSession:!Rt,detectSessionInUrl:!Rt,...typeof navigator<"u"&&navigator.locks?{lock:Bo(A.navigatorLock,(t,e)=>navigator.locks.request(t,{steal:!0},e))}:{}}});var Pd=typeof __BUILD_SHA__<"u"?`web-${__BUILD_SHA__}`:"web-dev",Id=`${import.meta.env.VITE_SUPABASE_URL}/functions/v1/v1-me/v1/engine/telemetry`,xd=1e4,Nd=crypto.randomUUID(),yr=0,jd=0,vr=[],Wo=null;function Vo(){yr++,ss=!1,Ho=Date.now()}var ss=!1,Ho=0;function Ko(){return ss}function wr(t,e={}){yr||(yr=1),vr.push({kind:"outcome",verb:t,ok:e.ok??!0,code:e.ok===!1?e.code??"error":void 0,error:e.ok===!1?e.error:void 0,duration_ms:Math.max(0,Math.round(e.ms??0)),counts:e.counts,fields:e.fields,session_id:e.session_id,version:Pd,run_id:Nd,seq:++jd,req:yr,event_id:crypto.randomUUID(),run_at:new Date().toISOString(),client:"web",author:"user"}),Wo??=setTimeout(()=>void Go(),xd)}var ns=null;async function zo(t,e,r=()=>({})){let n=performance.now();ns=null;try{let s=await e(),i=ns;return ns=null,wr(t,i?{ok:!1,...i,ms:performance.now()-n}:{...r(s),ok:!0,ms:performance.now()-n}),s}catch(s){throw wr(t,{ok:!1,code:s?.code,error:s instanceof Error?s.message:String(s),ms:performance.now()-n}),s}}async function Go(){if(Wo=null,!vr.length)return;let t=vr;vr=[];try{let{data:{session:e}}=await gr.auth.getSession();if(!e?.access_token)return;await fetch(Id,{method:"POST",keepalive:!0,headers:{"content-type":"application/json",authorization:`Bearer ${e.access_token}`,apikey:import.meta.env.VITE_SUPABASE_ANON_KEY},body:JSON.stringify({events:t})})}catch{}}typeof window<"u"&&window.addEventListener("pagehide",()=>{ss&&wr("page_leave",{counts:{seconds:Math.round((Date.now()-Ho)/1e3)}}),Go()});var Ld=`${import.meta.env.VITE_SUPABASE_URL}/functions/v1`;async function Ud(t){let{data:{session:e}}=await gr.auth.getSession(),r=e?.access_token??import.meta.env.VITE_SUPABASE_ANON_KEY,n=JSON.stringify({format:t.format,source_filename:t.sourceFilename,persist:t.persist,session_id:t.sessionId,selected_sequence_names:t.selectedSequenceNames,previously_selected_names:t.previouslySelectedNames}),s=typeof t.extract=="string"?t.extract:JSON.stringify(t.extract),{contentType:i,body:o}=await ti(n,s),a=new Set([502,503,504,529,546]),l=null;for(let c=0;;c++){try{l=await fetch(`${Ld}/v1-timeline-canonicalize/v1/timeline-canonicalize`,{method:"POST",headers:{"Content-Type":i,Authorization:`Bearer ${r}`},body:o})}catch(h){if(c>=2)throw h;l=null}if(l&&(l.ok||!a.has(l.status)))break;if(c>=2)throw l?.status===546?new Error("Our conversion server stopped this timeline three times in a row. That is a limit on our side, not a problem with your file. Please try again later; if it keeps failing, converting fewer sequences at a time gets it through, and we'd like to hear about it."):new Error(`The processing server timed out (${l?.status??"network error"}) \u2014 a server hiccup, not a problem with your file. Please try again in a minute.`);await new Promise(h=>setTimeout(h,1500*(c+1)))}if(!l.ok){let c=await l.json().catch(()=>({}));throw new Error(c?.error?.message??`canonicalize failed (${l.status})`)}return await l.json()}async function Jo(t){return!t.sessionId&&!Ko()&&Vo(),zo("timeline_read",()=>Ud(t),e=>({fields:[`format=${String(t.format).toLowerCase()}`,...t.selectedSequenceNames?.length?[]:["scope=project"]],counts:{timelines:e.session?.timelines?.length??0},session_id:e.session_id??void 0}))}var $d=[{ext:"mov",name:"QuickTime",container:"mov",codec:"prores",frameType:"intra",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0},{ext:"mp4",name:"MPEG-4",container:"mov",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0},{ext:"m4v",name:"MPEG-4 Video",container:"mov",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0},{ext:"m4a",name:"MPEG-4 Audio",container:"mov",codec:"aac",frameType:"intra",sparseStrategy:"full-file",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"mxf",name:"MXF",container:"mxf",codec:"varies",frameType:"intra",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0,notes:"Verified Resolve playback for XAVC-I NDF/DF. Coordinated 45-patch metadata rewrite (index entries + Duration fields). DNxHD foundation works; mid-clip trim works structurally; awaiting more corpus."},{ext:"r3d",name:"RED RAW",container:"r3d",codec:"r3d",frameType:"intra",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0,notes:"Verified Resolve playback (V-Raptor 6K). Trim/prepare/inspect run client-side as opaque WASM (mediaOp) \u2014 browser sees no algorithm; WS bridge retired. DRAGON era + Komodo + 8K need corpus expansion. Run oracle/i2o/cli/r3d-corpus.ts on new fixtures."},{ext:"braw",name:"Blackmagic RAW",container:"mov",codec:"braw",frameType:"intra",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0,notes:'Verified Resolve playback. Standard MP4 container with BRAW codec; reuses structure-preserving MOV walker. The "secret sauce" was knowing BRAW = MP4.'},{ext:"crm",name:"Canon Cinema RAW Light",container:"crm",codec:"crm",frameType:"intra",sparseStrategy:"byte-range",support:"planned",needsStructuralBytes:!1,trimSupported:!1,notes:"Frame-indexed single file. Canon SDK available."},{ext:"rmf",name:"Canon RAW (legacy)",container:"crm",codec:"crm",frameType:"intra",sparseStrategy:"byte-range",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"ari",name:"ARRIRAW",container:"frame-seq",codec:"arriraw",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1,notes:"8KB header + raw Bayer per frame. Sparse = select which .ari files to include."},{ext:"arx",name:"ARRIRAW HDE",container:"frame-seq",codec:"arriraw",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"dpx",name:"DPX",container:"frame-seq",codec:"dpx",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1,notes:"SMPTE 268M. Image data offset at byte 4. ~25MB per 4K frame."},{ext:"exr",name:"OpenEXR",container:"frame-seq",codec:"exr",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"tif",name:"TIFF",container:"frame-seq",codec:"tiff",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"tiff",name:"TIFF",container:"frame-seq",codec:"tiff",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"png",name:"PNG",container:"frame-seq",codec:"png",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"jpg",name:"JPEG",container:"frame-seq",codec:"jpeg",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"jpeg",name:"JPEG",container:"frame-seq",codec:"jpeg",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"psd",name:"Photoshop",container:"still",codec:"psd",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"tga",name:"Targa",container:"still",codec:"tga",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"bmp",name:"Bitmap",container:"still",codec:"bmp",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"gif",name:"GIF",container:"still",codec:"gif",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"webp",name:"WebP",container:"still",codec:"webp",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"avif",name:"AVIF",container:"still",codec:"avif",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"wav",name:"WAV",container:"audio",codec:"pcm",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!0,notes:"RIFF/WAV trim decoder ships. Poly WAV (8-24ch) could benefit from time-axis chunking."},{ext:"bwf",name:"Broadcast WAV",container:"audio",codec:"pcm",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!0,notes:"WAV + bext chunk (~602+ bytes) with timecode reference. Same trim decoder as WAV."},{ext:"aif",name:"AIFF",container:"audio",codec:"pcm",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1},{ext:"aiff",name:"AIFF",container:"audio",codec:"pcm",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1},{ext:"mp3",name:"MP3",container:"audio",codec:"mp3",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1},{ext:"aac",name:"AAC",container:"audio",codec:"aac",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1},{ext:"avi",name:"AVI",container:"avi",codec:"varies",frameType:"intra",sparseStrategy:"byte-range",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"mkv",name:"Matroska",container:"mkv",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"mts",name:"AVCHD",container:"mov",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"m2ts",name:"AVCHD",container:"mov",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"webm",name:"WebM",container:"mkv",codec:"vp9",frameType:"inter",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1}],Yo=new Map;for(let t of $d)Yo.set(t.ext,t);function Dd(t){let e=t.split(".").pop()?.toLowerCase();return e?Yo.get(e)??null:null}function Xo(t){return Dd(t)!==null}var th=ze(da());var eh=typeof __BUILD_SHA__<"u"?__BUILD_SHA__:"dev",Ar=class extends Error{constructor(e,r){super(r??"A new version of Conform was released while this page was open, so part of the app could no longer be loaded. Reload the page to continue \u2014 nothing has been sent yet."),this.name="StaleBuildError",this.chunk=e,this.buildSha=eh}};var ha=typeof __BUILD_SHA__<"u"?__BUILD_SHA__:"dev",Xf=900*1e3;async function rh(t=fetch,e=ha){if(!e||e==="dev"||e==="unknown")return!1;try{let r=await t(`/build-info.json?t=${Date.now()}`,{cache:"no-store"});if(!r.ok)return!1;let n=await r.json();return typeof n.sha=="string"&&n.sha!==""&&n.sha!=="unknown"&&n.sha!==e}catch{return!1}}async function fa(t=fetch,e=ha){if(await rh(t,e))throw new Ar("timeline-read","A new version of Conform was released while this page was open. Reload the page and drop the file again \u2014 nothing has been read or sent yet.")}function pa(){return typeof window<"u"&&!!window.__CONFORM_ENGINE__}async function ap(t){if(Xo(t.name))return await nh(t);let e=await Hr(t);if(e.format!=="unknown"&&Vr(e.format)){let r=e.format==="flame-archive"?(await ih(t)).session.timelines.filter(n=>n.kind!=="compound"&&n.tracks?.some(s=>s.items?.length)).map(n=>n.name??"").filter(Boolean):(await Zs(t,e.format)).names;return{kind:"timeline",format:e.format,name:t.name,observed_bytes:t.size,total_size:t.size,session:{id:null,inline:{timelines:r.map(n=>({name:n}))}},warnings:[],inspector:{layer:"timeline-core/wasm-inspect",version:"1",duration_ms:0}}}return{kind:"unknown",format:"unknown",name:t.name,observed_bytes:0,total_size:t.size,session:null,warnings:[{code:"container_corruption",message:`Unrecognized file: ${t.name}`}],inspector:{layer:"inspect/unknown",version:"1",duration_ms:0}}}async function nh(t){let e=Date.now(),r=await ri(t);if(!r)return{kind:"unknown",format:"unknown",name:t.name,observed_bytes:0,total_size:t.size,session:null,warnings:[{code:"container_corruption",message:"No browser-side probe available (proprietary format or unsupported extension)"}],inspector:{layer:"probe-media/local",version:"1",duration_ms:Date.now()-e}};let n=r.container??"media",s={metadata:{id:t.name,user_id:"",source_format:n,source_filename:t.name,source_file_sha256:null,source_file_bytes:t.size,parser_name:`media:${n}`,parser_version:"1",status:"ready",error_message:null,metadata:{},created_at:new Date().toISOString()},timelines:[],media_references:[r]};return{kind:"media",format:n,name:t.name,observed_bytes:0,total_size:t.size,session:{id:null,inline:s},warnings:[],inspector:{layer:"probe-media/local",version:"1",duration_ms:Date.now()-e}}}var ma=new Map,sh=t=>t.replace(/^[a-z]\d+:/,""),up=t=>ma.get(sh(t));async function ih(t,e={}){if(pa()){let{engine:o}=await import("./engine-WMOJ3HRU.js"),a=await o.canonicalize(t,e.selectedSequenceNames,e.previouslySelectedNames);for(let l of a.session.timelines??[])ma.set(l.id,a.session_id);return{session:a.session,sessionId:a.session_id,persistError:null}}let{format:r}=await Hr(t);if(!Vr(r))throw new Error(`No Rust timeline engine for format '${r}' (${t.name})`);await fa();let{fmt:n,extract:s}=await ei(t,r,e.selectedSequenceNames),i=await Jo({format:n,extract:s,sourceFilename:t.name,persist:e.persist,sessionId:e.sessionId,selectedSequenceNames:e.selectedSequenceNames,previouslySelectedNames:e.previouslySelectedNames});return{session:i.session,sessionId:i.session_id??i.session?.id??null,persistError:i.persist_error??null}}export{ih as canonicalizeTimelineFile,up as engineSessionFor,sh as engineTimelineId,ap as inspectFile};
|
|
67
|
+
${h.stack}`)}else{var v;a=(v=i?.stack)!==null&&v!==void 0?v:""}let w=this.url.toString().length;return i?.name==="AbortError"||i?.code==="ABORT_ERR"?(c="",l="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${w} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(h?.name==="HeadersOverflowError"||h?.code==="UND_ERR_HEADERS_OVERFLOW")&&(c="",l="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(l+=`. Your request URL is ${w} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(o=i?.name)!==null&&o!==void 0?o:"FetchError"}: ${i?.message}`,details:a,hint:l,code:c},data:null,count:null,status:0,statusText:""}})),s.then(t,e)}returns(){return this}overrideTypes(){return this}},Fu=class extends Du{select(t){let e=!1,r=(t??"*").split("").map(n=>/\s/.test(n)&&!e?"":(n==='"'&&(e=!e),n)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:n,referencedTable:s=n}={}){let i=s?`${s}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:n=r}={}){let s=typeof n>"u"?"offset":`${n}.offset`,i=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(s,`${t}`),this.url.searchParams.set(i,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.method==="GET"?this.headers.set("Accept","application/json"):this.headers.set("Accept","application/vnd.pgrst.object+json"),this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:n=!1,wal:s=!1,format:i="text"}={}){var o;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,n?"buffers":null,s?"wal":null].filter(Boolean).join("|"),l=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${l}"; options=${a};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},Ui=new RegExp("[,()]"),Xe=class extends Fu{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Ui.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Ui.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:n}={}){let s="";n==="plain"?s="pl":n==="phrase"?s="ph":n==="websearch"&&(s="w");let i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${s}fts${i}.${e}`),this}match(t){return Object.entries(t).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Bu=class{constructor(t,{headers:e={},schema:r,fetch:n,urlLengthLimit:s=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=n,this.urlLengthLimit=s}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:n}=e??{},s=r?"HEAD":"GET",i=!1,o=(t??"*").split("").map(c=>/\s/.test(c)&&!i?"":(c==='"'&&(i=!i),c)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",o),n&&l.append("Prefer",`count=${n}`),new Xe({method:s,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var n;let s="POST",{url:i,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(a.length>0){let l=[...new Set(a)].map(c=>`"${c}"`);i.searchParams.set("columns",l.join(","))}}return new Xe({method:s,url:i,headers:o,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:n,defaultToNull:s=!0}={}){var i;let o="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),n&&l.append("Prefer",`count=${n}`),s||l.append("Prefer","missing=default"),Array.isArray(t)){let c=t.reduce((h,m)=>h.concat(Object.keys(m)),[]);if(c.length>0){let h=[...new Set(c)].map(m=>`"${m}"`);a.searchParams.set("columns",h.join(","))}}return new Xe({method:o,url:a,headers:l,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let n="PATCH",{url:s,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Xe({method:n,url:s,headers:i,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:n,headers:s}=this.cloneRequestState();return t&&s.append("Prefer",`count=${t}`),new Xe({method:r,url:n,headers:s,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function ct(t){"@babel/helpers - typeof";return ct=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ct(t)}function qu(t,e){if(ct(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(ct(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Mu(t){var e=qu(t,"string");return ct(e)=="symbol"?e:e+""}function Wu(t,e,r){return(e=Mu(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function $i(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),r.push.apply(r,n)}return r}function Ht(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?$i(Object(r),!0).forEach(function(n){Wu(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):$i(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var Di=class Fi{constructor(e,{headers:r={},schema:n,fetch:s,timeout:i,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=n,this.urlLengthLimit=o;let a=s??globalThis.fetch;i!==void 0&&i>0?this.fetch=(l,c)=>{let h=new AbortController,m=setTimeout(()=>h.abort(),i),_=c?.signal;if(_){if(_.aborted)return clearTimeout(m),a(l,c);let f=()=>{clearTimeout(m),h.abort()};return _.addEventListener("abort",f,{once:!0}),a(l,Ht(Ht({},c),{},{signal:h.signal})).finally(()=>{clearTimeout(m),_.removeEventListener("abort",f)})}return a(l,Ht(Ht({},c),{},{signal:h.signal})).finally(()=>clearTimeout(m))}:this.fetch=a}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Bu(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Fi(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:n=!1,get:s=!1,count:i}={}){var o;let a,l=new URL(`${this.url}/rpc/${e}`),c,h=f=>f!==null&&typeof f=="object"&&(!Array.isArray(f)||f.some(h)),m=n&&Object.values(r).some(h);m?(a="POST",c=r):n||s?(a=n?"HEAD":"GET",Object.entries(r).filter(([f,y])=>y!==void 0).map(([f,y])=>[f,Array.isArray(y)?`{${y.join(",")}}`:`${y}`]).forEach(([f,y])=>{l.searchParams.append(f,y)})):(a="POST",c=r);let _=new Headers(this.headers);return m?_.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&_.set("Prefer",`count=${i}`),new Xe({method:a,url:l,headers:_,schema:this.schemaName,body:c,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}};var $o=ze(vn(),1);var mt=class extends Error{constructor(t,e){super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function fl(t,e,r){let n=new URL(e,t);if(r)for(let[s,i]of Object.entries(r))i!==void 0&&n.searchParams.set(s,i);return n.toString()}async function pl(t){return!t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function ml(t){let e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:n,query:s,body:i,headers:o}){let a=fl(t.baseUrl,n,s),l=await pl(t.auth),c=await e(a,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...o},body:i?JSON.stringify(i):void 0}),h=await c.text(),m=(c.headers.get("content-type")||"").includes("application/json"),_=m&&h?JSON.parse(h):h;if(!c.ok){let f=m?_:void 0,y=f?.error;throw new mt(y?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:y?.type,icebergCode:y?.code,details:f})}return{status:c.status,headers:c.headers,data:_}}}}function er(t){return t.join("")}var _l=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){let e=t?{parent:er(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(n=>({namespace:n}))}async createNamespace(t,e){let r={namespace:t.namespace,properties:e?.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${er(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${er(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${er(t.namespace)}`}),!0}catch(e){if(e instanceof mt&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof mt&&r.status===409)return;throw r}}};function Qe(t){return t.join("")}var gl=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r}async listTables(t){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables/${t.name}`,body:e});return{"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??!1)}})}async loadTable(t){let e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){let e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Qe(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof mt&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof mt&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},eo=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=ml({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new _l(this.client,e),this.tableOps=new gl(this.client,e,this.accessDelegation)}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t)}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e)}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};var rr=class extends Error{constructor(t,e="storage",r,n){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=n}};function nr(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var tr=class extends rr{constructor(t,e,r,n="storage"){super(t,n,e,r),this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},so=class extends rr{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var yl=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),vl=t=>{if(typeof t!="object"||t===null)return!1;let e=Object.getPrototypeOf(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},wn=t=>{if(Array.isArray(t))return t.map(r=>wn(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,n])=>{let s=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[s]=wn(n)}),e},wl=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function gt(t){"@babel/helpers - typeof";return gt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},gt(t)}function bl(t,e){if(gt(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(gt(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function El(t){var e=bl(t,"string");return gt(e)=="symbol"?e:e+""}function Sl(t,e,r){return(e=El(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function to(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),r.push.apply(r,n)}return r}function C(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?to(Object(r),!0).forEach(function(n){Sl(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):to(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var ro=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},Tl=async(t,e,r,n)=>{if(t&&typeof t=="object"&&"status"in t&&"ok"in t&&typeof t.status=="number"&&!r?.noResolveJson){let s=t,i=s.status||500;if(typeof s.json=="function")s.json().then(o=>{let a=o?.statusCode||o?.code||i+"";e(new tr(ro(o),i,a,n))}).catch(()=>{if(n==="vectors"){let o=i+"";e(new tr(s.statusText||`HTTP ${i} error`,i,o,n))}else{let o=i+"";e(new tr(s.statusText||`HTTP ${i} error`,i,o,n))}});else{let o=i+"";e(new tr(s.statusText||`HTTP ${i} error`,i,o,n))}}else e(new so(ro(t),t,n))},Al=(t,e,r,n)=>{let s={method:t,headers:e?.headers||{}};return t==="GET"||t==="HEAD"||!n?C(C({},s),r):(vl(n)?(s.headers=C({"Content-Type":"application/json"},e?.headers),s.body=JSON.stringify(n)):s.body=n,e?.duplex&&(s.duplex=e.duplex),C(C({},s),r))};async function _t(t,e,r,n,s,i,o){return new Promise((a,l)=>{t(r,Al(e,n,s,i)).then(c=>{if(!c.ok)throw c;if(n?.noResolveJson)return c;if(o==="vectors"){let h=c.headers.get("content-type");if(c.headers.get("content-length")==="0"||c.status===204)return{};if(!h||!h.includes("application/json"))return{}}return c.json()}).then(c=>a(c)).catch(c=>Tl(c,l,n,o))})}function io(t="storage"){return{get:async(e,r,n,s)=>_t(e,"GET",r,n,s,void 0,t),post:async(e,r,n,s,i)=>_t(e,"POST",r,s,i,n,t),put:async(e,r,n,s,i)=>_t(e,"PUT",r,s,i,n,t),head:async(e,r,n,s)=>_t(e,"HEAD",r,C(C({},n),{},{noResolveJson:!0}),s,void 0,t),remove:async(e,r,n,s,i)=>_t(e,"DELETE",r,s,i,n,t)}}var Rl=io("storage"),{get:yt,post:Ae,put:bn,head:kl,remove:En}=Rl,me=io("vectors"),Ze=class{constructor(t,e={},r,n="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=yl(r),this.namespace=n}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=C(C({},this.headers),{},{[t]:e}),this}async handleOperation(t){var e=this;try{return{data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(nr(r))return{data:null,error:r};throw r}}},Ol=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return{data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(nr(e))return{data:null,error:e};throw e}}},oo;oo=Symbol.toStringTag;var Pl=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[oo]="BlobDownloadBuilder",this.promise=null}asStream(){return new Ol(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return{data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(nr(e))return{data:null,error:e};throw e}}},Cl={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},no={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},Il=class extends Ze{constructor(t,e={},r,n){super(t,e,n,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,n){var s=this;return s.handleOperation(async()=>{let i,o=C(C({},no),n),a=C(C({},s.headers),t==="POST"&&{"x-upsert":String(o.upsert)}),l=o.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),l&&i.append("metadata",s.encodeMetadata(l)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),l&&!i.has("metadata")&&i.append("metadata",s.encodeMetadata(l))):(i=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=s.toBase64(s.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),n?.headers&&(a=C(C({},a),n.headers));let c=s._removeEmptyFolders(e),h=s._getFinalPath(c),m=await(t=="PUT"?bn:Ae)(s.fetch,`${s.url}/object/${h}`,i,C({headers:a},o?.duplex?{duplex:o.duplex}:{}));return{path:c,id:m.Id,fullPath:m.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,n){var s=this;let i=s._removeEmptyFolders(t),o=s._getFinalPath(i),a=new URL(s.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",e),s.handleOperation(async()=>{let l,c=C({upsert:no.upsert},n),h=C(C({},s.headers),{"x-upsert":String(c.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,h["cache-control"]=`max-age=${c.cacheControl}`,h["content-type"]=c.contentType),{path:i,fullPath:(await bn(s.fetch,a.toString(),l,{headers:h})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let n=r._getFinalPath(t),s=C({},r.headers);e?.upsert&&(s["x-upsert"]="true");let i=await Ae(r.fetch,`${r.url}/object/upload/sign/${n}`,{},{headers:s}),o=new URL(r.url+i.url),a=o.searchParams.get("token");if(!a)throw new rr("No token returned by API");return{signedUrl:o.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var n=this;return n.handleOperation(async()=>await Ae(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers}))}async copy(t,e,r){var n=this;return n.handleOperation(async()=>({path:(await Ae(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(t,e,r){var n=this;return n.handleOperation(async()=>{let s=n._getFinalPath(t),i=await Ae(n.fetch,`${n.url}/object/sign/${s}`,C({expiresIn:e},r?.transform?{transform:r.transform}:{}),{headers:n.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{signedUrl:encodeURI(`${n.url}${i.signedURL}${o}`)}})}async createSignedUrls(t,e,r){var n=this;return n.handleOperation(async()=>{let s=await Ae(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:e,paths:t},{headers:n.headers}),i=r?.download?`&download=${r.download===!0?"":r.download}`:"";return s.map(o=>C(C({},o),{},{signedUrl:o.signedURL?encodeURI(`${n.url}${o.signedURL}${i}`):null}))})}download(t,e,r){let n=typeof e?.transform<"u"?"render/image/authenticated":"object",s=this.transformOptsToQueryString(e?.transform||{}),i=s?`?${s}`:"",o=this._getFinalPath(t),a=()=>yt(this.fetch,`${this.url}/${n}/${o}${i}`,{headers:this.headers,noResolveJson:!0},r);return new Pl(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>wn(await yt(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await kl(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(n){if(e.shouldThrowOnError)throw n;if(nr(n)&&n instanceof so){let s=n.originalError;if([400,404].includes(s?.status))return{data:!1,error:n}}throw n}}getPublicUrl(t,e){let r=this._getFinalPath(t),n=[],s=e?.download?`download=${e.download===!0?"":e.download}`:"";s!==""&&n.push(s);let i=typeof e?.transform<"u"?"render/image":"object",o=this.transformOptsToQueryString(e?.transform||{});o!==""&&n.push(o);let a=n.join("&");return a!==""&&(a=`?${a}`),{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${r}${a}`)}}}async remove(t){var e=this;return e.handleOperation(async()=>await En(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var n=this;return n.handleOperation(async()=>{let s=C(C(C({},Cl),e),{},{prefix:t||""});return await Ae(n.fetch,`${n.url}/object/list/${n.bucketId}`,s,{headers:n.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let n=C({},t);return await Ae(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){let e=[];return t.width&&e.push(`width=${t.width}`),t.height&&e.push(`height=${t.height}`),t.resize&&e.push(`resize=${t.resize}`),t.format&&e.push(`format=${t.format}`),t.quality&&e.push(`quality=${t.quality}`),e.join("&")}},xl="2.97.0",vt={"X-Client-Info":`storage-js/${xl}`},Nl=class extends Ze{constructor(t,e={},r,n){let s=new URL(t);n?.useNewHostname&&/supabase\.(co|in|red)$/.test(s.hostname)&&!s.hostname.includes("storage.supabase.")&&(s.hostname=s.hostname.replace("supabase.","storage.supabase."));let i=s.href.replace(/\/$/,""),o=C(C({},vt),e);super(i,o,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await yt(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await yt(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await Ae(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await bn(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await Ae(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await En(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){let e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},jl=class extends Ze{constructor(t,e={},r){let n=t.replace(/\/$/,""),s=C(C({},vt),e);super(n,s,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await Ae(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);let n=r.toString(),s=n?`${e.url}/bucket?${n}`:`${e.url}/bucket`;return await yt(e.fetch,s,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await En(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!wl(t))throw new rr("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new eo({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(s,i){let o=s[i];return typeof o!="function"?o:async(...a)=>{try{return{data:await o.apply(s,a),error:null}}catch(l){if(n)throw l;return{data:null,error:l}}}}})}},Ll=class extends Ze{constructor(t,e={},r){let n=t.replace(/\/$/,""),s=C(C({},vt),{},{"Content-Type":"application/json"},e);super(n,s,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await me.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await me.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},Ul=class extends Ze{constructor(t,e={},r){let n=t.replace(/\/$/,""),s=C(C({},vt),{},{"Content-Type":"application/json"},e);super(n,s,r,"vectors")}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},$l=class extends Ze{constructor(t,e={},r){let n=t.replace(/\/$/,""),s=C(C({},vt),{},{"Content-Type":"application/json"},e);super(n,s,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await me.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Dl=class extends $l{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new Fl(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},Fl=class extends Ll{constructor(t,e,r,n){super(t,e,n),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new Bl(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Bl=class extends Ul{constructor(t,e,r,n,s){super(t,e,s),this.vectorBucketName=r,this.indexName=n}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,C(C({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},ao=class extends Nl{constructor(t,e={},r,n){super(t,e,r,n)}from(t){return new Il(this.url,this.headers,t,this.fetch)}get vectors(){return new Dl(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new jl(this.url+"/iceberg",this.headers,this.fetch)}};var Do=ze(ts(),1);k(A,ze(vn(),1));k(A,ze(ts(),1));var md="2.97.0",Tt="";typeof Deno<"u"?Tt="deno":typeof document<"u"?Tt="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Tt="react-native":Tt="node";var _d={"X-Client-Info":`supabase-js-${Tt}/${md}`},gd={headers:_d},yd={schema:"public"},vd={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},wd={};function At(t){"@babel/helpers - typeof";return At=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},At(t)}function bd(t,e){if(At(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e||"default");if(At(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ed(t){var e=bd(t,"string");return At(e)=="symbol"?e:e+""}function Sd(t,e,r){return(e=Ed(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Uo(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),r.push.apply(r,n)}return r}function se(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Uo(Object(r),!0).forEach(function(n){Sd(t,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Uo(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n))})}return t}var Td=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Ad=()=>Headers,Rd=(t,e,r)=>{let n=Td(r),s=Ad();return async(i,o)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,c=new s(o?.headers);return c.has("apikey")||c.set("apikey",t),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),n(i,se(se({},o),{},{headers:c}))}};function kd(t){return t.endsWith("/")?t:t+"/"}function Od(t,e){var r,n;let{db:s,auth:i,realtime:o,global:a}=t,{db:l,auth:c,realtime:h,global:m}=e,_={db:se(se({},l),s),auth:se(se({},c),i),realtime:se(se({},h),o),storage:{},global:se(se(se({},m),a),{},{headers:se(se({},(r=m?.headers)!==null&&r!==void 0?r:{}),(n=a?.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};return t.accessToken?_.accessToken=t.accessToken:delete _.accessToken,_}function Pd(t){let e=t?.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(kd(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var Cd=class extends Do.AuthClient{constructor(t){super(t)}},Fo=class{constructor(t,e,r){var n,s;this.supabaseUrl=t,this.supabaseKey=e;let i=Pd(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);let o=`sb-${i.hostname.split(".")[0]}-auth-token`,a={db:yd,realtime:wd,auth:se(se({},vd),{},{storageKey:o}),global:gd},l=Od(r??{},a);if(this.storageKey=(n=l.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(s=l.global.headers)!==null&&s!==void 0?s:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(h,m)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(m)} is not possible`)}});else{var c;this.auth=this._initSupabaseAuthClient((c=l.auth)!==null&&c!==void 0?c:{},this.headers,l.global.fetch)}this.fetch=Rd(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(se({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(h=>this.realtime.setAuth(h)).catch(h=>console.warn("Failed to set initial Realtime auth token:",h)),this.rest=new Di(new URL("rest/v1",i).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new ao(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new be.FunctionsClient(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();let{data:n}=await t.auth.getSession();return(e=(r=n.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:s,storageKey:i,flowType:o,lock:a,debug:l,throwOnError:c},h,m){let _={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Cd({url:this.authUrl.href,headers:se(se({},_),h),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:s,flowType:o,lock:a,debug:l,throwOnError:c,fetch:m,hasCustomAuthorizationHeader:Object.keys(this.headers).some(f=>f.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new $o.RealtimeClient(this.realtimeUrl.href,se(se({},t),{},{params:se(se({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e?.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}},rs=(t,e,r)=>new Fo(t,e,r);function Id(){if(typeof window<"u")return!1;let t=globalThis.process;if(!t)return!1;let e=t.version;if(e==null)return!1;let r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}Id()&&console.warn("\u26A0\uFE0F 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");function Bo(t,e){return async(r,n,s)=>{let i,o=()=>i??=s(),a=l=>i&&l?.name==="AbortError";try{return await t(r,n,o)}catch(l){if(a(l))return i;if(!l?.isAcquireTimeout)throw l;try{return await e(r,o)}catch(c){if(a(c))return i;throw c}}}}var Rt=typeof window<"u"&&!!window.__CONFORM_ENGINE__,qo=Rt?"http://127.0.0.1:9":import.meta.env.VITE_SUPABASE_URL,Mo=Rt?"offline":import.meta.env.VITE_SUPABASE_ANON_KEY;if(!qo)throw console.error("Missing VITE_SUPABASE_URL environment variable"),new Error("Missing Supabase URL environment variable");if(!Mo)throw console.error("Missing VITE_SUPABASE_ANON_KEY environment variable"),new Error("Missing Supabase anon key environment variable");var kt=rs(qo,Mo,{auth:{autoRefreshToken:!Rt,persistSession:!Rt,detectSessionInUrl:!Rt,...typeof navigator<"u"&&navigator.locks?{lock:Bo(A.navigatorLock,(t,e)=>navigator.locks.request(t,{steal:!0},e))}:{}}});var Wo=null;var Vo=()=>Wo?{"x-portal-pass":Wo}:{};var xd=typeof __BUILD_SHA__<"u"?`web-${__BUILD_SHA__}`:"web-dev",Nd=`${import.meta.env.VITE_SUPABASE_URL}/functions/v1/v1-me/v1/engine/telemetry`,jd=1e4,Ld=crypto.randomUUID(),yr=0,Ud=0,vr=[],Ho=null;function Ko(){yr++,ss=!1,zo=Date.now()}var ss=!1,zo=0;function Go(){return ss}function wr(t,e={}){yr||(yr=1),vr.push({kind:"outcome",verb:t,ok:e.ok??!0,code:e.ok===!1?e.code??"error":void 0,error:e.ok===!1?e.error:void 0,duration_ms:Math.max(0,Math.round(e.ms??0)),counts:e.counts,fields:e.fields,session_id:e.session_id,version:xd,run_id:Ld,seq:++Ud,req:yr,event_id:crypto.randomUUID(),run_at:new Date().toISOString(),client:"web",author:"user"}),Ho??=setTimeout(()=>void Yo(),jd)}var ns=null;async function Jo(t,e,r=()=>({})){let n=performance.now();ns=null;try{let s=await e(),i=ns;return ns=null,wr(t,i?{ok:!1,...i,ms:performance.now()-n}:{...r(s),ok:!0,ms:performance.now()-n}),s}catch(s){throw wr(t,{ok:!1,code:s?.code,error:s instanceof Error?s.message:String(s),ms:performance.now()-n}),s}}async function Yo(){if(Ho=null,!vr.length)return;let t=vr;vr=[];try{let{data:{session:e}}=await kt.auth.getSession();if(!e?.access_token)return;await fetch(Nd,{method:"POST",keepalive:!0,headers:{"content-type":"application/json",authorization:`Bearer ${e.access_token}`,apikey:import.meta.env.VITE_SUPABASE_ANON_KEY},body:JSON.stringify({events:t})})}catch{}}typeof window<"u"&&window.addEventListener("pagehide",()=>{ss&&wr("page_leave",{counts:{seconds:Math.round((Date.now()-zo)/1e3)}}),Yo()});var $d=`${import.meta.env.VITE_SUPABASE_URL}/functions/v1`;async function Dd(t){let{data:{session:e}}=await kt.auth.getSession(),r=e?.access_token??import.meta.env.VITE_SUPABASE_ANON_KEY,n=JSON.stringify({format:t.format,source_filename:t.sourceFilename,persist:t.persist,session_id:t.sessionId,selected_sequence_names:t.selectedSequenceNames,previously_selected_names:t.previouslySelectedNames}),s=typeof t.extract=="string"?t.extract:JSON.stringify(t.extract),{contentType:i,body:o}=await ti(n,s),a=new Set([502,503,504,529,546]),l=null;for(let c=0;;c++){try{l=await fetch(`${$d}/v1-timeline-canonicalize/v1/timeline-canonicalize`,{method:"POST",headers:{"Content-Type":i,Authorization:`Bearer ${r}`,...e?{}:Vo()},body:o})}catch(h){if(c>=2)throw h;l=null}if(l&&(l.ok||!a.has(l.status)))break;if(c>=2)throw l?.status===546?new Error("Our conversion server stopped this timeline three times in a row. That is a limit on our side, not a problem with your file. Please try again later; if it keeps failing, converting fewer sequences at a time gets it through, and we'd like to hear about it."):new Error(`The processing server timed out (${l?.status??"network error"}) \u2014 a server hiccup, not a problem with your file. Please try again in a minute.`);await new Promise(h=>setTimeout(h,1500*(c+1)))}if(!l.ok){let c=await l.json().catch(()=>({}));throw new Error(c?.error?.message??`canonicalize failed (${l.status})`)}return await l.json()}async function Xo(t){return!t.sessionId&&!Go()&&Ko(),Jo("timeline_read",()=>Dd(t),e=>({fields:[`format=${String(t.format).toLowerCase()}`,...t.selectedSequenceNames?.length?[]:["scope=project"]],counts:{timelines:e.session?.timelines?.length??0},session_id:e.session_id??void 0}))}var Fd=[{ext:"mov",name:"QuickTime",container:"mov",codec:"prores",frameType:"intra",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0},{ext:"mp4",name:"MPEG-4",container:"mov",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0},{ext:"m4v",name:"MPEG-4 Video",container:"mov",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0},{ext:"m4a",name:"MPEG-4 Audio",container:"mov",codec:"aac",frameType:"intra",sparseStrategy:"full-file",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"mxf",name:"MXF",container:"mxf",codec:"varies",frameType:"intra",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0,notes:"Verified Resolve playback for XAVC-I NDF/DF. Coordinated 45-patch metadata rewrite (index entries + Duration fields). DNxHD foundation works; mid-clip trim works structurally; awaiting more corpus."},{ext:"r3d",name:"RED RAW",container:"r3d",codec:"r3d",frameType:"intra",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0,notes:"Verified Resolve playback (V-Raptor 6K). Trim/prepare/inspect run client-side as opaque WASM (mediaOp) \u2014 browser sees no algorithm; WS bridge retired. DRAGON era + Komodo + 8K need corpus expansion. Run oracle/i2o/cli/r3d-corpus.ts on new fixtures."},{ext:"braw",name:"Blackmagic RAW",container:"mov",codec:"braw",frameType:"intra",sparseStrategy:"byte-range",support:"dedicated",needsStructuralBytes:!1,trimSupported:!0,notes:'Verified Resolve playback. Standard MP4 container with BRAW codec; reuses structure-preserving MOV walker. The "secret sauce" was knowing BRAW = MP4.'},{ext:"crm",name:"Canon Cinema RAW Light",container:"crm",codec:"crm",frameType:"intra",sparseStrategy:"byte-range",support:"planned",needsStructuralBytes:!1,trimSupported:!1,notes:"Frame-indexed single file. Canon SDK available."},{ext:"rmf",name:"Canon RAW (legacy)",container:"crm",codec:"crm",frameType:"intra",sparseStrategy:"byte-range",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"ari",name:"ARRIRAW",container:"frame-seq",codec:"arriraw",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1,notes:"8KB header + raw Bayer per frame. Sparse = select which .ari files to include."},{ext:"arx",name:"ARRIRAW HDE",container:"frame-seq",codec:"arriraw",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"dpx",name:"DPX",container:"frame-seq",codec:"dpx",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1,notes:"SMPTE 268M. Image data offset at byte 4. ~25MB per 4K frame."},{ext:"exr",name:"OpenEXR",container:"frame-seq",codec:"exr",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"tif",name:"TIFF",container:"frame-seq",codec:"tiff",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"tiff",name:"TIFF",container:"frame-seq",codec:"tiff",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"png",name:"PNG",container:"frame-seq",codec:"png",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"jpg",name:"JPEG",container:"frame-seq",codec:"jpeg",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"jpeg",name:"JPEG",container:"frame-seq",codec:"jpeg",frameType:"intra",sparseStrategy:"file-select",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"psd",name:"Photoshop",container:"still",codec:"psd",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"tga",name:"Targa",container:"still",codec:"tga",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"bmp",name:"Bitmap",container:"still",codec:"bmp",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"gif",name:"GIF",container:"still",codec:"gif",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"webp",name:"WebP",container:"still",codec:"webp",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"avif",name:"AVIF",container:"still",codec:"avif",frameType:"intra",sparseStrategy:"full-file",support:"planned",needsStructuralBytes:!1,trimSupported:!1},{ext:"wav",name:"WAV",container:"audio",codec:"pcm",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!0,notes:"RIFF/WAV trim decoder ships. Poly WAV (8-24ch) could benefit from time-axis chunking."},{ext:"bwf",name:"Broadcast WAV",container:"audio",codec:"pcm",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!0,notes:"WAV + bext chunk (~602+ bytes) with timecode reference. Same trim decoder as WAV."},{ext:"aif",name:"AIFF",container:"audio",codec:"pcm",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1},{ext:"aiff",name:"AIFF",container:"audio",codec:"pcm",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1},{ext:"mp3",name:"MP3",container:"audio",codec:"mp3",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1},{ext:"aac",name:"AAC",container:"audio",codec:"aac",frameType:"intra",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1},{ext:"avi",name:"AVI",container:"avi",codec:"varies",frameType:"intra",sparseStrategy:"byte-range",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"mkv",name:"Matroska",container:"mkv",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"mts",name:"AVCHD",container:"mov",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"m2ts",name:"AVCHD",container:"mov",codec:"h264",frameType:"inter",sparseStrategy:"byte-range",support:"container",needsStructuralBytes:!1,trimSupported:!1},{ext:"webm",name:"WebM",container:"mkv",codec:"vp9",frameType:"inter",sparseStrategy:"full-file",support:"full-file",needsStructuralBytes:!1,trimSupported:!1}],Qo=new Map;for(let t of Fd)Qo.set(t.ext,t);function Bd(t){let e=t.split(".").pop()?.toLowerCase();return e?Qo.get(e)??null:null}function Zo(t){return Bd(t)!==null}var nh=ze(fa());var rh=typeof __BUILD_SHA__<"u"?__BUILD_SHA__:"dev",Ar=class extends Error{constructor(e,r){super(r??"A new version of Conform was released while this page was open, so part of the app could no longer be loaded. Reload the page to continue \u2014 nothing has been sent yet."),this.name="StaleBuildError",this.chunk=e,this.buildSha=rh}};var pa=typeof __BUILD_SHA__<"u"?__BUILD_SHA__:"dev",rp=900*1e3;async function sh(t=fetch,e=pa){if(!e||e==="dev"||e==="unknown")return!1;try{let r=await t(`/build-info.json?t=${Date.now()}`,{cache:"no-store"});if(!r.ok)return!1;let n=await r.json();return typeof n.sha=="string"&&n.sha!==""&&n.sha!=="unknown"&&n.sha!==e}catch{return!1}}async function ma(t=fetch,e=pa){if(await sh(t,e))throw new Ar("timeline-read","A new version of Conform was released while this page was open. Reload the page and drop the file again \u2014 nothing has been read or sent yet.")}function _a(){return typeof window<"u"&&!!window.__CONFORM_ENGINE__}async function hp(t){if(Zo(t.name))return await ih(t);let e=await Hr(t);if(e.format!=="unknown"&&Vr(e.format)){let r=e.format==="flame-archive"?(await ah(t)).session.timelines.filter(n=>n.kind!=="compound"&&n.tracks?.some(s=>s.items?.length)).map(n=>n.name??"").filter(Boolean):(await Zs(t,e.format)).names;return{kind:"timeline",format:e.format,name:t.name,observed_bytes:t.size,total_size:t.size,session:{id:null,inline:{timelines:r.map(n=>({name:n}))}},warnings:[],inspector:{layer:"timeline-core/wasm-inspect",version:"1",duration_ms:0}}}return{kind:"unknown",format:"unknown",name:t.name,observed_bytes:0,total_size:t.size,session:null,warnings:[{code:"container_corruption",message:`Unrecognized file: ${t.name}`}],inspector:{layer:"inspect/unknown",version:"1",duration_ms:0}}}async function ih(t){let e=Date.now(),r=await ri(t);if(!r)return{kind:"unknown",format:"unknown",name:t.name,observed_bytes:0,total_size:t.size,session:null,warnings:[{code:"container_corruption",message:"No browser-side probe available (proprietary format or unsupported extension)"}],inspector:{layer:"probe-media/local",version:"1",duration_ms:Date.now()-e}};let n=r.container??"media",s={metadata:{id:t.name,user_id:"",source_format:n,source_filename:t.name,source_file_sha256:null,source_file_bytes:t.size,parser_name:`media:${n}`,parser_version:"1",status:"ready",error_message:null,metadata:{},created_at:new Date().toISOString()},timelines:[],media_references:[r]};return{kind:"media",format:n,name:t.name,observed_bytes:0,total_size:t.size,session:{id:null,inline:s},warnings:[],inspector:{layer:"probe-media/local",version:"1",duration_ms:Date.now()-e}}}var ga=new Map,oh=t=>t.replace(/^[a-z]\d+:/,""),fp=t=>ga.get(oh(t));async function ah(t,e={}){if(_a()){let{engine:o}=await import("./engine-WEGECPAH.js"),a=await o.canonicalize(t,e.selectedSequenceNames,e.previouslySelectedNames);for(let l of a.session.timelines??[])ga.set(l.id,a.session_id);return{session:a.session,sessionId:a.session_id,persistError:null}}let{format:r}=await Hr(t);if(!Vr(r))throw new Error(`No Rust timeline engine for format '${r}' (${t.name})`);await ma();let{fmt:n,extract:s}=await ei(t,r,e.selectedSequenceNames),i=await Xo({format:n,extract:s,sourceFilename:t.name,persist:e.persist,sessionId:e.sessionId,selectedSequenceNames:e.selectedSequenceNames,previouslySelectedNames:e.previouslySelectedNames});return{session:i.session,sessionId:i.session_id??i.session?.id??null,persistError:i.persist_error??null}}export{ah as canonicalizeTimelineFile,fp as engineSessionFor,oh as engineTimelineId,hp as inspectFile};
|