conformtools 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +92 -0
  2. package/dist/arriraw-Y5VXHXNX.js +525 -0
  3. package/dist/browser/timeline_core_bg.wasm +0 -0
  4. package/dist/chunk-35U7WGES.js +3 -0
  5. package/dist/chunk-3XTUTEKJ.js +102 -0
  6. package/dist/chunk-7D7H6VFW.js +3 -0
  7. package/dist/chunk-AACY2V3L.js +3 -0
  8. package/dist/chunk-AHNDJFQR.js +3 -0
  9. package/dist/chunk-C2ESM27Z.js +3 -0
  10. package/dist/chunk-DKGGJM6Z.js +3 -0
  11. package/dist/chunk-DRHOPOC7.js +3 -0
  12. package/dist/chunk-HJXRLQOI.js +3 -0
  13. package/dist/chunk-IDDQR56R.js +7 -0
  14. package/dist/chunk-JEMLKBH2.js +3 -0
  15. package/dist/chunk-NYB4ISL3.js +3 -0
  16. package/dist/chunk-P7OVDUA5.js +3 -0
  17. package/dist/chunk-PSANHDZM.js +3 -0
  18. package/dist/chunk-QDWB7QU7.js +3 -0
  19. package/dist/chunk-RXHNBSER.js +3 -0
  20. package/dist/chunk-SP5RGDAM.js +3 -0
  21. package/dist/chunk-TK55FA56.js +3 -0
  22. package/dist/chunk-UCMNH6Q6.js +3 -0
  23. package/dist/chunk-UUMHVA7R.js +3 -0
  24. package/dist/chunk-WWGQFOB2.js +64 -0
  25. package/dist/chunk-YPRTUS5W.js +3 -0
  26. package/dist/cli.js +11 -0
  27. package/dist/clip-state-B6JOX3JE.js +3 -0
  28. package/dist/cr3-wasm-X6Q4YMUU.js +3 -0
  29. package/dist/dng-wasm-EAB24KDN.js +3 -0
  30. package/dist/dpx-wasm-OX2D24ZB.js +3 -0
  31. package/dist/esm-SFFBP7PS.js +3 -0
  32. package/dist/exr-wasm-Z6BBPJSN.js +3 -0
  33. package/dist/h264-JHQCJTWP.js +3 -0
  34. package/dist/h264-mxf-4M63NBQK.js +3 -0
  35. package/dist/http.js +4 -0
  36. package/dist/inspect-6OM4FTVW.js +46 -0
  37. package/dist/isobmff-XL33CVJR.js +3 -0
  38. package/dist/mcp.js +13 -0
  39. package/dist/media_core-VSTO6CS4.js +9 -0
  40. package/dist/media_core_bg-BKXQLNFA.js +3 -0
  41. package/dist/media_core_bg-XIM7Y4R3.js +3 -0
  42. package/dist/mxf-VIANACTI.js +3 -0
  43. package/dist/onnxruntime-web-stub-PKJ2NZBF.js +3 -0
  44. package/dist/ops-7HVBBXUQ.js +3 -0
  45. package/dist/prores-TQEZ3KFH.js +526 -0
  46. package/dist/r3d-2QCFX7UX.js +3 -0
  47. package/dist/r3d-AT6NNIY3.js +1025 -0
  48. package/dist/source-BDJAUQVR.js +3 -0
  49. package/dist/sscd-sweep-IXM4OD7O.js +3 -0
  50. package/dist/still-E4HLCCST.js +3 -0
  51. package/dist/tiff-wasm-XYTQNL2F.js +3 -0
  52. package/dist/timeline_core-VK2ZWPCO.js +3 -0
  53. package/dist/timeline_core_bg-QEOVAIWP.js +3 -0
  54. package/dist/udf_bg-UTQ6BVXX.js +3 -0
  55. package/dist/wasm/media_core_bg.wasm +0 -0
  56. package/dist/wasm/udf_bg.wasm +0 -0
  57. package/dist/wasm-threads/media_core_bg.wasm +0 -0
  58. package/dist/wav-DXF73Y56.js +3 -0
  59. package/dist/zod-IPSV75LP.js +3 -0
  60. package/package.json +41 -0
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __conformRequire } from 'node:module'; const require = __conformRequire(import.meta.url);
3
+ import{e as kt,f as qr,h as Br,k as Fr}from"./chunk-35U7WGES.js";import"./chunk-P7OVDUA5.js";import"./chunk-UCMNH6Q6.js";import"./chunk-YPRTUS5W.js";import"./chunk-C2ESM27Z.js";import{b as Cn,c as P,d as Dr,e as E,f as Ie,g as re}from"./chunk-PSANHDZM.js";var Y={};Dr(Y,{__addDisposableResource:()=>ps,__assign:()=>ze,__asyncDelegator:()=>os,__asyncGenerator:()=>is,__asyncValues:()=>as,__await:()=>ve,__awaiter:()=>Zr,__classPrivateFieldGet:()=>hs,__classPrivateFieldIn:()=>fs,__classPrivateFieldSet:()=>ds,__createBinding:()=>Ye,__decorate:()=>Kr,__disposeResources:()=>ms,__esDecorate:()=>zr,__exportStar:()=>ts,__extends:()=>Wr,__generator:()=>es,__importDefault:()=>us,__importStar:()=>cs,__makeTemplateObject:()=>ls,__metadata:()=>Qr,__param:()=>Gr,__propKey:()=>Yr,__read:()=>It,__rest:()=>Hr,__rewriteRelativeImportExtension:()=>_s,__runInitializers:()=>Jr,__setFunctionName:()=>Xr,__spread:()=>rs,__spreadArray:()=>ns,__spreadArrays:()=>ss,__values:()=>Je,default:()=>Ln});function Wr(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Ot(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}function Hr(t,e){var r={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,s=Object.getOwnPropertySymbols(t);n<s.length;n++)e.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(r[s[n]]=t[s[n]]);return r}function Kr(t,e,r,s){var n=arguments.length,i=n<3?e:s===null?s=Object.getOwnPropertyDescriptor(e,r):s,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,r,s);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(n<3?o(i):n>3?o(e,r,i):o(e,r))||i);return n>3&&i&&Object.defineProperty(e,r,i),i}function Gr(t,e){return function(r,s){e(r,s,t)}}function zr(t,e,r,s,n,i){function o(y){if(y!==void 0&&typeof y!="function")throw new TypeError("Function expected");return y}for(var a=s.kind,l=a==="getter"?"get":a==="setter"?"set":"value",c=!e&&t?s.static?t:t.prototype:null,u=e||(c?Object.getOwnPropertyDescriptor(c,s.name):{}),d,f=!1,h=r.length-1;h>=0;h--){var p={};for(var m in s)p[m]=m==="access"?{}:s[m];for(var m in s.access)p.access[m]=s.access[m];p.addInitializer=function(y){if(f)throw new TypeError("Cannot add initializers after decoration has completed");i.push(o(y||null))};var _=(0,r[h])(a==="accessor"?{get:u.get,set:u.set}:u[l],p);if(a==="accessor"){if(_===void 0)continue;if(_===null||typeof _!="object")throw new TypeError("Object expected");(d=o(_.get))&&(u.get=d),(d=o(_.set))&&(u.set=d),(d=o(_.init))&&n.unshift(d)}else(d=o(_))&&(a==="field"?n.unshift(d):u[l]=d)}c&&Object.defineProperty(c,s.name,u),f=!0}function Jr(t,e,r){for(var s=arguments.length>2,n=0;n<e.length;n++)r=s?e[n].call(t,r):e[n].call(t);return s?r:void 0}function Yr(t){return typeof t=="symbol"?t:"".concat(t)}function Xr(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 Qr(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Zr(t,e,r,s){function n(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function a(u){try{c(s.next(u))}catch(d){o(d)}}function l(u){try{c(s.throw(u))}catch(d){o(d)}}function c(u){u.done?i(u.value):n(u.value).then(a,l)}c((s=s.apply(t,e||[])).next())})}function es(t,e){var r={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},s,n,i,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(c){return function(u){return l([c,u])}}function l(c){if(s)throw new TypeError("Generator is already executing.");for(;o&&(o=0,c[0]&&(r=0)),r;)try{if(s=1,n&&(i=c[0]&2?n.return:c[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,c[1])).done)return i;switch(n=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return r.label++,{value:c[1],done:!1};case 5:r.label++,n=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(u){c=[6,u],n=0}finally{s=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function ts(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Ye(e,t,r)}function Je(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],s=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&s>=t.length&&(t=void 0),{value:t&&t[s++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function It(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var s=r.call(t),n,i=[],o;try{for(;(e===void 0||e-- >0)&&!(n=s.next()).done;)i.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(r=s.return)&&r.call(s)}finally{if(o)throw o.error}}return i}function rs(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(It(arguments[e]));return t}function ss(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var s=Array(t),n=0,e=0;e<r;e++)for(var i=arguments[e],o=0,a=i.length;o<a;o++,n++)s[n]=i[o];return s}function ns(t,e,r){if(r||arguments.length===2)for(var s=0,n=e.length,i;s<n;s++)(i||!(s in e))&&(i||(i=Array.prototype.slice.call(e,0,s)),i[s]=e[s]);return t.concat(i||Array.prototype.slice.call(e))}function ve(t){return this instanceof ve?(this.v=t,this):new ve(t)}function is(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=r.apply(t,e||[]),n,i=[];return n=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",o),n[Symbol.asyncIterator]=function(){return this},n;function o(h){return function(p){return Promise.resolve(p).then(h,d)}}function a(h,p){s[h]&&(n[h]=function(m){return new Promise(function(_,y){i.push([h,m,_,y])>1||l(h,m)})},p&&(n[h]=p(n[h])))}function l(h,p){try{c(s[h](p))}catch(m){f(i[0][3],m)}}function c(h){h.value instanceof ve?Promise.resolve(h.value.v).then(u,d):f(i[0][2],h)}function u(h){l("next",h)}function d(h){l("throw",h)}function f(h,p){h(p),i.shift(),i.length&&l(i[0][0],i[0][1])}}function os(t){var e,r;return e={},s("next"),s("throw",function(n){throw n}),s("return"),e[Symbol.iterator]=function(){return this},e;function s(n,i){e[n]=t[n]?function(o){return(r=!r)?{value:ve(t[n](o)),done:!1}:i?i(o):o}:i}}function as(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 Je=="function"?Je(t):t[Symbol.iterator](),r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r);function s(i){r[i]=t[i]&&function(o){return new Promise(function(a,l){o=t[i](o),n(a,l,o.done,o.value)})}}function n(i,o,a,l){Promise.resolve(l).then(function(c){i({value:c,done:a})},o)}}function ls(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function cs(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r=Pt(t),s=0;s<r.length;s++)r[s]!=="default"&&Ye(e,t,r[s]);return jn(e,t),e}function us(t){return t&&t.__esModule?t:{default:t}}function hs(t,e,r,s){if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(t):s?s.value:e.get(t)}function ds(t,e,r,s,n){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(t,r):n?n.value=r:e.set(t,r),r}function fs(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 ps(t,e,r){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var s,n;if(r){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");s=e[Symbol.asyncDispose]}if(s===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");s=e[Symbol.dispose],r&&(n=s)}if(typeof s!="function")throw new TypeError("Object not disposable.");n&&(s=function(){try{n.call(this)}catch(i){return Promise.reject(i)}}),t.stack.push({value:e,dispose:s,async:r})}else r&&t.stack.push({async:!0});return e}function ms(t){function e(i){t.error=t.hasError?new Un(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,s=0;function n(){for(;r=t.stack.pop();)try{if(!r.async&&s===1)return s=0,t.stack.push(r),Promise.resolve().then(n);if(r.dispose){var i=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(i).then(n,function(o){return e(o),n()})}else s|=1}catch(o){e(o)}if(s===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return n()}function _s(t,e){return typeof t=="string"&&/^\.\.?\//.test(t)?t.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(r,s,n,i,o){return s?e?".jsx":".js":n&&(!i||!o)?r:n+i+"."+o.toLowerCase()+"js"}):t}var Ot,ze,Ye,jn,Pt,Un,Ln,X=Cn(()=>{Ot=function(t,e){return Ot=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&(r[n]=s[n])},Ot(t,e)};ze=function(){return ze=Object.assign||function(e){for(var r,s=1,n=arguments.length;s<n;s++){r=arguments[s];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},ze.apply(this,arguments)};Ye=Object.create?(function(t,e,r,s){s===void 0&&(s=r);var n=Object.getOwnPropertyDescriptor(e,r);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,s,n)}):(function(t,e,r,s){s===void 0&&(s=r),t[s]=e[r]});jn=Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e},Pt=function(t){return Pt=Object.getOwnPropertyNames||function(e){var r=[];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(r[r.length]=s);return r},Pt(t)};Un=typeof SuppressedError=="function"?SuppressedError:function(t,e,r){var s=new Error(r);return s.name="SuppressedError",s.error=t,s.suppressed=e,s};Ln={__extends:Wr,__assign:ze,__rest:Hr,__decorate:Kr,__param:Gr,__esDecorate:zr,__runInitializers:Jr,__propKey:Yr,__setFunctionName:Xr,__metadata:Qr,__awaiter:Zr,__generator:es,__createBinding:Ye,__exportStar:ts,__values:Je,__read:It,__spread:rs,__spreadArrays:ss,__spreadArray:ns,__await:ve,__asyncGenerator:is,__asyncDelegator:os,__asyncValues:as,__makeTemplateObject:ls,__importStar:cs,__importDefault:us,__classPrivateFieldGet:hs,__classPrivateFieldSet:ds,__classPrivateFieldIn:fs,__addDisposableResource:ps,__disposeResources:ms,__rewriteRelativeImportExtension:_s}});var gs=P(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.resolveFetch=void 0;var $n=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);Xe.resolveFetch=$n});var jt=P(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.FunctionRegion=Q.FunctionsHttpError=Q.FunctionsRelayError=Q.FunctionsFetchError=Q.FunctionsError=void 0;var we=class extends Error{constructor(e,r="FunctionsError",s){super(e),this.name=r,this.context=s}};Q.FunctionsError=we;var Ct=class extends we{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}};Q.FunctionsFetchError=Ct;var xt=class extends we{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}};Q.FunctionsRelayError=xt;var Nt=class extends we{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}};Q.FunctionsHttpError=Nt;var ys;(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"})(ys||(Q.FunctionRegion=ys={}))});var vs=P(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.FunctionsClient=void 0;var Dn=(X(),re(Y)),qn=gs(),be=jt(),Ut=class{constructor(e,{headers:r={},customFetch:s,region:n=be.FunctionRegion.Any}={}){this.url=e,this.headers=r,this.region=n,this.fetch=(0,qn.resolveFetch)(s)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return Dn.__awaiter(this,arguments,void 0,function*(r,s={}){var n;let i,o;try{let{headers:a,method:l,body:c,signal:u,timeout:d}=s,f={},{region:h}=s;h||(h=this.region);let p=new URL(`${this.url}/${r}`);h&&h!=="any"&&(f["x-region"]=h,p.searchParams.set("forceFunctionRegion",h));let m;c&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(f["Content-Type"]="application/octet-stream",m=c):typeof c=="string"?(f["Content-Type"]="text/plain",m=c):typeof FormData<"u"&&c instanceof FormData?m=c:(f["Content-Type"]="application/json",m=JSON.stringify(c)):c&&typeof c!="string"&&!(typeof Blob<"u"&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<"u"&&c instanceof FormData)?m=JSON.stringify(c):m=c;let _=u;d&&(o=new AbortController,i=setTimeout(()=>o.abort(),d),u?(_=o.signal,u.addEventListener("abort",()=>o.abort())):_=o.signal);let y=yield this.fetch(p.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},f),this.headers),a),body:m,signal:_}).catch(H=>{throw new be.FunctionsFetchError(H)}),S=y.headers.get("x-relay-error");if(S&&S==="true")throw new be.FunctionsRelayError(y);if(!y.ok)throw new be.FunctionsHttpError(y);let w=((n=y.headers.get("Content-Type"))!==null&&n!==void 0?n:"text/plain").split(";")[0].trim(),k;return w==="application/json"?k=yield y.json():w==="application/octet-stream"||w==="application/pdf"?k=yield y.blob():w==="text/event-stream"?k=y:w==="multipart/form-data"?k=yield y.formData():k=yield y.text(),{data:k,error:null,response:y}}catch(a){return{data:null,error:a,response:a instanceof be.FunctionsHttpError||a instanceof be.FunctionsRelayError?a.context:void 0}}finally{i&&clearTimeout(i)}})}};Qe.FunctionsClient=Ut});var ws=P(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.FunctionRegion=G.FunctionsRelayError=G.FunctionsHttpError=G.FunctionsFetchError=G.FunctionsError=G.FunctionsClient=void 0;var Bn=vs();Object.defineProperty(G,"FunctionsClient",{enumerable:!0,get:function(){return Bn.FunctionsClient}});var Ce=jt();Object.defineProperty(G,"FunctionsError",{enumerable:!0,get:function(){return Ce.FunctionsError}});Object.defineProperty(G,"FunctionsFetchError",{enumerable:!0,get:function(){return Ce.FunctionsFetchError}});Object.defineProperty(G,"FunctionsHttpError",{enumerable:!0,get:function(){return Ce.FunctionsHttpError}});Object.defineProperty(G,"FunctionsRelayError",{enumerable:!0,get:function(){return Ce.FunctionsRelayError}});Object.defineProperty(G,"FunctionRegion",{enumerable:!0,get:function(){return Ce.FunctionRegion}})});var $t=P(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.WebSocketFactory=void 0;var et=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 s=r.versions;if(s&&s.node){let n=s.node,i=parseInt(n.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
+ import ws from "ws"
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
+
7
+ Suggested solution: ${e.workaround}`),new Error(r)}static createWebSocket(e,r){let s=this.getWebSocketConstructor();return new s(e,r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return!1}}};Ne.WebSocketFactory=et;Ne.default=et});var Ts=P(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.version=void 0;tt.version="2.97.0"});var rt=P(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.CONNECTION_STATE=x.TRANSPORTS=x.CHANNEL_EVENTS=x.CHANNEL_STATES=x.SOCKET_STATES=x.MAX_PUSH_BUFFER_SIZE=x.WS_CLOSE_NORMAL=x.DEFAULT_TIMEOUT=x.VERSION=x.DEFAULT_VSN=x.VSN_2_0_0=x.VSN_1_0_0=x.DEFAULT_VERSION=void 0;var Cs=Ts();x.DEFAULT_VERSION=`realtime-js/${Cs.version}`;x.VSN_1_0_0="1.0.0";x.VSN_2_0_0="2.0.0";x.DEFAULT_VSN=x.VSN_2_0_0;x.VERSION=Cs.version;x.DEFAULT_TIMEOUT=1e4;x.WS_CLOSE_NORMAL=1e3;x.MAX_PUSH_BUFFER_SIZE=100;var ks;(function(t){t[t.connecting=0]="connecting",t[t.open=1]="open",t[t.closing=2]="closing",t[t.closed=3]="closed"})(ks||(x.SOCKET_STATES=ks={}));var Rs;(function(t){t.closed="closed",t.errored="errored",t.joined="joined",t.joining="joining",t.leaving="leaving"})(Rs||(x.CHANNEL_STATES=Rs={}));var Os;(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"})(Os||(x.CHANNEL_EVENTS=Os={}));var Ps;(function(t){t.websocket="websocket"})(Ps||(x.TRANSPORTS=Ps={}));var Is;(function(t){t.Connecting="connecting",t.Open="open",t.Closing="closing",t.Closed="closed"})(Is||(x.CONNECTION_STATE=Is={}))});var xs=P(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});var Dt=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 s=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(s))}_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,s;let n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,n)}_encodeJsonUserBroadcastPush(e){var r,s;let n=(s=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&s!==void 0?s:{},o=new TextEncoder().encode(JSON.stringify(n)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,s){var n,i;let o=e.topic,a=(n=e.ref)!==null&&n!==void 0?n:"",l=(i=e.join_ref)!==null&&i!==void 0?i:"",c=e.payload.event,u=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(u).length===0?"":JSON.stringify(u);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`metadata length ${d.length} exceeds maximum of 255`);let f=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+o.length+c.length+d.length,h=new ArrayBuffer(this.HEADER_LENGTH+f),p=new DataView(h),m=0;p.setUint8(m++,this.KINDS.userBroadcastPush),p.setUint8(m++,l.length),p.setUint8(m++,a.length),p.setUint8(m++,o.length),p.setUint8(m++,c.length),p.setUint8(m++,d.length),p.setUint8(m++,r),Array.from(l,y=>p.setUint8(m++,y.charCodeAt(0))),Array.from(a,y=>p.setUint8(m++,y.charCodeAt(0))),Array.from(o,y=>p.setUint8(m++,y.charCodeAt(0))),Array.from(c,y=>p.setUint8(m++,y.charCodeAt(0))),Array.from(d,y=>p.setUint8(m++,y.charCodeAt(0)));var _=new Uint8Array(h.byteLength+s.byteLength);return _.set(new Uint8Array(h),0),_.set(new Uint8Array(s),h.byteLength),_.buffer}decode(e,r){if(this._isArrayBuffer(e)){let s=this._binaryDecode(e);return r(s)}if(typeof e=="string"){let s=JSON.parse(e),[n,i,o,a,l]=s;return r({join_ref:n,ref:i,topic:o,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),s=r.getUint8(0),n=new TextDecoder;switch(s){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,r,n)}}_decodeUserBroadcast(e,r,s){let n=r.getUint8(1),i=r.getUint8(2),o=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,c=s.decode(e.slice(l,l+n));l=l+n;let u=s.decode(e.slice(l,l+i));l=l+i;let d=s.decode(e.slice(l,l+o));l=l+o;let f=e.slice(l,e.byteLength),h=a===this.JSON_ENCODING?JSON.parse(s.decode(f)):f,p={type:this.BROADCAST_EVENT,event:u,payload:h};return o>0&&(p.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:p}}_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(([s])=>r.includes(s)))}};qt.default=Dt});var Mt=P(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});var Bt=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))}};Ft.default=Bt});var st=P(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.httpEndpointURL=C.toTimestampString=C.toArray=C.toJson=C.toNumber=C.toBoolean=C.convertCell=C.convertColumn=C.convertChangeData=C.PostgresTypes=void 0;var U;(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"})(U||(C.PostgresTypes=U={}));var Gn=(t,e,r={})=>{var s;let n=(s=r.skipTypes)!==null&&s!==void 0?s:[];return e?Object.keys(e).reduce((i,o)=>(i[o]=(0,C.convertColumn)(o,t,e,n),i),{}):{}};C.convertChangeData=Gn;var zn=(t,e,r,s)=>{let n=e.find(a=>a.name===t),i=n?.type,o=r[t];return i&&!s.includes(i)?(0,C.convertCell)(i,o):Vt(o)};C.convertColumn=zn;var Jn=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return(0,C.toArray)(e,r)}switch(t){case U.bool:return(0,C.toBoolean)(e);case U.float4:case U.float8:case U.int2:case U.int4:case U.int8:case U.numeric:case U.oid:return(0,C.toNumber)(e);case U.json:case U.jsonb:return(0,C.toJson)(e);case U.timestamp:return(0,C.toTimestampString)(e);case U.abstime:case U.date:case U.daterange:case U.int4range:case U.int8range:case U.money:case U.reltime:case U.text:case U.time:case U.timestamptz:case U.timetz:case U.tsrange:case U.tstzrange:return Vt(e);default:return Vt(e)}};C.convertCell=Jn;var Vt=t=>t,Yn=t=>{switch(t){case"t":return!0;case"f":return!1;default:return t}};C.toBoolean=Yn;var Xn=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t};C.toNumber=Xn;var Qn=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t};C.toJson=Qn;var Zn=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,s=t[r];if(t[0]==="{"&&s==="}"){let i,o=t.slice(1,r);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(a=>(0,C.convertCell)(e,a))}return t};C.toArray=Zn;var ei=t=>typeof t=="string"?t.replace(" ","T"):t;C.toTimestampString=ei;var ti=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};C.httpEndpointURL=ti});var Ns=P(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});var ri=rt(),Wt=class{constructor(e,r,s={},n=ri.DEFAULT_TIMEOUT){this.channel=e,this.event=r,this.payload=s,this.timeout=n,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 s;return this._hasReceived(e)&&r((s=this.receivedResp)===null||s===void 0?void 0:s.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(s=>s.status===e).forEach(s=>s.callback(r))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}};Ht.default=Wt});var Gt=P(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.REALTIME_PRESENCE_LISTEN_EVENTS=void 0;var js;(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave"})(js||(je.REALTIME_PRESENCE_LISTEN_EVENTS=js={}));var Kt=class t{constructor(e,r){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.enabled=!1,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let s=r?.events||{state:"presence_state",diff:"presence_diff"};this.channel._on(s.state,{},n=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=t.syncState(this.state,n,i,o),this.pendingDiffs.forEach(l=>{this.state=t.syncDiff(this.state,l,i,o)}),this.pendingDiffs=[],a()}),this.channel._on(s.diff,{},n=>{let{onJoin:i,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(n):(this.state=t.syncDiff(this.state,n,i,o),a())}),this.onJoin((n,i,o)=>{this.channel._trigger("presence",{event:"join",key:n,currentPresences:i,newPresences:o})}),this.onLeave((n,i,o)=>{this.channel._trigger("presence",{event:"leave",key:n,currentPresences:i,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,r,s,n){let i=this.cloneDeep(e),o=this.transformState(r),a={},l={};return this.map(i,(c,u)=>{o[c]||(l[c]=u)}),this.map(o,(c,u)=>{let d=i[c];if(d){let f=u.map(_=>_.presence_ref),h=d.map(_=>_.presence_ref),p=u.filter(_=>h.indexOf(_.presence_ref)<0),m=d.filter(_=>f.indexOf(_.presence_ref)<0);p.length>0&&(a[c]=p),m.length>0&&(l[c]=m)}else a[c]=u}),this.syncDiff(i,{joins:a,leaves:l},s,n)}static syncDiff(e,r,s,n){let{joins:i,leaves:o}={joins:this.transformState(r.joins),leaves:this.transformState(r.leaves)};return s||(s=()=>{}),n||(n=()=>{}),this.map(i,(a,l)=>{var c;let u=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),u.length>0){let d=e[a].map(h=>h.presence_ref),f=u.filter(h=>d.indexOf(h.presence_ref)<0);e[a].unshift(...f)}s(a,u,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;let u=l.map(d=>d.presence_ref);c=c.filter(d=>u.indexOf(d.presence_ref)<0),e[a]=c,n(a,c,l),c.length===0&&delete e[a]}),e}static map(e,r){return Object.getOwnPropertyNames(e).map(s=>r(s,e[s]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((r,s)=>{let n=e[s];return"metas"in n?r[s]=n.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):r[s]=n,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()}};je.default=Kt});var Yt=P(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.REALTIME_CHANNEL_STATES=se.REALTIME_SUBSCRIBE_STATES=se.REALTIME_LISTEN_TYPES=se.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=void 0;var nt=(X(),re(Y)),L=rt(),zt=nt.__importDefault(Ns()),si=nt.__importDefault(Mt()),ni=nt.__importDefault(Gt()),Us=nt.__importStar(st()),ii=st(),Ls;(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE"})(Ls||(se.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=Ls={}));var Ue;(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system"})(Ue||(se.REALTIME_LISTEN_TYPES=Ue={}));var ue;(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR"})(ue||(se.REALTIME_SUBSCRIBE_STATES=ue={}));se.REALTIME_CHANNEL_STATES=L.CHANNEL_STATES;var Jt=class t{constructor(e,r={config:{}},s){var n,i;if(this.topic=e,this.params=r,this.socket=s,this.bindings={},this.state=L.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 zt.default(this,L.CHANNEL_EVENTS.join,this.params,this.timeout),this.rejoinTimer=new si.default(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=L.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=L.CHANNEL_STATES.closed,this.socket._remove(this)}),this._onError(o=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,o),this.state=L.CHANNEL_STATES.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=L.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=L.CHANNEL_STATES.errored,this.rejoinTimer.scheduleTimeout())}),this._on(L.CHANNEL_EVENTS.reply,{},(o,a)=>{this._trigger(this._replyEventName(a),o)}),this.presence=new ni.default(this),this.broadcastEndpointURL=(0,ii.httpEndpointURL)(this.socket.endPoint),this.private=this.params.config.private||!1,!this.private&&(!((i=(n=this.params.config)===null||n===void 0?void 0:n.broadcast)===null||i===void 0)&&i.replay))throw`tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var s,n,i;if(this.socket.isConnected()||this.socket.connect(),this.state==L.CHANNEL_STATES.closed){let{config:{broadcast:o,presence:a,private:l}}=this.params,c=(n=(s=this.bindings.postgres_changes)===null||s===void 0?void 0:s.map(h=>h.filter))!==null&&n!==void 0?n:[],u=!!this.bindings[Ue.PRESENCE]&&this.bindings[Ue.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,d={},f={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:u}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(h=>e?.(ue.CHANNEL_ERROR,h)),this._onClose(()=>e?.(ue.CLOSED)),this.updateJoinPayload(Object.assign({config:f},d)),this.joinedOnce=!0,this._rejoin(r),this.joinPush.receive("ok",async({postgres_changes:h})=>{var p;if(this.socket._isManualToken()||this.socket.setAuth(),h===void 0){e?.(ue.SUBSCRIBED);return}else{let m=this.bindings.postgres_changes,_=(p=m?.length)!==null&&p!==void 0?p:0,y=[];for(let S=0;S<_;S++){let w=m[S],{filter:{event:k,schema:H,table:j,filter:V}}=w,de=h&&h[S];if(de&&de.event===k&&t.isFilterValueEqual(de.schema,H)&&t.isFilterValueEqual(de.table,j)&&t.isFilterValueEqual(de.filter,V))y.push(Object.assign(Object.assign({},w),{id:de.id}));else{this.unsubscribe(),this.state=L.CHANNEL_STATES.errored,e?.(ue.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=y,e&&e(ue.SUBSCRIBED);return}}).receive("error",h=>{this.state=L.CHANNEL_STATES.errored,e?.(ue.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(h).join(", ")||"error")))}).receive("timeout",()=>{e?.(ue.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,s){return this.state===L.CHANNEL_STATES.joined&&e===Ue.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,s)}async httpSend(e,r,s={}){var n;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,(n=s.timeout)!==null&&n!==void 0?n: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 s,n;if(!this._canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");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,(s=r.timeout)!==null&&s!==void 0?s:this.timeout);return await((n=c.body)===null||n===void 0?void 0:n.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,a,l;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=L.CHANNEL_STATES.leaving;let r=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(L.CHANNEL_EVENTS.close,"leave",this._joinRef())};this.joinPush.destroy();let s=null;return new Promise(n=>{s=new zt.default(this,L.CHANNEL_EVENTS.leave,{},e),s.receive("ok",()=>{r(),n("ok")}).receive("timeout",()=>{r(),n("timed out")}).receive("error",()=>{n("error")}),s.send(),this._canPush()||s.trigger("ok",{})}).finally(()=>{s?.destroy()})}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=L.CHANNEL_STATES.closed,this.bindings={}}async _fetchWithTimeout(e,r,s){let n=new AbortController,i=setTimeout(()=>n.abort(),s),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:n.signal}));return clearTimeout(i),o}_push(e,r,s=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let n=new zt.default(this,e,r,s);return this._canPush()?n.send():this._addToPushBuffer(n),n}_addToPushBuffer(e){if(e.startTimeout(),this.pushBuffer.push(e),this.pushBuffer.length>L.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,s){return r}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,r,s){var n,i;let o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:u}=L.CHANNEL_EVENTS;if(s&&[a,l,c,u].indexOf(o)>=0&&s!==this._joinRef())return;let f=this._onMessage(o,r,s);if(r&&!f)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(n=this.bindings.postgres_changes)===null||n===void 0||n.filter(h=>{var p,m,_;return((p=h.filter)===null||p===void 0?void 0:p.event)==="*"||((_=(m=h.filter)===null||m===void 0?void 0:m.event)===null||_===void 0?void 0:_.toLocaleLowerCase())===o}).map(h=>h.callback(f,s)):(i=this.bindings[o])===null||i===void 0||i.filter(h=>{var p,m,_,y,S,w;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in h){let k=h.id,H=(p=h.filter)===null||p===void 0?void 0:p.event;return k&&((m=r.ids)===null||m===void 0?void 0:m.includes(k))&&(H==="*"||H?.toLocaleLowerCase()===((_=r.data)===null||_===void 0?void 0:_.type.toLocaleLowerCase()))}else{let k=(S=(y=h?.filter)===null||y===void 0?void 0:y.event)===null||S===void 0?void 0:S.toLocaleLowerCase();return k==="*"||k===((w=r?.event)===null||w===void 0?void 0:w.toLocaleLowerCase())}else return h.type.toLocaleLowerCase()===o}).map(h=>{if(typeof f=="object"&&"ids"in f){let p=f.data,{schema:m,table:_,commit_timestamp:y,type:S,errors:w}=p;f=Object.assign(Object.assign({},{schema:m,table:_,commit_timestamp:y,eventType:S,new:{},old:{},errors:w}),this._getPayloadRecords(p))}h.callback(f,s)})}_isClosed(){return this.state===L.CHANNEL_STATES.closed}_isJoined(){return this.state===L.CHANNEL_STATES.joined}_isJoining(){return this.state===L.CHANNEL_STATES.joining}_isLeaving(){return this.state===L.CHANNEL_STATES.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,r,s){let n=e.toLocaleLowerCase(),i={type:n,filter:r,callback:s};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this}_off(e,r){let s=e.toLocaleLowerCase();return this.bindings[s]&&(this.bindings[s]=this.bindings[s].filter(n=>{var i;return!(((i=n.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===s&&t.isEqual(n.filter,r))})),this}static isEqual(e,r){if(Object.keys(e).length!==Object.keys(r).length)return!1;for(let s in e)if(e[s]!==r[s])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(L.CHANNEL_EVENTS.close,{},e)}_onError(e){this._on(L.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=L.CHANNEL_STATES.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let r={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(r.new=Us.convertChangeData(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=Us.convertChangeData(e.columns,e.old_record)),r}};se.default=Jt});var $s=P(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});var ot=(X(),re(Y)),oi=ot.__importDefault($t()),q=rt(),ai=ot.__importDefault(xs()),li=ot.__importDefault(Mt()),ci=st(),ui=ot.__importDefault(Yt()),Xt=()=>{},it={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},hi=[1e3,2e3,5e3,1e4],di=1e4,fi=`
8
+ addEventListener("message", (e) => {
9
+ if (e.data.event === "start") {
10
+ setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
11
+ }
12
+ });`,Qt=class{constructor(e,r){var s;if(this.accessTokenValue=null,this.apiKey=null,this._manuallySetToken=!1,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers={},this.params={},this.timeout=q.DEFAULT_TIMEOUT,this.transport=null,this.heartbeatIntervalMs=it.HEARTBEAT_INTERVAL,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Xt,this.ref=0,this.reconnectTimer=null,this.vsn=q.DEFAULT_VSN,this.logger=Xt,this.conn=null,this.sendBuffer=[],this.serializer=new ai.default,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._connectionState="disconnected",this._wasManualDisconnect=!1,this._authPromise=null,this._heartbeatSentAt=null,this._resolveFetch=n=>n?(...i)=>n(...i):(...i)=>fetch(...i),!(!((s=r?.params)===null||s===void 0)&&s.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey,this.endPoint=`${e}/${q.TRANSPORTS.websocket}`,this.httpEndpoint=(0,ci.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=oi.default.createWebSocket(this.endpointURL())}catch(e){this._setConnectionState("disconnected");let r=e.message;throw r.includes("Node.js")?new Error(`${r}
13
+
14
+ To use Realtime in Node.js, you need to provide a WebSocket implementation:
15
+
16
+ Option 1: Use Node.js 22+ which has native WebSocket support
17
+ Option 2: Install and provide the "ws" package:
18
+
19
+ npm install ws
20
+
21
+ import ws from "ws"
22
+ const client = new RealtimeClient(url, {
23
+ ...options,
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 s=setTimeout(()=>{this._setConnectionState("disconnected")},100);this.conn.onclose=()=>{clearTimeout(s),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,s){this.logger(e,r,s)}connectionState(){switch(this.conn&&this.conn.readyState){case q.SOCKET_STATES.connecting:return q.CONNECTION_STATE.Connecting;case q.SOCKET_STATES.open:return q.CONNECTION_STATE.Open;case q.SOCKET_STATES.closing:return q.CONNECTION_STATE.Closing;default:return q.CONNECTION_STATE.Closed}}isConnected(){return this.connectionState()===q.CONNECTION_STATE.Open}isConnecting(){return this._connectionState==="connecting"}isDisconnecting(){return this._connectionState==="disconnecting"}channel(e,r={config:{}}){let s=`realtime:${e}`,n=this.getChannels().find(i=>i.topic===s);if(n)return n;{let i=new ui.default(`realtime:${e}`,r,this);return this.channels.push(i),i}}push(e){let{topic:r,event:s,payload:n,ref:i}=e,o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};this.log("push",`${r} ${s} (${i})`,n),this.isConnected()?o():this.sendBuffer.push(o)}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise}finally{this._authPromise=null}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){var e;if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(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(q.WS_CLOSE_NORMAL,"heartbeat timeout"),setTimeout(()=>{var r;this.isConnected()||(r=this.reconnectTimer)===null||r===void 0||r.scheduleTimeout()},it.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(s=>s.topic===e&&(s._isJoined()||s._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(u){this.log("error","error in heartbeat callback",u)}this._heartbeatSentAt=null,this.pendingHeartbeatRef=null}let{topic:s,event:n,payload:i,ref:o}=r,a=o?`(${o})`:"",l=i.status||"";this.log("receive",`${l} ${s} ${n} ${a}`.trim(),i),this.channels.filter(c=>c._isMember(s)).forEach(c=>c._trigger(n,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===q.SOCKET_STATES.open&&this._onConnOpen())}_teardownConnection(){if(this.conn){if(this.conn.readyState===q.SOCKET_STATES.open||this.conn.readyState===q.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(q.CHANNEL_EVENTS.error))}_appendParams(e,r){if(Object.keys(r).length===0)return e;let s=e.match(/\?/)?"&":"?",n=new URLSearchParams(r);return`${e}${s}${n}`}_workerObjectUrl(e){let r;if(e)r=e;else{let s=new Blob([fi],{type:"application/javascript"});r=URL.createObjectURL(s)}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,s=!1;if(e)r=e,s=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(n){this.log("error","Error fetching access token from callback",n),r=this.accessTokenValue}else r=this.accessTokenValue;s?this._manuallySetToken=!0:this.accessToken&&(this._manuallySetToken=!1),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(n=>{let i={access_token:r,version:q.DEFAULT_VERSION};r&&n.updateJoinPayload(i),n.joinedOnce&&n._isJoined()&&n._push(q.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(s=>{try{s(r)}catch(n){this.log("error",`error in ${e} callback`,n)}})}catch(s){this.log("error",`error triggering ${e} callbacks`,s)}}_setupReconnectionTimer(){this.reconnectTimer=new li.default(async()=>{setTimeout(async()=>{await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()},it.RECONNECT_DELAY)},this.reconnectAfterMs)}_initializeOptions(e){var r,s,n,i,o,a,l,c,u,d,f,h;switch(this.transport=(r=e?.transport)!==null&&r!==void 0?r:null,this.timeout=(s=e?.timeout)!==null&&s!==void 0?s:q.DEFAULT_TIMEOUT,this.heartbeatIntervalMs=(n=e?.heartbeatIntervalMs)!==null&&n!==void 0?n:it.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:Xt,this.vsn=(l=e?.vsn)!==null&&l!==void 0?l:q.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:(p=>hi[p-1]||di),this.vsn){case q.VSN_1_0_0:this.encode=(u=e?.encode)!==null&&u!==void 0?u:((p,m)=>m(JSON.stringify(p))),this.decode=(d=e?.decode)!==null&&d!==void 0?d:((p,m)=>m(JSON.parse(p)));break;case q.VSN_2_0_0:this.encode=(f=e?.encode)!==null&&f!==void 0?f:this.serializer.encode.bind(this.serializer),this.decode=(h=e?.decode)!==null&&h!==void 0?h:this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${this.vsn}`)}if(this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl}}};Zt.default=Qt});var er=P(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.WebSocketFactory=F.REALTIME_CHANNEL_STATES=F.REALTIME_SUBSCRIBE_STATES=F.REALTIME_PRESENCE_LISTEN_EVENTS=F.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=F.REALTIME_LISTEN_TYPES=F.RealtimeClient=F.RealtimeChannel=F.RealtimePresence=void 0;var at=(X(),re(Y)),pi=at.__importDefault($s());F.RealtimeClient=pi.default;var Le=at.__importStar(Yt());F.RealtimeChannel=Le.default;Object.defineProperty(F,"REALTIME_LISTEN_TYPES",{enumerable:!0,get:function(){return Le.REALTIME_LISTEN_TYPES}});Object.defineProperty(F,"REALTIME_POSTGRES_CHANGES_LISTEN_EVENT",{enumerable:!0,get:function(){return Le.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT}});Object.defineProperty(F,"REALTIME_SUBSCRIBE_STATES",{enumerable:!0,get:function(){return Le.REALTIME_SUBSCRIBE_STATES}});Object.defineProperty(F,"REALTIME_CHANNEL_STATES",{enumerable:!0,get:function(){return Le.REALTIME_CHANNEL_STATES}});var Ds=at.__importStar(Gt());F.RealtimePresence=Ds.default;Object.defineProperty(F,"REALTIME_PRESENCE_LISTEN_EVENTS",{enumerable:!0,get:function(){return Ds.REALTIME_PRESENCE_LISTEN_EVENTS}});var mi=at.__importDefault($t());F.WebSocketFactory=mi.default});var nr=P(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.version=void 0;dt.version="2.97.0"});var ft=P(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.JWKS_TTL=N.BASE64URL_REGEX=N.API_VERSIONS=N.API_VERSION_HEADER_NAME=N.NETWORK_FAILURE=N.DEFAULT_HEADERS=N.AUDIENCE=N.STORAGE_KEY=N.GOTRUE_URL=N.EXPIRY_MARGIN_MS=N.AUTO_REFRESH_TICK_THRESHOLD=N.AUTO_REFRESH_TICK_DURATION_MS=void 0;var Wi=nr();N.AUTO_REFRESH_TICK_DURATION_MS=30*1e3;N.AUTO_REFRESH_TICK_THRESHOLD=3;N.EXPIRY_MARGIN_MS=N.AUTO_REFRESH_TICK_THRESHOLD*N.AUTO_REFRESH_TICK_DURATION_MS;N.GOTRUE_URL="http://localhost:9999";N.STORAGE_KEY="supabase.auth.token";N.AUDIENCE="";N.DEFAULT_HEADERS={"X-Client-Info":`gotrue-js/${Wi.version}`};N.NETWORK_FAILURE={MAX_RETRIES:10,RETRY_INTERVAL:2};N.API_VERSION_HEADER_NAME="X-Supabase-Api-Version";N.API_VERSIONS={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}};N.BASE64URL_REGEX=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i;N.JWKS_TTL=600*1e3});var me=P(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.AuthInvalidJwtError=O.AuthWeakPasswordError=O.AuthRetryableFetchError=O.AuthPKCECodeVerifierMissingError=O.AuthPKCEGrantCodeExchangeError=O.AuthImplicitGrantRedirectError=O.AuthInvalidCredentialsError=O.AuthInvalidTokenResponseError=O.AuthSessionMissingError=O.CustomAuthError=O.AuthUnknownError=O.AuthApiError=O.AuthError=void 0;O.isAuthError=pe;O.isAuthApiError=Hi;O.isAuthSessionMissingError=Ki;O.isAuthImplicitGrantRedirectError=Gi;O.isAuthPKCECodeVerifierMissingError=zi;O.isAuthRetryableFetchError=Ji;O.isAuthWeakPasswordError=Yi;var Te=class extends Error{constructor(e,r,s){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=r,this.code=s}};O.AuthError=Te;function pe(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}var ir=class extends Te{constructor(e,r,s){super(e,r,s),this.name="AuthApiError",this.status=r,this.code=s}};O.AuthApiError=ir;function Hi(t){return pe(t)&&t.name==="AuthApiError"}var or=class extends Te{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r}};O.AuthUnknownError=or;var Z=class extends Te{constructor(e,r,s,n){super(e,s,n),this.name=r,this.status=s}};O.CustomAuthError=Z;var ar=class extends Z{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};O.AuthSessionMissingError=ar;function Ki(t){return pe(t)&&t.name==="AuthSessionMissingError"}var lr=class extends Z{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}};O.AuthInvalidTokenResponseError=lr;var cr=class extends Z{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}};O.AuthInvalidCredentialsError=cr;var ur=class extends Z{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}}};O.AuthImplicitGrantRedirectError=ur;function Gi(t){return pe(t)&&t.name==="AuthImplicitGrantRedirectError"}var hr=class extends Z{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}}};O.AuthPKCEGrantCodeExchangeError=hr;var dr=class extends Z{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")}};O.AuthPKCECodeVerifierMissingError=dr;function zi(t){return pe(t)&&t.name==="AuthPKCECodeVerifierMissingError"}var fr=class extends Z{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0)}};O.AuthRetryableFetchError=fr;function Ji(t){return pe(t)&&t.name==="AuthRetryableFetchError"}var pr=class extends Z{constructor(e,r,s){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=s}};O.AuthWeakPasswordError=pr;function Yi(t){return pe(t)&&t.name==="AuthWeakPasswordError"}var mr=class extends Z{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt")}};O.AuthInvalidJwtError=mr});var mt=P(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.byteToBase64URL=Me;ee.byteFromBase64URL=_r;ee.stringToBase64URL=Qi;ee.stringFromBase64URL=Zi;ee.codepointToUTF8=zs;ee.stringToUTF8=gr;ee.stringFromUTF8=Js;ee.base64UrlToUint8Array=eo;ee.stringToUint8Array=to;ee.bytesToBase64URL=ro;var pt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Gs=`
26
+ \r=`.split(""),Xi=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Gs.length;e+=1)t[Gs[e].charCodeAt(0)]=-2;for(let e=0;e<pt.length;e+=1)t[pt[e].charCodeAt(0)]=e;return t})();function Me(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let s=e.queue>>e.queuedBits-6&63;r(pt[s]),e.queuedBits-=6}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let s=e.queue>>e.queuedBits-6&63;r(pt[s]),e.queuedBits-=6}}function _r(t,e,r){let s=Xi[t];if(s>-1)for(e.queue=e.queue<<6|s,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else{if(s===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function Qi(t){let e=[],r=n=>{e.push(n)},s={queue:0,queuedBits:0};return gr(t,n=>{Me(n,s,r)}),Me(null,s,r),e.join("")}function Zi(t){let e=[],r=o=>{e.push(String.fromCodePoint(o))},s={utf8seq:0,codepoint:0},n={queue:0,queuedBits:0},i=o=>{Js(o,s,r)};for(let o=0;o<t.length;o+=1)_r(t.charCodeAt(o),n,i);return e.join("")}function zs(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 gr(t,e){for(let r=0;r<t.length;r+=1){let s=t.charCodeAt(r);if(s>55295&&s<=56319){let n=(s-55296)*1024&65535;s=(t.charCodeAt(r+1)-56320&65535|n)+65536,r+=1}zs(s,e)}}function Js(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let s=1;s<6;s+=1)if((t>>7-s&1)===0){e.utf8seq=s;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 eo(t){let e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};for(let n=0;n<t.length;n+=1)_r(t.charCodeAt(n),r,s);return new Uint8Array(e)}function to(t){let e=[];return gr(t,r=>e.push(r)),new Uint8Array(e)}function ro(t){let e=[],r={queue:0,queuedBits:0},s=n=>{e.push(n)};return t.forEach(n=>Me(n,r,s)),Me(null,r,s),e.join("")}});var ke=P(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.Deferred=R.removeItemAsync=R.getItemAsync=R.setItemAsync=R.looksLikeFetchResponse=R.resolveFetch=R.supportsLocalStorage=R.isBrowser=void 0;R.expiresAt=so;R.generateCallbackId=no;R.parseParametersFromURL=ao;R.decodeJWT=po;R.sleep=mo;R.retryable=_o;R.generatePKCEVerifier=Qs;R.generatePKCEChallenge=Zs;R.getCodeChallengeAndMethod=vo;R.parseResponseAPIVersion=bo;R.validateExp=Eo;R.getAlgorithm=So;R.validateUUID=To;R.userNotAvailableProxy=ko;R.insecureUserWarningProxy=Ro;R.deepClone=Oo;var Xs=ft(),Ys=me(),yr=mt();function so(t){return Math.round(Date.now()/1e3)+t}function no(){return Symbol("auth-callback")}var io=()=>typeof window<"u"&&typeof document<"u";R.isBrowser=io;var _e={tested:!1,writable:!1},oo=()=>{if(!(0,R.isBrowser)())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(_e.tested)return _e.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),_e.tested=!0,_e.writable=!0}catch{_e.tested=!0,_e.writable=!1}return _e.writable};R.supportsLocalStorage=oo;function ao(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((n,i)=>{e[i]=n})}catch{}return r.searchParams.forEach((s,n)=>{e[n]=s}),e}var lo=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);R.resolveFetch=lo;var co=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function";R.looksLikeFetchResponse=co;var uo=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r))};R.setItemAsync=uo;var ho=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}};R.getItemAsync=ho;var fo=async(t,e)=>{await t.removeItem(e)};R.removeItemAsync=fo;var _t=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r})}};R.Deferred=_t;_t.promiseConstructor=Promise;function po(t){let e=t.split(".");if(e.length!==3)throw new Ys.AuthInvalidJwtError("Invalid JWT structure");for(let s=0;s<e.length;s++)if(!Xs.BASE64URL_REGEX.test(e[s]))throw new Ys.AuthInvalidJwtError("JWT not in base64url format");return{header:JSON.parse((0,yr.stringFromBase64URL)(e[0])),payload:JSON.parse((0,yr.stringFromBase64URL)(e[1])),signature:(0,yr.base64UrlToUint8Array)(e[2]),raw:{header:e[0],payload:e[1]}}}async function mo(t){return await new Promise(e=>{setTimeout(()=>e(null),t)})}function _o(t,e){return new Promise((s,n)=>{(async()=>{for(let i=0;i<1/0;i++)try{let o=await t(i);if(!e(i,null,o)){s(o);return}}catch(o){if(!e(i,o)){n(o);return}}})()})}function go(t){return("0"+t.toString(16)).substr(-2)}function Qs(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",s=r.length,n="";for(let i=0;i<56;i++)n+=r.charAt(Math.floor(Math.random()*s));return n}return crypto.getRandomValues(e),Array.from(e,go).join("")}async function yo(t){let r=new TextEncoder().encode(t),s=await crypto.subtle.digest("SHA-256",r),n=new Uint8Array(s);return Array.from(n).map(i=>String.fromCharCode(i)).join("")}async function Zs(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 yo(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function vo(t,e,r=!1){let s=Qs(),n=s;r&&(n+="/PASSWORD_RECOVERY"),await(0,R.setItemAsync)(t,`${e}-code-verifier`,n);let i=await Zs(s);return[i,s===i?"plain":"s256"]}var wo=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function bo(t){let e=t.headers.get(Xs.API_VERSION_HEADER_NAME);if(!e||!e.match(wo))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Eo(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 So(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 Ao=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function To(t){if(!Ao.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function ko(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return!0;if(typeof r=="symbol"){let s=r.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="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 Ro(t,e){return new Proxy(t,{get:(r,s,n)=>{if(s==="__isInsecureUserWarningProxy")return!0;if(typeof s=="symbol"){let i=s.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,s,n)}return!e.value&&typeof s=="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,s,n)}})}function Oo(t){return JSON.parse(JSON.stringify(t))}});var br=P(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.handleError=wr;oe._request=xo;oe._sessionResponse=en;oe._sessionResponsePassword=jo;oe._userResponse=Uo;oe._ssoResponse=Lo;oe._generateLinkResponse=$o;oe._noResolveJsonResponse=Do;var Po=(X(),re(Y)),gt=ft(),vr=ke(),fe=me(),ge=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Io=[502,503,504];async function wr(t){var e;if(!(0,vr.looksLikeFetchResponse)(t))throw new fe.AuthRetryableFetchError(ge(t),0);if(Io.includes(t.status))throw new fe.AuthRetryableFetchError(ge(t),t.status);let r;try{r=await t.json()}catch(i){throw new fe.AuthUnknownError(ge(i),i)}let s,n=(0,vr.parseResponseAPIVersion)(t);if(n&&n.getTime()>=gt.API_VERSIONS["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?s=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(s=r.error_code),s){if(s==="weak_password")throw new fe.AuthWeakPasswordError(ge(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(s==="session_not_found")throw new fe.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 fe.AuthWeakPasswordError(ge(r),t.status,r.weak_password.reasons);throw new fe.AuthApiError(ge(r),t.status||500,s)}var Co=(t,e,r,s)=>{let n={method:t,headers:e?.headers||{}};return t==="GET"?n:(n.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),n.body=JSON.stringify(s),Object.assign(Object.assign({},n),r))};async function xo(t,e,r,s){var n;let i=Object.assign({},s?.headers);i[gt.API_VERSION_HEADER_NAME]||(i[gt.API_VERSION_HEADER_NAME]=gt.API_VERSIONS["2024-01-01"].name),s?.jwt&&(i.Authorization=`Bearer ${s.jwt}`);let o=(n=s?.query)!==null&&n!==void 0?n:{};s?.redirectTo&&(o.redirect_to=s.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await No(t,e,r+a,{headers:i,noResolveJson:s?.noResolveJson},{},s?.body);return s?.xform?s?.xform(l):{data:Object.assign({},l),error:null}}async function No(t,e,r,s,n,i){let o=Co(e,s,n,i),a;try{a=await t(r,Object.assign({},o))}catch(l){throw console.error(l),new fe.AuthRetryableFetchError(ge(l),0)}if(a.ok||await wr(a),s?.noResolveJson)return a;try{return await a.json()}catch(l){await wr(l)}}function en(t){var e;let r=null;qo(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=(0,vr.expiresAt)(t.expires_in)));let s=(e=t.user)!==null&&e!==void 0?e:t;return{data:{session:r,user:s},error:null}}function jo(t){let e=en(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,s)=>r&&typeof s=="string",!0)&&(e.data.weak_password=t.weak_password),e}function Uo(t){var e;return{data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Lo(t){return{data:t,error:null}}function $o(t){let{action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i}=t,o=Po.__rest(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:s,redirect_to:n,verification_type:i},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function Do(t){return t}function qo(t){return t.access_token&&t.refresh_token&&t.expires_in}});var Er=P(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.SIGN_OUT_SCOPES=void 0;yt.SIGN_OUT_SCOPES=["global","local","others"]});var vt=P(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});var Bo=(X(),re(Y)),$=br(),ye=ke(),Sr=Er(),K=me(),Ar=class{constructor({url:e="",headers:r={},fetch:s}){this.url=e,this.headers=r,this.fetch=(0,ye.resolveFetch)(s),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=Sr.SIGN_OUT_SCOPES[0]){if(Sr.SIGN_OUT_SCOPES.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Sr.SIGN_OUT_SCOPES.join(", ")}`);try{return await(0,$._request)(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(s){if((0,K.isAuthError)(s))return{data:null,error:s};throw s}}async inviteUserByEmail(e,r={}){try{return await(0,$._request)(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:$._userResponse})}catch(s){if((0,K.isAuthError)(s))return{data:{user:null},error:s};throw s}}async generateLink(e){try{let{options:r}=e,s=Bo.__rest(e,["options"]),n=Object.assign(Object.assign({},s),r);return"newEmail"in s&&(n.new_email=s?.newEmail,delete n.newEmail),await(0,$._request)(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:$._generateLinkResponse,redirectTo:r?.redirectTo})}catch(r){if((0,K.isAuthError)(r))return{data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await(0,$._request)(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:$._userResponse})}catch(r){if((0,K.isAuthError)(r))return{data:{user:null},error:r};throw r}}async listUsers(e){var r,s,n,i,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},u=await(0,$._request)(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:$._noResolveJsonResponse});if(u.error)throw u.error;let d=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,h=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return h.length>0&&(h.forEach(p=>{let m=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(p.split(";")[1].split("=")[1]);c[`${_}Page`]=m}),c.total=parseInt(f)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if((0,K.isAuthError)(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){(0,ye.validateUUID)(e);try{return await(0,$._request)(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:$._userResponse})}catch(r){if((0,K.isAuthError)(r))return{data:{user:null},error:r};throw r}}async updateUserById(e,r){(0,ye.validateUUID)(e);try{return await(0,$._request)(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:$._userResponse})}catch(s){if((0,K.isAuthError)(s))return{data:{user:null},error:s};throw s}}async deleteUser(e,r=!1){(0,ye.validateUUID)(e);try{return await(0,$._request)(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:$._userResponse})}catch(s){if((0,K.isAuthError)(s))return{data:{user:null},error:s};throw s}}async _listFactors(e){(0,ye.validateUUID)(e.userId);try{let{data:r,error:s}=await(0,$._request)(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:n=>({data:{factors:n},error:null})});return{data:r,error:s}}catch(r){if((0,K.isAuthError)(r))return{data:null,error:r};throw r}}async _deleteFactor(e){(0,ye.validateUUID)(e.userId),(0,ye.validateUUID)(e.id);try{return{data:await(0,$._request)(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if((0,K.isAuthError)(r))return{data:null,error:r};throw r}}async _listOAuthClients(e){var r,s,n,i,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},u=await(0,$._request)(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(s=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&s!==void 0?s:"",per_page:(i=(n=e?.perPage)===null||n===void 0?void 0:n.toString())!==null&&i!==void 0?i:""},xform:$._noResolveJsonResponse});if(u.error)throw u.error;let d=await u.json(),f=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,h=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return h.length>0&&(h.forEach(p=>{let m=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(p.split(";")[1].split("=")[1]);c[`${_}Page`]=m}),c.total=parseInt(f)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if((0,K.isAuthError)(c))return{data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await(0,$._request)(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if((0,K.isAuthError)(r))return{data:null,error:r};throw r}}async _getOAuthClient(e){try{return await(0,$._request)(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if((0,K.isAuthError)(r))return{data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await(0,$._request)(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:s=>({data:s,error:null})})}catch(s){if((0,K.isAuthError)(s))return{data:null,error:s};throw s}}async _deleteOAuthClient(e){try{return await(0,$._request)(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if((0,K.isAuthError)(r))return{data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await(0,$._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,K.isAuthError)(r))return{data:null,error:r};throw r}}};Tr.default=Ar});var tn=P(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.memoryLocalStorageAdapter=Fo;function Fo(t={}){return{getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r},removeItem:e=>{delete t[e]}}}});var Rr=P(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.ProcessLockAcquireTimeoutError=W.NavigatorLockAcquireTimeoutError=W.LockAcquireTimeoutError=W.internals=void 0;W.navigatorLock=Vo;W.processLock=Wo;var Mo=ke();W.internals={debug:!!(globalThis&&(0,Mo.supportsLocalStorage)()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};var Ve=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}};W.LockAcquireTimeoutError=Ve;var We=class extends Ve{};W.NavigatorLockAcquireTimeoutError=We;var wt=class extends Ve{};W.ProcessLockAcquireTimeoutError=wt;async function Vo(t,e,r){W.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let s=new globalThis.AbortController;e>0&&setTimeout(()=>{s.abort(),W.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:s.signal},async n=>{if(n){W.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,n.name);try{return await r()}finally{W.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,n.name)}}else{if(e===0)throw W.internals.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new We(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(W.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(n){throw n?.name==="AbortError"?new We(`Acquiring an exclusive Navigator LockManager lock "${t}" timed out waiting ${e}ms`):n}}var rn={};async function Wo(t,e,r){var s;let n=(s=rn[t])!==null&&s!==void 0?s:Promise.resolve(),i=(async()=>{try{return await n,null}catch{return null}})(),o=(async()=>{let a=null;try{let l=e>=0?new Promise((c,u)=>{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.`),u(new wt(`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 rn[t]=(async()=>{try{return await o}catch(a){if(a&&a.isAcquireTimeout){try{await n}catch{}return null}throw a}})(),await o}});var sn=P(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.polyfillGlobalThis=Ho;function Ho(){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 on=P(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.getAddress=nn;Re.fromHex=Ko;Re.toHex=Go;Re.createSiweMessage=zo;function nn(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Ko(t){return parseInt(t,16)}function Go(t){let e=new TextEncoder().encode(t);return"0x"+Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}function zo(t){var e;let{chainId:r,domain:s,expirationTime:n,issuedAt:i=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:u,uri:d,version:f}=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(!s)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(f!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
27
+ `))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}let h=nn(t.address),p=u?`${u}://${s}`:s,m=t.statement?`${t.statement}
28
+ `:"",_=`${p} wants you to sign in with your Ethereum account:
29
+ ${h}
30
+
31
+ ${m}`,y=`URI: ${d}
32
+ Version: ${f}
33
+ Chain ID: ${r}${o?`
34
+ Nonce: ${o}`:""}
35
+ Issued At: ${i.toISOString()}`;if(n&&(y+=`
36
+ Expiration Time: ${n.toISOString()}`),a&&(y+=`
37
+ Not Before: ${a.toISOString()}`),l&&(y+=`
38
+ Request ID: ${l}`),c){let S=`
39
+ Resources:`;for(let w of c){if(!w||typeof w!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${w}`);S+=`
40
+ - ${w}`}y+=S}return`${_}
41
+ ${y}`}});var ln=P(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.WebAuthnUnknownError=he.WebAuthnError=void 0;he.isWebAuthnError=Jo;he.identifyRegistrationError=Yo;he.identifyAuthenticationError=Xo;var an=Ir(),D=class extends Error{constructor({message:e,code:r,cause:s,name:n}){var i;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(i=n??(s instanceof Error?s.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}};he.WebAuthnError=D;var Pr=class extends D{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}};he.WebAuthnUnknownError=Pr;function Jo(t){return typeof t=="object"&&t!==null&&"__isWebAuthnError"in t}function Yo({error:t,options:e}){var r,s,n;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 D({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 D({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new D({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new D({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 D({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new D({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 D({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new D({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,an.isValidDomain)(o)){if(i.rp.id!==o)return new D({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new D({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 D({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 D({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 D({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Xo({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 D({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new D({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let s=window.location.hostname;if((0,an.isValidDomain)(s)){if(r.rpId!==s)return new D({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new D({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new D({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 D({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}});var Ir=P(I=>{"use strict";Object.defineProperty(I,"__esModule",{value:!0});I.WebAuthnApi=I.DEFAULT_REQUEST_OPTIONS=I.DEFAULT_CREATION_OPTIONS=I.webAuthnAbortService=I.WebAuthnAbortService=I.identifyAuthenticationError=I.identifyRegistrationError=I.isWebAuthnError=I.WebAuthnError=void 0;I.deserializeCredentialCreationOptions=Zo;I.deserializeCredentialRequestOptions=ea;I.serializeCredentialCreationResponse=ta;I.serializeCredentialRequestResponse=ra;I.isValidDomain=sa;I.createCredential=hn;I.getCredential=dn;I.mergeCredentialCreationOptions=fn;I.mergeCredentialRequestOptions=pn;var un=(X(),re(Y)),ie=mt(),ae=me(),Qo=ke(),le=ln();Object.defineProperty(I,"identifyAuthenticationError",{enumerable:!0,get:function(){return le.identifyAuthenticationError}});Object.defineProperty(I,"identifyRegistrationError",{enumerable:!0,get:function(){return le.identifyRegistrationError}});Object.defineProperty(I,"isWebAuthnError",{enumerable:!0,get:function(){return le.isWebAuthnError}});Object.defineProperty(I,"WebAuthnError",{enumerable:!0,get:function(){return le.WebAuthnError}});var bt=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}}};I.WebAuthnAbortService=bt;I.webAuthnAbortService=new bt;function Zo(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:s}=t,n=un.__rest(t,["challenge","user","excludeCredentials"]),i=(0,ie.base64UrlToUint8Array)(e).buffer,o=Object.assign(Object.assign({},r),{id:(0,ie.base64UrlToUint8Array)(r.id).buffer}),a=Object.assign(Object.assign({},n),{challenge:i,user:o});if(s&&s.length>0){a.excludeCredentials=new Array(s.length);for(let l=0;l<s.length;l++){let c=s[l];a.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:(0,ie.base64UrlToUint8Array)(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return a}function ea(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,s=un.__rest(t,["challenge","allowCredentials"]),n=(0,ie.base64UrlToUint8Array)(e).buffer,i=Object.assign(Object.assign({},s),{challenge:n});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,ie.base64UrlToUint8Array)(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return i}function ta(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,ie.bytesToBase64URL)(new Uint8Array(t.response.attestationObject)),clientDataJSON:(0,ie.bytesToBase64URL)(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function ra(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,s=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:(0,ie.bytesToBase64URL)(new Uint8Array(n.authenticatorData)),clientDataJSON:(0,ie.bytesToBase64URL)(new Uint8Array(n.clientDataJSON)),signature:(0,ie.bytesToBase64URL)(new Uint8Array(n.signature)),userHandle:n.userHandle?(0,ie.bytesToBase64URL)(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function sa(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function cn(){var t,e;return!!((0,Qo.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 hn(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new le.WebAuthnUnknownError("Browser returned unexpected credential type",e)}:{data:null,error:new le.WebAuthnUnknownError("Empty credential response",e)}}catch(e){return{data:null,error:(0,le.identifyRegistrationError)({error:e,options:t})}}}async function dn(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new le.WebAuthnUnknownError("Browser returned unexpected credential type",e)}:{data:null,error:new le.WebAuthnUnknownError("Empty credential response",e)}}catch(e){return{data:null,error:(0,le.identifyAuthenticationError)({error:e,options:t})}}}I.DEFAULT_CREATION_OPTIONS={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"};I.DEFAULT_REQUEST_OPTIONS={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Et(...t){let e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(let n of t)if(n)for(let i in n){let o=n[i];if(o!==void 0)if(Array.isArray(o))s[i]=o;else if(r(o))s[i]=o;else if(e(o)){let a=s[i];e(a)?s[i]=Et(a,o):s[i]=Et(o)}else s[i]=o}return s}function fn(t,e){return Et(I.DEFAULT_CREATION_OPTIONS,t,e||{})}function pn(t,e){return Et(I.DEFAULT_REQUEST_OPTIONS,t,e||{})}var Cr=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:s,signal:n},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=n??I.webAuthnAbortService.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:u}=a.webauthn.credential_options.publicKey;if(!u.name){let d=s;if(d)u.name=`${u.id}:${d}`;else{let h=(await this.client.getUser()).data.user,p=((o=h?.user_metadata)===null||o===void 0?void 0:o.name)||h?.email||h?.id||"User";u.name=`${u.id}:${p}`}}u.displayName||(u.displayName=u.name)}switch(a.webauthn.type){case"create":{let u=fn(a.webauthn.credential_options.publicKey,i?.create),{data:d,error:f}=await hn({publicKey:u,signal:c});return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:f}}case"request":{let u=pn(a.webauthn.credential_options.publicKey,i?.request),{data:d,error:f}=await dn(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:u,signal:c}));return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:f}}}}catch(a){return(0,ae.isAuthError)(a)?{data:null,error:a}:{data:null,error:new ae.AuthUnknownError("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:s}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new ae.AuthError("rpId is required for WebAuthn authentication")};try{if(!cn())return{data:null,error:new ae.AuthUnknownError("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:n},{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:s,credential_response:l.credential_response}})}catch(o){return(0,ae.isAuthError)(o)?{data:null,error:o}:{data:null,error:new ae.AuthUnknownError("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new ae.AuthError("rpId is required for WebAuthn registration")};try{if(!cn())return{data:null,error:new ae.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(u=>{var d;return(d=u.data)===null||d===void 0?void 0:d.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===e&&f.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u?.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:s},signal:n},{create:i});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:s,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(o){return(0,ae.isAuthError)(o)?{data:null,error:o}:{data:null,error:new ae.AuthUnknownError("Unexpected error in register",o)}}}};I.WebAuthnApi=Cr});var Nr=P(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});var na=(X(),re(Y)),ia=na.__importDefault(vt()),z=ft(),g=me(),T=br(),v=ke(),mn=tn(),_n=Rr(),oa=sn(),aa=nr(),gn=mt(),St=on(),He=Ir();(0,oa.polyfillGlobalThis)();var la={url:z.GOTRUE_URL,storageKey:z.STORAGE_KEY,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:z.DEFAULT_HEADERS,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4,skipAutoInitialize:!1};async function yn(t,e,r){return await r()}var Oe={},At=class t{get jwks(){var e,r;return(r=(e=Oe[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Oe[this.storageKey]=Object.assign(Object.assign({},Oe[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=Oe[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Oe[this.storageKey]=Object.assign(Object.assign({},Oe[this.storageKey]),{cachedAt:e})}constructor(e){var r,s,n;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({},la),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,v.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 ia.default({url:i.url,headers:i.headers,fetch:i.fetch}),this.url=i.url,this.headers=i.headers,this.fetch=(0,v.resolveFetch)(i.fetch),this.lock=i.lock||yn,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,v.isBrowser)()&&(!((s=globalThis?.navigator)===null||s===void 0)&&s.locks)?this.lock=_n.navigatorLock:this.lock=yn,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 He.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,v.supportsLocalStorage)()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=(0,mn.memoryLocalStorageAdapter)(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=(0,mn.memoryLocalStorageAdapter)(this.memoryStorage)),(0,v.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)}(n=this.broadcastChannel)===null||n===void 0||n.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} (${aa.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={},s="none";if((0,v.isBrowser)()&&(r=(0,v.parseParametersFromURL)(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),(0,v.isBrowser)()&&this.detectSessionInUrl&&s!=="none"){let{data:n,error:i}=await this._getSessionFromURL(r,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),(0,g.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}=n;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return(0,g.isAuthError)(r)?this._returnResult({error:r}):this._returnResult({error:new g.AuthUnknownError("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{let i=await(0,T._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e?.options)===null||n===void 0?void 0:n.captchaToken}},xform:T._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,g.isAuthError)(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,s,n;try{let i;if("email"in e){let{email:u,password:d,options:f}=e,h=null,p=null;this.flowType==="pkce"&&([h,p]=await(0,v.getCodeChallengeAndMethod)(this.storage,this.storageKey)),i=await(0,T._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:f?.emailRedirectTo,body:{email:u,password:d,data:(r=f?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:f?.captchaToken},code_challenge:h,code_challenge_method:p},xform:T._sessionResponse})}else if("phone"in e){let{phone:u,password:d,options:f}=e;i=await(0,T._request)(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(s=f?.data)!==null&&s!==void 0?s:{},channel:(n=f?.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:f?.captchaToken}},xform:T._sessionResponse})}else throw new g.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,v.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,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.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,T._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:T._sessionResponsePassword})}else if("phone"in e){let{phone:i,password:o,options:a}=e;r=await(0,T._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:T._sessionResponsePassword})}else throw new g.AuthInvalidCredentialsError("You must provide either an email or phone number and a password");let{data:s,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!s||!s.session||!s.user){let i=new g.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:i})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:n})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,s,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(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,s,n,i,o,a,l,c,u,d,f;let h,p;if("message"in e)h=e.message,p=e.signature;else{let{chain:m,wallet:_,statement:y,options:S}=e,w;if((0,v.isBrowser)())if(typeof _=="object")w=_;else{let ce=window;if("ethereum"in ce&&typeof ce.ethereum=="object"&&"request"in ce.ethereum&&typeof ce.ethereum.request=="function")w=ce.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 _!="object"||!S?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=_}let k=new URL((r=S?.url)!==null&&r!==void 0?r:window.location.href),H=await w.request({method:"eth_requestAccounts"}).then(ce=>ce).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!H||H.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let j=(0,St.getAddress)(H[0]),V=(s=S?.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!V){let ce=await w.request({method:"eth_chainId"});V=(0,St.fromHex)(ce)}let de={domain:k.host,address:j,statement:y,uri:k.href,version:"1",chainId:V,nonce:(n=S?.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(o=(i=S?.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=S?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=S?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=S?.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(u=S?.signInWithEthereum)===null||u===void 0?void 0:u.resources};h=(0,St.createSiweMessage)(de),p=await w.request({method:"personal_sign",params:[(0,St.toHex)(h),j]})}try{let{data:m,error:_}=await(0,T._request)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:h,signature:p},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:T._sessionResponse});if(_)throw _;if(!m||!m.session||!m.user){let y=new g.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:y})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:Object.assign({},m),error:_})}catch(m){if((0,g.isAuthError)(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async signInWithSolana(e){var r,s,n,i,o,a,l,c,u,d,f,h;let p,m;if("message"in e)p=e.message,m=e.signature;else{let{chain:_,wallet:y,statement:S,options:w}=e,k;if((0,v.isBrowser)())if(typeof y=="object")k=y;else{let j=window;if("solana"in j&&typeof j.solana=="object"&&("signIn"in j.solana&&typeof j.solana.signIn=="function"||"signMessage"in j.solana&&typeof j.solana.signMessage=="function"))k=j.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 y!="object"||!w?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");k=y}let H=new URL((r=w?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in k&&k.signIn){let j=await k.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},w?.signInWithSolana),{version:"1",domain:H.host,uri:H.href}),S?{statement:S}:null)),V;if(Array.isArray(j)&&j[0]&&typeof j[0]=="object")V=j[0];else if(j&&typeof j=="object"&&"signedMessage"in j&&"signature"in j)V=j;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in V&&"signature"in V&&(typeof V.signedMessage=="string"||V.signedMessage instanceof Uint8Array)&&V.signature instanceof Uint8Array)p=typeof V.signedMessage=="string"?V.signedMessage:new TextDecoder().decode(V.signedMessage),m=V.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in k)||typeof k.signMessage!="function"||!("publicKey"in k)||typeof k!="object"||!k.publicKey||!("toBase58"in k.publicKey)||typeof k.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=[`${H.host} wants you to sign in with your Solana account:`,k.publicKey.toBase58(),...S?["",S,""]:[""],"Version: 1",`URI: ${H.href}`,`Issued At: ${(n=(s=w?.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=w?.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${w.signInWithSolana.notBefore}`]:[],...!((o=w?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${w.signInWithSolana.expirationTime}`]:[],...!((a=w?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${w.signInWithSolana.chainId}`]:[],...!((l=w?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${w.signInWithSolana.nonce}`]:[],...!((c=w?.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${w.signInWithSolana.requestId}`]:[],...!((d=(u=w?.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||d===void 0)&&d.length?["Resources",...w.signInWithSolana.resources.map(V=>`- ${V}`)]:[]].join(`
42
+ `);let j=await k.signMessage(new TextEncoder().encode(p),"utf8");if(!j||!(j instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");m=j}}try{let{data:_,error:y}=await(0,T._request)(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:(0,gn.bytesToBase64URL)(m)},!((f=e.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:T._sessionResponse});if(y)throw y;if(!_||!_.session||!_.user){let S=new g.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:S})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:y})}catch(_){if((0,g.isAuthError)(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e){let r=await(0,v.getItemAsync)(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new g.AuthPKCECodeVerifierMissingError;let{data:i,error:o}=await(0,T._request)(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:T._sessionResponse});if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){let a=new g.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:n??null}),error:o})}catch(i){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.isAuthError)(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{let{options:r,provider:s,token:n,access_token:i,nonce:o}=e,a=await(0,T._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:T._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 u=new g.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:u})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:c})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,o;try{if("email"in e){let{email:a,options:l}=e,c=null,u=null;this.flowType==="pkce"&&([c,u]=await(0,v.getCodeChallengeAndMethod)(this.storage,this.storageKey));let{error:d}=await(0,T._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:l}=e,{data:c,error:u}=await(0,T._request)(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=l?.data)!==null&&n!==void 0?n:{},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:u})}throw new g.AuthInvalidCredentialsError("You must provide either an email or phone number.")}catch(a){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.isAuthError)(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,s;try{let n,i;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);let{data:o,error:a}=await(0,T._request)(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:T._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(n){if((0,g.isAuthError)(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await(0,v.getCodeChallengeAndMethod)(this.storage,this.storageKey));let c=await(0,T._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:(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&s!==void 0?s:void 0}),!((n=e?.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:T._ssoResponse});return!((i=c.data)===null||i===void 0)&&i.url&&(0,v.isBrowser)()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(a){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.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:s}=e;if(s)throw s;if(!r)throw new g.AuthSessionMissingError;let{error:n}=await(0,T._request)(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if((0,g.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:s,type:n,options:i}=e,{error:o}=await(0,T._request)(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:n,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:s,type:n,options:i}=e,{data:o,error:a}=await(0,T._request)(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:a})}throw new g.AuthInvalidCredentialsError("You must provide either an email or phone number and a type")}catch(r){if((0,g.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 s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){let n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}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,v.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 s=e.expires_at?e.expires_at*1e3-Date.now()<z.EXPIRY_MARGIN_MS:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){let o=await(0,v.getItemAsync)(this.userStorage,this.storageKey+"-user");o?.user?e.user=o.user:e.user=(0,v.userNotAvailableProxy)()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=(0,v.insecureUserWarningProxy)(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;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,T._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:T._userResponse}):await this._useSession(async r=>{var s,n,i;let{data:o,error:a}=r;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new g.AuthSessionMissingError}:await(0,T._request)(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:T._userResponse})})}catch(r){if((0,g.isAuthError)(r))return(0,g.isAuthSessionMissingError)(r)&&(await this._removeSession(),await(0,v.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 s=>{let{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new g.AuthSessionMissingError;let o=n.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await(0,v.getCodeChallengeAndMethod)(this.storage,this.storageKey));let{data:c,error:u}=await(0,T._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:T._userResponse});if(u)throw u;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(s){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.isAuthError)(s))return this._returnResult({data:{user:null},error:s});throw s}}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 g.AuthSessionMissingError;let r=Date.now()/1e3,s=r,n=!0,i=null,{payload:o}=(0,v.decodeJWT)(e.access_token);if(o.exp&&(s=o.exp,n=s<=r),n){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:s-r,expires_at:s},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,g.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 s;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!e?.refresh_token)throw new g.AuthSessionMissingError;let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!(0,v.isBrowser)())throw new g.AuthImplicitGrantRedirectError("No browser detected.");if(e.error||e.error_description||e.error_code)throw new g.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 g.AuthPKCEGrantCodeExchangeError("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new g.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 g.AuthPKCEGrantCodeExchangeError("No code detected.");let{data:S,error:w}=await this._exchangeCodeForSession(e.code);if(w)throw w;let k=new URL(window.location.href);return k.searchParams.delete("code"),window.history.replaceState(window.history.state,"",k.toString()),{data:{session:S.session,redirectType:null},error:null}}let{provider_token:s,provider_refresh_token:n,access_token:i,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!i||!a||!o||!c)throw new g.AuthImplicitGrantRedirectError("No session defined in URL");let u=Math.round(Date.now()/1e3),d=parseInt(a),f=u+d;l&&(f=parseInt(l));let h=f-u;h*1e3<=z.AUTO_REFRESH_TICK_DURATION_MS&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${h}s, should have been closer to ${d}s`);let p=f-d;u-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,f,u):u-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",p,f,u);let{data:m,error:_}=await this._getUser(i);if(_)throw _;let y={provider_token:s,provider_refresh_token:n,access_token:i,expires_in:d,expires_at:f,refresh_token:o,token_type:c,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:y,redirectType:e.type},error:null})}catch(s){if((0,g.isAuthError)(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_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,v.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 s;let{data:n,error:i}=r;if(i&&!(0,g.isAuthSessionMissingError)(i))return this._returnResult({error:i});let o=(s=n.session)===null||s===void 0?void 0:s.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!((0,g.isAuthApiError)(a)&&(a.status===404||a.status===401||a.status===403)||(0,g.isAuthSessionMissingError)(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=(0,v.generateCallbackId)(),s={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,s),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{let{data:{session:i},error:o}=r;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await(0,v.getCodeChallengeAndMethod)(this.storage,this.storageKey,!0));try{return await(0,T._request)(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.isAuthError)(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{let{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if((0,g.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:s,error:n}=await this._useSession(async i=>{var o,a,l,c,u;let{data:d,error:f}=i;if(f)throw f;let h=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await(0,T._request)(this.fetch,"GET",h,{headers:this.headers,jwt:(u=(c=d.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(n)throw n;return(0,v.isBrowser)()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s?.url),this._returnResult({data:{provider:e.provider,url:s?.url},error:null})}catch(s){if((0,g.isAuthError)(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{let{error:n,data:{session:i}}=r;if(n)throw n;let{options:o,provider:a,token:l,access_token:c,nonce:u}=e,d=await(0,T._request)(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i?.access_token)!==null&&s!==void 0?s:void 0,body:{provider:a,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:T._sessionResponse}),{data:f,error:h}=d;return h?this._returnResult({data:{user:null,session:null},error:h}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new g.AuthInvalidTokenResponseError}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:h}))}catch(n){if(await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`),(0,g.isAuthError)(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,n;let{data:i,error:o}=r;if(o)throw o;return await(0,T._request)(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if((0,g.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 s=Date.now();return await(0,v.retryable)(async n=>(n>0&&await(0,v.sleep)(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await(0,T._request)(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:T._sessionResponse})),(n,i)=>{let o=200*Math.pow(2,n);return i&&(0,g.isAuthRetryableFetchError)(i)&&Date.now()+o-s<z.AUTO_REFRESH_TICK_DURATION_MS})}catch(s){if(this._debug(r,"error",s),(0,g.isAuthError)(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}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 s=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",s),(0,v.isBrowser)()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,r;let s="#_recoverAndRefresh()";this._debug(s,"begin");try{let n=await(0,v.getItemAsync)(this.storage,this.storageKey);if(n&&this.userStorage){let o=await(0,v.getItemAsync)(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:n.user},await(0,v.setItemAsync)(this.userStorage,this.storageKey+"-user",o)),n.user=(e=o?.user)!==null&&e!==void 0?e:(0,v.userNotAvailableProxy)()}else if(n&&!n.user&&!n.user){let o=await(0,v.getItemAsync)(this.storage,this.storageKey+"-user");o&&o?.user?(n.user=o.user,await(0,v.removeItemAsync)(this.storage,this.storageKey+"-user"),await(0,v.setItemAsync)(this.storage,this.storageKey,n)):n.user=(0,v.userNotAvailableProxy)()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}let i=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<z.EXPIRY_MARGIN_MS;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${z.EXPIRY_MARGIN_MS}s`),i){if(this.autoRefreshToken&&n.refresh_token){let{error:o}=await this._callRefreshToken(n.refresh_token);o&&(console.error(o),(0,g.isAuthRetryableFetchError)(o)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:a}=await this._getUser(n.access_token);!a&&o?.user?(n.user=o.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(s,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new g.AuthSessionMissingError;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new v.Deferred;let{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new g.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(n,"error",i),(0,g.isAuthError)(i)){let o={data:null,error:i};return(0,g.isAuthRetryableFetchError)(i)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&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(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await(0,v.removeItemAsync)(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await(0,v.setItemAsync)(this.userStorage,this.storageKey+"-user",{user:r.user});let n=Object.assign({},r);delete n.user;let i=(0,v.deepClone)(n);await(0,v.setItemAsync)(this.storage,this.storageKey,i)}else{let n=(0,v.deepClone)(r);await(0,v.setItemAsync)(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await(0,v.removeItemAsync)(this.storage,this.storageKey),await(0,v.removeItemAsync)(this.storage,this.storageKey+"-code-verifier"),await(0,v.removeItemAsync)(this.storage,this.storageKey+"-user"),this.userStorage&&await(0,v.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,v.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(),z.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:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let n=Math.floor((s.expires_at*1e3-e)/z.AUTO_REFRESH_TICK_DURATION_MS);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${z.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${z.AUTO_REFRESH_TICK_THRESHOLD} ticks`),n<=z.AUTO_REFRESH_TICK_THRESHOLD&&await this._callRefreshToken(s.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 _n.LockAcquireTimeoutError)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!(0,v.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,s){let n=[`provider=${encodeURIComponent(r)}`];if(s?.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s?.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){let[i,o]=await(0,v.getCodeChallengeAndMethod)(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});n.push(a.toString())}if(s?.queryParams){let i=new URLSearchParams(s.queryParams);n.push(i.toString())}return s?.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var s;let{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await(0,T._request)(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;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,T._request)(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(s=i?.session)===null||s===void 0?void 0:s.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((n=l?.totp)===null||n===void 0)&&n.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if((0,g.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 s;let{data:n,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,He.serializeCredentialCreationResponse)(e.webauthn.credential_response):(0,He.serializeCredentialRequestResponse)(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await(0,T._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.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,g.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 s;let{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});let o=await(0,T._request)(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=n?.session)===null||s===void 0?void 0:s.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,He.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,He.deserializeCredentialRequestOptions)(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};let n={all:[],phone:[],totp:[],webauthn:[]};for(let i of(e=r?.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,i;if(e)try{let{payload:h}=(0,v.decodeJWT)(e),p=null;h.aal&&(p=h.aal);let m=p,{data:{user:_},error:y}=await this.getUser(e);if(y)return this._returnResult({data:null,error:y});((s=(r=_?.factors)===null||r===void 0?void 0:r.filter(k=>k.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(m="aal2");let w=h.amr||[];return{data:{currentLevel:p,nextLevel:m,currentAuthenticationMethods:w},error:null}}catch(h){if((0,g.isAuthError)(h))return this._returnResult({data:null,error:h});throw h}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,v.decodeJWT)(o.access_token),c=null;l.aal&&(c=l.aal);let u=c;((i=(n=o.user.factors)===null||n===void 0?void 0:n.filter(h=>h.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(u="aal2");let f=l.amr||[];return{data:{currentLevel:c,nextLevel:u,currentAuthenticationMethods:f},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await(0,T._request)(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new g.AuthSessionMissingError})})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{let{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new g.AuthSessionMissingError});let o=await(0,T._request)(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&(0,v.isBrowser)()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(s){if((0,g.isAuthError)(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{let{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new g.AuthSessionMissingError});let o=await(0,T._request)(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&(0,v.isBrowser)()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(s){if((0,g.isAuthError)(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await(0,T._request)(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new g.AuthSessionMissingError})})}catch(e){if((0,g.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await(0,T._request)(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new g.AuthSessionMissingError})})}catch(r){if((0,g.isAuthError)(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(a=>a.kid===e);if(s)return s;let n=Date.now();if(s=this.jwks.keys.find(a=>a.kid===e),s&&this.jwks_cached_at+z.JWKS_TTL>n)return s;let{data:i,error:o}=await(0,T._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=n,s=i.keys.find(a=>a.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){let{data:h,error:p}=await this.getSession();if(p||!h.session)return this._returnResult({data:null,error:p});s=h.session.access_token}let{header:n,payload:i,signature:o,raw:{header:a,payload:l}}=(0,v.decodeJWT)(s);r?.allowExpired||(0,v.validateExp)(i.exp);let c=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!c){let{error:h}=await this.getUser(s);if(h)throw h;return{data:{claims:i,header:n,signature:o},error:null}}let u=(0,v.getAlgorithm)(n.alg),d=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,o,(0,gn.stringToUint8Array)(`${a}.${l}`)))throw new g.AuthInvalidJwtError("Invalid JWT signature");return{data:{claims:i,header:n,signature:o},error:null}}catch(s){if((0,g.isAuthError)(s))return this._returnResult({data:null,error:s});throw s}}};At.nextInstanceID={};xr.default=At});var vn=P(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});var ca=(X(),re(Y)),ua=ca.__importDefault(vt()),ha=ua.default;jr.default=ha});var wn=P(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});var da=(X(),re(Y)),fa=da.__importDefault(Nr()),pa=fa.default;Ur.default=pa});var Lr=P(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.processLock=M.lockInternals=M.NavigatorLockAcquireTimeoutError=M.navigatorLock=M.AuthClient=M.AuthAdminApi=M.GoTrueClient=M.GoTrueAdminApi=void 0;var Pe=(X(),re(Y)),ma=Pe.__importDefault(vt());M.GoTrueAdminApi=ma.default;var _a=Pe.__importDefault(Nr());M.GoTrueClient=_a.default;var ga=Pe.__importDefault(vn());M.AuthAdminApi=ga.default;var ya=Pe.__importDefault(wn());M.AuthClient=ya.default;Pe.__exportStar(Er(),M);Pe.__exportStar(me(),M);var Tt=Rr();Object.defineProperty(M,"navigatorLock",{enumerable:!0,get:function(){return Tt.navigatorLock}});Object.defineProperty(M,"NavigatorLockAcquireTimeoutError",{enumerable:!0,get:function(){return Tt.NavigatorLockAcquireTimeoutError}});Object.defineProperty(M,"lockInternals",{enumerable:!0,get:function(){return Tt.internals}});Object.defineProperty(M,"processLock",{enumerable:!0,get:function(){return Tt.processLock}})});var Vr=[{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:"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"}],xn=new Map,Mr=new Map;for(let t of Vr){for(let e of t.aliases)xn.set(e.toLowerCase(),t);for(let e of t.extensions){let r=Mr.get(e.toLowerCase())??[];r.push(t),Mr.set(e.toLowerCase(),r)}}var Ba=new Set(Vr.map(t=>t.canonical));async function Rt(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(".drt"))return{format:"resolve-drt",confidence:"high",details:"DaVinci Resolve Timeline (.drt)"};if(e.endsWith(".fcpxml"))return{format:"resolve-fcpxml",confidence:"high",details:"FCPXML file (.fcpxml) \u2014 DaVinci Resolve or Final Cut Pro X export"};if(e.endsWith(".xml"))return await Nn(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:s}=await import("./esm-SFFBP7PS.js"),n=s(new Uint8Array(await t.arrayBuffer()));for(let[i,o]of Object.entries(n)){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 Nn(t){try{let e=await t.text(),s=new DOMParser().parseFromString(e,"text/xml");if(s.querySelector("parsererror"))return{format:"unknown",confidence:"high",details:"Invalid XML file"};if(s.querySelectorAll("track[premiereTrackType]").length>0)return{format:"premiere-xml",confidence:"high",details:"Found premiereTrackType attribute on track element"};if(s.querySelector("xmeml")){let a=s.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 b={};Dr(b,{FunctionRegion:()=>te.FunctionRegion,FunctionsError:()=>te.FunctionsError,FunctionsFetchError:()=>te.FunctionsFetchError,FunctionsHttpError:()=>te.FunctionsHttpError,FunctionsRelayError:()=>te.FunctionsRelayError,PostgrestError:()=>Lt,SupabaseClient:()=>An,createClient:()=>$r});var te=Ie(ws(),1);var Lt=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},Fn=class{constructor(t){var e,r,s;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=(s=t.urlLengthLimit)!==null&&s!==void 0?s: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 s=this.fetch,n=s(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,u=i.statusText;if(i.ok){var d,f;if(r.method!=="HEAD"){var h;let y=await i.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&(!((h=r.headers.get("Accept"))===null||h===void 0)&&h.includes("application/vnd.pgrst.plan+text"))?a=y:a=JSON.parse(y))}let m=(d=r.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),_=(f=i.headers.get("content-range"))===null||f===void 0?void 0:f.split("/");m&&_&&_.length>1&&(l=parseInt(_[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,u="Not Acceptable"):a.length===1?a=a[0]:a=null)}else{var p;let m=await i.text();try{o=JSON.parse(m),Array.isArray(o)&&i.status===404&&(a=[],o=null,c=200,u="OK")}catch{i.status===404&&m===""?(c=204,u="No Content"):o={message:m}}if(o&&r.isMaybeSingle&&(!(o==null||(p=o.details)===null||p===void 0)&&p.includes("0 rows"))&&(o=null,c=200,u="OK"),o&&r.shouldThrowOnError)throw new Lt(o)}return{error:o,data:a,count:l,status:c,statusText:u}});return this.shouldThrowOnError||(n=n.catch(i=>{var o;let a="",l="",c="",u=i?.cause;if(u){var d,f,h,p;let y=(d=u?.message)!==null&&d!==void 0?d:"",S=(f=u?.code)!==null&&f!==void 0?f:"";a=`${(h=i?.name)!==null&&h!==void 0?h:"FetchError"}: ${i?.message}`,a+=`
43
+
44
+ Caused by: ${(p=u?.name)!==null&&p!==void 0?p:"Error"}: ${y}`,S&&(a+=` (${S})`),u?.stack&&(a+=`
45
+ ${u.stack}`)}else{var m;a=(m=i?.stack)!==null&&m!==void 0?m:""}let _=this.url.toString().length;return i?.name==="AbortError"||i?.code==="ABORT_ERR"?(c="",l="Request was aborted (timeout or manual cancellation)",_>this.urlLengthLimit&&(l+=`. Note: Your request URL is ${_} 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.`)):(u?.name==="HeadersOverflowError"||u?.code==="UND_ERR_HEADERS_OVERFLOW")&&(c="",l="HTTP headers exceeded server limits (typically 16KB)",_>this.urlLengthLimit&&(l+=`. Your request URL is ${_} 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:""}})),n.then(t,e)}returns(){return this}overrideTypes(){return this}},Mn=class extends Fn{select(t){let e=!1,r=(t??"*").split("").map(s=>/\s/.test(s)&&!e?"":(s==='"'&&(e=!e),s)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:s,referencedTable:n=s}={}){let i=n?`${n}.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 s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:s=r}={}){let n=typeof s>"u"?"offset":`${s}.offset`,i=typeof s>"u"?"limit":`${s}.limit`;return this.url.searchParams.set(n,`${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:s=!1,wal:n=!1,format:i="text"}={}){var o;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,s?"buffers":null,n?"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}},bs=new RegExp("[,()]"),Ee=class extends Mn{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(s=>typeof s=="string"&&bs.test(s)?`"${s}"`:`${s}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(s=>typeof s=="string"&&bs.test(s)?`"${s}"`:`${s}`).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:s}={}){let n="";s==="plain"?n="pl":s==="phrase"?n="ph":s==="websearch"&&(n="w");let i=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${n}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 s=r?`${r}.or`:"or";return this.url.searchParams.append(s,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Vn=class{constructor(t,{headers:e={},schema:r,fetch:s,urlLengthLimit:n=8e3}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=s,this.urlLengthLimit=n}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=!1,count:s}=e??{},n=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),s&&l.append("Prefer",`count=${s}`),new Ee({method:n,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var s;let n="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 Ee({method:n,url:i,headers:o,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:s,defaultToNull:n=!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),s&&l.append("Prefer",`count=${s}`),n||l.append("Prefer","missing=default"),Array.isArray(t)){let c=t.reduce((u,d)=>u.concat(Object.keys(d)),[]);if(c.length>0){let u=[...new Set(c)].map(d=>`"${d}"`);a.searchParams.set("columns",u.join(","))}}return new Ee({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 s="PATCH",{url:n,headers:i}=this.cloneRequestState();return e&&i.append("Prefer",`count=${e}`),new Ee({method:s,url:n,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:s,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new Ee({method:r,url:s,headers:n,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function xe(t){"@babel/helpers - typeof";return xe=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},xe(t)}function Wn(t,e){if(xe(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(xe(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Hn(t){var e=Wn(t,"string");return xe(e)=="symbol"?e:e+""}function Kn(t,e,r){return(e=Hn(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Es(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function Ze(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Es(Object(r),!0).forEach(function(s){Kn(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Es(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var Ss=class As{constructor(e,{headers:r={},schema:s,fetch:n,timeout:i,urlLengthLimit:o=8e3}={}){this.url=e,this.headers=new Headers(r),this.schemaName=s,this.urlLengthLimit=o;let a=n??globalThis.fetch;i!==void 0&&i>0?this.fetch=(l,c)=>{let u=new AbortController,d=setTimeout(()=>u.abort(),i),f=c?.signal;if(f){if(f.aborted)return clearTimeout(d),a(l,c);let h=()=>{clearTimeout(d),u.abort()};return f.addEventListener("abort",h,{once:!0}),a(l,Ze(Ze({},c),{},{signal:u.signal})).finally(()=>{clearTimeout(d),f.removeEventListener("abort",h)})}return a(l,Ze(Ze({},c),{},{signal:u.signal})).finally(()=>clearTimeout(d))}: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 Vn(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new As(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:s=!1,get:n=!1,count:i}={}){var o;let a,l=new URL(`${this.url}/rpc/${e}`),c,u=h=>h!==null&&typeof h=="object"&&(!Array.isArray(h)||h.some(u)),d=s&&Object.values(r).some(u);d?(a="POST",c=r):s||n?(a=s?"HEAD":"GET",Object.entries(r).filter(([h,p])=>p!==void 0).map(([h,p])=>[h,Array.isArray(p)?`{${p.join(",")}}`:`${p}`]).forEach(([h,p])=>{l.searchParams.append(h,p)})):(a="POST",c=r);let f=new Headers(this.headers);return d?f.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&f.set("Prefer",`count=${i}`),new Ee({method:a,url:l,headers:f,schema:this.schemaName,body:c,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit})}};var En=Ie(er(),1);var $e=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 _i(t,e,r){let s=new URL(e,t);if(r)for(let[n,i]of Object.entries(r))i!==void 0&&s.searchParams.set(n,i);return s.toString()}async function gi(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 yi(t){let e=t.fetchImpl??globalThis.fetch;return{async request({method:r,path:s,query:n,body:i,headers:o}){let a=_i(t.baseUrl,s,n),l=await gi(t.auth),c=await e(a,{method:r,headers:{...i?{"Content-Type":"application/json"}:{},...l,...o},body:i?JSON.stringify(i):void 0}),u=await c.text(),d=(c.headers.get("content-type")||"").includes("application/json"),f=d&&u?JSON.parse(u):u;if(!c.ok){let h=d?f:void 0,p=h?.error;throw new $e(p?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:p?.type,icebergCode:p?.code,details:h})}return{status:c.status,headers:c.headers,data:f}}}}function lt(t){return t.join("")}var vi=class{constructor(t,e=""){this.client=t,this.prefix=e}async listNamespaces(t){let e=t?{parent:lt(t.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(s=>({namespace:s}))}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/${lt(t.namespace)}`})}async loadNamespaceMetadata(t){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${lt(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${lt(t.namespace)}`}),!0}catch(e){if(e instanceof $e&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof $e&&r.status===409)return;throw r}}};function Se(t){return t.join("")}var wi=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/${Se(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/${Se(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/${Se(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/${Se(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/${Se(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/${Se(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof $e&&r.status===404)return!1;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof $e&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},qs=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=yi({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new vi(this.client,e),this.tableOps=new wi(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 ut=class extends Error{constructor(t,e="storage",r,s){super(t),this.__isStorageError=!0,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=s}};function ht(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}var ct=class extends ut{constructor(t,e,r,s="storage"){super(t,s,e,r),this.name=s==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}},Vs=class extends ut{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e}};var bi=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Ei=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)},tr=t=>{if(Array.isArray(t))return t.map(r=>tr(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,s])=>{let n=r.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));e[n]=tr(s)}),e},Si=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t);function qe(t){"@babel/helpers - typeof";return qe=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},qe(t)}function Ai(t,e){if(qe(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(qe(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ti(t){var e=Ai(t,"string");return qe(e)=="symbol"?e:e+""}function ki(t,e,r){return(e=Ti(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Bs(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function A(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Bs(Object(r),!0).forEach(function(s){ki(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Bs(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var Fs=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)},Ri=async(t,e,r,s)=>{if(t&&typeof t=="object"&&"status"in t&&"ok"in t&&typeof t.status=="number"&&!r?.noResolveJson){let n=t,i=n.status||500;if(typeof n.json=="function")n.json().then(o=>{let a=o?.statusCode||o?.code||i+"";e(new ct(Fs(o),i,a,s))}).catch(()=>{if(s==="vectors"){let o=i+"";e(new ct(n.statusText||`HTTP ${i} error`,i,o,s))}else{let o=i+"";e(new ct(n.statusText||`HTTP ${i} error`,i,o,s))}});else{let o=i+"";e(new ct(n.statusText||`HTTP ${i} error`,i,o,s))}}else e(new Vs(Fs(t),t,s))},Oi=(t,e,r,s)=>{let n={method:t,headers:e?.headers||{}};return t==="GET"||t==="HEAD"||!s?A(A({},n),r):(Ei(s)?(n.headers=A({"Content-Type":"application/json"},e?.headers),n.body=JSON.stringify(s)):n.body=s,e?.duplex&&(n.duplex=e.duplex),A(A({},n),r))};async function De(t,e,r,s,n,i,o){return new Promise((a,l)=>{t(r,Oi(e,s,n,i)).then(c=>{if(!c.ok)throw c;if(s?.noResolveJson)return c;if(o==="vectors"){let u=c.headers.get("content-type");if(c.headers.get("content-length")==="0"||c.status===204)return{};if(!u||!u.includes("application/json"))return{}}return c.json()}).then(c=>a(c)).catch(c=>Ri(c,l,s,o))})}function Ws(t="storage"){return{get:async(e,r,s,n)=>De(e,"GET",r,s,n,void 0,t),post:async(e,r,s,n,i)=>De(e,"POST",r,n,i,s,t),put:async(e,r,s,n,i)=>De(e,"PUT",r,n,i,s,t),head:async(e,r,s,n)=>De(e,"HEAD",r,A(A({},s),{},{noResolveJson:!0}),n,void 0,t),remove:async(e,r,s,n,i)=>De(e,"DELETE",r,n,i,s,t)}}var Pi=Ws("storage"),{get:Be,post:ne,put:rr,head:Ii,remove:sr}=Pi,J=Ws("vectors"),Ae=class{constructor(t,e={},r,s="storage"){this.shouldThrowOnError=!1,this.url=t,this.headers=e,this.fetch=bi(r),this.namespace=s}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=A(A({},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(ht(r))return{data:null,error:r};throw r}}},Ci=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(ht(e))return{data:null,error:e};throw e}}},Hs;Hs=Symbol.toStringTag;var xi=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[Hs]="BlobDownloadBuilder",this.promise=null}asStream(){return new Ci(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(ht(e))return{data:null,error:e};throw e}}},Ni={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Ms={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1},ji=class extends Ae{constructor(t,e={},r,s){super(t,e,s,"storage"),this.bucketId=r}async uploadOrUpdate(t,e,r,s){var n=this;return n.handleOperation(async()=>{let i,o=A(A({},Ms),s),a=A(A({},n.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",n.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",n.encodeMetadata(l))):(i=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=n.toBase64(n.encodeMetadata(l))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),s?.headers&&(a=A(A({},a),s.headers));let c=n._removeEmptyFolders(e),u=n._getFinalPath(c),d=await(t=="PUT"?rr:ne)(n.fetch,`${n.url}/object/${u}`,i,A({headers:a},o?.duplex?{duplex:o.duplex}:{}));return{path:c,id:d.Id,fullPath:d.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,s){var n=this;let i=n._removeEmptyFolders(t),o=n._getFinalPath(i),a=new URL(n.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",e),n.handleOperation(async()=>{let l,c=A({upsert:Ms.upsert},s),u=A(A({},n.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,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType),{path:i,fullPath:(await rr(n.fetch,a.toString(),l,{headers:u})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let s=r._getFinalPath(t),n=A({},r.headers);e?.upsert&&(n["x-upsert"]="true");let i=await ne(r.fetch,`${r.url}/object/upload/sign/${s}`,{},{headers:n}),o=new URL(r.url+i.url),a=o.searchParams.get("token");if(!a)throw new ut("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 s=this;return s.handleOperation(async()=>await ne(s.fetch,`${s.url}/object/move`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:s.headers}))}async copy(t,e,r){var s=this;return s.handleOperation(async()=>({path:(await ne(s.fetch,`${s.url}/object/copy`,{bucketId:s.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:s.headers})).Key}))}async createSignedUrl(t,e,r){var s=this;return s.handleOperation(async()=>{let n=s._getFinalPath(t),i=await ne(s.fetch,`${s.url}/object/sign/${n}`,A({expiresIn:e},r?.transform?{transform:r.transform}:{}),{headers:s.headers}),o=r?.download?`&download=${r.download===!0?"":r.download}`:"";return{signedUrl:encodeURI(`${s.url}${i.signedURL}${o}`)}})}async createSignedUrls(t,e,r){var s=this;return s.handleOperation(async()=>{let n=await ne(s.fetch,`${s.url}/object/sign/${s.bucketId}`,{expiresIn:e,paths:t},{headers:s.headers}),i=r?.download?`&download=${r.download===!0?"":r.download}`:"";return n.map(o=>A(A({},o),{},{signedUrl:o.signedURL?encodeURI(`${s.url}${o.signedURL}${i}`):null}))})}download(t,e,r){let s=typeof e?.transform<"u"?"render/image/authenticated":"object",n=this.transformOptsToQueryString(e?.transform||{}),i=n?`?${n}`:"",o=this._getFinalPath(t),a=()=>Be(this.fetch,`${this.url}/${s}/${o}${i}`,{headers:this.headers,noResolveJson:!0},r);return new xi(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>tr(await Be(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await Ii(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(s){if(e.shouldThrowOnError)throw s;if(ht(s)&&s instanceof Vs){let n=s.originalError;if([400,404].includes(n?.status))return{data:!1,error:s}}throw s}}getPublicUrl(t,e){let r=this._getFinalPath(t),s=[],n=e?.download?`download=${e.download===!0?"":e.download}`:"";n!==""&&s.push(n);let i=typeof e?.transform<"u"?"render/image":"object",o=this.transformOptsToQueryString(e?.transform||{});o!==""&&s.push(o);let a=s.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 sr(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var s=this;return s.handleOperation(async()=>{let n=A(A(A({},Ni),e),{},{prefix:t||""});return await ne(s.fetch,`${s.url}/object/list/${s.bucketId}`,n,{headers:s.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let s=A({},t);return await ne(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,s,{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("&")}},Ui="2.97.0",Fe={"X-Client-Info":`storage-js/${Ui}`},Li=class extends Ae{constructor(t,e={},r,s){let n=new URL(t);s?.useNewHostname&&/supabase\.(co|in|red)$/.test(n.hostname)&&!n.hostname.includes("storage.supabase.")&&(n.hostname=n.hostname.replace("supabase.","storage.supabase."));let i=n.href.replace(/\/$/,""),o=A(A({},Fe),e);super(i,o,r,"storage")}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await Be(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Be(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:!1}){var r=this;return r.handleOperation(async()=>await ne(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 rr(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 ne(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await sr(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():""}},$i=class extends Ae{constructor(t,e={},r){let s=t.replace(/\/$/,""),n=A(A({},Fe),e);super(s,n,r,"storage")}async createBucket(t){var e=this;return e.handleOperation(async()=>await ne(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 s=r.toString(),n=s?`${e.url}/bucket?${s}`:`${e.url}/bucket`;return await Be(e.fetch,n,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await sr(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!Si(t))throw new ut("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 qs({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),s=this.shouldThrowOnError;return new Proxy(r,{get(n,i){let o=n[i];return typeof o!="function"?o:async(...a)=>{try{return{data:await o.apply(n,a),error:null}}catch(l){if(s)throw l;return{data:null,error:l}}}}})}},Di=class extends Ae{constructor(t,e={},r){let s=t.replace(/\/$/,""),n=A(A({},Fe),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createIndex(t){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await J.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await J.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},qi=class extends Ae{constructor(t,e={},r){let s=t.replace(/\/$/,""),n=A(A({},Fe),{},{"Content-Type":"application/json"},e);super(s,n,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 J.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await J.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 J.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await J.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 J.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},Bi=class extends Ae{constructor(t,e={},r){let s=t.replace(/\/$/,""),n=A(A({},Fe),{},{"Content-Type":"application/json"},e);super(s,n,r,"vectors")}async createBucket(t){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await J.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},Fi=class extends Bi{constructor(t,e={}){super(t,e.headers||{},e.fetch)}from(t){return new Mi(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)}},Mi=class extends Di{constructor(t,e,r,s){super(t,e,s),this.vectorBucketName=r}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,A(A({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,A(A({},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 Vi(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Vi=class extends qi{constructor(t,e,r,s,n){super(t,e,n),this.vectorBucketName=r,this.indexName=s}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,A(A({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,A(A({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,A(A({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,A(A({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,A(A({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},Ks=class extends Li{constructor(t,e={},r,s){super(t,e,r,s)}from(t){return new ji(this.url,this.headers,t,this.fetch)}get vectors(){return new Fi(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new $i(this.url+"/iceberg",this.headers,this.fetch)}};var Sn=Ie(Lr(),1);E(b,Ie(er(),1));E(b,Ie(Lr(),1));var va="2.97.0",Ke="";typeof Deno<"u"?Ke="deno":typeof document<"u"?Ke="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Ke="react-native":Ke="node";var wa={"X-Client-Info":`supabase-js-${Ke}/${va}`},ba={headers:wa},Ea={schema:"public"},Sa={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Aa={};function Ge(t){"@babel/helpers - typeof";return Ge=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},Ge(t)}function Ta(t,e){if(Ge(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e||"default");if(Ge(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ka(t){var e=Ta(t,"string");return Ge(e)=="symbol"?e:e+""}function Ra(t,e,r){return(e=ka(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function bn(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function B(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?bn(Object(r),!0).forEach(function(s){Ra(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):bn(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}var Oa=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Pa=()=>Headers,Ia=(t,e,r)=>{let s=Oa(r),n=Pa();return async(i,o)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,c=new n(o?.headers);return c.has("apikey")||c.set("apikey",t),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),s(i,B(B({},o),{},{headers:c}))}};function Ca(t){return t.endsWith("/")?t:t+"/"}function xa(t,e){var r,s;let{db:n,auth:i,realtime:o,global:a}=t,{db:l,auth:c,realtime:u,global:d}=e,f={db:B(B({},l),n),auth:B(B({},c),i),realtime:B(B({},u),o),storage:{},global:B(B(B({},d),a),{},{headers:B(B({},(r=d?.headers)!==null&&r!==void 0?r:{}),(s=a?.headers)!==null&&s!==void 0?s:{})}),accessToken:async()=>""};return t.accessToken?f.accessToken=t.accessToken:delete f.accessToken,f}function Na(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(Ca(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var ja=class extends Sn.AuthClient{constructor(t){super(t)}},An=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;let i=Na(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:Ea,realtime:Aa,auth:B(B({},Sa),{},{storageKey:o}),global:ba},l=xa(r??{},a);if(this.storageKey=(s=l.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(u,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} 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=Ia(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(B({headers:this.headers,accessToken:this._getAccessToken.bind(this)},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(u=>this.realtime.setAuth(u)).catch(u=>console.warn("Failed to set initial Realtime auth token:",u)),this.rest=new Ss(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 Ks(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new te.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:s}=await t.auth.getSession();return(e=(r=s.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:s,userStorage:n,storageKey:i,flowType:o,lock:a,debug:l,throwOnError:c},u,d){let f={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new ja({url:this.authUrl.href,headers:B(B({},f),u),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:o,lock:a,debug:l,throwOnError:c,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(h=>h.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new En.RealtimeClient(this.realtimeUrl.href,B(B({},t),{},{params:B(B({},{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)}},$r=(t,e,r)=>new An(t,e,r);function Ua(){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}Ua()&&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");var Tn=import.meta.env.VITE_SUPABASE_URL,kn=import.meta.env.VITE_SUPABASE_ANON_KEY;if(!Tn)throw console.error("Missing VITE_SUPABASE_URL environment variable"),new Error("Missing Supabase URL environment variable");if(!kn)throw console.error("Missing VITE_SUPABASE_ANON_KEY environment variable"),new Error("Missing Supabase anon key environment variable");var Rn=$r(Tn,kn,{auth:{autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0}});var La=`${import.meta.env.VITE_SUPABASE_URL}/functions/v1`,pc=import.meta.env.VITE_LOCAL_API_URL?.replace(/\/$/,"");async function On(t){let{data:{session:e}}=await Rn.auth.getSession(),r=e?.access_token??import.meta.env.VITE_SUPABASE_ANON_KEY,s=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}),n=typeof t.extract=="string"?t.extract:JSON.stringify(t.extract),i=s+`
46
+ `+n,o=new Set([502,503,504,529,546]),a=null;for(let l=0;;l++){try{a=await fetch(`${La}/v1-timeline-canonicalize/v1/timeline-canonicalize`,{method:"POST",headers:{"Content-Type":"application/x-ct-canonicalize-v1",Authorization:`Bearer ${r}`},body:i})}catch(c){if(l>=2)throw c;a=null}if(a&&(a.ok||!o.has(a.status)))break;if(l>=2)throw a?.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 (${a?.status??"network error"}) \u2014 a server hiccup, not a problem with your file. Please try again in a minute.`);await new Promise(c=>setTimeout(c,1500*(l+1)))}if(!a.ok){let l=await a.json().catch(()=>({}));throw new Error(l?.error?.message??`canonicalize failed (${a.status})`)}return await a.json()}var $a=[{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}],Pn=new Map;for(let t of $a)Pn.set(t.ext,t);function Da(t){let e=t.split(".").pop()?.toLowerCase();return e?Pn.get(e)??null:null}function In(t){return Da(t)!==null}async function Ac(t){if(In(t.name))return await qa(t);let e=await Rt(t);if(e.format!=="unknown"&&kt(e.format)){let{names:r}=await qr(t,e.format);return{kind:"timeline",format:e.format,name:t.name,observed_bytes:t.size,total_size:t.size,session:{id:null,inline:{timelines:r.map(s=>({name:s}))}},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 qa(t){let e=Date.now(),r=await Fr(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 s=r.container??"media",n={metadata:{id:t.name,user_id:"",source_format:s,source_filename:t.name,source_file_sha256:null,source_file_bytes:t.size,parser_name:`media:${s}`,parser_version:"1",status:"ready",error_message:null,metadata:{},created_at:new Date().toISOString()},timelines:[],media_references:[r]};return{kind:"media",format:s,name:t.name,observed_bytes:0,total_size:t.size,session:{id:null,inline:n},warnings:[],inspector:{layer:"probe-media/local",version:"1",duration_ms:Date.now()-e}}}async function Tc(t,e={}){let{format:r}=await Rt(t);if(!kt(r))throw new Error(`No Rust timeline engine for format '${r}' (${t.name})`);let{fmt:s,extract:n}=await Br(t,r,e.selectedSequenceNames),i=await On({format:s,extract:n,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{Tc as canonicalizeTimelineFile,Ac as inspectFile};